diffusers 0.31.0__py3-none-any.whl → 0.32.1__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 (214) hide show
  1. diffusers/__init__.py +66 -5
  2. diffusers/callbacks.py +56 -3
  3. diffusers/configuration_utils.py +1 -1
  4. diffusers/dependency_versions_table.py +1 -1
  5. diffusers/image_processor.py +25 -17
  6. diffusers/loaders/__init__.py +22 -3
  7. diffusers/loaders/ip_adapter.py +538 -15
  8. diffusers/loaders/lora_base.py +124 -118
  9. diffusers/loaders/lora_conversion_utils.py +318 -3
  10. diffusers/loaders/lora_pipeline.py +1688 -368
  11. diffusers/loaders/peft.py +379 -0
  12. diffusers/loaders/single_file_model.py +71 -4
  13. diffusers/loaders/single_file_utils.py +519 -9
  14. diffusers/loaders/textual_inversion.py +3 -3
  15. diffusers/loaders/transformer_flux.py +181 -0
  16. diffusers/loaders/transformer_sd3.py +89 -0
  17. diffusers/loaders/unet.py +17 -4
  18. diffusers/models/__init__.py +47 -14
  19. diffusers/models/activations.py +22 -9
  20. diffusers/models/attention.py +13 -4
  21. diffusers/models/attention_flax.py +1 -1
  22. diffusers/models/attention_processor.py +2059 -281
  23. diffusers/models/autoencoders/__init__.py +5 -0
  24. diffusers/models/autoencoders/autoencoder_dc.py +620 -0
  25. diffusers/models/autoencoders/autoencoder_kl.py +2 -1
  26. diffusers/models/autoencoders/autoencoder_kl_allegro.py +1149 -0
  27. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +36 -27
  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 +29 -495
  36. diffusers/models/controlnet_sd3.py +25 -379
  37. diffusers/models/controlnet_sparsectrl.py +46 -718
  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 +838 -43
  49. diffusers/models/model_loading_utils.py +88 -6
  50. diffusers/models/modeling_flax_utils.py +1 -1
  51. diffusers/models/modeling_utils.py +72 -26
  52. diffusers/models/normalization.py +78 -13
  53. diffusers/models/transformers/__init__.py +5 -0
  54. diffusers/models/transformers/auraflow_transformer_2d.py +2 -2
  55. diffusers/models/transformers/cogvideox_transformer_3d.py +46 -11
  56. diffusers/models/transformers/dit_transformer_2d.py +1 -1
  57. diffusers/models/transformers/latte_transformer_3d.py +4 -4
  58. diffusers/models/transformers/pixart_transformer_2d.py +1 -1
  59. diffusers/models/transformers/sana_transformer.py +488 -0
  60. diffusers/models/transformers/stable_audio_transformer.py +1 -1
  61. diffusers/models/transformers/transformer_2d.py +1 -1
  62. diffusers/models/transformers/transformer_allegro.py +422 -0
  63. diffusers/models/transformers/transformer_cogview3plus.py +1 -1
  64. diffusers/models/transformers/transformer_flux.py +30 -9
  65. diffusers/models/transformers/transformer_hunyuan_video.py +789 -0
  66. diffusers/models/transformers/transformer_ltx.py +469 -0
  67. diffusers/models/transformers/transformer_mochi.py +499 -0
  68. diffusers/models/transformers/transformer_sd3.py +105 -17
  69. diffusers/models/transformers/transformer_temporal.py +1 -1
  70. diffusers/models/unets/unet_1d_blocks.py +1 -1
  71. diffusers/models/unets/unet_2d.py +8 -1
  72. diffusers/models/unets/unet_2d_blocks.py +88 -21
  73. diffusers/models/unets/unet_2d_condition.py +1 -1
  74. diffusers/models/unets/unet_3d_blocks.py +9 -7
  75. diffusers/models/unets/unet_motion_model.py +5 -5
  76. diffusers/models/unets/unet_spatio_temporal_condition.py +23 -0
  77. diffusers/models/unets/unet_stable_cascade.py +2 -2
  78. diffusers/models/unets/uvit_2d.py +1 -1
  79. diffusers/models/upsampling.py +8 -0
  80. diffusers/pipelines/__init__.py +34 -0
  81. diffusers/pipelines/allegro/__init__.py +48 -0
  82. diffusers/pipelines/allegro/pipeline_allegro.py +938 -0
  83. diffusers/pipelines/allegro/pipeline_output.py +23 -0
  84. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +8 -2
  85. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1 -1
  86. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +0 -6
  87. diffusers/pipelines/animatediff/pipeline_animatediff_video2video_controlnet.py +8 -8
  88. diffusers/pipelines/audioldm2/modeling_audioldm2.py +3 -3
  89. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +1 -8
  90. diffusers/pipelines/auto_pipeline.py +53 -6
  91. diffusers/pipelines/blip_diffusion/modeling_blip2.py +1 -1
  92. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +50 -22
  93. diffusers/pipelines/cogvideo/pipeline_cogvideox_fun_control.py +51 -20
  94. diffusers/pipelines/cogvideo/pipeline_cogvideox_image2video.py +69 -21
  95. diffusers/pipelines/cogvideo/pipeline_cogvideox_video2video.py +47 -21
  96. diffusers/pipelines/cogview3/pipeline_cogview3plus.py +1 -1
  97. diffusers/pipelines/controlnet/__init__.py +86 -80
  98. diffusers/pipelines/controlnet/multicontrolnet.py +7 -178
  99. diffusers/pipelines/controlnet/pipeline_controlnet.py +11 -2
  100. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +1 -2
  101. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +1 -2
  102. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +1 -2
  103. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +3 -3
  104. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +1 -3
  105. diffusers/pipelines/controlnet/pipeline_controlnet_union_inpaint_sd_xl.py +1790 -0
  106. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl.py +1501 -0
  107. diffusers/pipelines/controlnet/pipeline_controlnet_union_sd_xl_img2img.py +1627 -0
  108. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +5 -1
  109. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +53 -19
  110. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet_inpainting.py +7 -7
  111. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +31 -8
  112. diffusers/pipelines/flux/__init__.py +13 -1
  113. diffusers/pipelines/flux/modeling_flux.py +47 -0
  114. diffusers/pipelines/flux/pipeline_flux.py +204 -29
  115. diffusers/pipelines/flux/pipeline_flux_control.py +889 -0
  116. diffusers/pipelines/flux/pipeline_flux_control_img2img.py +945 -0
  117. diffusers/pipelines/flux/pipeline_flux_control_inpaint.py +1141 -0
  118. diffusers/pipelines/flux/pipeline_flux_controlnet.py +49 -27
  119. diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py +40 -30
  120. diffusers/pipelines/flux/pipeline_flux_controlnet_inpainting.py +78 -56
  121. diffusers/pipelines/flux/pipeline_flux_fill.py +969 -0
  122. diffusers/pipelines/flux/pipeline_flux_img2img.py +33 -27
  123. diffusers/pipelines/flux/pipeline_flux_inpaint.py +36 -29
  124. diffusers/pipelines/flux/pipeline_flux_prior_redux.py +492 -0
  125. diffusers/pipelines/flux/pipeline_output.py +16 -0
  126. diffusers/pipelines/hunyuan_video/__init__.py +48 -0
  127. diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py +687 -0
  128. diffusers/pipelines/hunyuan_video/pipeline_output.py +20 -0
  129. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +5 -1
  130. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +9 -9
  131. diffusers/pipelines/kolors/text_encoder.py +2 -2
  132. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -1
  133. diffusers/pipelines/ltx/__init__.py +50 -0
  134. diffusers/pipelines/ltx/pipeline_ltx.py +789 -0
  135. diffusers/pipelines/ltx/pipeline_ltx_image2video.py +885 -0
  136. diffusers/pipelines/ltx/pipeline_output.py +20 -0
  137. diffusers/pipelines/lumina/pipeline_lumina.py +1 -8
  138. diffusers/pipelines/mochi/__init__.py +48 -0
  139. diffusers/pipelines/mochi/pipeline_mochi.py +748 -0
  140. diffusers/pipelines/mochi/pipeline_output.py +20 -0
  141. diffusers/pipelines/pag/__init__.py +7 -0
  142. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1 -2
  143. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_inpaint.py +1 -2
  144. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1 -3
  145. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl_img2img.py +1 -3
  146. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +5 -1
  147. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +6 -13
  148. diffusers/pipelines/pag/pipeline_pag_sana.py +886 -0
  149. diffusers/pipelines/pag/pipeline_pag_sd_3.py +6 -6
  150. diffusers/pipelines/pag/pipeline_pag_sd_3_img2img.py +1058 -0
  151. diffusers/pipelines/pag/pipeline_pag_sd_img2img.py +3 -0
  152. diffusers/pipelines/pag/pipeline_pag_sd_inpaint.py +1356 -0
  153. diffusers/pipelines/pipeline_flax_utils.py +1 -1
  154. diffusers/pipelines/pipeline_loading_utils.py +25 -4
  155. diffusers/pipelines/pipeline_utils.py +35 -6
  156. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +6 -13
  157. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +6 -13
  158. diffusers/pipelines/sana/__init__.py +47 -0
  159. diffusers/pipelines/sana/pipeline_output.py +21 -0
  160. diffusers/pipelines/sana/pipeline_sana.py +884 -0
  161. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +12 -1
  162. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +18 -3
  163. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +216 -20
  164. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +62 -9
  165. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +57 -8
  166. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +11 -1
  167. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +0 -8
  168. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +0 -8
  169. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +0 -8
  170. diffusers/pipelines/unidiffuser/modeling_uvit.py +2 -2
  171. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
  172. diffusers/quantizers/auto.py +14 -1
  173. diffusers/quantizers/bitsandbytes/bnb_quantizer.py +4 -1
  174. diffusers/quantizers/gguf/__init__.py +1 -0
  175. diffusers/quantizers/gguf/gguf_quantizer.py +159 -0
  176. diffusers/quantizers/gguf/utils.py +456 -0
  177. diffusers/quantizers/quantization_config.py +280 -2
  178. diffusers/quantizers/torchao/__init__.py +15 -0
  179. diffusers/quantizers/torchao/torchao_quantizer.py +292 -0
  180. diffusers/schedulers/scheduling_ddpm.py +2 -6
  181. diffusers/schedulers/scheduling_ddpm_parallel.py +2 -6
  182. diffusers/schedulers/scheduling_deis_multistep.py +28 -9
  183. diffusers/schedulers/scheduling_dpmsolver_multistep.py +35 -9
  184. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +35 -8
  185. diffusers/schedulers/scheduling_dpmsolver_sde.py +4 -4
  186. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +48 -10
  187. diffusers/schedulers/scheduling_euler_discrete.py +4 -4
  188. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +153 -6
  189. diffusers/schedulers/scheduling_heun_discrete.py +4 -4
  190. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +4 -4
  191. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +4 -4
  192. diffusers/schedulers/scheduling_lcm.py +2 -6
  193. diffusers/schedulers/scheduling_lms_discrete.py +4 -4
  194. diffusers/schedulers/scheduling_repaint.py +1 -1
  195. diffusers/schedulers/scheduling_sasolver.py +28 -9
  196. diffusers/schedulers/scheduling_tcd.py +2 -6
  197. diffusers/schedulers/scheduling_unipc_multistep.py +53 -8
  198. diffusers/training_utils.py +16 -2
  199. diffusers/utils/__init__.py +5 -0
  200. diffusers/utils/constants.py +1 -0
  201. diffusers/utils/dummy_pt_objects.py +180 -0
  202. diffusers/utils/dummy_torch_and_transformers_objects.py +270 -0
  203. diffusers/utils/dynamic_modules_utils.py +3 -3
  204. diffusers/utils/hub_utils.py +31 -39
  205. diffusers/utils/import_utils.py +67 -0
  206. diffusers/utils/peft_utils.py +3 -0
  207. diffusers/utils/testing_utils.py +56 -1
  208. diffusers/utils/torch_utils.py +3 -0
  209. {diffusers-0.31.0.dist-info → diffusers-0.32.1.dist-info}/METADATA +6 -6
  210. {diffusers-0.31.0.dist-info → diffusers-0.32.1.dist-info}/RECORD +214 -162
  211. {diffusers-0.31.0.dist-info → diffusers-0.32.1.dist-info}/WHEEL +1 -1
  212. {diffusers-0.31.0.dist-info → diffusers-0.32.1.dist-info}/LICENSE +0 -0
  213. {diffusers-0.31.0.dist-info → diffusers-0.32.1.dist-info}/entry_points.txt +0 -0
  214. {diffusers-0.31.0.dist-info → diffusers-0.32.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,788 @@
1
+ # Copyright 2024 The HuggingFace 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
+ from dataclasses import dataclass
16
+ from typing import Any, Dict, List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from torch import nn
20
+ from torch.nn import functional as F
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...loaders import FromOriginalModelMixin
24
+ from ...utils import BaseOutput, logging
25
+ from ..attention_processor import (
26
+ ADDED_KV_ATTENTION_PROCESSORS,
27
+ CROSS_ATTENTION_PROCESSORS,
28
+ AttentionProcessor,
29
+ AttnAddedKVProcessor,
30
+ AttnProcessor,
31
+ )
32
+ from ..embeddings import TimestepEmbedding, Timesteps
33
+ from ..modeling_utils import ModelMixin
34
+ from ..unets.unet_2d_blocks import UNetMidBlock2DCrossAttn
35
+ from ..unets.unet_2d_condition import UNet2DConditionModel
36
+ from ..unets.unet_motion_model import CrossAttnDownBlockMotion, DownBlockMotion
37
+
38
+
39
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
40
+
41
+
42
+ @dataclass
43
+ class SparseControlNetOutput(BaseOutput):
44
+ """
45
+ The output of [`SparseControlNetModel`].
46
+
47
+ Args:
48
+ down_block_res_samples (`tuple[torch.Tensor]`):
49
+ A tuple of downsample activations at different resolutions for each downsampling block. Each tensor should
50
+ be of shape `(batch_size, channel * resolution, height //resolution, width // resolution)`. Output can be
51
+ used to condition the original UNet's downsampling activations.
52
+ mid_down_block_re_sample (`torch.Tensor`):
53
+ The activation of the middle block (the lowest sample resolution). Each tensor should be of shape
54
+ `(batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution)`.
55
+ Output can be used to condition the original UNet's middle block activation.
56
+ """
57
+
58
+ down_block_res_samples: Tuple[torch.Tensor]
59
+ mid_block_res_sample: torch.Tensor
60
+
61
+
62
+ class SparseControlNetConditioningEmbedding(nn.Module):
63
+ def __init__(
64
+ self,
65
+ conditioning_embedding_channels: int,
66
+ conditioning_channels: int = 3,
67
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
68
+ ):
69
+ super().__init__()
70
+
71
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
72
+ self.blocks = nn.ModuleList([])
73
+
74
+ for i in range(len(block_out_channels) - 1):
75
+ channel_in = block_out_channels[i]
76
+ channel_out = block_out_channels[i + 1]
77
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
78
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
79
+
80
+ self.conv_out = zero_module(
81
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
82
+ )
83
+
84
+ def forward(self, conditioning: torch.Tensor) -> torch.Tensor:
85
+ embedding = self.conv_in(conditioning)
86
+ embedding = F.silu(embedding)
87
+
88
+ for block in self.blocks:
89
+ embedding = block(embedding)
90
+ embedding = F.silu(embedding)
91
+
92
+ embedding = self.conv_out(embedding)
93
+ return embedding
94
+
95
+
96
+ class SparseControlNetModel(ModelMixin, ConfigMixin, FromOriginalModelMixin):
97
+ """
98
+ A SparseControlNet model as described in [SparseCtrl: Adding Sparse Controls to Text-to-Video Diffusion
99
+ Models](https://arxiv.org/abs/2311.16933).
100
+
101
+ Args:
102
+ in_channels (`int`, defaults to 4):
103
+ The number of channels in the input sample.
104
+ conditioning_channels (`int`, defaults to 4):
105
+ The number of input channels in the controlnet conditional embedding module. If
106
+ `concat_condition_embedding` is True, the value provided here is incremented by 1.
107
+ flip_sin_to_cos (`bool`, defaults to `True`):
108
+ Whether to flip the sin to cos in the time embedding.
109
+ freq_shift (`int`, defaults to 0):
110
+ The frequency shift to apply to the time embedding.
111
+ down_block_types (`tuple[str]`, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
112
+ The tuple of downsample blocks to use.
113
+ only_cross_attention (`Union[bool, Tuple[bool]]`, defaults to `False`):
114
+ block_out_channels (`tuple[int]`, defaults to `(320, 640, 1280, 1280)`):
115
+ The tuple of output channels for each block.
116
+ layers_per_block (`int`, defaults to 2):
117
+ The number of layers per block.
118
+ downsample_padding (`int`, defaults to 1):
119
+ The padding to use for the downsampling convolution.
120
+ mid_block_scale_factor (`float`, defaults to 1):
121
+ The scale factor to use for the mid block.
122
+ act_fn (`str`, defaults to "silu"):
123
+ The activation function to use.
124
+ norm_num_groups (`int`, *optional*, defaults to 32):
125
+ The number of groups to use for the normalization. If None, normalization and activation layers is skipped
126
+ in post-processing.
127
+ norm_eps (`float`, defaults to 1e-5):
128
+ The epsilon to use for the normalization.
129
+ cross_attention_dim (`int`, defaults to 1280):
130
+ The dimension of the cross attention features.
131
+ transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
132
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
133
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
134
+ [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
135
+ transformer_layers_per_mid_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
136
+ The number of transformer layers to use in each layer in the middle block.
137
+ attention_head_dim (`int` or `Tuple[int]`, defaults to 8):
138
+ The dimension of the attention heads.
139
+ num_attention_heads (`int` or `Tuple[int]`, *optional*):
140
+ The number of heads to use for multi-head attention.
141
+ use_linear_projection (`bool`, defaults to `False`):
142
+ upcast_attention (`bool`, defaults to `False`):
143
+ resnet_time_scale_shift (`str`, defaults to `"default"`):
144
+ Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
145
+ conditioning_embedding_out_channels (`Tuple[int]`, defaults to `(16, 32, 96, 256)`):
146
+ The tuple of output channel for each block in the `conditioning_embedding` layer.
147
+ global_pool_conditions (`bool`, defaults to `False`):
148
+ TODO(Patrick) - unused parameter
149
+ controlnet_conditioning_channel_order (`str`, defaults to `rgb`):
150
+ motion_max_seq_length (`int`, defaults to `32`):
151
+ The maximum sequence length to use in the motion module.
152
+ motion_num_attention_heads (`int` or `Tuple[int]`, defaults to `8`):
153
+ The number of heads to use in each attention layer of the motion module.
154
+ concat_conditioning_mask (`bool`, defaults to `True`):
155
+ use_simplified_condition_embedding (`bool`, defaults to `True`):
156
+ """
157
+
158
+ _supports_gradient_checkpointing = True
159
+
160
+ @register_to_config
161
+ def __init__(
162
+ self,
163
+ in_channels: int = 4,
164
+ conditioning_channels: int = 4,
165
+ flip_sin_to_cos: bool = True,
166
+ freq_shift: int = 0,
167
+ down_block_types: Tuple[str, ...] = (
168
+ "CrossAttnDownBlockMotion",
169
+ "CrossAttnDownBlockMotion",
170
+ "CrossAttnDownBlockMotion",
171
+ "DownBlockMotion",
172
+ ),
173
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
174
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
175
+ layers_per_block: int = 2,
176
+ downsample_padding: int = 1,
177
+ mid_block_scale_factor: float = 1,
178
+ act_fn: str = "silu",
179
+ norm_num_groups: Optional[int] = 32,
180
+ norm_eps: float = 1e-5,
181
+ cross_attention_dim: int = 768,
182
+ transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
183
+ transformer_layers_per_mid_block: Optional[Union[int, Tuple[int]]] = None,
184
+ temporal_transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
185
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8,
186
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
187
+ use_linear_projection: bool = False,
188
+ upcast_attention: bool = False,
189
+ resnet_time_scale_shift: str = "default",
190
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
191
+ global_pool_conditions: bool = False,
192
+ controlnet_conditioning_channel_order: str = "rgb",
193
+ motion_max_seq_length: int = 32,
194
+ motion_num_attention_heads: int = 8,
195
+ concat_conditioning_mask: bool = True,
196
+ use_simplified_condition_embedding: bool = True,
197
+ ):
198
+ super().__init__()
199
+ self.use_simplified_condition_embedding = use_simplified_condition_embedding
200
+
201
+ # If `num_attention_heads` is not defined (which is the case for most models)
202
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
203
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
204
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
205
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
206
+ # which is why we correct for the naming here.
207
+ num_attention_heads = num_attention_heads or attention_head_dim
208
+
209
+ # Check inputs
210
+ if len(block_out_channels) != len(down_block_types):
211
+ raise ValueError(
212
+ f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
213
+ )
214
+
215
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
216
+ raise ValueError(
217
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
218
+ )
219
+
220
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
221
+ raise ValueError(
222
+ f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
223
+ )
224
+
225
+ if isinstance(transformer_layers_per_block, int):
226
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
227
+ if isinstance(temporal_transformer_layers_per_block, int):
228
+ temporal_transformer_layers_per_block = [temporal_transformer_layers_per_block] * len(down_block_types)
229
+
230
+ # input
231
+ conv_in_kernel = 3
232
+ conv_in_padding = (conv_in_kernel - 1) // 2
233
+ self.conv_in = nn.Conv2d(
234
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
235
+ )
236
+
237
+ if concat_conditioning_mask:
238
+ conditioning_channels = conditioning_channels + 1
239
+
240
+ self.concat_conditioning_mask = concat_conditioning_mask
241
+
242
+ # control net conditioning embedding
243
+ if use_simplified_condition_embedding:
244
+ self.controlnet_cond_embedding = zero_module(
245
+ nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
246
+ )
247
+ else:
248
+ self.controlnet_cond_embedding = SparseControlNetConditioningEmbedding(
249
+ conditioning_embedding_channels=block_out_channels[0],
250
+ block_out_channels=conditioning_embedding_out_channels,
251
+ conditioning_channels=conditioning_channels,
252
+ )
253
+
254
+ # time
255
+ time_embed_dim = block_out_channels[0] * 4
256
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
257
+ timestep_input_dim = block_out_channels[0]
258
+
259
+ self.time_embedding = TimestepEmbedding(
260
+ timestep_input_dim,
261
+ time_embed_dim,
262
+ act_fn=act_fn,
263
+ )
264
+
265
+ self.down_blocks = nn.ModuleList([])
266
+ self.controlnet_down_blocks = nn.ModuleList([])
267
+
268
+ if isinstance(cross_attention_dim, int):
269
+ cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
270
+
271
+ if isinstance(only_cross_attention, bool):
272
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
273
+
274
+ if isinstance(attention_head_dim, int):
275
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
276
+
277
+ if isinstance(num_attention_heads, int):
278
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
279
+
280
+ if isinstance(motion_num_attention_heads, int):
281
+ motion_num_attention_heads = (motion_num_attention_heads,) * len(down_block_types)
282
+
283
+ # down
284
+ output_channel = block_out_channels[0]
285
+
286
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
287
+ controlnet_block = zero_module(controlnet_block)
288
+ self.controlnet_down_blocks.append(controlnet_block)
289
+
290
+ for i, down_block_type in enumerate(down_block_types):
291
+ input_channel = output_channel
292
+ output_channel = block_out_channels[i]
293
+ is_final_block = i == len(block_out_channels) - 1
294
+
295
+ if down_block_type == "CrossAttnDownBlockMotion":
296
+ down_block = CrossAttnDownBlockMotion(
297
+ in_channels=input_channel,
298
+ out_channels=output_channel,
299
+ temb_channels=time_embed_dim,
300
+ dropout=0,
301
+ num_layers=layers_per_block,
302
+ transformer_layers_per_block=transformer_layers_per_block[i],
303
+ resnet_eps=norm_eps,
304
+ resnet_time_scale_shift=resnet_time_scale_shift,
305
+ resnet_act_fn=act_fn,
306
+ resnet_groups=norm_num_groups,
307
+ resnet_pre_norm=True,
308
+ num_attention_heads=num_attention_heads[i],
309
+ cross_attention_dim=cross_attention_dim[i],
310
+ add_downsample=not is_final_block,
311
+ dual_cross_attention=False,
312
+ use_linear_projection=use_linear_projection,
313
+ only_cross_attention=only_cross_attention[i],
314
+ upcast_attention=upcast_attention,
315
+ temporal_num_attention_heads=motion_num_attention_heads[i],
316
+ temporal_max_seq_length=motion_max_seq_length,
317
+ temporal_transformer_layers_per_block=temporal_transformer_layers_per_block[i],
318
+ temporal_double_self_attention=False,
319
+ )
320
+ elif down_block_type == "DownBlockMotion":
321
+ down_block = DownBlockMotion(
322
+ in_channels=input_channel,
323
+ out_channels=output_channel,
324
+ temb_channels=time_embed_dim,
325
+ dropout=0,
326
+ num_layers=layers_per_block,
327
+ resnet_eps=norm_eps,
328
+ resnet_time_scale_shift=resnet_time_scale_shift,
329
+ resnet_act_fn=act_fn,
330
+ resnet_groups=norm_num_groups,
331
+ resnet_pre_norm=True,
332
+ add_downsample=not is_final_block,
333
+ temporal_num_attention_heads=motion_num_attention_heads[i],
334
+ temporal_max_seq_length=motion_max_seq_length,
335
+ temporal_transformer_layers_per_block=temporal_transformer_layers_per_block[i],
336
+ temporal_double_self_attention=False,
337
+ )
338
+ else:
339
+ raise ValueError(
340
+ "Invalid `block_type` encountered. Must be one of `CrossAttnDownBlockMotion` or `DownBlockMotion`"
341
+ )
342
+
343
+ self.down_blocks.append(down_block)
344
+
345
+ for _ in range(layers_per_block):
346
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
347
+ controlnet_block = zero_module(controlnet_block)
348
+ self.controlnet_down_blocks.append(controlnet_block)
349
+
350
+ if not is_final_block:
351
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
352
+ controlnet_block = zero_module(controlnet_block)
353
+ self.controlnet_down_blocks.append(controlnet_block)
354
+
355
+ # mid
356
+ mid_block_channels = block_out_channels[-1]
357
+
358
+ controlnet_block = nn.Conv2d(mid_block_channels, mid_block_channels, kernel_size=1)
359
+ controlnet_block = zero_module(controlnet_block)
360
+ self.controlnet_mid_block = controlnet_block
361
+
362
+ if transformer_layers_per_mid_block is None:
363
+ transformer_layers_per_mid_block = (
364
+ transformer_layers_per_block[-1] if isinstance(transformer_layers_per_block[-1], int) else 1
365
+ )
366
+
367
+ self.mid_block = UNetMidBlock2DCrossAttn(
368
+ in_channels=mid_block_channels,
369
+ temb_channels=time_embed_dim,
370
+ dropout=0,
371
+ num_layers=1,
372
+ transformer_layers_per_block=transformer_layers_per_mid_block,
373
+ resnet_eps=norm_eps,
374
+ resnet_time_scale_shift=resnet_time_scale_shift,
375
+ resnet_act_fn=act_fn,
376
+ resnet_groups=norm_num_groups,
377
+ resnet_pre_norm=True,
378
+ num_attention_heads=num_attention_heads[-1],
379
+ output_scale_factor=mid_block_scale_factor,
380
+ cross_attention_dim=cross_attention_dim[-1],
381
+ dual_cross_attention=False,
382
+ use_linear_projection=use_linear_projection,
383
+ upcast_attention=upcast_attention,
384
+ attention_type="default",
385
+ )
386
+
387
+ @classmethod
388
+ def from_unet(
389
+ cls,
390
+ unet: UNet2DConditionModel,
391
+ controlnet_conditioning_channel_order: str = "rgb",
392
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
393
+ load_weights_from_unet: bool = True,
394
+ conditioning_channels: int = 3,
395
+ ) -> "SparseControlNetModel":
396
+ r"""
397
+ Instantiate a [`SparseControlNetModel`] from [`UNet2DConditionModel`].
398
+
399
+ Parameters:
400
+ unet (`UNet2DConditionModel`):
401
+ The UNet model weights to copy to the [`SparseControlNetModel`]. All configuration options are also
402
+ copied where applicable.
403
+ """
404
+ transformer_layers_per_block = (
405
+ unet.config.transformer_layers_per_block if "transformer_layers_per_block" in unet.config else 1
406
+ )
407
+ down_block_types = unet.config.down_block_types
408
+
409
+ for i in range(len(down_block_types)):
410
+ if "CrossAttn" in down_block_types[i]:
411
+ down_block_types[i] = "CrossAttnDownBlockMotion"
412
+ elif "Down" in down_block_types[i]:
413
+ down_block_types[i] = "DownBlockMotion"
414
+ else:
415
+ raise ValueError("Invalid `block_type` encountered. Must be a cross-attention or down block")
416
+
417
+ controlnet = cls(
418
+ in_channels=unet.config.in_channels,
419
+ conditioning_channels=conditioning_channels,
420
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
421
+ freq_shift=unet.config.freq_shift,
422
+ down_block_types=unet.config.down_block_types,
423
+ only_cross_attention=unet.config.only_cross_attention,
424
+ block_out_channels=unet.config.block_out_channels,
425
+ layers_per_block=unet.config.layers_per_block,
426
+ downsample_padding=unet.config.downsample_padding,
427
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
428
+ act_fn=unet.config.act_fn,
429
+ norm_num_groups=unet.config.norm_num_groups,
430
+ norm_eps=unet.config.norm_eps,
431
+ cross_attention_dim=unet.config.cross_attention_dim,
432
+ transformer_layers_per_block=transformer_layers_per_block,
433
+ attention_head_dim=unet.config.attention_head_dim,
434
+ num_attention_heads=unet.config.num_attention_heads,
435
+ use_linear_projection=unet.config.use_linear_projection,
436
+ upcast_attention=unet.config.upcast_attention,
437
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
438
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
439
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
440
+ )
441
+
442
+ if load_weights_from_unet:
443
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict(), strict=False)
444
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict(), strict=False)
445
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict(), strict=False)
446
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict(), strict=False)
447
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict(), strict=False)
448
+
449
+ return controlnet
450
+
451
+ @property
452
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
453
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
454
+ r"""
455
+ Returns:
456
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
457
+ indexed by its weight name.
458
+ """
459
+ # set recursively
460
+ processors = {}
461
+
462
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
463
+ if hasattr(module, "get_processor"):
464
+ processors[f"{name}.processor"] = module.get_processor()
465
+
466
+ for sub_name, child in module.named_children():
467
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
468
+
469
+ return processors
470
+
471
+ for name, module in self.named_children():
472
+ fn_recursive_add_processors(name, module, processors)
473
+
474
+ return processors
475
+
476
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
477
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
478
+ r"""
479
+ Sets the attention processor to use to compute attention.
480
+
481
+ Parameters:
482
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
483
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
484
+ for **all** `Attention` layers.
485
+
486
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
487
+ processor. This is strongly recommended when setting trainable attention processors.
488
+
489
+ """
490
+ count = len(self.attn_processors.keys())
491
+
492
+ if isinstance(processor, dict) and len(processor) != count:
493
+ raise ValueError(
494
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
495
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
496
+ )
497
+
498
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
499
+ if hasattr(module, "set_processor"):
500
+ if not isinstance(processor, dict):
501
+ module.set_processor(processor)
502
+ else:
503
+ module.set_processor(processor.pop(f"{name}.processor"))
504
+
505
+ for sub_name, child in module.named_children():
506
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
507
+
508
+ for name, module in self.named_children():
509
+ fn_recursive_attn_processor(name, module, processor)
510
+
511
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
512
+ def set_default_attn_processor(self):
513
+ """
514
+ Disables custom attention processors and sets the default attention implementation.
515
+ """
516
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
517
+ processor = AttnAddedKVProcessor()
518
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
519
+ processor = AttnProcessor()
520
+ else:
521
+ raise ValueError(
522
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
523
+ )
524
+
525
+ self.set_attn_processor(processor)
526
+
527
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attention_slice
528
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
529
+ r"""
530
+ Enable sliced attention computation.
531
+
532
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
533
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
534
+
535
+ Args:
536
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
537
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
538
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
539
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
540
+ must be a multiple of `slice_size`.
541
+ """
542
+ sliceable_head_dims = []
543
+
544
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
545
+ if hasattr(module, "set_attention_slice"):
546
+ sliceable_head_dims.append(module.sliceable_head_dim)
547
+
548
+ for child in module.children():
549
+ fn_recursive_retrieve_sliceable_dims(child)
550
+
551
+ # retrieve number of attention layers
552
+ for module in self.children():
553
+ fn_recursive_retrieve_sliceable_dims(module)
554
+
555
+ num_sliceable_layers = len(sliceable_head_dims)
556
+
557
+ if slice_size == "auto":
558
+ # half the attention head size is usually a good trade-off between
559
+ # speed and memory
560
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
561
+ elif slice_size == "max":
562
+ # make smallest slice possible
563
+ slice_size = num_sliceable_layers * [1]
564
+
565
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
566
+
567
+ if len(slice_size) != len(sliceable_head_dims):
568
+ raise ValueError(
569
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
570
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
571
+ )
572
+
573
+ for i in range(len(slice_size)):
574
+ size = slice_size[i]
575
+ dim = sliceable_head_dims[i]
576
+ if size is not None and size > dim:
577
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
578
+
579
+ # Recursively walk through all the children.
580
+ # Any children which exposes the set_attention_slice method
581
+ # gets the message
582
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
583
+ if hasattr(module, "set_attention_slice"):
584
+ module.set_attention_slice(slice_size.pop())
585
+
586
+ for child in module.children():
587
+ fn_recursive_set_attention_slice(child, slice_size)
588
+
589
+ reversed_slice_size = list(reversed(slice_size))
590
+ for module in self.children():
591
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
592
+
593
+ def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
594
+ if isinstance(module, (CrossAttnDownBlockMotion, DownBlockMotion, UNetMidBlock2DCrossAttn)):
595
+ module.gradient_checkpointing = value
596
+
597
+ def forward(
598
+ self,
599
+ sample: torch.Tensor,
600
+ timestep: Union[torch.Tensor, float, int],
601
+ encoder_hidden_states: torch.Tensor,
602
+ controlnet_cond: torch.Tensor,
603
+ conditioning_scale: float = 1.0,
604
+ timestep_cond: Optional[torch.Tensor] = None,
605
+ attention_mask: Optional[torch.Tensor] = None,
606
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
607
+ conditioning_mask: Optional[torch.Tensor] = None,
608
+ guess_mode: bool = False,
609
+ return_dict: bool = True,
610
+ ) -> Union[SparseControlNetOutput, Tuple[Tuple[torch.Tensor, ...], torch.Tensor]]:
611
+ """
612
+ The [`SparseControlNetModel`] forward method.
613
+
614
+ Args:
615
+ sample (`torch.Tensor`):
616
+ The noisy input tensor.
617
+ timestep (`Union[torch.Tensor, float, int]`):
618
+ The number of timesteps to denoise an input.
619
+ encoder_hidden_states (`torch.Tensor`):
620
+ The encoder hidden states.
621
+ controlnet_cond (`torch.Tensor`):
622
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
623
+ conditioning_scale (`float`, defaults to `1.0`):
624
+ The scale factor for ControlNet outputs.
625
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
626
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
627
+ timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
628
+ Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
629
+ timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
630
+ embeddings.
631
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
632
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
633
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
634
+ negative values to the attention scores corresponding to "discard" tokens.
635
+ added_cond_kwargs (`dict`):
636
+ Additional conditions for the Stable Diffusion XL UNet.
637
+ cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
638
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
639
+ guess_mode (`bool`, defaults to `False`):
640
+ In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
641
+ you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
642
+ return_dict (`bool`, defaults to `True`):
643
+ Whether or not to return a [`~models.controlnet.ControlNetOutput`] instead of a plain tuple.
644
+ Returns:
645
+ [`~models.controlnet.ControlNetOutput`] **or** `tuple`:
646
+ If `return_dict` is `True`, a [`~models.controlnet.ControlNetOutput`] is returned, otherwise a tuple is
647
+ returned where the first element is the sample tensor.
648
+ """
649
+ sample_batch_size, sample_channels, sample_num_frames, sample_height, sample_width = sample.shape
650
+ sample = torch.zeros_like(sample)
651
+
652
+ # check channel order
653
+ channel_order = self.config.controlnet_conditioning_channel_order
654
+
655
+ if channel_order == "rgb":
656
+ # in rgb order by default
657
+ ...
658
+ elif channel_order == "bgr":
659
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
660
+ else:
661
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
662
+
663
+ # prepare attention_mask
664
+ if attention_mask is not None:
665
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
666
+ attention_mask = attention_mask.unsqueeze(1)
667
+
668
+ # 1. time
669
+ timesteps = timestep
670
+ if not torch.is_tensor(timesteps):
671
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
672
+ # This would be a good case for the `match` statement (Python 3.10+)
673
+ is_mps = sample.device.type == "mps"
674
+ if isinstance(timestep, float):
675
+ dtype = torch.float32 if is_mps else torch.float64
676
+ else:
677
+ dtype = torch.int32 if is_mps else torch.int64
678
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
679
+ elif len(timesteps.shape) == 0:
680
+ timesteps = timesteps[None].to(sample.device)
681
+
682
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
683
+ timesteps = timesteps.expand(sample.shape[0])
684
+
685
+ t_emb = self.time_proj(timesteps)
686
+
687
+ # timesteps does not contain any weights and will always return f32 tensors
688
+ # but time_embedding might actually be running in fp16. so we need to cast here.
689
+ # there might be better ways to encapsulate this.
690
+ t_emb = t_emb.to(dtype=sample.dtype)
691
+
692
+ emb = self.time_embedding(t_emb, timestep_cond)
693
+ emb = emb.repeat_interleave(sample_num_frames, dim=0)
694
+
695
+ # 2. pre-process
696
+ batch_size, channels, num_frames, height, width = sample.shape
697
+
698
+ sample = sample.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
699
+ sample = self.conv_in(sample)
700
+
701
+ batch_frames, channels, height, width = sample.shape
702
+ sample = sample[:, None].reshape(sample_batch_size, sample_num_frames, channels, height, width)
703
+
704
+ if self.concat_conditioning_mask:
705
+ controlnet_cond = torch.cat([controlnet_cond, conditioning_mask], dim=1)
706
+
707
+ batch_size, channels, num_frames, height, width = controlnet_cond.shape
708
+ controlnet_cond = controlnet_cond.permute(0, 2, 1, 3, 4).reshape(
709
+ batch_size * num_frames, channels, height, width
710
+ )
711
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
712
+ batch_frames, channels, height, width = controlnet_cond.shape
713
+ controlnet_cond = controlnet_cond[:, None].reshape(batch_size, num_frames, channels, height, width)
714
+
715
+ sample = sample + controlnet_cond
716
+
717
+ batch_size, num_frames, channels, height, width = sample.shape
718
+ sample = sample.reshape(sample_batch_size * sample_num_frames, channels, height, width)
719
+
720
+ # 3. down
721
+ down_block_res_samples = (sample,)
722
+ for downsample_block in self.down_blocks:
723
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
724
+ sample, res_samples = downsample_block(
725
+ hidden_states=sample,
726
+ temb=emb,
727
+ encoder_hidden_states=encoder_hidden_states,
728
+ attention_mask=attention_mask,
729
+ num_frames=num_frames,
730
+ cross_attention_kwargs=cross_attention_kwargs,
731
+ )
732
+ else:
733
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb, num_frames=num_frames)
734
+
735
+ down_block_res_samples += res_samples
736
+
737
+ # 4. mid
738
+ if self.mid_block is not None:
739
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
740
+ sample = self.mid_block(
741
+ sample,
742
+ emb,
743
+ encoder_hidden_states=encoder_hidden_states,
744
+ attention_mask=attention_mask,
745
+ cross_attention_kwargs=cross_attention_kwargs,
746
+ )
747
+ else:
748
+ sample = self.mid_block(sample, emb)
749
+
750
+ # 5. Control net blocks
751
+ controlnet_down_block_res_samples = ()
752
+
753
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
754
+ down_block_res_sample = controlnet_block(down_block_res_sample)
755
+ controlnet_down_block_res_samples = controlnet_down_block_res_samples + (down_block_res_sample,)
756
+
757
+ down_block_res_samples = controlnet_down_block_res_samples
758
+ mid_block_res_sample = self.controlnet_mid_block(sample)
759
+
760
+ # 6. scaling
761
+ if guess_mode and not self.config.global_pool_conditions:
762
+ scales = torch.logspace(-1, 0, len(down_block_res_samples) + 1, device=sample.device) # 0.1 to 1.0
763
+ scales = scales * conditioning_scale
764
+ down_block_res_samples = [sample * scale for sample, scale in zip(down_block_res_samples, scales)]
765
+ mid_block_res_sample = mid_block_res_sample * scales[-1] # last one
766
+ else:
767
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
768
+ mid_block_res_sample = mid_block_res_sample * conditioning_scale
769
+
770
+ if self.config.global_pool_conditions:
771
+ down_block_res_samples = [
772
+ torch.mean(sample, dim=(2, 3), keepdim=True) for sample in down_block_res_samples
773
+ ]
774
+ mid_block_res_sample = torch.mean(mid_block_res_sample, dim=(2, 3), keepdim=True)
775
+
776
+ if not return_dict:
777
+ return (down_block_res_samples, mid_block_res_sample)
778
+
779
+ return SparseControlNetOutput(
780
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
781
+ )
782
+
783
+
784
+ # Copied from diffusers.models.controlnets.controlnet.zero_module
785
+ def zero_module(module: nn.Module) -> nn.Module:
786
+ for p in module.parameters():
787
+ nn.init.zeros_(p)
788
+ return module