diffusers 0.23.1__py3-none-any.whl → 0.25.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (238) hide show
  1. diffusers/__init__.py +26 -2
  2. diffusers/commands/fp16_safetensors.py +10 -11
  3. diffusers/configuration_utils.py +13 -8
  4. diffusers/dependency_versions_check.py +0 -1
  5. diffusers/dependency_versions_table.py +5 -5
  6. diffusers/experimental/rl/value_guided_sampling.py +1 -1
  7. diffusers/image_processor.py +463 -51
  8. diffusers/loaders/__init__.py +82 -0
  9. diffusers/loaders/ip_adapter.py +159 -0
  10. diffusers/loaders/lora.py +1553 -0
  11. diffusers/loaders/lora_conversion_utils.py +284 -0
  12. diffusers/loaders/single_file.py +637 -0
  13. diffusers/loaders/textual_inversion.py +455 -0
  14. diffusers/loaders/unet.py +828 -0
  15. diffusers/loaders/utils.py +59 -0
  16. diffusers/models/__init__.py +26 -9
  17. diffusers/models/activations.py +9 -6
  18. diffusers/models/attention.py +301 -29
  19. diffusers/models/attention_flax.py +9 -1
  20. diffusers/models/attention_processor.py +378 -6
  21. diffusers/models/autoencoders/__init__.py +5 -0
  22. diffusers/models/{autoencoder_asym_kl.py → autoencoders/autoencoder_asym_kl.py} +17 -12
  23. diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +47 -23
  24. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +402 -0
  25. diffusers/models/{autoencoder_tiny.py → autoencoders/autoencoder_tiny.py} +24 -28
  26. diffusers/models/{consistency_decoder_vae.py → autoencoders/consistency_decoder_vae.py} +51 -44
  27. diffusers/models/{vae.py → autoencoders/vae.py} +71 -17
  28. diffusers/models/controlnet.py +59 -39
  29. diffusers/models/controlnet_flax.py +19 -18
  30. diffusers/models/downsampling.py +338 -0
  31. diffusers/models/embeddings.py +112 -29
  32. diffusers/models/embeddings_flax.py +2 -0
  33. diffusers/models/lora.py +131 -1
  34. diffusers/models/modeling_flax_utils.py +14 -8
  35. diffusers/models/modeling_outputs.py +17 -0
  36. diffusers/models/modeling_utils.py +37 -29
  37. diffusers/models/normalization.py +110 -4
  38. diffusers/models/resnet.py +299 -652
  39. diffusers/models/transformer_2d.py +22 -5
  40. diffusers/models/transformer_temporal.py +183 -1
  41. diffusers/models/unet_2d_blocks_flax.py +5 -0
  42. diffusers/models/unet_2d_condition.py +46 -0
  43. diffusers/models/unet_2d_condition_flax.py +13 -13
  44. diffusers/models/unet_3d_blocks.py +957 -173
  45. diffusers/models/unet_3d_condition.py +16 -8
  46. diffusers/models/unet_kandinsky3.py +535 -0
  47. diffusers/models/unet_motion_model.py +48 -33
  48. diffusers/models/unet_spatio_temporal_condition.py +489 -0
  49. diffusers/models/upsampling.py +454 -0
  50. diffusers/models/uvit_2d.py +471 -0
  51. diffusers/models/vae_flax.py +7 -0
  52. diffusers/models/vq_model.py +12 -3
  53. diffusers/optimization.py +16 -9
  54. diffusers/pipelines/__init__.py +137 -76
  55. diffusers/pipelines/amused/__init__.py +62 -0
  56. diffusers/pipelines/amused/pipeline_amused.py +328 -0
  57. diffusers/pipelines/amused/pipeline_amused_img2img.py +347 -0
  58. diffusers/pipelines/amused/pipeline_amused_inpaint.py +378 -0
  59. diffusers/pipelines/animatediff/pipeline_animatediff.py +66 -8
  60. diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
  61. diffusers/pipelines/auto_pipeline.py +23 -13
  62. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
  63. diffusers/pipelines/controlnet/pipeline_controlnet.py +238 -35
  64. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +148 -37
  65. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +155 -41
  66. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +123 -43
  67. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +216 -39
  68. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +106 -34
  69. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
  70. diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
  71. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
  72. diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
  73. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
  74. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
  75. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
  76. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
  77. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
  78. diffusers/pipelines/deprecated/__init__.py +153 -0
  79. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/__init__.py +3 -3
  80. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion.py +177 -34
  81. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion_img2img.py +182 -37
  82. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_output.py +1 -1
  83. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/__init__.py +1 -1
  84. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/mel.py +2 -2
  85. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/pipeline_audio_diffusion.py +4 -4
  86. diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/__init__.py +1 -1
  87. diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/pipeline_latent_diffusion_uncond.py +4 -4
  88. diffusers/pipelines/{pndm → deprecated/pndm}/__init__.py +1 -1
  89. diffusers/pipelines/{pndm → deprecated/pndm}/pipeline_pndm.py +4 -4
  90. diffusers/pipelines/{repaint → deprecated/repaint}/__init__.py +1 -1
  91. diffusers/pipelines/{repaint → deprecated/repaint}/pipeline_repaint.py +5 -5
  92. diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/__init__.py +1 -1
  93. diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/pipeline_score_sde_ve.py +5 -4
  94. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/__init__.py +6 -6
  95. diffusers/pipelines/{spectrogram_diffusion/continous_encoder.py → deprecated/spectrogram_diffusion/continuous_encoder.py} +2 -2
  96. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/midi_utils.py +1 -1
  97. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/notes_encoder.py +2 -2
  98. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/pipeline_spectrogram_diffusion.py +8 -7
  99. diffusers/pipelines/deprecated/stable_diffusion_variants/__init__.py +55 -0
  100. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_cycle_diffusion.py +34 -13
  101. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_onnx_stable_diffusion_inpaint_legacy.py +7 -6
  102. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_inpaint_legacy.py +12 -11
  103. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_model_editing.py +17 -11
  104. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_paradigms.py +11 -10
  105. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_pix2pix_zero.py +14 -13
  106. diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/__init__.py +1 -1
  107. diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/pipeline_stochastic_karras_ve.py +4 -4
  108. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/__init__.py +3 -3
  109. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/modeling_text_unet.py +83 -51
  110. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion.py +4 -4
  111. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_dual_guided.py +7 -6
  112. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_image_variation.py +7 -6
  113. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_text_to_image.py +7 -6
  114. diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/__init__.py +3 -3
  115. diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/pipeline_vq_diffusion.py +5 -5
  116. diffusers/pipelines/dit/pipeline_dit.py +1 -0
  117. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
  118. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
  119. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
  120. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
  121. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
  122. diffusers/pipelines/kandinsky3/__init__.py +49 -0
  123. diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +98 -0
  124. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +589 -0
  125. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +654 -0
  126. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +111 -11
  127. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +102 -9
  128. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
  129. diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
  130. diffusers/pipelines/onnx_utils.py +8 -5
  131. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
  132. diffusers/pipelines/pipeline_flax_utils.py +11 -8
  133. diffusers/pipelines/pipeline_utils.py +63 -42
  134. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +247 -38
  135. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +3 -3
  136. diffusers/pipelines/stable_diffusion/__init__.py +37 -65
  137. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +75 -78
  138. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
  139. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
  140. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
  141. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +174 -11
  142. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
  143. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
  144. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +178 -11
  145. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +224 -13
  146. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +74 -20
  147. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +4 -0
  148. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +7 -0
  149. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +5 -0
  150. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -0
  151. diffusers/pipelines/stable_diffusion_attend_and_excite/__init__.py +48 -0
  152. diffusers/pipelines/{stable_diffusion → stable_diffusion_attend_and_excite}/pipeline_stable_diffusion_attend_and_excite.py +6 -2
  153. diffusers/pipelines/stable_diffusion_diffedit/__init__.py +48 -0
  154. diffusers/pipelines/{stable_diffusion → stable_diffusion_diffedit}/pipeline_stable_diffusion_diffedit.py +3 -3
  155. diffusers/pipelines/stable_diffusion_gligen/__init__.py +50 -0
  156. diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen.py +3 -2
  157. diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen_text_image.py +4 -3
  158. diffusers/pipelines/stable_diffusion_k_diffusion/__init__.py +60 -0
  159. diffusers/pipelines/{stable_diffusion → stable_diffusion_k_diffusion}/pipeline_stable_diffusion_k_diffusion.py +7 -1
  160. diffusers/pipelines/stable_diffusion_ldm3d/__init__.py +48 -0
  161. diffusers/pipelines/{stable_diffusion → stable_diffusion_ldm3d}/pipeline_stable_diffusion_ldm3d.py +51 -7
  162. diffusers/pipelines/stable_diffusion_panorama/__init__.py +48 -0
  163. diffusers/pipelines/{stable_diffusion → stable_diffusion_panorama}/pipeline_stable_diffusion_panorama.py +57 -8
  164. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +58 -6
  165. diffusers/pipelines/stable_diffusion_sag/__init__.py +48 -0
  166. diffusers/pipelines/{stable_diffusion → stable_diffusion_sag}/pipeline_stable_diffusion_sag.py +68 -10
  167. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +194 -17
  168. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +205 -16
  169. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +206 -17
  170. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +23 -17
  171. diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
  172. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +652 -0
  173. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
  174. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +115 -14
  175. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
  176. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +6 -0
  177. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +23 -3
  178. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +334 -10
  179. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +1331 -0
  180. diffusers/pipelines/unclip/pipeline_unclip.py +2 -1
  181. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +1 -0
  182. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
  183. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
  184. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
  185. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
  186. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
  187. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -1
  188. diffusers/schedulers/__init__.py +4 -4
  189. diffusers/schedulers/deprecated/__init__.py +50 -0
  190. diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
  191. diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
  192. diffusers/schedulers/scheduling_amused.py +162 -0
  193. diffusers/schedulers/scheduling_consistency_models.py +2 -0
  194. diffusers/schedulers/scheduling_ddim.py +1 -3
  195. diffusers/schedulers/scheduling_ddim_inverse.py +2 -7
  196. diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
  197. diffusers/schedulers/scheduling_ddpm.py +47 -3
  198. diffusers/schedulers/scheduling_ddpm_parallel.py +47 -3
  199. diffusers/schedulers/scheduling_deis_multistep.py +28 -6
  200. diffusers/schedulers/scheduling_dpmsolver_multistep.py +28 -6
  201. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +28 -6
  202. diffusers/schedulers/scheduling_dpmsolver_sde.py +3 -3
  203. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +28 -6
  204. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +59 -3
  205. diffusers/schedulers/scheduling_euler_discrete.py +102 -16
  206. diffusers/schedulers/scheduling_heun_discrete.py +17 -5
  207. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +17 -5
  208. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +17 -5
  209. diffusers/schedulers/scheduling_lcm.py +123 -29
  210. diffusers/schedulers/scheduling_lms_discrete.py +3 -3
  211. diffusers/schedulers/scheduling_pndm.py +1 -3
  212. diffusers/schedulers/scheduling_repaint.py +1 -3
  213. diffusers/schedulers/scheduling_unipc_multistep.py +28 -6
  214. diffusers/schedulers/scheduling_utils.py +3 -1
  215. diffusers/schedulers/scheduling_utils_flax.py +3 -1
  216. diffusers/training_utils.py +1 -1
  217. diffusers/utils/__init__.py +1 -2
  218. diffusers/utils/constants.py +10 -12
  219. diffusers/utils/dummy_pt_objects.py +75 -0
  220. diffusers/utils/dummy_torch_and_transformers_objects.py +105 -0
  221. diffusers/utils/dynamic_modules_utils.py +18 -22
  222. diffusers/utils/export_utils.py +8 -3
  223. diffusers/utils/hub_utils.py +24 -36
  224. diffusers/utils/logging.py +11 -11
  225. diffusers/utils/outputs.py +5 -5
  226. diffusers/utils/peft_utils.py +88 -44
  227. diffusers/utils/state_dict_utils.py +8 -0
  228. diffusers/utils/testing_utils.py +199 -1
  229. diffusers/utils/torch_utils.py +4 -4
  230. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/METADATA +86 -69
  231. diffusers-0.25.0.dist-info/RECORD +360 -0
  232. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/WHEEL +1 -1
  233. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/entry_points.txt +0 -1
  234. diffusers/loaders.py +0 -3336
  235. diffusers-0.23.1.dist-info/RECORD +0 -323
  236. /diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/modeling_roberta_series.py +0 -0
  237. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/LICENSE +0 -0
  238. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/top_level.txt +0 -0
@@ -18,20 +18,20 @@ import torch
18
18
  import torch.nn.functional as F
19
19
  from torch import nn
20
20
 
21
- from ..configuration_utils import ConfigMixin, register_to_config
22
- from ..schedulers import ConsistencyDecoderScheduler
23
- from ..utils import BaseOutput
24
- from ..utils.accelerate_utils import apply_forward_hook
25
- from ..utils.torch_utils import randn_tensor
26
- from .attention_processor import (
21
+ from ...configuration_utils import ConfigMixin, register_to_config
22
+ from ...schedulers import ConsistencyDecoderScheduler
23
+ from ...utils import BaseOutput
24
+ from ...utils.accelerate_utils import apply_forward_hook
25
+ from ...utils.torch_utils import randn_tensor
26
+ from ..attention_processor import (
27
27
  ADDED_KV_ATTENTION_PROCESSORS,
28
28
  CROSS_ATTENTION_PROCESSORS,
29
29
  AttentionProcessor,
30
30
  AttnAddedKVProcessor,
31
31
  AttnProcessor,
32
32
  )
33
- from .modeling_utils import ModelMixin
34
- from .unet_2d import UNet2DModel
33
+ from ..modeling_utils import ModelMixin
34
+ from ..unet_2d import UNet2DModel
35
35
  from .vae import DecoderOutput, DiagonalGaussianDistribution, Encoder
36
36
 
37
37
 
@@ -56,9 +56,9 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
56
56
  Examples:
57
57
  ```py
58
58
  >>> import torch
59
- >>> from diffusers import DiffusionPipeline, ConsistencyDecoderVAE
59
+ >>> from diffusers import StableDiffusionPipeline, ConsistencyDecoderVAE
60
60
 
61
- >>> vae = ConsistencyDecoderVAE.from_pretrained("openai/consistency-decoder", torch_dtype=pipe.torch_dtype)
61
+ >>> vae = ConsistencyDecoderVAE.from_pretrained("openai/consistency-decoder", torch_dtype=torch.float16)
62
62
  >>> pipe = StableDiffusionPipeline.from_pretrained(
63
63
  ... "runwayml/stable-diffusion-v1-5", vae=vae, torch_dtype=torch.float16
64
64
  ... ).to("cuda")
@@ -70,39 +70,39 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
70
70
  @register_to_config
71
71
  def __init__(
72
72
  self,
73
- scaling_factor=0.18215,
74
- latent_channels=4,
75
- encoder_act_fn="silu",
76
- encoder_block_out_channels=(128, 256, 512, 512),
77
- encoder_double_z=True,
78
- encoder_down_block_types=(
73
+ scaling_factor: float = 0.18215,
74
+ latent_channels: int = 4,
75
+ encoder_act_fn: str = "silu",
76
+ encoder_block_out_channels: Tuple[int, ...] = (128, 256, 512, 512),
77
+ encoder_double_z: bool = True,
78
+ encoder_down_block_types: Tuple[str, ...] = (
79
79
  "DownEncoderBlock2D",
80
80
  "DownEncoderBlock2D",
81
81
  "DownEncoderBlock2D",
82
82
  "DownEncoderBlock2D",
83
83
  ),
84
- encoder_in_channels=3,
85
- encoder_layers_per_block=2,
86
- encoder_norm_num_groups=32,
87
- encoder_out_channels=4,
88
- decoder_add_attention=False,
89
- decoder_block_out_channels=(320, 640, 1024, 1024),
90
- decoder_down_block_types=(
84
+ encoder_in_channels: int = 3,
85
+ encoder_layers_per_block: int = 2,
86
+ encoder_norm_num_groups: int = 32,
87
+ encoder_out_channels: int = 4,
88
+ decoder_add_attention: bool = False,
89
+ decoder_block_out_channels: Tuple[int, ...] = (320, 640, 1024, 1024),
90
+ decoder_down_block_types: Tuple[str, ...] = (
91
91
  "ResnetDownsampleBlock2D",
92
92
  "ResnetDownsampleBlock2D",
93
93
  "ResnetDownsampleBlock2D",
94
94
  "ResnetDownsampleBlock2D",
95
95
  ),
96
- decoder_downsample_padding=1,
97
- decoder_in_channels=7,
98
- decoder_layers_per_block=3,
99
- decoder_norm_eps=1e-05,
100
- decoder_norm_num_groups=32,
101
- decoder_num_train_timesteps=1024,
102
- decoder_out_channels=6,
103
- decoder_resnet_time_scale_shift="scale_shift",
104
- decoder_time_embedding_type="learned",
105
- decoder_up_block_types=(
96
+ decoder_downsample_padding: int = 1,
97
+ decoder_in_channels: int = 7,
98
+ decoder_layers_per_block: int = 3,
99
+ decoder_norm_eps: float = 1e-05,
100
+ decoder_norm_num_groups: int = 32,
101
+ decoder_num_train_timesteps: int = 1024,
102
+ decoder_out_channels: int = 6,
103
+ decoder_resnet_time_scale_shift: str = "scale_shift",
104
+ decoder_time_embedding_type: str = "learned",
105
+ decoder_up_block_types: Tuple[str, ...] = (
106
106
  "ResnetUpsampleBlock2D",
107
107
  "ResnetUpsampleBlock2D",
108
108
  "ResnetUpsampleBlock2D",
@@ -138,6 +138,7 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
138
138
  )
139
139
  self.decoder_scheduler = ConsistencyDecoderScheduler()
140
140
  self.register_to_config(block_out_channels=encoder_block_out_channels)
141
+ self.register_to_config(force_upcast=False)
141
142
  self.register_buffer(
142
143
  "means",
143
144
  torch.tensor([0.38862467, 0.02253063, 0.07381133, -0.0171294])[None, :, None, None],
@@ -152,7 +153,7 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
152
153
  self.use_slicing = False
153
154
  self.use_tiling = False
154
155
 
155
- # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.enable_tiling
156
+ # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.enable_tiling
156
157
  def enable_tiling(self, use_tiling: bool = True):
157
158
  r"""
158
159
  Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
@@ -161,7 +162,7 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
161
162
  """
162
163
  self.use_tiling = use_tiling
163
164
 
164
- # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.disable_tiling
165
+ # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.disable_tiling
165
166
  def disable_tiling(self):
166
167
  r"""
167
168
  Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
@@ -169,7 +170,7 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
169
170
  """
170
171
  self.enable_tiling(False)
171
172
 
172
- # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.enable_slicing
173
+ # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.enable_slicing
173
174
  def enable_slicing(self):
174
175
  r"""
175
176
  Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
@@ -177,7 +178,7 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
177
178
  """
178
179
  self.use_slicing = True
179
180
 
180
- # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.disable_slicing
181
+ # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.disable_slicing
181
182
  def disable_slicing(self):
182
183
  r"""
183
184
  Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
@@ -304,8 +305,8 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
304
305
  z: torch.FloatTensor,
305
306
  generator: Optional[torch.Generator] = None,
306
307
  return_dict: bool = True,
307
- num_inference_steps=2,
308
- ) -> Union[DecoderOutput, torch.FloatTensor]:
308
+ num_inference_steps: int = 2,
309
+ ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
309
310
  z = (z * self.config.scaling_factor - self.means) / self.stds
310
311
 
311
312
  scale_factor = 2 ** (len(self.config.block_out_channels) - 1)
@@ -332,15 +333,15 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
332
333
 
333
334
  return DecoderOutput(sample=x_0)
334
335
 
335
- # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.blend_v
336
- def blend_v(self, a, b, blend_extent):
336
+ # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.blend_v
337
+ def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
337
338
  blend_extent = min(a.shape[2], b.shape[2], blend_extent)
338
339
  for y in range(blend_extent):
339
340
  b[:, :, y, :] = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
340
341
  return b
341
342
 
342
- # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.blend_h
343
- def blend_h(self, a, b, blend_extent):
343
+ # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.blend_h
344
+ def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
344
345
  blend_extent = min(a.shape[3], b.shape[3], blend_extent)
345
346
  for x in range(blend_extent):
346
347
  b[:, :, :, x] = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
@@ -407,7 +408,7 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
407
408
  sample_posterior: bool = False,
408
409
  return_dict: bool = True,
409
410
  generator: Optional[torch.Generator] = None,
410
- ) -> Union[DecoderOutput, torch.FloatTensor]:
411
+ ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
411
412
  r"""
412
413
  Args:
413
414
  sample (`torch.FloatTensor`): Input sample.
@@ -415,6 +416,12 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
415
416
  Whether to sample from the posterior.
416
417
  return_dict (`bool`, *optional*, defaults to `True`):
417
418
  Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
419
+ generator (`torch.Generator`, *optional*, defaults to `None`):
420
+ Generator to use for sampling.
421
+
422
+ Returns:
423
+ [`DecoderOutput`] or `tuple`:
424
+ If return_dict is True, a [`DecoderOutput`] is returned, otherwise a plain `tuple` is returned.
418
425
  """
419
426
  x = sample
420
427
  posterior = self.encode(x).latent_dist
@@ -18,11 +18,16 @@ import numpy as np
18
18
  import torch
19
19
  import torch.nn as nn
20
20
 
21
- from ..utils import BaseOutput, is_torch_version
22
- from ..utils.torch_utils import randn_tensor
23
- from .activations import get_activation
24
- from .attention_processor import SpatialNorm
25
- from .unet_2d_blocks import AutoencoderTinyBlock, UNetMidBlock2D, get_down_block, get_up_block
21
+ from ...utils import BaseOutput, is_torch_version
22
+ from ...utils.torch_utils import randn_tensor
23
+ from ..activations import get_activation
24
+ from ..attention_processor import SpatialNorm
25
+ from ..unet_2d_blocks import (
26
+ AutoencoderTinyBlock,
27
+ UNetMidBlock2D,
28
+ get_down_block,
29
+ get_up_block,
30
+ )
26
31
 
27
32
 
28
33
  @dataclass
@@ -72,6 +77,7 @@ class Encoder(nn.Module):
72
77
  norm_num_groups: int = 32,
73
78
  act_fn: str = "silu",
74
79
  double_z: bool = True,
80
+ mid_block_add_attention=True,
75
81
  ):
76
82
  super().__init__()
77
83
  self.layers_per_block = layers_per_block
@@ -119,6 +125,7 @@ class Encoder(nn.Module):
119
125
  attention_head_dim=block_out_channels[-1],
120
126
  resnet_groups=norm_num_groups,
121
127
  temb_channels=None,
128
+ add_attention=mid_block_add_attention,
122
129
  )
123
130
 
124
131
  # out
@@ -208,6 +215,7 @@ class Decoder(nn.Module):
208
215
  norm_num_groups: int = 32,
209
216
  act_fn: str = "silu",
210
217
  norm_type: str = "group", # group, spatial
218
+ mid_block_add_attention=True,
211
219
  ):
212
220
  super().__init__()
213
221
  self.layers_per_block = layers_per_block
@@ -235,6 +243,7 @@ class Decoder(nn.Module):
235
243
  attention_head_dim=block_out_channels[-1],
236
244
  resnet_groups=norm_num_groups,
237
245
  temb_channels=temb_channels,
246
+ add_attention=mid_block_add_attention,
238
247
  )
239
248
 
240
249
  # up
@@ -274,7 +283,9 @@ class Decoder(nn.Module):
274
283
  self.gradient_checkpointing = False
275
284
 
276
285
  def forward(
277
- self, sample: torch.FloatTensor, latent_embeds: Optional[torch.FloatTensor] = None
286
+ self,
287
+ sample: torch.FloatTensor,
288
+ latent_embeds: Optional[torch.FloatTensor] = None,
278
289
  ) -> torch.FloatTensor:
279
290
  r"""The forward method of the `Decoder` class."""
280
291
 
@@ -292,14 +303,20 @@ class Decoder(nn.Module):
292
303
  if is_torch_version(">=", "1.11.0"):
293
304
  # middle
294
305
  sample = torch.utils.checkpoint.checkpoint(
295
- create_custom_forward(self.mid_block), sample, latent_embeds, use_reentrant=False
306
+ create_custom_forward(self.mid_block),
307
+ sample,
308
+ latent_embeds,
309
+ use_reentrant=False,
296
310
  )
297
311
  sample = sample.to(upscale_dtype)
298
312
 
299
313
  # up
300
314
  for up_block in self.up_blocks:
301
315
  sample = torch.utils.checkpoint.checkpoint(
302
- create_custom_forward(up_block), sample, latent_embeds, use_reentrant=False
316
+ create_custom_forward(up_block),
317
+ sample,
318
+ latent_embeds,
319
+ use_reentrant=False,
303
320
  )
304
321
  else:
305
322
  # middle
@@ -540,7 +557,10 @@ class MaskConditionDecoder(nn.Module):
540
557
  if is_torch_version(">=", "1.11.0"):
541
558
  # middle
542
559
  sample = torch.utils.checkpoint.checkpoint(
543
- create_custom_forward(self.mid_block), sample, latent_embeds, use_reentrant=False
560
+ create_custom_forward(self.mid_block),
561
+ sample,
562
+ latent_embeds,
563
+ use_reentrant=False,
544
564
  )
545
565
  sample = sample.to(upscale_dtype)
546
566
 
@@ -548,7 +568,10 @@ class MaskConditionDecoder(nn.Module):
548
568
  if image is not None and mask is not None:
549
569
  masked_image = (1 - mask) * image
550
570
  im_x = torch.utils.checkpoint.checkpoint(
551
- create_custom_forward(self.condition_encoder), masked_image, mask, use_reentrant=False
571
+ create_custom_forward(self.condition_encoder),
572
+ masked_image,
573
+ mask,
574
+ use_reentrant=False,
552
575
  )
553
576
 
554
577
  # up
@@ -558,7 +581,10 @@ class MaskConditionDecoder(nn.Module):
558
581
  mask_ = nn.functional.interpolate(mask, size=sample.shape[-2:], mode="nearest")
559
582
  sample = sample * mask_ + sample_ * (1 - mask_)
560
583
  sample = torch.utils.checkpoint.checkpoint(
561
- create_custom_forward(up_block), sample, latent_embeds, use_reentrant=False
584
+ create_custom_forward(up_block),
585
+ sample,
586
+ latent_embeds,
587
+ use_reentrant=False,
562
588
  )
563
589
  if image is not None and mask is not None:
564
590
  sample = sample * mask + im_x[str(tuple(sample.shape))] * (1 - mask)
@@ -573,7 +599,9 @@ class MaskConditionDecoder(nn.Module):
573
599
  if image is not None and mask is not None:
574
600
  masked_image = (1 - mask) * image
575
601
  im_x = torch.utils.checkpoint.checkpoint(
576
- create_custom_forward(self.condition_encoder), masked_image, mask
602
+ create_custom_forward(self.condition_encoder),
603
+ masked_image,
604
+ mask,
577
605
  )
578
606
 
579
607
  # up
@@ -754,7 +782,10 @@ class DiagonalGaussianDistribution(object):
754
782
  def sample(self, generator: Optional[torch.Generator] = None) -> torch.FloatTensor:
755
783
  # make sure sample is on the same device as the parameters and has same dtype
756
784
  sample = randn_tensor(
757
- self.mean.shape, generator=generator, device=self.parameters.device, dtype=self.parameters.dtype
785
+ self.mean.shape,
786
+ generator=generator,
787
+ device=self.parameters.device,
788
+ dtype=self.parameters.dtype,
758
789
  )
759
790
  x = self.mean + self.std * sample
760
791
  return x
@@ -764,7 +795,10 @@ class DiagonalGaussianDistribution(object):
764
795
  return torch.Tensor([0.0])
765
796
  else:
766
797
  if other is None:
767
- return 0.5 * torch.sum(torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar, dim=[1, 2, 3])
798
+ return 0.5 * torch.sum(
799
+ torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar,
800
+ dim=[1, 2, 3],
801
+ )
768
802
  else:
769
803
  return 0.5 * torch.sum(
770
804
  torch.pow(self.mean - other.mean, 2) / other.var
@@ -779,7 +813,10 @@ class DiagonalGaussianDistribution(object):
779
813
  if self.deterministic:
780
814
  return torch.Tensor([0.0])
781
815
  logtwopi = np.log(2.0 * np.pi)
782
- return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var, dim=dims)
816
+ return 0.5 * torch.sum(
817
+ logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
818
+ dim=dims,
819
+ )
783
820
 
784
821
  def mode(self) -> torch.Tensor:
785
822
  return self.mean
@@ -820,7 +857,16 @@ class EncoderTiny(nn.Module):
820
857
  if i == 0:
821
858
  layers.append(nn.Conv2d(in_channels, num_channels, kernel_size=3, padding=1))
822
859
  else:
823
- layers.append(nn.Conv2d(num_channels, num_channels, kernel_size=3, padding=1, stride=2, bias=False))
860
+ layers.append(
861
+ nn.Conv2d(
862
+ num_channels,
863
+ num_channels,
864
+ kernel_size=3,
865
+ padding=1,
866
+ stride=2,
867
+ bias=False,
868
+ )
869
+ )
824
870
 
825
871
  for _ in range(num_block):
826
872
  layers.append(AutoencoderTinyBlock(num_channels, num_channels, act_fn))
@@ -899,7 +945,15 @@ class DecoderTiny(nn.Module):
899
945
  layers.append(nn.Upsample(scale_factor=upsampling_scaling_factor))
900
946
 
901
947
  conv_out_channel = num_channels if not is_final_block else out_channels
902
- layers.append(nn.Conv2d(num_channels, conv_out_channel, kernel_size=3, padding=1, bias=is_final_block))
948
+ layers.append(
949
+ nn.Conv2d(
950
+ num_channels,
951
+ conv_out_channel,
952
+ kernel_size=3,
953
+ padding=1,
954
+ bias=is_final_block,
955
+ )
956
+ )
903
957
 
904
958
  self.layers = nn.Sequential(*layers)
905
959
  self.gradient_checkpointing = False
@@ -30,12 +30,7 @@ from .attention_processor import (
30
30
  )
31
31
  from .embeddings import TextImageProjection, TextImageTimeEmbedding, TextTimeEmbedding, TimestepEmbedding, Timesteps
32
32
  from .modeling_utils import ModelMixin
33
- from .unet_2d_blocks import (
34
- CrossAttnDownBlock2D,
35
- DownBlock2D,
36
- UNetMidBlock2DCrossAttn,
37
- get_down_block,
38
- )
33
+ from .unet_2d_blocks import CrossAttnDownBlock2D, DownBlock2D, UNetMidBlock2D, UNetMidBlock2DCrossAttn, get_down_block
39
34
  from .unet_2d_condition import UNet2DConditionModel
40
35
 
41
36
 
@@ -76,7 +71,7 @@ class ControlNetConditioningEmbedding(nn.Module):
76
71
  self,
77
72
  conditioning_embedding_channels: int,
78
73
  conditioning_channels: int = 3,
79
- block_out_channels: Tuple[int] = (16, 32, 96, 256),
74
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
80
75
  ):
81
76
  super().__init__()
82
77
 
@@ -171,6 +166,9 @@ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlnetMixin):
171
166
  conditioning_embedding_out_channels (`tuple[int]`, *optional*, defaults to `(16, 32, 96, 256)`):
172
167
  The tuple of output channel for each block in the `conditioning_embedding` layer.
173
168
  global_pool_conditions (`bool`, defaults to `False`):
169
+ TODO(Patrick) - unused parameter.
170
+ addition_embed_type_num_heads (`int`, defaults to 64):
171
+ The number of heads to use for the `TextTimeEmbedding` layer.
174
172
  """
175
173
 
176
174
  _supports_gradient_checkpointing = True
@@ -182,14 +180,15 @@ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlnetMixin):
182
180
  conditioning_channels: int = 3,
183
181
  flip_sin_to_cos: bool = True,
184
182
  freq_shift: int = 0,
185
- down_block_types: Tuple[str] = (
183
+ down_block_types: Tuple[str, ...] = (
186
184
  "CrossAttnDownBlock2D",
187
185
  "CrossAttnDownBlock2D",
188
186
  "CrossAttnDownBlock2D",
189
187
  "DownBlock2D",
190
188
  ),
189
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
191
190
  only_cross_attention: Union[bool, Tuple[bool]] = False,
192
- block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
191
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
193
192
  layers_per_block: int = 2,
194
193
  downsample_padding: int = 1,
195
194
  mid_block_scale_factor: float = 1,
@@ -197,11 +196,11 @@ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlnetMixin):
197
196
  norm_num_groups: Optional[int] = 32,
198
197
  norm_eps: float = 1e-5,
199
198
  cross_attention_dim: int = 1280,
200
- transformer_layers_per_block: Union[int, Tuple[int]] = 1,
199
+ transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
201
200
  encoder_hid_dim: Optional[int] = None,
202
201
  encoder_hid_dim_type: Optional[str] = None,
203
- attention_head_dim: Union[int, Tuple[int]] = 8,
204
- num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
202
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8,
203
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
205
204
  use_linear_projection: bool = False,
206
205
  class_embed_type: Optional[str] = None,
207
206
  addition_embed_type: Optional[str] = None,
@@ -211,9 +210,9 @@ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlnetMixin):
211
210
  resnet_time_scale_shift: str = "default",
212
211
  projection_class_embeddings_input_dim: Optional[int] = None,
213
212
  controlnet_conditioning_channel_order: str = "rgb",
214
- conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
213
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
215
214
  global_pool_conditions: bool = False,
216
- addition_embed_type_num_heads=64,
215
+ addition_embed_type_num_heads: int = 64,
217
216
  ):
218
217
  super().__init__()
219
218
 
@@ -406,28 +405,44 @@ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlnetMixin):
406
405
  controlnet_block = zero_module(controlnet_block)
407
406
  self.controlnet_mid_block = controlnet_block
408
407
 
409
- self.mid_block = UNetMidBlock2DCrossAttn(
410
- transformer_layers_per_block=transformer_layers_per_block[-1],
411
- in_channels=mid_block_channel,
412
- temb_channels=time_embed_dim,
413
- resnet_eps=norm_eps,
414
- resnet_act_fn=act_fn,
415
- output_scale_factor=mid_block_scale_factor,
416
- resnet_time_scale_shift=resnet_time_scale_shift,
417
- cross_attention_dim=cross_attention_dim,
418
- num_attention_heads=num_attention_heads[-1],
419
- resnet_groups=norm_num_groups,
420
- use_linear_projection=use_linear_projection,
421
- upcast_attention=upcast_attention,
422
- )
408
+ if mid_block_type == "UNetMidBlock2DCrossAttn":
409
+ self.mid_block = UNetMidBlock2DCrossAttn(
410
+ transformer_layers_per_block=transformer_layers_per_block[-1],
411
+ in_channels=mid_block_channel,
412
+ temb_channels=time_embed_dim,
413
+ resnet_eps=norm_eps,
414
+ resnet_act_fn=act_fn,
415
+ output_scale_factor=mid_block_scale_factor,
416
+ resnet_time_scale_shift=resnet_time_scale_shift,
417
+ cross_attention_dim=cross_attention_dim,
418
+ num_attention_heads=num_attention_heads[-1],
419
+ resnet_groups=norm_num_groups,
420
+ use_linear_projection=use_linear_projection,
421
+ upcast_attention=upcast_attention,
422
+ )
423
+ elif mid_block_type == "UNetMidBlock2D":
424
+ self.mid_block = UNetMidBlock2D(
425
+ in_channels=block_out_channels[-1],
426
+ temb_channels=time_embed_dim,
427
+ num_layers=0,
428
+ resnet_eps=norm_eps,
429
+ resnet_act_fn=act_fn,
430
+ output_scale_factor=mid_block_scale_factor,
431
+ resnet_groups=norm_num_groups,
432
+ resnet_time_scale_shift=resnet_time_scale_shift,
433
+ add_attention=False,
434
+ )
435
+ else:
436
+ raise ValueError(f"unknown mid_block_type : {mid_block_type}")
423
437
 
424
438
  @classmethod
425
439
  def from_unet(
426
440
  cls,
427
441
  unet: UNet2DConditionModel,
428
442
  controlnet_conditioning_channel_order: str = "rgb",
429
- conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
443
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
430
444
  load_weights_from_unet: bool = True,
445
+ conditioning_channels: int = 3,
431
446
  ):
432
447
  r"""
433
448
  Instantiate a [`ControlNetModel`] from [`UNet2DConditionModel`].
@@ -474,8 +489,10 @@ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlnetMixin):
474
489
  upcast_attention=unet.config.upcast_attention,
475
490
  resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
476
491
  projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
492
+ mid_block_type=unet.config.mid_block_type,
477
493
  controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
478
494
  conditioning_embedding_out_channels=conditioning_embedding_out_channels,
495
+ conditioning_channels=conditioning_channels,
479
496
  )
480
497
 
481
498
  if load_weights_from_unet:
@@ -570,7 +587,7 @@ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlnetMixin):
570
587
  self.set_attn_processor(processor, _remove_lora=True)
571
588
 
572
589
  # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice
573
- def set_attention_slice(self, slice_size):
590
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
574
591
  r"""
575
592
  Enable sliced attention computation.
576
593
 
@@ -635,7 +652,7 @@ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlnetMixin):
635
652
  for module in self.children():
636
653
  fn_recursive_set_attention_slice(module, reversed_slice_size)
637
654
 
638
- def _set_gradient_checkpointing(self, module, value=False):
655
+ def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
639
656
  if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
640
657
  module.gradient_checkpointing = value
641
658
 
@@ -653,7 +670,7 @@ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlnetMixin):
653
670
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
654
671
  guess_mode: bool = False,
655
672
  return_dict: bool = True,
656
- ) -> Union[ControlNetOutput, Tuple]:
673
+ ) -> Union[ControlNetOutput, Tuple[Tuple[torch.FloatTensor, ...], torch.FloatTensor]]:
657
674
  """
658
675
  The [`ControlNetModel`] forward method.
659
676
 
@@ -794,13 +811,16 @@ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlnetMixin):
794
811
 
795
812
  # 4. mid
796
813
  if self.mid_block is not None:
797
- sample = self.mid_block(
798
- sample,
799
- emb,
800
- encoder_hidden_states=encoder_hidden_states,
801
- attention_mask=attention_mask,
802
- cross_attention_kwargs=cross_attention_kwargs,
803
- )
814
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
815
+ sample = self.mid_block(
816
+ sample,
817
+ emb,
818
+ encoder_hidden_states=encoder_hidden_states,
819
+ attention_mask=attention_mask,
820
+ cross_attention_kwargs=cross_attention_kwargs,
821
+ )
822
+ else:
823
+ sample = self.mid_block(sample, emb)
804
824
 
805
825
  # 5. Control net blocks
806
826