diffusers 0.30.3__py3-none-any.whl → 0.32.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 (268) hide show
  1. diffusers/__init__.py +97 -4
  2. diffusers/callbacks.py +56 -3
  3. diffusers/configuration_utils.py +13 -1
  4. diffusers/image_processor.py +282 -71
  5. diffusers/loaders/__init__.py +24 -3
  6. diffusers/loaders/ip_adapter.py +543 -16
  7. diffusers/loaders/lora_base.py +138 -125
  8. diffusers/loaders/lora_conversion_utils.py +647 -0
  9. diffusers/loaders/lora_pipeline.py +2216 -230
  10. diffusers/loaders/peft.py +380 -0
  11. diffusers/loaders/single_file_model.py +71 -4
  12. diffusers/loaders/single_file_utils.py +597 -10
  13. diffusers/loaders/textual_inversion.py +5 -3
  14. diffusers/loaders/transformer_flux.py +181 -0
  15. diffusers/loaders/transformer_sd3.py +89 -0
  16. diffusers/loaders/unet.py +56 -12
  17. diffusers/models/__init__.py +49 -12
  18. diffusers/models/activations.py +22 -9
  19. diffusers/models/adapter.py +53 -53
  20. diffusers/models/attention.py +98 -13
  21. diffusers/models/attention_flax.py +1 -1
  22. diffusers/models/attention_processor.py +2160 -346
  23. diffusers/models/autoencoders/__init__.py +5 -0
  24. diffusers/models/autoencoders/autoencoder_dc.py +620 -0
  25. diffusers/models/autoencoders/autoencoder_kl.py +73 -12
  26. diffusers/models/autoencoders/autoencoder_kl_allegro.py +1149 -0
  27. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +213 -105
  28. diffusers/models/autoencoders/autoencoder_kl_hunyuan_video.py +1176 -0
  29. diffusers/models/autoencoders/autoencoder_kl_ltx.py +1338 -0
  30. diffusers/models/autoencoders/autoencoder_kl_mochi.py +1166 -0
  31. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +3 -10
  32. diffusers/models/autoencoders/autoencoder_tiny.py +4 -2
  33. diffusers/models/autoencoders/vae.py +18 -5
  34. diffusers/models/controlnet.py +47 -802
  35. diffusers/models/controlnet_flux.py +70 -0
  36. diffusers/models/controlnet_sd3.py +26 -376
  37. diffusers/models/controlnet_sparsectrl.py +46 -719
  38. diffusers/models/controlnets/__init__.py +23 -0
  39. diffusers/models/controlnets/controlnet.py +872 -0
  40. diffusers/models/{controlnet_flax.py → controlnets/controlnet_flax.py} +5 -5
  41. diffusers/models/controlnets/controlnet_flux.py +536 -0
  42. diffusers/models/{controlnet_hunyuan.py → controlnets/controlnet_hunyuan.py} +7 -7
  43. diffusers/models/controlnets/controlnet_sd3.py +489 -0
  44. diffusers/models/controlnets/controlnet_sparsectrl.py +788 -0
  45. diffusers/models/controlnets/controlnet_union.py +832 -0
  46. diffusers/models/{controlnet_xs.py → controlnets/controlnet_xs.py} +14 -13
  47. diffusers/models/controlnets/multicontrolnet.py +183 -0
  48. diffusers/models/embeddings.py +996 -92
  49. diffusers/models/embeddings_flax.py +23 -9
  50. diffusers/models/model_loading_utils.py +264 -14
  51. diffusers/models/modeling_flax_utils.py +1 -1
  52. diffusers/models/modeling_utils.py +334 -51
  53. diffusers/models/normalization.py +157 -13
  54. diffusers/models/transformers/__init__.py +6 -0
  55. diffusers/models/transformers/auraflow_transformer_2d.py +3 -2
  56. diffusers/models/transformers/cogvideox_transformer_3d.py +69 -13
  57. diffusers/models/transformers/dit_transformer_2d.py +1 -1
  58. diffusers/models/transformers/latte_transformer_3d.py +4 -4
  59. diffusers/models/transformers/pixart_transformer_2d.py +10 -2
  60. diffusers/models/transformers/sana_transformer.py +488 -0
  61. diffusers/models/transformers/stable_audio_transformer.py +1 -1
  62. diffusers/models/transformers/transformer_2d.py +1 -1
  63. diffusers/models/transformers/transformer_allegro.py +422 -0
  64. diffusers/models/transformers/transformer_cogview3plus.py +386 -0
  65. diffusers/models/transformers/transformer_flux.py +189 -51
  66. diffusers/models/transformers/transformer_hunyuan_video.py +789 -0
  67. diffusers/models/transformers/transformer_ltx.py +469 -0
  68. diffusers/models/transformers/transformer_mochi.py +499 -0
  69. diffusers/models/transformers/transformer_sd3.py +112 -18
  70. diffusers/models/transformers/transformer_temporal.py +1 -1
  71. diffusers/models/unets/unet_1d_blocks.py +1 -1
  72. diffusers/models/unets/unet_2d.py +8 -1
  73. diffusers/models/unets/unet_2d_blocks.py +88 -21
  74. diffusers/models/unets/unet_2d_condition.py +9 -9
  75. diffusers/models/unets/unet_3d_blocks.py +9 -7
  76. diffusers/models/unets/unet_motion_model.py +46 -68
  77. diffusers/models/unets/unet_spatio_temporal_condition.py +23 -0
  78. diffusers/models/unets/unet_stable_cascade.py +2 -2
  79. diffusers/models/unets/uvit_2d.py +1 -1
  80. diffusers/models/upsampling.py +14 -6
  81. diffusers/pipelines/__init__.py +69 -6
  82. diffusers/pipelines/allegro/__init__.py +48 -0
  83. diffusers/pipelines/allegro/pipeline_allegro.py +938 -0
  84. diffusers/pipelines/allegro/pipeline_output.py +23 -0
  85. diffusers/pipelines/animatediff/__init__.py +2 -0
  86. diffusers/pipelines/animatediff/pipeline_animatediff.py +45 -21
  87. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +52 -22
  88. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +18 -4
  89. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +3 -1
  90. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +104 -72
  91. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +1341 -0
  92. diffusers/pipelines/audioldm2/modeling_audioldm2.py +3 -3
  93. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +2 -9
  94. diffusers/pipelines/auto_pipeline.py +88 -10
  95. diffusers/pipelines/blip_diffusion/modeling_blip2.py +1 -1
  96. diffusers/pipelines/cogvideo/__init__.py +2 -0
  97. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +80 -39
  98. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +825 -0
  99. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +108 -50
  100. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +89 -50
  101. diffusers/pipelines/cogview3/__init__.py +47 -0
  102. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +674 -0
  103. diffusers/pipelines/cogview3/pipeline_output.py +21 -0
  104. diffusers/pipelines/controlnet/__init__.py +86 -80
  105. diffusers/pipelines/controlnet/multicontrolnet.py +7 -178
  106. diffusers/pipelines/controlnet/pipeline_controlnet.py +20 -3
  107. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +9 -2
  108. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +9 -2
  109. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +37 -15
  110. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +12 -4
  111. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +9 -4
  112. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +1790 -0
  113. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +1501 -0
  114. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +1627 -0
  115. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +22 -4
  116. diffusers/pipelines/controlnet_sd3/__init__.py +4 -0
  117. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +56 -20
  118. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +1153 -0
  119. diffusers/pipelines/ddpm/pipeline_ddpm.py +2 -2
  120. diffusers/pipelines/deepfloyd_if/pipeline_output.py +6 -5
  121. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +16 -4
  122. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +1 -1
  123. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +32 -9
  124. diffusers/pipelines/flux/__init__.py +23 -1
  125. diffusers/pipelines/flux/modeling_flux.py +47 -0
  126. diffusers/pipelines/flux/pipeline_flux.py +256 -48
  127. diffusers/pipelines/flux/pipeline_flux_control.py +889 -0
  128. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +945 -0
  129. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +1141 -0
  130. diffusers/pipelines/flux/pipeline_flux_controlnet.py +1006 -0
  131. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +998 -0
  132. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +1204 -0
  133. diffusers/pipelines/flux/pipeline_flux_fill.py +969 -0
  134. diffusers/pipelines/flux/pipeline_flux_img2img.py +856 -0
  135. diffusers/pipelines/flux/pipeline_flux_inpaint.py +1022 -0
  136. diffusers/pipelines/flux/pipeline_flux_prior_redux.py +492 -0
  137. diffusers/pipelines/flux/pipeline_output.py +16 -0
  138. diffusers/pipelines/free_noise_utils.py +365 -5
  139. diffusers/pipelines/hunyuan_video/__init__.py +48 -0
  140. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +687 -0
  141. diffusers/pipelines/hunyuan_video/pipeline_output.py +20 -0
  142. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +20 -4
  143. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +9 -9
  144. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +2 -2
  145. diffusers/pipelines/kolors/pipeline_kolors.py +1 -1
  146. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +14 -11
  147. diffusers/pipelines/kolors/text_encoder.py +2 -2
  148. diffusers/pipelines/kolors/tokenizer.py +4 -0
  149. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +1 -1
  150. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +1 -1
  151. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -1
  152. diffusers/pipelines/latte/pipeline_latte.py +2 -2
  153. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +15 -3
  154. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +15 -3
  155. diffusers/pipelines/ltx/__init__.py +50 -0
  156. diffusers/pipelines/ltx/pipeline_ltx.py +789 -0
  157. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +885 -0
  158. diffusers/pipelines/ltx/pipeline_output.py +20 -0
  159. diffusers/pipelines/lumina/pipeline_lumina.py +3 -10
  160. diffusers/pipelines/mochi/__init__.py +48 -0
  161. diffusers/pipelines/mochi/pipeline_mochi.py +748 -0
  162. diffusers/pipelines/mochi/pipeline_output.py +20 -0
  163. diffusers/pipelines/pag/__init__.py +13 -0
  164. diffusers/pipelines/pag/pag_utils.py +8 -2
  165. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +2 -3
  166. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1543 -0
  167. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +3 -5
  168. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1683 -0
  169. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +22 -6
  170. diffusers/pipelines/pag/pipeline_pag_kolors.py +1 -1
  171. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +7 -14
  172. diffusers/pipelines/pag/pipeline_pag_sana.py +886 -0
  173. diffusers/pipelines/pag/pipeline_pag_sd.py +18 -6
  174. diffusers/pipelines/pag/pipeline_pag_sd_3.py +18 -9
  175. diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +1058 -0
  176. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +5 -1
  177. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +1094 -0
  178. diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +1356 -0
  179. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +18 -6
  180. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +31 -16
  181. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +42 -19
  182. diffusers/pipelines/pia/pipeline_pia.py +2 -0
  183. diffusers/pipelines/pipeline_flax_utils.py +1 -1
  184. diffusers/pipelines/pipeline_loading_utils.py +250 -31
  185. diffusers/pipelines/pipeline_utils.py +158 -186
  186. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +7 -14
  187. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +7 -14
  188. diffusers/pipelines/sana/__init__.py +47 -0
  189. diffusers/pipelines/sana/pipeline_output.py +21 -0
  190. diffusers/pipelines/sana/pipeline_sana.py +884 -0
  191. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +12 -1
  192. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +35 -3
  193. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +2 -2
  194. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +46 -9
  195. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +1 -1
  196. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +1 -1
  197. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +241 -81
  198. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +228 -23
  199. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +82 -13
  200. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +60 -11
  201. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +11 -1
  202. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -1
  203. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +16 -4
  204. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +16 -4
  205. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +16 -12
  206. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +29 -22
  207. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +29 -22
  208. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +1 -1
  209. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +1 -1
  210. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +16 -4
  211. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +15 -3
  212. diffusers/pipelines/unidiffuser/modeling_uvit.py +2 -2
  213. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
  214. diffusers/quantizers/__init__.py +16 -0
  215. diffusers/quantizers/auto.py +139 -0
  216. diffusers/quantizers/base.py +233 -0
  217. diffusers/quantizers/bitsandbytes/__init__.py +2 -0
  218. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +561 -0
  219. diffusers/quantizers/bitsandbytes/utils.py +306 -0
  220. diffusers/quantizers/gguf/__init__.py +1 -0
  221. diffusers/quantizers/gguf/gguf_quantizer.py +159 -0
  222. diffusers/quantizers/gguf/utils.py +456 -0
  223. diffusers/quantizers/quantization_config.py +669 -0
  224. diffusers/quantizers/torchao/__init__.py +15 -0
  225. diffusers/quantizers/torchao/torchao_quantizer.py +285 -0
  226. diffusers/schedulers/scheduling_ddim.py +4 -1
  227. diffusers/schedulers/scheduling_ddim_cogvideox.py +4 -1
  228. diffusers/schedulers/scheduling_ddim_parallel.py +4 -1
  229. diffusers/schedulers/scheduling_ddpm.py +6 -7
  230. diffusers/schedulers/scheduling_ddpm_parallel.py +6 -7
  231. diffusers/schedulers/scheduling_deis_multistep.py +102 -6
  232. diffusers/schedulers/scheduling_dpmsolver_multistep.py +113 -6
  233. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +111 -5
  234. diffusers/schedulers/scheduling_dpmsolver_sde.py +125 -10
  235. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +126 -7
  236. diffusers/schedulers/scheduling_edm_euler.py +8 -6
  237. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +4 -1
  238. diffusers/schedulers/scheduling_euler_discrete.py +92 -7
  239. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +153 -6
  240. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +4 -5
  241. diffusers/schedulers/scheduling_heun_discrete.py +114 -8
  242. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +116 -11
  243. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +110 -8
  244. diffusers/schedulers/scheduling_lcm.py +2 -6
  245. diffusers/schedulers/scheduling_lms_discrete.py +76 -1
  246. diffusers/schedulers/scheduling_repaint.py +1 -1
  247. diffusers/schedulers/scheduling_sasolver.py +102 -6
  248. diffusers/schedulers/scheduling_tcd.py +2 -6
  249. diffusers/schedulers/scheduling_unclip.py +4 -1
  250. diffusers/schedulers/scheduling_unipc_multistep.py +127 -5
  251. diffusers/training_utils.py +63 -19
  252. diffusers/utils/__init__.py +7 -1
  253. diffusers/utils/constants.py +1 -0
  254. diffusers/utils/dummy_pt_objects.py +240 -0
  255. diffusers/utils/dummy_torch_and_transformers_objects.py +435 -0
  256. diffusers/utils/dynamic_modules_utils.py +3 -3
  257. diffusers/utils/hub_utils.py +44 -40
  258. diffusers/utils/import_utils.py +98 -8
  259. diffusers/utils/loading_utils.py +28 -4
  260. diffusers/utils/peft_utils.py +6 -3
  261. diffusers/utils/testing_utils.py +115 -1
  262. diffusers/utils/torch_utils.py +3 -0
  263. {diffusers-0.30.3.dist-info → diffusers-0.32.0.dist-info}/METADATA +73 -72
  264. {diffusers-0.30.3.dist-info → diffusers-0.32.0.dist-info}/RECORD +268 -193
  265. {diffusers-0.30.3.dist-info → diffusers-0.32.0.dist-info}/WHEEL +1 -1
  266. {diffusers-0.30.3.dist-info → diffusers-0.32.0.dist-info}/LICENSE +0 -0
  267. {diffusers-0.30.3.dist-info → diffusers-0.32.0.dist-info}/entry_points.txt +0 -0
  268. {diffusers-0.30.3.dist-info → diffusers-0.32.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,70 @@
1
+ # Copyright 2024 Black Forest Labs, The HuggingFace Team and The InstantX 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
+
16
+ from typing import List
17
+
18
+ from ..utils import deprecate, logging
19
+ from .controlnets.controlnet_flux import FluxControlNetModel, FluxControlNetOutput, FluxMultiControlNetModel
20
+
21
+
22
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
23
+
24
+
25
+ class FluxControlNetOutput(FluxControlNetOutput):
26
+ def __init__(self, *args, **kwargs):
27
+ deprecation_message = "Importing `FluxControlNetOutput` from `diffusers.models.controlnet_flux` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_flux import FluxControlNetOutput`, instead."
28
+ deprecate("diffusers.models.controlnet_flux.FluxControlNetOutput", "0.34", deprecation_message)
29
+ super().__init__(*args, **kwargs)
30
+
31
+
32
+ class FluxControlNetModel(FluxControlNetModel):
33
+ def __init__(
34
+ self,
35
+ patch_size: int = 1,
36
+ in_channels: int = 64,
37
+ num_layers: int = 19,
38
+ num_single_layers: int = 38,
39
+ attention_head_dim: int = 128,
40
+ num_attention_heads: int = 24,
41
+ joint_attention_dim: int = 4096,
42
+ pooled_projection_dim: int = 768,
43
+ guidance_embeds: bool = False,
44
+ axes_dims_rope: List[int] = [16, 56, 56],
45
+ num_mode: int = None,
46
+ conditioning_embedding_channels: int = None,
47
+ ):
48
+ deprecation_message = "Importing `FluxControlNetModel` from `diffusers.models.controlnet_flux` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_flux import FluxControlNetModel`, instead."
49
+ deprecate("diffusers.models.controlnet_flux.FluxControlNetModel", "0.34", deprecation_message)
50
+ super().__init__(
51
+ patch_size=patch_size,
52
+ in_channels=in_channels,
53
+ num_layers=num_layers,
54
+ num_single_layers=num_single_layers,
55
+ attention_head_dim=attention_head_dim,
56
+ num_attention_heads=num_attention_heads,
57
+ joint_attention_dim=joint_attention_dim,
58
+ pooled_projection_dim=pooled_projection_dim,
59
+ guidance_embeds=guidance_embeds,
60
+ axes_dims_rope=axes_dims_rope,
61
+ num_mode=num_mode,
62
+ conditioning_embedding_channels=conditioning_embedding_channels,
63
+ )
64
+
65
+
66
+ class FluxMultiControlNetModel(FluxMultiControlNetModel):
67
+ def __init__(self, *args, **kwargs):
68
+ deprecation_message = "Importing `FluxMultiControlNetModel` from `diffusers.models.controlnet_flux` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_flux import FluxMultiControlNetModel`, instead."
69
+ deprecate("diffusers.models.controlnet_flux.FluxMultiControlNetModel", "0.34", deprecation_message)
70
+ super().__init__(*args, **kwargs)
@@ -13,35 +13,21 @@
13
13
  # limitations under the License.
14
14
 
15
15
 
16
- from dataclasses import dataclass
17
- from typing import Any, Dict, List, Optional, Tuple, Union
18
-
19
- import torch
20
- import torch.nn as nn
21
-
22
- from ..configuration_utils import ConfigMixin, register_to_config
23
- from ..loaders import FromOriginalModelMixin, PeftAdapterMixin
24
- from ..models.attention import JointTransformerBlock
25
- from ..models.attention_processor import Attention, AttentionProcessor, FusedJointAttnProcessor2_0
26
- from ..models.modeling_outputs import Transformer2DModelOutput
27
- from ..models.modeling_utils import ModelMixin
28
- from ..utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
29
- from .controlnet import BaseOutput, zero_module
30
- from .embeddings import CombinedTimestepTextProjEmbeddings, PatchEmbed
16
+ from ..utils import deprecate, logging
17
+ from .controlnets.controlnet_sd3 import SD3ControlNetModel, SD3ControlNetOutput, SD3MultiControlNetModel
31
18
 
32
19
 
33
20
  logger = logging.get_logger(__name__) # pylint: disable=invalid-name
34
21
 
35
22
 
36
- @dataclass
37
- class SD3ControlNetOutput(BaseOutput):
38
- controlnet_block_samples: Tuple[torch.Tensor]
39
-
23
+ class SD3ControlNetOutput(SD3ControlNetOutput):
24
+ def __init__(self, *args, **kwargs):
25
+ deprecation_message = "Importing `SD3ControlNetOutput` from `diffusers.models.controlnet_sd3` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_sd3 import SD3ControlNetOutput`, instead."
26
+ deprecate("diffusers.models.controlnet_sd3.SD3ControlNetOutput", "0.34", deprecation_message)
27
+ super().__init__(*args, **kwargs)
40
28
 
41
- class SD3ControlNetModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
42
- _supports_gradient_checkpointing = True
43
29
 
44
- @register_to_config
30
+ class SD3ControlNetModel(SD3ControlNetModel):
45
31
  def __init__(
46
32
  self,
47
33
  sample_size: int = 128,
@@ -55,364 +41,28 @@ class SD3ControlNetModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginal
55
41
  pooled_projection_dim: int = 2048,
56
42
  out_channels: int = 16,
57
43
  pos_embed_max_size: int = 96,
44
+ extra_conditioning_channels: int = 0,
58
45
  ):
59
- super().__init__()
60
- default_out_channels = in_channels
61
- self.out_channels = out_channels if out_channels is not None else default_out_channels
62
- self.inner_dim = num_attention_heads * attention_head_dim
63
-
64
- self.pos_embed = PatchEmbed(
65
- height=sample_size,
66
- width=sample_size,
46
+ deprecation_message = "Importing `SD3ControlNetModel` from `diffusers.models.controlnet_sd3` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_sd3 import SD3ControlNetModel`, instead."
47
+ deprecate("diffusers.models.controlnet_sd3.SD3ControlNetModel", "0.34", deprecation_message)
48
+ super().__init__(
49
+ sample_size=sample_size,
67
50
  patch_size=patch_size,
68
51
  in_channels=in_channels,
69
- embed_dim=self.inner_dim,
52
+ num_layers=num_layers,
53
+ attention_head_dim=attention_head_dim,
54
+ num_attention_heads=num_attention_heads,
55
+ joint_attention_dim=joint_attention_dim,
56
+ caption_projection_dim=caption_projection_dim,
57
+ pooled_projection_dim=pooled_projection_dim,
58
+ out_channels=out_channels,
70
59
  pos_embed_max_size=pos_embed_max_size,
60
+ extra_conditioning_channels=extra_conditioning_channels,
71
61
  )
72
- self.time_text_embed = CombinedTimestepTextProjEmbeddings(
73
- embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
74
- )
75
- self.context_embedder = nn.Linear(joint_attention_dim, caption_projection_dim)
76
-
77
- # `attention_head_dim` is doubled to account for the mixing.
78
- # It needs to crafted when we get the actual checkpoints.
79
- self.transformer_blocks = nn.ModuleList(
80
- [
81
- JointTransformerBlock(
82
- dim=self.inner_dim,
83
- num_attention_heads=num_attention_heads,
84
- attention_head_dim=self.config.attention_head_dim,
85
- context_pre_only=False,
86
- )
87
- for i in range(num_layers)
88
- ]
89
- )
90
-
91
- # controlnet_blocks
92
- self.controlnet_blocks = nn.ModuleList([])
93
- for _ in range(len(self.transformer_blocks)):
94
- controlnet_block = nn.Linear(self.inner_dim, self.inner_dim)
95
- controlnet_block = zero_module(controlnet_block)
96
- self.controlnet_blocks.append(controlnet_block)
97
- pos_embed_input = PatchEmbed(
98
- height=sample_size,
99
- width=sample_size,
100
- patch_size=patch_size,
101
- in_channels=in_channels,
102
- embed_dim=self.inner_dim,
103
- pos_embed_type=None,
104
- )
105
- self.pos_embed_input = zero_module(pos_embed_input)
106
-
107
- self.gradient_checkpointing = False
108
-
109
- # Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
110
- def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
111
- """
112
- Sets the attention processor to use [feed forward
113
- chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
114
-
115
- Parameters:
116
- chunk_size (`int`, *optional*):
117
- The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
118
- over each tensor of dim=`dim`.
119
- dim (`int`, *optional*, defaults to `0`):
120
- The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
121
- or dim=1 (sequence length).
122
- """
123
- if dim not in [0, 1]:
124
- raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}")
125
-
126
- # By default chunk size is 1
127
- chunk_size = chunk_size or 1
128
-
129
- def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
130
- if hasattr(module, "set_chunk_feed_forward"):
131
- module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
132
-
133
- for child in module.children():
134
- fn_recursive_feed_forward(child, chunk_size, dim)
135
-
136
- for module in self.children():
137
- fn_recursive_feed_forward(module, chunk_size, dim)
138
-
139
- @property
140
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
141
- def attn_processors(self) -> Dict[str, AttentionProcessor]:
142
- r"""
143
- Returns:
144
- `dict` of attention processors: A dictionary containing all attention processors used in the model with
145
- indexed by its weight name.
146
- """
147
- # set recursively
148
- processors = {}
149
-
150
- def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
151
- if hasattr(module, "get_processor"):
152
- processors[f"{name}.processor"] = module.get_processor()
153
-
154
- for sub_name, child in module.named_children():
155
- fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
156
-
157
- return processors
158
-
159
- for name, module in self.named_children():
160
- fn_recursive_add_processors(name, module, processors)
161
-
162
- return processors
163
-
164
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
165
- def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
166
- r"""
167
- Sets the attention processor to use to compute attention.
168
-
169
- Parameters:
170
- processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
171
- The instantiated processor class or a dictionary of processor classes that will be set as the processor
172
- for **all** `Attention` layers.
173
-
174
- If `processor` is a dict, the key needs to define the path to the corresponding cross attention
175
- processor. This is strongly recommended when setting trainable attention processors.
176
-
177
- """
178
- count = len(self.attn_processors.keys())
179
-
180
- if isinstance(processor, dict) and len(processor) != count:
181
- raise ValueError(
182
- f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
183
- f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
184
- )
185
-
186
- def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
187
- if hasattr(module, "set_processor"):
188
- if not isinstance(processor, dict):
189
- module.set_processor(processor)
190
- else:
191
- module.set_processor(processor.pop(f"{name}.processor"))
192
-
193
- for sub_name, child in module.named_children():
194
- fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
195
-
196
- for name, module in self.named_children():
197
- fn_recursive_attn_processor(name, module, processor)
198
-
199
- # Copied from diffusers.models.transformers.transformer_sd3.SD3Transformer2DModel.fuse_qkv_projections
200
- def fuse_qkv_projections(self):
201
- """
202
- Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
203
- are fused. For cross-attention modules, key and value projection matrices are fused.
204
-
205
- <Tip warning={true}>
206
-
207
- This API is 🧪 experimental.
208
-
209
- </Tip>
210
- """
211
- self.original_attn_processors = None
212
-
213
- for _, attn_processor in self.attn_processors.items():
214
- if "Added" in str(attn_processor.__class__.__name__):
215
- raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
216
-
217
- self.original_attn_processors = self.attn_processors
218
-
219
- for module in self.modules():
220
- if isinstance(module, Attention):
221
- module.fuse_projections(fuse=True)
222
-
223
- self.set_attn_processor(FusedJointAttnProcessor2_0())
224
-
225
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
226
- def unfuse_qkv_projections(self):
227
- """Disables the fused QKV projection if enabled.
228
-
229
- <Tip warning={true}>
230
-
231
- This API is 🧪 experimental.
232
-
233
- </Tip>
234
-
235
- """
236
- if self.original_attn_processors is not None:
237
- self.set_attn_processor(self.original_attn_processors)
238
-
239
- def _set_gradient_checkpointing(self, module, value=False):
240
- if hasattr(module, "gradient_checkpointing"):
241
- module.gradient_checkpointing = value
242
-
243
- @classmethod
244
- def from_transformer(cls, transformer, num_layers=12, load_weights_from_transformer=True):
245
- config = transformer.config
246
- config["num_layers"] = num_layers or config.num_layers
247
- controlnet = cls(**config)
248
-
249
- if load_weights_from_transformer:
250
- controlnet.pos_embed.load_state_dict(transformer.pos_embed.state_dict())
251
- controlnet.time_text_embed.load_state_dict(transformer.time_text_embed.state_dict())
252
- controlnet.context_embedder.load_state_dict(transformer.context_embedder.state_dict())
253
- controlnet.transformer_blocks.load_state_dict(transformer.transformer_blocks.state_dict(), strict=False)
254
-
255
- controlnet.pos_embed_input = zero_module(controlnet.pos_embed_input)
256
-
257
- return controlnet
258
-
259
- def forward(
260
- self,
261
- hidden_states: torch.FloatTensor,
262
- controlnet_cond: torch.Tensor,
263
- conditioning_scale: float = 1.0,
264
- encoder_hidden_states: torch.FloatTensor = None,
265
- pooled_projections: torch.FloatTensor = None,
266
- timestep: torch.LongTensor = None,
267
- joint_attention_kwargs: Optional[Dict[str, Any]] = None,
268
- return_dict: bool = True,
269
- ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
270
- """
271
- The [`SD3Transformer2DModel`] forward method.
272
-
273
- Args:
274
- hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
275
- Input `hidden_states`.
276
- controlnet_cond (`torch.Tensor`):
277
- The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
278
- conditioning_scale (`float`, defaults to `1.0`):
279
- The scale factor for ControlNet outputs.
280
- encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
281
- Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
282
- pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
283
- from the embeddings of input conditions.
284
- timestep ( `torch.LongTensor`):
285
- Used to indicate denoising step.
286
- joint_attention_kwargs (`dict`, *optional*):
287
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
288
- `self.processor` in
289
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
290
- return_dict (`bool`, *optional*, defaults to `True`):
291
- Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
292
- tuple.
293
-
294
- Returns:
295
- If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
296
- `tuple` where the first element is the sample tensor.
297
- """
298
- if joint_attention_kwargs is not None:
299
- joint_attention_kwargs = joint_attention_kwargs.copy()
300
- lora_scale = joint_attention_kwargs.pop("scale", 1.0)
301
- else:
302
- lora_scale = 1.0
303
-
304
- if USE_PEFT_BACKEND:
305
- # weight the lora layers by setting `lora_scale` for each PEFT layer
306
- scale_lora_layers(self, lora_scale)
307
- else:
308
- if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
309
- logger.warning(
310
- "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
311
- )
312
-
313
- hidden_states = self.pos_embed(hidden_states) # takes care of adding positional embeddings too.
314
- temb = self.time_text_embed(timestep, pooled_projections)
315
- encoder_hidden_states = self.context_embedder(encoder_hidden_states)
316
-
317
- # add
318
- hidden_states = hidden_states + self.pos_embed_input(controlnet_cond)
319
-
320
- block_res_samples = ()
321
-
322
- for block in self.transformer_blocks:
323
- if self.training and self.gradient_checkpointing:
324
-
325
- def create_custom_forward(module, return_dict=None):
326
- def custom_forward(*inputs):
327
- if return_dict is not None:
328
- return module(*inputs, return_dict=return_dict)
329
- else:
330
- return module(*inputs)
331
-
332
- return custom_forward
333
-
334
- ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
335
- hidden_states = torch.utils.checkpoint.checkpoint(
336
- create_custom_forward(block),
337
- hidden_states,
338
- encoder_hidden_states,
339
- temb,
340
- **ckpt_kwargs,
341
- )
342
-
343
- else:
344
- encoder_hidden_states, hidden_states = block(
345
- hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states, temb=temb
346
- )
347
-
348
- block_res_samples = block_res_samples + (hidden_states,)
349
-
350
- controlnet_block_res_samples = ()
351
- for block_res_sample, controlnet_block in zip(block_res_samples, self.controlnet_blocks):
352
- block_res_sample = controlnet_block(block_res_sample)
353
- controlnet_block_res_samples = controlnet_block_res_samples + (block_res_sample,)
354
-
355
- # 6. scaling
356
- controlnet_block_res_samples = [sample * conditioning_scale for sample in controlnet_block_res_samples]
357
-
358
- if USE_PEFT_BACKEND:
359
- # remove `lora_scale` from each PEFT layer
360
- unscale_lora_layers(self, lora_scale)
361
-
362
- if not return_dict:
363
- return (controlnet_block_res_samples,)
364
-
365
- return SD3ControlNetOutput(controlnet_block_samples=controlnet_block_res_samples)
366
-
367
-
368
- class SD3MultiControlNetModel(ModelMixin):
369
- r"""
370
- `SD3ControlNetModel` wrapper class for Multi-SD3ControlNet
371
-
372
- This module is a wrapper for multiple instances of the `SD3ControlNetModel`. The `forward()` API is designed to be
373
- compatible with `SD3ControlNetModel`.
374
-
375
- Args:
376
- controlnets (`List[SD3ControlNetModel]`):
377
- Provides additional conditioning to the unet during the denoising process. You must set multiple
378
- `SD3ControlNetModel` as a list.
379
- """
380
-
381
- def __init__(self, controlnets):
382
- super().__init__()
383
- self.nets = nn.ModuleList(controlnets)
384
-
385
- def forward(
386
- self,
387
- hidden_states: torch.FloatTensor,
388
- controlnet_cond: List[torch.tensor],
389
- conditioning_scale: List[float],
390
- pooled_projections: torch.FloatTensor,
391
- encoder_hidden_states: torch.FloatTensor = None,
392
- timestep: torch.LongTensor = None,
393
- joint_attention_kwargs: Optional[Dict[str, Any]] = None,
394
- return_dict: bool = True,
395
- ) -> Union[SD3ControlNetOutput, Tuple]:
396
- for i, (image, scale, controlnet) in enumerate(zip(controlnet_cond, conditioning_scale, self.nets)):
397
- block_samples = controlnet(
398
- hidden_states=hidden_states,
399
- timestep=timestep,
400
- encoder_hidden_states=encoder_hidden_states,
401
- pooled_projections=pooled_projections,
402
- controlnet_cond=image,
403
- conditioning_scale=scale,
404
- joint_attention_kwargs=joint_attention_kwargs,
405
- return_dict=return_dict,
406
- )
407
62
 
408
- # merge samples
409
- if i == 0:
410
- control_block_samples = block_samples
411
- else:
412
- control_block_samples = [
413
- control_block_sample + block_sample
414
- for control_block_sample, block_sample in zip(control_block_samples[0], block_samples[0])
415
- ]
416
- control_block_samples = (tuple(control_block_samples),)
417
63
 
418
- return control_block_samples
64
+ class SD3MultiControlNetModel(SD3MultiControlNetModel):
65
+ def __init__(self, *args, **kwargs):
66
+ deprecation_message = "Importing `SD3MultiControlNetModel` from `diffusers.models.controlnet_sd3` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_sd3 import SD3MultiControlNetModel`, instead."
67
+ deprecate("diffusers.models.controlnet_sd3.SD3MultiControlNetModel", "0.34", deprecation_message)
68
+ super().__init__(*args, **kwargs)