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,558 @@
1
+ # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """
15
+ Adapted from
16
+ https://github.com/huggingface/transformers/blob/c409cd81777fb27aadc043ed3d8339dbc020fb3b/src/transformers/quantizers/quantizer_bnb_4bit.py
17
+ """
18
+
19
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
20
+
21
+ from ...utils import get_module_from_name
22
+ from ..base import DiffusersQuantizer
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ from ...models.modeling_utils import ModelMixin
27
+
28
+ from ...utils import (
29
+ is_accelerate_available,
30
+ is_accelerate_version,
31
+ is_bitsandbytes_available,
32
+ is_bitsandbytes_version,
33
+ is_torch_available,
34
+ logging,
35
+ )
36
+
37
+
38
+ if is_torch_available():
39
+ import torch
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+
44
+ class BnB4BitDiffusersQuantizer(DiffusersQuantizer):
45
+ """
46
+ 4-bit quantization from bitsandbytes.py quantization method:
47
+ before loading: converts transformer layers into Linear4bit during loading: load 16bit weight and pass to the
48
+ layer object after: quantizes individual weights in Linear4bit into 4bit at the first .cuda() call saving:
49
+ from state dict, as usual; saves weights and `quant_state` components
50
+ loading:
51
+ need to locate `quant_state` components and pass to Param4bit constructor
52
+ """
53
+
54
+ use_keep_in_fp32_modules = True
55
+ requires_calibration = False
56
+
57
+ def __init__(self, quantization_config, **kwargs):
58
+ super().__init__(quantization_config, **kwargs)
59
+
60
+ if self.quantization_config.llm_int8_skip_modules is not None:
61
+ self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
62
+
63
+ def validate_environment(self, *args, **kwargs):
64
+ if not torch.cuda.is_available():
65
+ raise RuntimeError("No GPU found. A GPU is needed for quantization.")
66
+ if not is_accelerate_available() or is_accelerate_version("<", "0.26.0"):
67
+ raise ImportError(
68
+ "Using `bitsandbytes` 4-bit quantization requires Accelerate: `pip install 'accelerate>=0.26.0'`"
69
+ )
70
+ if not is_bitsandbytes_available() or is_bitsandbytes_version("<", "0.43.3"):
71
+ raise ImportError(
72
+ "Using `bitsandbytes` 4-bit quantization requires the latest version of bitsandbytes: `pip install -U bitsandbytes`"
73
+ )
74
+
75
+ if kwargs.get("from_flax", False):
76
+ raise ValueError(
77
+ "Converting into 4-bit weights from flax weights is currently not supported, please make"
78
+ " sure the weights are in PyTorch format."
79
+ )
80
+
81
+ device_map = kwargs.get("device_map", None)
82
+ if (
83
+ device_map is not None
84
+ and isinstance(device_map, dict)
85
+ and not self.quantization_config.llm_int8_enable_fp32_cpu_offload
86
+ ):
87
+ device_map_without_no_convert = {
88
+ key: device_map[key] for key in device_map.keys() if key not in self.modules_to_not_convert
89
+ }
90
+ if "cpu" in device_map_without_no_convert.values() or "disk" in device_map_without_no_convert.values():
91
+ raise ValueError(
92
+ "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the "
93
+ "quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules "
94
+ "in 32-bit, you need to set `load_in_8bit_fp32_cpu_offload=True` and pass a custom `device_map` to "
95
+ "`from_pretrained`. Check "
96
+ "https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu "
97
+ "for more details. "
98
+ )
99
+
100
+ def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
101
+ if target_dtype != torch.int8:
102
+ from accelerate.utils import CustomDtype
103
+
104
+ logger.info("target_dtype {target_dtype} is replaced by `CustomDtype.INT4` for 4-bit BnB quantization")
105
+ return CustomDtype.INT4
106
+ else:
107
+ raise ValueError(f"Wrong `target_dtype` ({target_dtype}) provided.")
108
+
109
+ def check_if_quantized_param(
110
+ self,
111
+ model: "ModelMixin",
112
+ param_value: "torch.Tensor",
113
+ param_name: str,
114
+ state_dict: Dict[str, Any],
115
+ **kwargs,
116
+ ) -> bool:
117
+ import bitsandbytes as bnb
118
+
119
+ module, tensor_name = get_module_from_name(model, param_name)
120
+ if isinstance(module._parameters.get(tensor_name, None), bnb.nn.Params4bit):
121
+ # Add here check for loaded components' dtypes once serialization is implemented
122
+ return True
123
+ elif isinstance(module, bnb.nn.Linear4bit) and tensor_name == "bias":
124
+ # bias could be loaded by regular set_module_tensor_to_device() from accelerate,
125
+ # but it would wrongly use uninitialized weight there.
126
+ return True
127
+ else:
128
+ return False
129
+
130
+ def create_quantized_param(
131
+ self,
132
+ model: "ModelMixin",
133
+ param_value: "torch.Tensor",
134
+ param_name: str,
135
+ target_device: "torch.device",
136
+ state_dict: Dict[str, Any],
137
+ unexpected_keys: Optional[List[str]] = None,
138
+ ):
139
+ import bitsandbytes as bnb
140
+
141
+ module, tensor_name = get_module_from_name(model, param_name)
142
+
143
+ if tensor_name not in module._parameters:
144
+ raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
145
+
146
+ old_value = getattr(module, tensor_name)
147
+
148
+ if tensor_name == "bias":
149
+ if param_value is None:
150
+ new_value = old_value.to(target_device)
151
+ else:
152
+ new_value = param_value.to(target_device)
153
+
154
+ new_value = torch.nn.Parameter(new_value, requires_grad=old_value.requires_grad)
155
+ module._parameters[tensor_name] = new_value
156
+ return
157
+
158
+ if not isinstance(module._parameters[tensor_name], bnb.nn.Params4bit):
159
+ raise ValueError("this function only loads `Linear4bit components`")
160
+ if (
161
+ old_value.device == torch.device("meta")
162
+ and target_device not in ["meta", torch.device("meta")]
163
+ and param_value is None
164
+ ):
165
+ raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {target_device}.")
166
+
167
+ # construct `new_value` for the module._parameters[tensor_name]:
168
+ if self.pre_quantized:
169
+ # 4bit loading. Collecting components for restoring quantized weight
170
+ # This can be expanded to make a universal call for any quantized weight loading
171
+
172
+ if not self.is_serializable:
173
+ raise ValueError(
174
+ "Detected int4 weights but the version of bitsandbytes is not compatible with int4 serialization. "
175
+ "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
176
+ )
177
+
178
+ if (param_name + ".quant_state.bitsandbytes__fp4" not in state_dict) and (
179
+ param_name + ".quant_state.bitsandbytes__nf4" not in state_dict
180
+ ):
181
+ raise ValueError(
182
+ f"Supplied state dict for {param_name} does not contain `bitsandbytes__*` and possibly other `quantized_stats` components."
183
+ )
184
+
185
+ quantized_stats = {}
186
+ for k, v in state_dict.items():
187
+ # `startswith` to counter for edge cases where `param_name`
188
+ # substring can be present in multiple places in the `state_dict`
189
+ if param_name + "." in k and k.startswith(param_name):
190
+ quantized_stats[k] = v
191
+ if unexpected_keys is not None and k in unexpected_keys:
192
+ unexpected_keys.remove(k)
193
+
194
+ new_value = bnb.nn.Params4bit.from_prequantized(
195
+ data=param_value,
196
+ quantized_stats=quantized_stats,
197
+ requires_grad=False,
198
+ device=target_device,
199
+ )
200
+ else:
201
+ new_value = param_value.to("cpu")
202
+ kwargs = old_value.__dict__
203
+ new_value = bnb.nn.Params4bit(new_value, requires_grad=False, **kwargs).to(target_device)
204
+
205
+ module._parameters[tensor_name] = new_value
206
+
207
+ def check_quantized_param_shape(self, param_name, current_param_shape, loaded_param_shape):
208
+ n = current_param_shape.numel()
209
+ inferred_shape = (n,) if "bias" in param_name else ((n + 1) // 2, 1)
210
+ if loaded_param_shape != inferred_shape:
211
+ raise ValueError(
212
+ f"Expected the flattened shape of the current param ({param_name}) to be {loaded_param_shape} but is {inferred_shape}."
213
+ )
214
+ else:
215
+ return True
216
+
217
+ def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
218
+ # need more space for buffers that are created during quantization
219
+ max_memory = {key: val * 0.90 for key, val in max_memory.items()}
220
+ return max_memory
221
+
222
+ def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
223
+ if torch_dtype is None:
224
+ # We force the `dtype` to be float16, this is a requirement from `bitsandbytes`
225
+ logger.info(
226
+ "Overriding torch_dtype=%s with `torch_dtype=torch.float16` due to "
227
+ "requirements of `bitsandbytes` to enable model loading in 8-bit or 4-bit. "
228
+ "Pass your own torch_dtype to specify the dtype of the remaining non-linear layers or pass"
229
+ " torch_dtype=torch.float16 to remove this warning.",
230
+ torch_dtype,
231
+ )
232
+ torch_dtype = torch.float16
233
+ return torch_dtype
234
+
235
+ # (sayakpaul): I think it could be better to disable custom `device_map`s
236
+ # for the first phase of the integration in the interest of simplicity.
237
+ # Commenting this for discussions on the PR.
238
+ # def update_device_map(self, device_map):
239
+ # if device_map is None:
240
+ # device_map = {"": torch.cuda.current_device()}
241
+ # logger.info(
242
+ # "The device_map was not initialized. "
243
+ # "Setting device_map to {'':torch.cuda.current_device()}. "
244
+ # "If you want to use the model for inference, please set device_map ='auto' "
245
+ # )
246
+ # return device_map
247
+
248
+ def _process_model_before_weight_loading(
249
+ self,
250
+ model: "ModelMixin",
251
+ device_map,
252
+ keep_in_fp32_modules: List[str] = [],
253
+ **kwargs,
254
+ ):
255
+ from .utils import replace_with_bnb_linear
256
+
257
+ load_in_8bit_fp32_cpu_offload = self.quantization_config.llm_int8_enable_fp32_cpu_offload
258
+
259
+ # We may keep some modules such as the `proj_out` in their original dtype for numerical stability reasons
260
+ self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
261
+
262
+ if not isinstance(self.modules_to_not_convert, list):
263
+ self.modules_to_not_convert = [self.modules_to_not_convert]
264
+
265
+ self.modules_to_not_convert.extend(keep_in_fp32_modules)
266
+
267
+ # Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk`
268
+ if isinstance(device_map, dict) and len(device_map.keys()) > 1:
269
+ keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
270
+
271
+ if len(keys_on_cpu) > 0 and not load_in_8bit_fp32_cpu_offload:
272
+ raise ValueError(
273
+ "If you want to offload some keys to `cpu` or `disk`, you need to set "
274
+ "`llm_int8_enable_fp32_cpu_offload=True`. Note that these modules will not be "
275
+ " converted to 8-bit but kept in 32-bit."
276
+ )
277
+ self.modules_to_not_convert.extend(keys_on_cpu)
278
+
279
+ # Purge `None`.
280
+ # Unlike `transformers`, we don't know if we should always keep certain modules in FP32
281
+ # in case of diffusion transformer models. For language models and others alike, `lm_head`
282
+ # and tied modules are usually kept in FP32.
283
+ self.modules_to_not_convert = [module for module in self.modules_to_not_convert if module is not None]
284
+
285
+ model = replace_with_bnb_linear(
286
+ model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
287
+ )
288
+ model.config.quantization_config = self.quantization_config
289
+
290
+ def _process_model_after_weight_loading(self, model: "ModelMixin", **kwargs):
291
+ model.is_loaded_in_4bit = True
292
+ model.is_4bit_serializable = self.is_serializable
293
+ return model
294
+
295
+ @property
296
+ def is_serializable(self):
297
+ # Because we're mandating `bitsandbytes` 0.43.3.
298
+ return True
299
+
300
+ @property
301
+ def is_trainable(self) -> bool:
302
+ # Because we're mandating `bitsandbytes` 0.43.3.
303
+ return True
304
+
305
+ def _dequantize(self, model):
306
+ from .utils import dequantize_and_replace
307
+
308
+ is_model_on_cpu = model.device.type == "cpu"
309
+ if is_model_on_cpu:
310
+ logger.info(
311
+ "Model was found to be on CPU (could happen as a result of `enable_model_cpu_offload()`). So, moving it to GPU. After dequantization, will move the model back to CPU again to preserve the previous device."
312
+ )
313
+ model.to(torch.cuda.current_device())
314
+
315
+ model = dequantize_and_replace(
316
+ model, self.modules_to_not_convert, quantization_config=self.quantization_config
317
+ )
318
+ if is_model_on_cpu:
319
+ model.to("cpu")
320
+ return model
321
+
322
+
323
+ class BnB8BitDiffusersQuantizer(DiffusersQuantizer):
324
+ """
325
+ 8-bit quantization from bitsandbytes quantization method:
326
+ before loading: converts transformer layers into Linear8bitLt during loading: load 16bit weight and pass to the
327
+ layer object after: quantizes individual weights in Linear8bitLt into 8bit at fitst .cuda() call
328
+ saving:
329
+ from state dict, as usual; saves weights and 'SCB' component
330
+ loading:
331
+ need to locate SCB component and pass to the Linear8bitLt object
332
+ """
333
+
334
+ use_keep_in_fp32_modules = True
335
+ requires_calibration = False
336
+
337
+ def __init__(self, quantization_config, **kwargs):
338
+ super().__init__(quantization_config, **kwargs)
339
+
340
+ if self.quantization_config.llm_int8_skip_modules is not None:
341
+ self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
342
+
343
+ def validate_environment(self, *args, **kwargs):
344
+ if not torch.cuda.is_available():
345
+ raise RuntimeError("No GPU found. A GPU is needed for quantization.")
346
+ if not is_accelerate_available() or is_accelerate_version("<", "0.26.0"):
347
+ raise ImportError(
348
+ "Using `bitsandbytes` 8-bit quantization requires Accelerate: `pip install 'accelerate>=0.26.0'`"
349
+ )
350
+ if not is_bitsandbytes_available() or is_bitsandbytes_version("<", "0.43.3"):
351
+ raise ImportError(
352
+ "Using `bitsandbytes` 8-bit quantization requires the latest version of bitsandbytes: `pip install -U bitsandbytes`"
353
+ )
354
+
355
+ if kwargs.get("from_flax", False):
356
+ raise ValueError(
357
+ "Converting into 8-bit weights from flax weights is currently not supported, please make"
358
+ " sure the weights are in PyTorch format."
359
+ )
360
+
361
+ device_map = kwargs.get("device_map", None)
362
+ if (
363
+ device_map is not None
364
+ and isinstance(device_map, dict)
365
+ and not self.quantization_config.llm_int8_enable_fp32_cpu_offload
366
+ ):
367
+ device_map_without_no_convert = {
368
+ key: device_map[key] for key in device_map.keys() if key not in self.modules_to_not_convert
369
+ }
370
+ if "cpu" in device_map_without_no_convert.values() or "disk" in device_map_without_no_convert.values():
371
+ raise ValueError(
372
+ "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the "
373
+ "quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules "
374
+ "in 32-bit, you need to set `load_in_8bit_fp32_cpu_offload=True` and pass a custom `device_map` to "
375
+ "`from_pretrained`. Check "
376
+ "https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu "
377
+ "for more details. "
378
+ )
379
+
380
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.adjust_max_memory
381
+ def adjust_max_memory(self, max_memory: Dict[str, Union[int, str]]) -> Dict[str, Union[int, str]]:
382
+ # need more space for buffers that are created during quantization
383
+ max_memory = {key: val * 0.90 for key, val in max_memory.items()}
384
+ return max_memory
385
+
386
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.update_torch_dtype
387
+ def update_torch_dtype(self, torch_dtype: "torch.dtype") -> "torch.dtype":
388
+ if torch_dtype is None:
389
+ # We force the `dtype` to be float16, this is a requirement from `bitsandbytes`
390
+ logger.info(
391
+ "Overriding torch_dtype=%s with `torch_dtype=torch.float16` due to "
392
+ "requirements of `bitsandbytes` to enable model loading in 8-bit or 4-bit. "
393
+ "Pass your own torch_dtype to specify the dtype of the remaining non-linear layers or pass"
394
+ " torch_dtype=torch.float16 to remove this warning.",
395
+ torch_dtype,
396
+ )
397
+ torch_dtype = torch.float16
398
+ return torch_dtype
399
+
400
+ # # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.update_device_map
401
+ # def update_device_map(self, device_map):
402
+ # if device_map is None:
403
+ # device_map = {"": torch.cuda.current_device()}
404
+ # logger.info(
405
+ # "The device_map was not initialized. "
406
+ # "Setting device_map to {'':torch.cuda.current_device()}. "
407
+ # "If you want to use the model for inference, please set device_map ='auto' "
408
+ # )
409
+ # return device_map
410
+
411
+ def adjust_target_dtype(self, target_dtype: "torch.dtype") -> "torch.dtype":
412
+ if target_dtype != torch.int8:
413
+ logger.info("target_dtype {target_dtype} is replaced by `torch.int8` for 8-bit BnB quantization")
414
+ return torch.int8
415
+
416
+ def check_if_quantized_param(
417
+ self,
418
+ model: "ModelMixin",
419
+ param_value: "torch.Tensor",
420
+ param_name: str,
421
+ state_dict: Dict[str, Any],
422
+ **kwargs,
423
+ ):
424
+ import bitsandbytes as bnb
425
+
426
+ module, tensor_name = get_module_from_name(model, param_name)
427
+ if isinstance(module._parameters.get(tensor_name, None), bnb.nn.Int8Params):
428
+ if self.pre_quantized:
429
+ if param_name.replace("weight", "SCB") not in state_dict.keys():
430
+ raise ValueError("Missing quantization component `SCB`")
431
+ if param_value.dtype != torch.int8:
432
+ raise ValueError(
433
+ f"Incompatible dtype `{param_value.dtype}` when loading 8-bit prequantized weight. Expected `torch.int8`."
434
+ )
435
+ return True
436
+ return False
437
+
438
+ def create_quantized_param(
439
+ self,
440
+ model: "ModelMixin",
441
+ param_value: "torch.Tensor",
442
+ param_name: str,
443
+ target_device: "torch.device",
444
+ state_dict: Dict[str, Any],
445
+ unexpected_keys: Optional[List[str]] = None,
446
+ ):
447
+ import bitsandbytes as bnb
448
+
449
+ fp16_statistics_key = param_name.replace("weight", "SCB")
450
+ fp16_weights_format_key = param_name.replace("weight", "weight_format")
451
+
452
+ fp16_statistics = state_dict.get(fp16_statistics_key, None)
453
+ fp16_weights_format = state_dict.get(fp16_weights_format_key, None)
454
+
455
+ module, tensor_name = get_module_from_name(model, param_name)
456
+ if tensor_name not in module._parameters:
457
+ raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.")
458
+
459
+ old_value = getattr(module, tensor_name)
460
+
461
+ if not isinstance(module._parameters[tensor_name], bnb.nn.Int8Params):
462
+ raise ValueError(f"Parameter `{tensor_name}` should only be a `bnb.nn.Int8Params` instance.")
463
+ if (
464
+ old_value.device == torch.device("meta")
465
+ and target_device not in ["meta", torch.device("meta")]
466
+ and param_value is None
467
+ ):
468
+ raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {target_device}.")
469
+
470
+ new_value = param_value.to("cpu")
471
+ if self.pre_quantized and not self.is_serializable:
472
+ raise ValueError(
473
+ "Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. "
474
+ "Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`."
475
+ )
476
+
477
+ kwargs = old_value.__dict__
478
+ new_value = bnb.nn.Int8Params(new_value, requires_grad=False, **kwargs).to(target_device)
479
+
480
+ module._parameters[tensor_name] = new_value
481
+ if fp16_statistics is not None:
482
+ setattr(module.weight, "SCB", fp16_statistics.to(target_device))
483
+ if unexpected_keys is not None:
484
+ unexpected_keys.remove(fp16_statistics_key)
485
+
486
+ # We just need to pop the `weight_format` keys from the state dict to remove unneeded
487
+ # messages. The correct format is correctly retrieved during the first forward pass.
488
+ if fp16_weights_format is not None and unexpected_keys is not None:
489
+ unexpected_keys.remove(fp16_weights_format_key)
490
+
491
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer._process_model_after_weight_loading with 4bit->8bit
492
+ def _process_model_after_weight_loading(self, model: "ModelMixin", **kwargs):
493
+ model.is_loaded_in_8bit = True
494
+ model.is_8bit_serializable = self.is_serializable
495
+ return model
496
+
497
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer._process_model_before_weight_loading
498
+ def _process_model_before_weight_loading(
499
+ self,
500
+ model: "ModelMixin",
501
+ device_map,
502
+ keep_in_fp32_modules: List[str] = [],
503
+ **kwargs,
504
+ ):
505
+ from .utils import replace_with_bnb_linear
506
+
507
+ load_in_8bit_fp32_cpu_offload = self.quantization_config.llm_int8_enable_fp32_cpu_offload
508
+
509
+ # We may keep some modules such as the `proj_out` in their original dtype for numerical stability reasons
510
+ self.modules_to_not_convert = self.quantization_config.llm_int8_skip_modules
511
+
512
+ if not isinstance(self.modules_to_not_convert, list):
513
+ self.modules_to_not_convert = [self.modules_to_not_convert]
514
+
515
+ self.modules_to_not_convert.extend(keep_in_fp32_modules)
516
+
517
+ # Extend `self.modules_to_not_convert` to keys that are supposed to be offloaded to `cpu` or `disk`
518
+ if isinstance(device_map, dict) and len(device_map.keys()) > 1:
519
+ keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
520
+
521
+ if len(keys_on_cpu) > 0 and not load_in_8bit_fp32_cpu_offload:
522
+ raise ValueError(
523
+ "If you want to offload some keys to `cpu` or `disk`, you need to set "
524
+ "`llm_int8_enable_fp32_cpu_offload=True`. Note that these modules will not be "
525
+ " converted to 8-bit but kept in 32-bit."
526
+ )
527
+ self.modules_to_not_convert.extend(keys_on_cpu)
528
+
529
+ # Purge `None`.
530
+ # Unlike `transformers`, we don't know if we should always keep certain modules in FP32
531
+ # in case of diffusion transformer models. For language models and others alike, `lm_head`
532
+ # and tied modules are usually kept in FP32.
533
+ self.modules_to_not_convert = [module for module in self.modules_to_not_convert if module is not None]
534
+
535
+ model = replace_with_bnb_linear(
536
+ model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
537
+ )
538
+ model.config.quantization_config = self.quantization_config
539
+
540
+ @property
541
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.is_serializable
542
+ def is_serializable(self):
543
+ # Because we're mandating `bitsandbytes` 0.43.3.
544
+ return True
545
+
546
+ @property
547
+ # Copied from diffusers.quantizers.bitsandbytes.bnb_quantizer.BnB4BitDiffusersQuantizer.is_serializable
548
+ def is_trainable(self) -> bool:
549
+ # Because we're mandating `bitsandbytes` 0.43.3.
550
+ return True
551
+
552
+ def _dequantize(self, model):
553
+ from .utils import dequantize_and_replace
554
+
555
+ model = dequantize_and_replace(
556
+ model, self.modules_to_not_convert, quantization_config=self.quantization_config
557
+ )
558
+ return model