diffusers 0.30.2__py3-none-any.whl → 0.31.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. diffusers/__init__.py +38 -2
  2. diffusers/configuration_utils.py +12 -0
  3. diffusers/dependency_versions_table.py +1 -1
  4. diffusers/image_processor.py +257 -54
  5. diffusers/loaders/__init__.py +2 -0
  6. diffusers/loaders/ip_adapter.py +5 -1
  7. diffusers/loaders/lora_base.py +14 -7
  8. diffusers/loaders/lora_conversion_utils.py +332 -0
  9. diffusers/loaders/lora_pipeline.py +707 -41
  10. diffusers/loaders/peft.py +1 -0
  11. diffusers/loaders/single_file_utils.py +81 -4
  12. diffusers/loaders/textual_inversion.py +2 -0
  13. diffusers/loaders/unet.py +39 -8
  14. diffusers/models/__init__.py +4 -0
  15. diffusers/models/adapter.py +53 -53
  16. diffusers/models/attention.py +86 -10
  17. diffusers/models/attention_processor.py +169 -133
  18. diffusers/models/autoencoders/autoencoder_kl.py +71 -11
  19. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +287 -85
  20. diffusers/models/controlnet_flux.py +536 -0
  21. diffusers/models/controlnet_sd3.py +7 -3
  22. diffusers/models/controlnet_sparsectrl.py +0 -1
  23. diffusers/models/embeddings.py +238 -61
  24. diffusers/models/embeddings_flax.py +23 -9
  25. diffusers/models/model_loading_utils.py +182 -14
  26. diffusers/models/modeling_utils.py +283 -46
  27. diffusers/models/normalization.py +79 -0
  28. diffusers/models/transformers/__init__.py +1 -0
  29. diffusers/models/transformers/auraflow_transformer_2d.py +1 -0
  30. diffusers/models/transformers/cogvideox_transformer_3d.py +58 -36
  31. diffusers/models/transformers/pixart_transformer_2d.py +9 -1
  32. diffusers/models/transformers/transformer_cogview3plus.py +386 -0
  33. diffusers/models/transformers/transformer_flux.py +161 -44
  34. diffusers/models/transformers/transformer_sd3.py +7 -1
  35. diffusers/models/unets/unet_2d_condition.py +8 -8
  36. diffusers/models/unets/unet_motion_model.py +41 -63
  37. diffusers/models/upsampling.py +6 -6
  38. diffusers/pipelines/__init__.py +40 -7
  39. diffusers/pipelines/animatediff/__init__.py +2 -0
  40. diffusers/pipelines/animatediff/pipeline_animatediff.py +45 -21
  41. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +44 -20
  42. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +18 -4
  43. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +2 -0
  44. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +104 -66
  45. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +1341 -0
  46. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +1 -1
  47. diffusers/pipelines/auto_pipeline.py +39 -8
  48. diffusers/pipelines/cogvideo/__init__.py +6 -0
  49. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +32 -34
  50. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +794 -0
  51. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +837 -0
  52. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +825 -0
  53. diffusers/pipelines/cogvideo/pipeline_output.py +20 -0
  54. diffusers/pipelines/cogview3/__init__.py +47 -0
  55. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +674 -0
  56. diffusers/pipelines/cogview3/pipeline_output.py +21 -0
  57. diffusers/pipelines/controlnet/pipeline_controlnet.py +9 -1
  58. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +8 -0
  59. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +8 -0
  60. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +36 -13
  61. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +9 -1
  62. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +8 -1
  63. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +17 -3
  64. diffusers/pipelines/controlnet_sd3/__init__.py +4 -0
  65. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +3 -1
  66. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +1153 -0
  67. diffusers/pipelines/ddpm/pipeline_ddpm.py +2 -2
  68. diffusers/pipelines/deepfloyd_if/pipeline_output.py +6 -5
  69. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +16 -4
  70. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +1 -1
  71. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +1 -1
  72. diffusers/pipelines/flux/__init__.py +10 -0
  73. diffusers/pipelines/flux/pipeline_flux.py +53 -20
  74. diffusers/pipelines/flux/pipeline_flux_controlnet.py +984 -0
  75. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +988 -0
  76. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1182 -0
  77. diffusers/pipelines/flux/pipeline_flux_img2img.py +850 -0
  78. diffusers/pipelines/flux/pipeline_flux_inpaint.py +1015 -0
  79. diffusers/pipelines/free_noise_utils.py +365 -5
  80. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +15 -3
  81. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +2 -2
  82. diffusers/pipelines/kolors/pipeline_kolors.py +1 -1
  83. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +14 -11
  84. diffusers/pipelines/kolors/tokenizer.py +4 -0
  85. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +1 -1
  86. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +1 -1
  87. diffusers/pipelines/latte/pipeline_latte.py +2 -2
  88. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +15 -3
  89. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +15 -3
  90. diffusers/pipelines/lumina/pipeline_lumina.py +2 -2
  91. diffusers/pipelines/pag/__init__.py +6 -0
  92. diffusers/pipelines/pag/pag_utils.py +8 -2
  93. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1 -1
  94. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1544 -0
  95. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +2 -2
  96. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1685 -0
  97. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +17 -5
  98. diffusers/pipelines/pag/pipeline_pag_kolors.py +1 -1
  99. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +1 -1
  100. diffusers/pipelines/pag/pipeline_pag_sd.py +18 -6
  101. diffusers/pipelines/pag/pipeline_pag_sd_3.py +12 -3
  102. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +5 -1
  103. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +1091 -0
  104. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +18 -6
  105. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +31 -16
  106. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +42 -19
  107. diffusers/pipelines/pia/pipeline_pia.py +2 -0
  108. diffusers/pipelines/pipeline_loading_utils.py +225 -27
  109. diffusers/pipelines/pipeline_utils.py +123 -180
  110. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +1 -1
  111. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +1 -1
  112. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +35 -3
  113. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +2 -2
  114. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +28 -6
  115. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +1 -1
  116. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +1 -1
  117. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +241 -81
  118. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +12 -3
  119. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +20 -4
  120. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +3 -3
  121. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -1
  122. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +16 -4
  123. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +16 -4
  124. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +16 -4
  125. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +29 -14
  126. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +29 -14
  127. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +1 -1
  128. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +1 -1
  129. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +16 -4
  130. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +15 -3
  131. diffusers/quantizers/__init__.py +16 -0
  132. diffusers/quantizers/auto.py +126 -0
  133. diffusers/quantizers/base.py +233 -0
  134. diffusers/quantizers/bitsandbytes/__init__.py +2 -0
  135. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +558 -0
  136. diffusers/quantizers/bitsandbytes/utils.py +306 -0
  137. diffusers/quantizers/quantization_config.py +391 -0
  138. diffusers/schedulers/scheduling_ddim.py +4 -1
  139. diffusers/schedulers/scheduling_ddim_cogvideox.py +4 -1
  140. diffusers/schedulers/scheduling_ddim_parallel.py +4 -1
  141. diffusers/schedulers/scheduling_ddpm.py +4 -1
  142. diffusers/schedulers/scheduling_ddpm_parallel.py +4 -1
  143. diffusers/schedulers/scheduling_deis_multistep.py +78 -1
  144. diffusers/schedulers/scheduling_dpmsolver_multistep.py +82 -1
  145. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +80 -1
  146. diffusers/schedulers/scheduling_dpmsolver_sde.py +125 -10
  147. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +82 -1
  148. diffusers/schedulers/scheduling_edm_euler.py +8 -6
  149. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +4 -1
  150. diffusers/schedulers/scheduling_euler_discrete.py +92 -7
  151. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +4 -5
  152. diffusers/schedulers/scheduling_heun_discrete.py +114 -8
  153. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +116 -11
  154. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +110 -8
  155. diffusers/schedulers/scheduling_lms_discrete.py +76 -1
  156. diffusers/schedulers/scheduling_sasolver.py +78 -1
  157. diffusers/schedulers/scheduling_unclip.py +4 -1
  158. diffusers/schedulers/scheduling_unipc_multistep.py +78 -1
  159. diffusers/training_utils.py +48 -18
  160. diffusers/utils/__init__.py +2 -1
  161. diffusers/utils/dummy_pt_objects.py +60 -0
  162. diffusers/utils/dummy_torch_and_transformers_objects.py +195 -0
  163. diffusers/utils/hub_utils.py +16 -4
  164. diffusers/utils/import_utils.py +31 -8
  165. diffusers/utils/loading_utils.py +28 -4
  166. diffusers/utils/peft_utils.py +3 -3
  167. diffusers/utils/testing_utils.py +59 -0
  168. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/METADATA +7 -6
  169. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/RECORD +173 -147
  170. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/WHEEL +1 -1
  171. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/LICENSE +0 -0
  172. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/entry_points.txt +0 -0
  173. {diffusers-0.30.2.dist-info → diffusers-0.31.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,391 @@
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+
4
+ # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ Adapted from
20
+ https://github.com/huggingface/transformers/blob/52cb4034ada381fe1ffe8d428a1076e5411a8026/src/transformers/utils/quantization_config.py
21
+ """
22
+
23
+ import copy
24
+ import importlib.metadata
25
+ import json
26
+ import os
27
+ from dataclasses import dataclass
28
+ from enum import Enum
29
+ from typing import Any, Dict, Union
30
+
31
+ from packaging import version
32
+
33
+ from ..utils import is_torch_available, logging
34
+
35
+
36
+ if is_torch_available():
37
+ import torch
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+
42
+ class QuantizationMethod(str, Enum):
43
+ BITS_AND_BYTES = "bitsandbytes"
44
+
45
+
46
+ @dataclass
47
+ class QuantizationConfigMixin:
48
+ """
49
+ Mixin class for quantization config
50
+ """
51
+
52
+ quant_method: QuantizationMethod
53
+ _exclude_attributes_at_init = []
54
+
55
+ @classmethod
56
+ def from_dict(cls, config_dict, return_unused_kwargs=False, **kwargs):
57
+ """
58
+ Instantiates a [`QuantizationConfigMixin`] from a Python dictionary of parameters.
59
+
60
+ Args:
61
+ config_dict (`Dict[str, Any]`):
62
+ Dictionary that will be used to instantiate the configuration object.
63
+ return_unused_kwargs (`bool`,*optional*, defaults to `False`):
64
+ Whether or not to return a list of unused keyword arguments. Used for `from_pretrained` method in
65
+ `PreTrainedModel`.
66
+ kwargs (`Dict[str, Any]`):
67
+ Additional parameters from which to initialize the configuration object.
68
+
69
+ Returns:
70
+ [`QuantizationConfigMixin`]: The configuration object instantiated from those parameters.
71
+ """
72
+
73
+ config = cls(**config_dict)
74
+
75
+ to_remove = []
76
+ for key, value in kwargs.items():
77
+ if hasattr(config, key):
78
+ setattr(config, key, value)
79
+ to_remove.append(key)
80
+ for key in to_remove:
81
+ kwargs.pop(key, None)
82
+
83
+ if return_unused_kwargs:
84
+ return config, kwargs
85
+ else:
86
+ return config
87
+
88
+ def to_json_file(self, json_file_path: Union[str, os.PathLike]):
89
+ """
90
+ Save this instance to a JSON file.
91
+
92
+ Args:
93
+ json_file_path (`str` or `os.PathLike`):
94
+ Path to the JSON file in which this configuration instance's parameters will be saved.
95
+ use_diff (`bool`, *optional*, defaults to `True`):
96
+ If set to `True`, only the difference between the config instance and the default
97
+ `QuantizationConfig()` is serialized to JSON file.
98
+ """
99
+ with open(json_file_path, "w", encoding="utf-8") as writer:
100
+ config_dict = self.to_dict()
101
+ json_string = json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
102
+
103
+ writer.write(json_string)
104
+
105
+ def to_dict(self) -> Dict[str, Any]:
106
+ """
107
+ Serializes this instance to a Python dictionary. Returns:
108
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
109
+ """
110
+ return copy.deepcopy(self.__dict__)
111
+
112
+ def __iter__(self):
113
+ """allows `dict(obj)` for situations where obj may be a dict or QuantizationConfigMixin"""
114
+ for attr, value in copy.deepcopy(self.__dict__).items():
115
+ yield attr, value
116
+
117
+ def __repr__(self):
118
+ return f"{self.__class__.__name__} {self.to_json_string()}"
119
+
120
+ def to_json_string(self, use_diff: bool = True) -> str:
121
+ """
122
+ Serializes this instance to a JSON string.
123
+
124
+ Args:
125
+ use_diff (`bool`, *optional*, defaults to `True`):
126
+ If set to `True`, only the difference between the config instance and the default `PretrainedConfig()`
127
+ is serialized to JSON string.
128
+
129
+ Returns:
130
+ `str`: String containing all the attributes that make up this configuration instance in JSON format.
131
+ """
132
+ if use_diff is True:
133
+ config_dict = self.to_diff_dict()
134
+ else:
135
+ config_dict = self.to_dict()
136
+ return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
137
+
138
+ def update(self, **kwargs):
139
+ """
140
+ Updates attributes of this class instance with attributes from `kwargs` if they match existing attributes,
141
+ returning all the unused kwargs.
142
+
143
+ Args:
144
+ kwargs (`Dict[str, Any]`):
145
+ Dictionary of attributes to tentatively update this class.
146
+
147
+ Returns:
148
+ `Dict[str, Any]`: Dictionary containing all the key-value pairs that were not used to update the instance.
149
+ """
150
+ to_remove = []
151
+ for key, value in kwargs.items():
152
+ if hasattr(self, key):
153
+ setattr(self, key, value)
154
+ to_remove.append(key)
155
+
156
+ # Remove all the attributes that were updated, without modifying the input dict
157
+ unused_kwargs = {key: value for key, value in kwargs.items() if key not in to_remove}
158
+ return unused_kwargs
159
+
160
+
161
+ @dataclass
162
+ class BitsAndBytesConfig(QuantizationConfigMixin):
163
+ """
164
+ This is a wrapper class about all possible attributes and features that you can play with a model that has been
165
+ loaded using `bitsandbytes`.
166
+
167
+ This replaces `load_in_8bit` or `load_in_4bit`therefore both options are mutually exclusive.
168
+
169
+ Currently only supports `LLM.int8()`, `FP4`, and `NF4` quantization. If more methods are added to `bitsandbytes`,
170
+ then more arguments will be added to this class.
171
+
172
+ Args:
173
+ load_in_8bit (`bool`, *optional*, defaults to `False`):
174
+ This flag is used to enable 8-bit quantization with LLM.int8().
175
+ load_in_4bit (`bool`, *optional*, defaults to `False`):
176
+ This flag is used to enable 4-bit quantization by replacing the Linear layers with FP4/NF4 layers from
177
+ `bitsandbytes`.
178
+ llm_int8_threshold (`float`, *optional*, defaults to 6.0):
179
+ This corresponds to the outlier threshold for outlier detection as described in `LLM.int8() : 8-bit Matrix
180
+ Multiplication for Transformers at Scale` paper: https://arxiv.org/abs/2208.07339 Any hidden states value
181
+ that is above this threshold will be considered an outlier and the operation on those values will be done
182
+ in fp16. Values are usually normally distributed, that is, most values are in the range [-3.5, 3.5], but
183
+ there are some exceptional systematic outliers that are very differently distributed for large models.
184
+ These outliers are often in the interval [-60, -6] or [6, 60]. Int8 quantization works well for values of
185
+ magnitude ~5, but beyond that, there is a significant performance penalty. A good default threshold is 6,
186
+ but a lower threshold might be needed for more unstable models (small models, fine-tuning).
187
+ llm_int8_skip_modules (`List[str]`, *optional*):
188
+ An explicit list of the modules that we do not want to convert in 8-bit. This is useful for models such as
189
+ Jukebox that has several heads in different places and not necessarily at the last position. For example
190
+ for `CausalLM` models, the last `lm_head` is typically kept in its original `dtype`.
191
+ llm_int8_enable_fp32_cpu_offload (`bool`, *optional*, defaults to `False`):
192
+ This flag is used for advanced use cases and users that are aware of this feature. If you want to split
193
+ your model in different parts and run some parts in int8 on GPU and some parts in fp32 on CPU, you can use
194
+ this flag. This is useful for offloading large models such as `google/flan-t5-xxl`. Note that the int8
195
+ operations will not be run on CPU.
196
+ llm_int8_has_fp16_weight (`bool`, *optional*, defaults to `False`):
197
+ This flag runs LLM.int8() with 16-bit main weights. This is useful for fine-tuning as the weights do not
198
+ have to be converted back and forth for the backward pass.
199
+ bnb_4bit_compute_dtype (`torch.dtype` or str, *optional*, defaults to `torch.float32`):
200
+ This sets the computational type which might be different than the input type. For example, inputs might be
201
+ fp32, but computation can be set to bf16 for speedups.
202
+ bnb_4bit_quant_type (`str`, *optional*, defaults to `"fp4"`):
203
+ This sets the quantization data type in the bnb.nn.Linear4Bit layers. Options are FP4 and NF4 data types
204
+ which are specified by `fp4` or `nf4`.
205
+ bnb_4bit_use_double_quant (`bool`, *optional*, defaults to `False`):
206
+ This flag is used for nested quantization where the quantization constants from the first quantization are
207
+ quantized again.
208
+ bnb_4bit_quant_storage (`torch.dtype` or str, *optional*, defaults to `torch.uint8`):
209
+ This sets the storage type to pack the quanitzed 4-bit prarams.
210
+ kwargs (`Dict[str, Any]`, *optional*):
211
+ Additional parameters from which to initialize the configuration object.
212
+ """
213
+
214
+ _exclude_attributes_at_init = ["_load_in_4bit", "_load_in_8bit", "quant_method"]
215
+
216
+ def __init__(
217
+ self,
218
+ load_in_8bit=False,
219
+ load_in_4bit=False,
220
+ llm_int8_threshold=6.0,
221
+ llm_int8_skip_modules=None,
222
+ llm_int8_enable_fp32_cpu_offload=False,
223
+ llm_int8_has_fp16_weight=False,
224
+ bnb_4bit_compute_dtype=None,
225
+ bnb_4bit_quant_type="fp4",
226
+ bnb_4bit_use_double_quant=False,
227
+ bnb_4bit_quant_storage=None,
228
+ **kwargs,
229
+ ):
230
+ self.quant_method = QuantizationMethod.BITS_AND_BYTES
231
+
232
+ if load_in_4bit and load_in_8bit:
233
+ raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
234
+
235
+ self._load_in_8bit = load_in_8bit
236
+ self._load_in_4bit = load_in_4bit
237
+ self.llm_int8_threshold = llm_int8_threshold
238
+ self.llm_int8_skip_modules = llm_int8_skip_modules
239
+ self.llm_int8_enable_fp32_cpu_offload = llm_int8_enable_fp32_cpu_offload
240
+ self.llm_int8_has_fp16_weight = llm_int8_has_fp16_weight
241
+ self.bnb_4bit_quant_type = bnb_4bit_quant_type
242
+ self.bnb_4bit_use_double_quant = bnb_4bit_use_double_quant
243
+
244
+ if bnb_4bit_compute_dtype is None:
245
+ self.bnb_4bit_compute_dtype = torch.float32
246
+ elif isinstance(bnb_4bit_compute_dtype, str):
247
+ self.bnb_4bit_compute_dtype = getattr(torch, bnb_4bit_compute_dtype)
248
+ elif isinstance(bnb_4bit_compute_dtype, torch.dtype):
249
+ self.bnb_4bit_compute_dtype = bnb_4bit_compute_dtype
250
+ else:
251
+ raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype")
252
+
253
+ if bnb_4bit_quant_storage is None:
254
+ self.bnb_4bit_quant_storage = torch.uint8
255
+ elif isinstance(bnb_4bit_quant_storage, str):
256
+ if bnb_4bit_quant_storage not in ["float16", "float32", "int8", "uint8", "float64", "bfloat16"]:
257
+ raise ValueError(
258
+ "`bnb_4bit_quant_storage` must be a valid string (one of 'float16', 'float32', 'int8', 'uint8', 'float64', 'bfloat16') "
259
+ )
260
+ self.bnb_4bit_quant_storage = getattr(torch, bnb_4bit_quant_storage)
261
+ elif isinstance(bnb_4bit_quant_storage, torch.dtype):
262
+ self.bnb_4bit_quant_storage = bnb_4bit_quant_storage
263
+ else:
264
+ raise ValueError("bnb_4bit_quant_storage must be a string or a torch.dtype")
265
+
266
+ if kwargs and not all(k in self._exclude_attributes_at_init for k in kwargs):
267
+ logger.warning(f"Unused kwargs: {list(kwargs.keys())}. These kwargs are not used in {self.__class__}.")
268
+
269
+ self.post_init()
270
+
271
+ @property
272
+ def load_in_4bit(self):
273
+ return self._load_in_4bit
274
+
275
+ @load_in_4bit.setter
276
+ def load_in_4bit(self, value: bool):
277
+ if not isinstance(value, bool):
278
+ raise TypeError("load_in_4bit must be a boolean")
279
+
280
+ if self.load_in_8bit and value:
281
+ raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
282
+ self._load_in_4bit = value
283
+
284
+ @property
285
+ def load_in_8bit(self):
286
+ return self._load_in_8bit
287
+
288
+ @load_in_8bit.setter
289
+ def load_in_8bit(self, value: bool):
290
+ if not isinstance(value, bool):
291
+ raise TypeError("load_in_8bit must be a boolean")
292
+
293
+ if self.load_in_4bit and value:
294
+ raise ValueError("load_in_4bit and load_in_8bit are both True, but only one can be used at the same time")
295
+ self._load_in_8bit = value
296
+
297
+ def post_init(self):
298
+ r"""
299
+ Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.
300
+ """
301
+ if not isinstance(self.load_in_4bit, bool):
302
+ raise TypeError("load_in_4bit must be a boolean")
303
+
304
+ if not isinstance(self.load_in_8bit, bool):
305
+ raise TypeError("load_in_8bit must be a boolean")
306
+
307
+ if not isinstance(self.llm_int8_threshold, float):
308
+ raise TypeError("llm_int8_threshold must be a float")
309
+
310
+ if self.llm_int8_skip_modules is not None and not isinstance(self.llm_int8_skip_modules, list):
311
+ raise TypeError("llm_int8_skip_modules must be a list of strings")
312
+ if not isinstance(self.llm_int8_enable_fp32_cpu_offload, bool):
313
+ raise TypeError("llm_int8_enable_fp32_cpu_offload must be a boolean")
314
+
315
+ if not isinstance(self.llm_int8_has_fp16_weight, bool):
316
+ raise TypeError("llm_int8_has_fp16_weight must be a boolean")
317
+
318
+ if self.bnb_4bit_compute_dtype is not None and not isinstance(self.bnb_4bit_compute_dtype, torch.dtype):
319
+ raise TypeError("bnb_4bit_compute_dtype must be torch.dtype")
320
+
321
+ if not isinstance(self.bnb_4bit_quant_type, str):
322
+ raise TypeError("bnb_4bit_quant_type must be a string")
323
+
324
+ if not isinstance(self.bnb_4bit_use_double_quant, bool):
325
+ raise TypeError("bnb_4bit_use_double_quant must be a boolean")
326
+
327
+ if self.load_in_4bit and not version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse(
328
+ "0.39.0"
329
+ ):
330
+ raise ValueError(
331
+ "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version"
332
+ )
333
+
334
+ def is_quantizable(self):
335
+ r"""
336
+ Returns `True` if the model is quantizable, `False` otherwise.
337
+ """
338
+ return self.load_in_8bit or self.load_in_4bit
339
+
340
+ def quantization_method(self):
341
+ r"""
342
+ This method returns the quantization method used for the model. If the model is not quantizable, it returns
343
+ `None`.
344
+ """
345
+ if self.load_in_8bit:
346
+ return "llm_int8"
347
+ elif self.load_in_4bit and self.bnb_4bit_quant_type == "fp4":
348
+ return "fp4"
349
+ elif self.load_in_4bit and self.bnb_4bit_quant_type == "nf4":
350
+ return "nf4"
351
+ else:
352
+ return None
353
+
354
+ def to_dict(self) -> Dict[str, Any]:
355
+ """
356
+ Serializes this instance to a Python dictionary. Returns:
357
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
358
+ """
359
+ output = copy.deepcopy(self.__dict__)
360
+ output["bnb_4bit_compute_dtype"] = str(output["bnb_4bit_compute_dtype"]).split(".")[1]
361
+ output["bnb_4bit_quant_storage"] = str(output["bnb_4bit_quant_storage"]).split(".")[1]
362
+ output["load_in_4bit"] = self.load_in_4bit
363
+ output["load_in_8bit"] = self.load_in_8bit
364
+
365
+ return output
366
+
367
+ def __repr__(self):
368
+ config_dict = self.to_dict()
369
+ return f"{self.__class__.__name__} {json.dumps(config_dict, indent=2, sort_keys=True)}\n"
370
+
371
+ def to_diff_dict(self) -> Dict[str, Any]:
372
+ """
373
+ Removes all attributes from config which correspond to the default config attributes for better readability and
374
+ serializes to a Python dictionary.
375
+
376
+ Returns:
377
+ `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,
378
+ """
379
+ config_dict = self.to_dict()
380
+
381
+ # get the default config dict
382
+ default_config_dict = BitsAndBytesConfig().to_dict()
383
+
384
+ serializable_config_dict = {}
385
+
386
+ # only serialize values that differ from the default config
387
+ for key, value in config_dict.items():
388
+ if value != default_config_dict[key]:
389
+ serializable_config_dict[key] = value
390
+
391
+ return serializable_config_dict
@@ -463,7 +463,10 @@ class DDIMScheduler(SchedulerMixin, ConfigMixin):
463
463
  prev_sample = prev_sample + variance
464
464
 
465
465
  if not return_dict:
466
- return (prev_sample,)
466
+ return (
467
+ prev_sample,
468
+ pred_original_sample,
469
+ )
467
470
 
468
471
  return DDIMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
469
472
 
@@ -394,7 +394,10 @@ class CogVideoXDDIMScheduler(SchedulerMixin, ConfigMixin):
394
394
  prev_sample = a_t * sample + b_t * pred_original_sample
395
395
 
396
396
  if not return_dict:
397
- return (prev_sample,)
397
+ return (
398
+ prev_sample,
399
+ pred_original_sample,
400
+ )
398
401
 
399
402
  return DDIMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
400
403
 
@@ -480,7 +480,10 @@ class DDIMParallelScheduler(SchedulerMixin, ConfigMixin):
480
480
  prev_sample = prev_sample + variance
481
481
 
482
482
  if not return_dict:
483
- return (prev_sample,)
483
+ return (
484
+ prev_sample,
485
+ pred_original_sample,
486
+ )
484
487
 
485
488
  return DDIMParallelSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
486
489
 
@@ -492,7 +492,10 @@ class DDPMScheduler(SchedulerMixin, ConfigMixin):
492
492
  pred_prev_sample = pred_prev_sample + variance
493
493
 
494
494
  if not return_dict:
495
- return (pred_prev_sample,)
495
+ return (
496
+ pred_prev_sample,
497
+ pred_original_sample,
498
+ )
496
499
 
497
500
  return DDPMSchedulerOutput(prev_sample=pred_prev_sample, pred_original_sample=pred_original_sample)
498
501
 
@@ -500,7 +500,10 @@ class DDPMParallelScheduler(SchedulerMixin, ConfigMixin):
500
500
  pred_prev_sample = pred_prev_sample + variance
501
501
 
502
502
  if not return_dict:
503
- return (pred_prev_sample,)
503
+ return (
504
+ pred_prev_sample,
505
+ pred_original_sample,
506
+ )
504
507
 
505
508
  return DDPMParallelSchedulerOutput(prev_sample=pred_prev_sample, pred_original_sample=pred_original_sample)
506
509
 
@@ -22,10 +22,14 @@ import numpy as np
22
22
  import torch
23
23
 
24
24
  from ..configuration_utils import ConfigMixin, register_to_config
25
- from ..utils import deprecate
25
+ from ..utils import deprecate, is_scipy_available
26
26
  from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
27
27
 
28
28
 
29
+ if is_scipy_available():
30
+ import scipy.stats
31
+
32
+
29
33
  # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
30
34
  def betas_for_alpha_bar(
31
35
  num_diffusion_timesteps,
@@ -111,6 +115,11 @@ class DEISMultistepScheduler(SchedulerMixin, ConfigMixin):
111
115
  use_karras_sigmas (`bool`, *optional*, defaults to `False`):
112
116
  Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
113
117
  the sigmas are determined according to a sequence of noise levels {σi}.
118
+ use_exponential_sigmas (`bool`, *optional*, defaults to `False`):
119
+ Whether to use exponential sigmas for step sizes in the noise schedule during the sampling process.
120
+ use_beta_sigmas (`bool`, *optional*, defaults to `False`):
121
+ Whether to use beta sigmas for step sizes in the noise schedule during the sampling process. Refer to [Beta
122
+ Sampling is All You Need](https://huggingface.co/papers/2407.12173) for more information.
114
123
  timestep_spacing (`str`, defaults to `"linspace"`):
115
124
  The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
116
125
  Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
@@ -138,9 +147,17 @@ class DEISMultistepScheduler(SchedulerMixin, ConfigMixin):
138
147
  solver_type: str = "logrho",
139
148
  lower_order_final: bool = True,
140
149
  use_karras_sigmas: Optional[bool] = False,
150
+ use_exponential_sigmas: Optional[bool] = False,
151
+ use_beta_sigmas: Optional[bool] = False,
141
152
  timestep_spacing: str = "linspace",
142
153
  steps_offset: int = 0,
143
154
  ):
155
+ if self.config.use_beta_sigmas and not is_scipy_available():
156
+ raise ImportError("Make sure to install scipy if you want to use beta sigmas.")
157
+ if sum([self.config.use_beta_sigmas, self.config.use_exponential_sigmas, self.config.use_karras_sigmas]) > 1:
158
+ raise ValueError(
159
+ "Only one of `config.use_beta_sigmas`, `config.use_exponential_sigmas`, `config.use_karras_sigmas` can be used."
160
+ )
144
161
  if trained_betas is not None:
145
162
  self.betas = torch.tensor(trained_betas, dtype=torch.float32)
146
163
  elif beta_schedule == "linear":
@@ -255,6 +272,12 @@ class DEISMultistepScheduler(SchedulerMixin, ConfigMixin):
255
272
  sigmas = self._convert_to_karras(in_sigmas=sigmas, num_inference_steps=num_inference_steps)
256
273
  timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas]).round()
257
274
  sigmas = np.concatenate([sigmas, sigmas[-1:]]).astype(np.float32)
275
+ elif self.config.use_exponential_sigmas:
276
+ sigmas = self._convert_to_exponential(in_sigmas=sigmas, num_inference_steps=self.num_inference_steps)
277
+ timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas])
278
+ elif self.config.use_beta_sigmas:
279
+ sigmas = self._convert_to_beta(in_sigmas=sigmas, num_inference_steps=self.num_inference_steps)
280
+ timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas])
258
281
  else:
259
282
  sigmas = np.interp(timesteps, np.arange(0, len(sigmas)), sigmas)
260
283
  sigma_last = ((1 - self.alphas_cumprod[0]) / self.alphas_cumprod[0]) ** 0.5
@@ -366,6 +389,60 @@ class DEISMultistepScheduler(SchedulerMixin, ConfigMixin):
366
389
  sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
367
390
  return sigmas
368
391
 
392
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_exponential
393
+ def _convert_to_exponential(self, in_sigmas: torch.Tensor, num_inference_steps: int) -> torch.Tensor:
394
+ """Constructs an exponential noise schedule."""
395
+
396
+ # Hack to make sure that other schedulers which copy this function don't break
397
+ # TODO: Add this logic to the other schedulers
398
+ if hasattr(self.config, "sigma_min"):
399
+ sigma_min = self.config.sigma_min
400
+ else:
401
+ sigma_min = None
402
+
403
+ if hasattr(self.config, "sigma_max"):
404
+ sigma_max = self.config.sigma_max
405
+ else:
406
+ sigma_max = None
407
+
408
+ sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()
409
+ sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()
410
+
411
+ sigmas = torch.linspace(math.log(sigma_max), math.log(sigma_min), num_inference_steps).exp()
412
+ return sigmas
413
+
414
+ # Copied from diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler._convert_to_beta
415
+ def _convert_to_beta(
416
+ self, in_sigmas: torch.Tensor, num_inference_steps: int, alpha: float = 0.6, beta: float = 0.6
417
+ ) -> torch.Tensor:
418
+ """From "Beta Sampling is All You Need" [arXiv:2407.12173] (Lee et. al, 2024)"""
419
+
420
+ # Hack to make sure that other schedulers which copy this function don't break
421
+ # TODO: Add this logic to the other schedulers
422
+ if hasattr(self.config, "sigma_min"):
423
+ sigma_min = self.config.sigma_min
424
+ else:
425
+ sigma_min = None
426
+
427
+ if hasattr(self.config, "sigma_max"):
428
+ sigma_max = self.config.sigma_max
429
+ else:
430
+ sigma_max = None
431
+
432
+ sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()
433
+ sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()
434
+
435
+ sigmas = torch.Tensor(
436
+ [
437
+ sigma_min + (ppf * (sigma_max - sigma_min))
438
+ for ppf in [
439
+ scipy.stats.beta.ppf(timestep, alpha, beta)
440
+ for timestep in 1 - np.linspace(0, 1, num_inference_steps)
441
+ ]
442
+ ]
443
+ )
444
+ return sigmas
445
+
369
446
  def convert_model_output(
370
447
  self,
371
448
  model_output: torch.Tensor,