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
@@ -12,6 +12,7 @@
12
12
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  # See the License for the specific language governing permissions and
14
14
  # limitations under the License.
15
+
15
16
  from dataclasses import dataclass
16
17
  from typing import Any, Dict, List, Optional, Tuple, Union
17
18
 
@@ -22,6 +23,7 @@ import torch.utils.checkpoint
22
23
  from ..configuration_utils import ConfigMixin, register_to_config
23
24
  from ..loaders import UNet2DConditionLoadersMixin
24
25
  from ..utils import BaseOutput, logging
26
+ from .activations import get_activation
25
27
  from .attention_processor import (
26
28
  ADDED_KV_ATTENTION_PROCESSORS,
27
29
  CROSS_ATTENTION_PROCESSORS,
@@ -98,14 +100,19 @@ class UNet3DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin)
98
100
  sample_size: Optional[int] = None,
99
101
  in_channels: int = 4,
100
102
  out_channels: int = 4,
101
- down_block_types: Tuple[str] = (
103
+ down_block_types: Tuple[str, ...] = (
102
104
  "CrossAttnDownBlock3D",
103
105
  "CrossAttnDownBlock3D",
104
106
  "CrossAttnDownBlock3D",
105
107
  "DownBlock3D",
106
108
  ),
107
- up_block_types: Tuple[str] = ("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D"),
108
- block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
109
+ up_block_types: Tuple[str, ...] = (
110
+ "UpBlock3D",
111
+ "CrossAttnUpBlock3D",
112
+ "CrossAttnUpBlock3D",
113
+ "CrossAttnUpBlock3D",
114
+ ),
115
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
109
116
  layers_per_block: int = 2,
110
117
  downsample_padding: int = 1,
111
118
  mid_block_scale_factor: float = 1,
@@ -173,6 +180,7 @@ class UNet3DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin)
173
180
  attention_head_dim=attention_head_dim,
174
181
  in_channels=block_out_channels[0],
175
182
  num_layers=1,
183
+ norm_num_groups=norm_num_groups,
176
184
  )
177
185
 
178
186
  # class embedding
@@ -265,7 +273,7 @@ class UNet3DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin)
265
273
  self.conv_norm_out = nn.GroupNorm(
266
274
  num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
267
275
  )
268
- self.conv_act = nn.SiLU()
276
+ self.conv_act = get_activation("silu")
269
277
  else:
270
278
  self.conv_norm_out = None
271
279
  self.conv_act = None
@@ -301,7 +309,7 @@ class UNet3DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin)
301
309
  return processors
302
310
 
303
311
  # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice
304
- def set_attention_slice(self, slice_size):
312
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
305
313
  r"""
306
314
  Enable sliced attention computation.
307
315
 
@@ -403,7 +411,7 @@ class UNet3DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin)
403
411
  for name, module in self.named_children():
404
412
  fn_recursive_attn_processor(name, module, processor)
405
413
 
406
- def enable_forward_chunking(self, chunk_size=None, dim=0):
414
+ def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
407
415
  """
408
416
  Sets the attention processor to use [feed forward
409
417
  chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
@@ -459,7 +467,7 @@ class UNet3DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin)
459
467
 
460
468
  self.set_attn_processor(processor, _remove_lora=True)
461
469
 
462
- def _set_gradient_checkpointing(self, module, value=False):
470
+ def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
463
471
  if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):
464
472
  module.gradient_checkpointing = value
465
473
 
@@ -509,7 +517,7 @@ class UNet3DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin)
509
517
  down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
510
518
  mid_block_additional_residual: Optional[torch.Tensor] = None,
511
519
  return_dict: bool = True,
512
- ) -> Union[UNet3DConditionOutput, Tuple]:
520
+ ) -> Union[UNet3DConditionOutput, Tuple[torch.FloatTensor]]:
513
521
  r"""
514
522
  The [`UNet3DConditionModel`] forward method.
515
523
 
@@ -0,0 +1,535 @@
1
+ # Copyright 2023 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 Dict, Tuple, Union
17
+
18
+ import torch
19
+ import torch.utils.checkpoint
20
+ from torch import nn
21
+
22
+ from ..configuration_utils import ConfigMixin, register_to_config
23
+ from ..utils import BaseOutput, logging
24
+ from .attention_processor import Attention, AttentionProcessor, AttnProcessor
25
+ from .embeddings import TimestepEmbedding, Timesteps
26
+ from .modeling_utils import ModelMixin
27
+
28
+
29
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
30
+
31
+
32
+ @dataclass
33
+ class Kandinsky3UNetOutput(BaseOutput):
34
+ sample: torch.FloatTensor = None
35
+
36
+
37
+ class Kandinsky3EncoderProj(nn.Module):
38
+ def __init__(self, encoder_hid_dim, cross_attention_dim):
39
+ super().__init__()
40
+ self.projection_linear = nn.Linear(encoder_hid_dim, cross_attention_dim, bias=False)
41
+ self.projection_norm = nn.LayerNorm(cross_attention_dim)
42
+
43
+ def forward(self, x):
44
+ x = self.projection_linear(x)
45
+ x = self.projection_norm(x)
46
+ return x
47
+
48
+
49
+ class Kandinsky3UNet(ModelMixin, ConfigMixin):
50
+ @register_to_config
51
+ def __init__(
52
+ self,
53
+ in_channels: int = 4,
54
+ time_embedding_dim: int = 1536,
55
+ groups: int = 32,
56
+ attention_head_dim: int = 64,
57
+ layers_per_block: Union[int, Tuple[int]] = 3,
58
+ block_out_channels: Tuple[int] = (384, 768, 1536, 3072),
59
+ cross_attention_dim: Union[int, Tuple[int]] = 4096,
60
+ encoder_hid_dim: int = 4096,
61
+ ):
62
+ super().__init__()
63
+
64
+ # TOOD(Yiyi): Give better name and put into config for the following 4 parameters
65
+ expansion_ratio = 4
66
+ compression_ratio = 2
67
+ add_cross_attention = (False, True, True, True)
68
+ add_self_attention = (False, True, True, True)
69
+
70
+ out_channels = in_channels
71
+ init_channels = block_out_channels[0] // 2
72
+ self.time_proj = Timesteps(init_channels, flip_sin_to_cos=False, downscale_freq_shift=1)
73
+
74
+ self.time_embedding = TimestepEmbedding(
75
+ init_channels,
76
+ time_embedding_dim,
77
+ )
78
+
79
+ self.add_time_condition = Kandinsky3AttentionPooling(
80
+ time_embedding_dim, cross_attention_dim, attention_head_dim
81
+ )
82
+
83
+ self.conv_in = nn.Conv2d(in_channels, init_channels, kernel_size=3, padding=1)
84
+
85
+ self.encoder_hid_proj = Kandinsky3EncoderProj(encoder_hid_dim, cross_attention_dim)
86
+
87
+ hidden_dims = [init_channels] + list(block_out_channels)
88
+ in_out_dims = list(zip(hidden_dims[:-1], hidden_dims[1:]))
89
+ text_dims = [cross_attention_dim if is_exist else None for is_exist in add_cross_attention]
90
+ num_blocks = len(block_out_channels) * [layers_per_block]
91
+ layer_params = [num_blocks, text_dims, add_self_attention]
92
+ rev_layer_params = map(reversed, layer_params)
93
+
94
+ cat_dims = []
95
+ self.num_levels = len(in_out_dims)
96
+ self.down_blocks = nn.ModuleList([])
97
+ for level, ((in_dim, out_dim), res_block_num, text_dim, self_attention) in enumerate(
98
+ zip(in_out_dims, *layer_params)
99
+ ):
100
+ down_sample = level != (self.num_levels - 1)
101
+ cat_dims.append(out_dim if level != (self.num_levels - 1) else 0)
102
+ self.down_blocks.append(
103
+ Kandinsky3DownSampleBlock(
104
+ in_dim,
105
+ out_dim,
106
+ time_embedding_dim,
107
+ text_dim,
108
+ res_block_num,
109
+ groups,
110
+ attention_head_dim,
111
+ expansion_ratio,
112
+ compression_ratio,
113
+ down_sample,
114
+ self_attention,
115
+ )
116
+ )
117
+
118
+ self.up_blocks = nn.ModuleList([])
119
+ for level, ((out_dim, in_dim), res_block_num, text_dim, self_attention) in enumerate(
120
+ zip(reversed(in_out_dims), *rev_layer_params)
121
+ ):
122
+ up_sample = level != 0
123
+ self.up_blocks.append(
124
+ Kandinsky3UpSampleBlock(
125
+ in_dim,
126
+ cat_dims.pop(),
127
+ out_dim,
128
+ time_embedding_dim,
129
+ text_dim,
130
+ res_block_num,
131
+ groups,
132
+ attention_head_dim,
133
+ expansion_ratio,
134
+ compression_ratio,
135
+ up_sample,
136
+ self_attention,
137
+ )
138
+ )
139
+
140
+ self.conv_norm_out = nn.GroupNorm(groups, init_channels)
141
+ self.conv_act_out = nn.SiLU()
142
+ self.conv_out = nn.Conv2d(init_channels, out_channels, kernel_size=3, padding=1)
143
+
144
+ @property
145
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
146
+ r"""
147
+ Returns:
148
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
149
+ indexed by its weight name.
150
+ """
151
+ # set recursively
152
+ processors = {}
153
+
154
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
155
+ if hasattr(module, "set_processor"):
156
+ processors[f"{name}.processor"] = module.processor
157
+
158
+ for sub_name, child in module.named_children():
159
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
160
+
161
+ return processors
162
+
163
+ for name, module in self.named_children():
164
+ fn_recursive_add_processors(name, module, processors)
165
+
166
+ return processors
167
+
168
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
169
+ r"""
170
+ Sets the attention processor to use to compute attention.
171
+
172
+ Parameters:
173
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
174
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
175
+ for **all** `Attention` layers.
176
+
177
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
178
+ processor. This is strongly recommended when setting trainable attention processors.
179
+
180
+ """
181
+ count = len(self.attn_processors.keys())
182
+
183
+ if isinstance(processor, dict) and len(processor) != count:
184
+ raise ValueError(
185
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
186
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
187
+ )
188
+
189
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
190
+ if hasattr(module, "set_processor"):
191
+ if not isinstance(processor, dict):
192
+ module.set_processor(processor)
193
+ else:
194
+ module.set_processor(processor.pop(f"{name}.processor"))
195
+
196
+ for sub_name, child in module.named_children():
197
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
198
+
199
+ for name, module in self.named_children():
200
+ fn_recursive_attn_processor(name, module, processor)
201
+
202
+ def set_default_attn_processor(self):
203
+ """
204
+ Disables custom attention processors and sets the default attention implementation.
205
+ """
206
+ self.set_attn_processor(AttnProcessor())
207
+
208
+ def _set_gradient_checkpointing(self, module, value=False):
209
+ if hasattr(module, "gradient_checkpointing"):
210
+ module.gradient_checkpointing = value
211
+
212
+ def forward(self, sample, timestep, encoder_hidden_states=None, encoder_attention_mask=None, return_dict=True):
213
+ if encoder_attention_mask is not None:
214
+ encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
215
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
216
+
217
+ if not torch.is_tensor(timestep):
218
+ dtype = torch.float32 if isinstance(timestep, float) else torch.int32
219
+ timestep = torch.tensor([timestep], dtype=dtype, device=sample.device)
220
+ elif len(timestep.shape) == 0:
221
+ timestep = timestep[None].to(sample.device)
222
+
223
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
224
+ timestep = timestep.expand(sample.shape[0])
225
+ time_embed_input = self.time_proj(timestep).to(sample.dtype)
226
+ time_embed = self.time_embedding(time_embed_input)
227
+
228
+ encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
229
+
230
+ if encoder_hidden_states is not None:
231
+ time_embed = self.add_time_condition(time_embed, encoder_hidden_states, encoder_attention_mask)
232
+
233
+ hidden_states = []
234
+ sample = self.conv_in(sample)
235
+ for level, down_sample in enumerate(self.down_blocks):
236
+ sample = down_sample(sample, time_embed, encoder_hidden_states, encoder_attention_mask)
237
+ if level != self.num_levels - 1:
238
+ hidden_states.append(sample)
239
+
240
+ for level, up_sample in enumerate(self.up_blocks):
241
+ if level != 0:
242
+ sample = torch.cat([sample, hidden_states.pop()], dim=1)
243
+ sample = up_sample(sample, time_embed, encoder_hidden_states, encoder_attention_mask)
244
+
245
+ sample = self.conv_norm_out(sample)
246
+ sample = self.conv_act_out(sample)
247
+ sample = self.conv_out(sample)
248
+
249
+ if not return_dict:
250
+ return (sample,)
251
+ return Kandinsky3UNetOutput(sample=sample)
252
+
253
+
254
+ class Kandinsky3UpSampleBlock(nn.Module):
255
+ def __init__(
256
+ self,
257
+ in_channels,
258
+ cat_dim,
259
+ out_channels,
260
+ time_embed_dim,
261
+ context_dim=None,
262
+ num_blocks=3,
263
+ groups=32,
264
+ head_dim=64,
265
+ expansion_ratio=4,
266
+ compression_ratio=2,
267
+ up_sample=True,
268
+ self_attention=True,
269
+ ):
270
+ super().__init__()
271
+ up_resolutions = [[None, True if up_sample else None, None, None]] + [[None] * 4] * (num_blocks - 1)
272
+ hidden_channels = (
273
+ [(in_channels + cat_dim, in_channels)]
274
+ + [(in_channels, in_channels)] * (num_blocks - 2)
275
+ + [(in_channels, out_channels)]
276
+ )
277
+ attentions = []
278
+ resnets_in = []
279
+ resnets_out = []
280
+
281
+ self.self_attention = self_attention
282
+ self.context_dim = context_dim
283
+
284
+ if self_attention:
285
+ attentions.append(
286
+ Kandinsky3AttentionBlock(out_channels, time_embed_dim, None, groups, head_dim, expansion_ratio)
287
+ )
288
+ else:
289
+ attentions.append(nn.Identity())
290
+
291
+ for (in_channel, out_channel), up_resolution in zip(hidden_channels, up_resolutions):
292
+ resnets_in.append(
293
+ Kandinsky3ResNetBlock(in_channel, in_channel, time_embed_dim, groups, compression_ratio, up_resolution)
294
+ )
295
+
296
+ if context_dim is not None:
297
+ attentions.append(
298
+ Kandinsky3AttentionBlock(
299
+ in_channel, time_embed_dim, context_dim, groups, head_dim, expansion_ratio
300
+ )
301
+ )
302
+ else:
303
+ attentions.append(nn.Identity())
304
+
305
+ resnets_out.append(
306
+ Kandinsky3ResNetBlock(in_channel, out_channel, time_embed_dim, groups, compression_ratio)
307
+ )
308
+
309
+ self.attentions = nn.ModuleList(attentions)
310
+ self.resnets_in = nn.ModuleList(resnets_in)
311
+ self.resnets_out = nn.ModuleList(resnets_out)
312
+
313
+ def forward(self, x, time_embed, context=None, context_mask=None, image_mask=None):
314
+ for attention, resnet_in, resnet_out in zip(self.attentions[1:], self.resnets_in, self.resnets_out):
315
+ x = resnet_in(x, time_embed)
316
+ if self.context_dim is not None:
317
+ x = attention(x, time_embed, context, context_mask, image_mask)
318
+ x = resnet_out(x, time_embed)
319
+
320
+ if self.self_attention:
321
+ x = self.attentions[0](x, time_embed, image_mask=image_mask)
322
+ return x
323
+
324
+
325
+ class Kandinsky3DownSampleBlock(nn.Module):
326
+ def __init__(
327
+ self,
328
+ in_channels,
329
+ out_channels,
330
+ time_embed_dim,
331
+ context_dim=None,
332
+ num_blocks=3,
333
+ groups=32,
334
+ head_dim=64,
335
+ expansion_ratio=4,
336
+ compression_ratio=2,
337
+ down_sample=True,
338
+ self_attention=True,
339
+ ):
340
+ super().__init__()
341
+ attentions = []
342
+ resnets_in = []
343
+ resnets_out = []
344
+
345
+ self.self_attention = self_attention
346
+ self.context_dim = context_dim
347
+
348
+ if self_attention:
349
+ attentions.append(
350
+ Kandinsky3AttentionBlock(in_channels, time_embed_dim, None, groups, head_dim, expansion_ratio)
351
+ )
352
+ else:
353
+ attentions.append(nn.Identity())
354
+
355
+ up_resolutions = [[None] * 4] * (num_blocks - 1) + [[None, None, False if down_sample else None, None]]
356
+ hidden_channels = [(in_channels, out_channels)] + [(out_channels, out_channels)] * (num_blocks - 1)
357
+ for (in_channel, out_channel), up_resolution in zip(hidden_channels, up_resolutions):
358
+ resnets_in.append(
359
+ Kandinsky3ResNetBlock(in_channel, out_channel, time_embed_dim, groups, compression_ratio)
360
+ )
361
+
362
+ if context_dim is not None:
363
+ attentions.append(
364
+ Kandinsky3AttentionBlock(
365
+ out_channel, time_embed_dim, context_dim, groups, head_dim, expansion_ratio
366
+ )
367
+ )
368
+ else:
369
+ attentions.append(nn.Identity())
370
+
371
+ resnets_out.append(
372
+ Kandinsky3ResNetBlock(
373
+ out_channel, out_channel, time_embed_dim, groups, compression_ratio, up_resolution
374
+ )
375
+ )
376
+
377
+ self.attentions = nn.ModuleList(attentions)
378
+ self.resnets_in = nn.ModuleList(resnets_in)
379
+ self.resnets_out = nn.ModuleList(resnets_out)
380
+
381
+ def forward(self, x, time_embed, context=None, context_mask=None, image_mask=None):
382
+ if self.self_attention:
383
+ x = self.attentions[0](x, time_embed, image_mask=image_mask)
384
+
385
+ for attention, resnet_in, resnet_out in zip(self.attentions[1:], self.resnets_in, self.resnets_out):
386
+ x = resnet_in(x, time_embed)
387
+ if self.context_dim is not None:
388
+ x = attention(x, time_embed, context, context_mask, image_mask)
389
+ x = resnet_out(x, time_embed)
390
+ return x
391
+
392
+
393
+ class Kandinsky3ConditionalGroupNorm(nn.Module):
394
+ def __init__(self, groups, normalized_shape, context_dim):
395
+ super().__init__()
396
+ self.norm = nn.GroupNorm(groups, normalized_shape, affine=False)
397
+ self.context_mlp = nn.Sequential(nn.SiLU(), nn.Linear(context_dim, 2 * normalized_shape))
398
+ self.context_mlp[1].weight.data.zero_()
399
+ self.context_mlp[1].bias.data.zero_()
400
+
401
+ def forward(self, x, context):
402
+ context = self.context_mlp(context)
403
+
404
+ for _ in range(len(x.shape[2:])):
405
+ context = context.unsqueeze(-1)
406
+
407
+ scale, shift = context.chunk(2, dim=1)
408
+ x = self.norm(x) * (scale + 1.0) + shift
409
+ return x
410
+
411
+
412
+ class Kandinsky3Block(nn.Module):
413
+ def __init__(self, in_channels, out_channels, time_embed_dim, kernel_size=3, norm_groups=32, up_resolution=None):
414
+ super().__init__()
415
+ self.group_norm = Kandinsky3ConditionalGroupNorm(norm_groups, in_channels, time_embed_dim)
416
+ self.activation = nn.SiLU()
417
+ if up_resolution is not None and up_resolution:
418
+ self.up_sample = nn.ConvTranspose2d(in_channels, in_channels, kernel_size=2, stride=2)
419
+ else:
420
+ self.up_sample = nn.Identity()
421
+
422
+ padding = int(kernel_size > 1)
423
+ self.projection = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, padding=padding)
424
+
425
+ if up_resolution is not None and not up_resolution:
426
+ self.down_sample = nn.Conv2d(out_channels, out_channels, kernel_size=2, stride=2)
427
+ else:
428
+ self.down_sample = nn.Identity()
429
+
430
+ def forward(self, x, time_embed):
431
+ x = self.group_norm(x, time_embed)
432
+ x = self.activation(x)
433
+ x = self.up_sample(x)
434
+ x = self.projection(x)
435
+ x = self.down_sample(x)
436
+ return x
437
+
438
+
439
+ class Kandinsky3ResNetBlock(nn.Module):
440
+ def __init__(
441
+ self, in_channels, out_channels, time_embed_dim, norm_groups=32, compression_ratio=2, up_resolutions=4 * [None]
442
+ ):
443
+ super().__init__()
444
+ kernel_sizes = [1, 3, 3, 1]
445
+ hidden_channel = max(in_channels, out_channels) // compression_ratio
446
+ hidden_channels = (
447
+ [(in_channels, hidden_channel)] + [(hidden_channel, hidden_channel)] * 2 + [(hidden_channel, out_channels)]
448
+ )
449
+ self.resnet_blocks = nn.ModuleList(
450
+ [
451
+ Kandinsky3Block(in_channel, out_channel, time_embed_dim, kernel_size, norm_groups, up_resolution)
452
+ for (in_channel, out_channel), kernel_size, up_resolution in zip(
453
+ hidden_channels, kernel_sizes, up_resolutions
454
+ )
455
+ ]
456
+ )
457
+ self.shortcut_up_sample = (
458
+ nn.ConvTranspose2d(in_channels, in_channels, kernel_size=2, stride=2)
459
+ if True in up_resolutions
460
+ else nn.Identity()
461
+ )
462
+ self.shortcut_projection = (
463
+ nn.Conv2d(in_channels, out_channels, kernel_size=1) if in_channels != out_channels else nn.Identity()
464
+ )
465
+ self.shortcut_down_sample = (
466
+ nn.Conv2d(out_channels, out_channels, kernel_size=2, stride=2)
467
+ if False in up_resolutions
468
+ else nn.Identity()
469
+ )
470
+
471
+ def forward(self, x, time_embed):
472
+ out = x
473
+ for resnet_block in self.resnet_blocks:
474
+ out = resnet_block(out, time_embed)
475
+
476
+ x = self.shortcut_up_sample(x)
477
+ x = self.shortcut_projection(x)
478
+ x = self.shortcut_down_sample(x)
479
+ x = x + out
480
+ return x
481
+
482
+
483
+ class Kandinsky3AttentionPooling(nn.Module):
484
+ def __init__(self, num_channels, context_dim, head_dim=64):
485
+ super().__init__()
486
+ self.attention = Attention(
487
+ context_dim,
488
+ context_dim,
489
+ dim_head=head_dim,
490
+ out_dim=num_channels,
491
+ out_bias=False,
492
+ )
493
+
494
+ def forward(self, x, context, context_mask=None):
495
+ context_mask = context_mask.to(dtype=context.dtype)
496
+ context = self.attention(context.mean(dim=1, keepdim=True), context, context_mask)
497
+ return x + context.squeeze(1)
498
+
499
+
500
+ class Kandinsky3AttentionBlock(nn.Module):
501
+ def __init__(self, num_channels, time_embed_dim, context_dim=None, norm_groups=32, head_dim=64, expansion_ratio=4):
502
+ super().__init__()
503
+ self.in_norm = Kandinsky3ConditionalGroupNorm(norm_groups, num_channels, time_embed_dim)
504
+ self.attention = Attention(
505
+ num_channels,
506
+ context_dim or num_channels,
507
+ dim_head=head_dim,
508
+ out_dim=num_channels,
509
+ out_bias=False,
510
+ )
511
+
512
+ hidden_channels = expansion_ratio * num_channels
513
+ self.out_norm = Kandinsky3ConditionalGroupNorm(norm_groups, num_channels, time_embed_dim)
514
+ self.feed_forward = nn.Sequential(
515
+ nn.Conv2d(num_channels, hidden_channels, kernel_size=1, bias=False),
516
+ nn.SiLU(),
517
+ nn.Conv2d(hidden_channels, num_channels, kernel_size=1, bias=False),
518
+ )
519
+
520
+ def forward(self, x, time_embed, context=None, context_mask=None, image_mask=None):
521
+ height, width = x.shape[-2:]
522
+ out = self.in_norm(x, time_embed)
523
+ out = out.reshape(x.shape[0], -1, height * width).permute(0, 2, 1)
524
+ context = context if context is not None else out
525
+ if context_mask is not None:
526
+ context_mask = context_mask.to(dtype=context.dtype)
527
+
528
+ out = self.attention(out, context, context_mask)
529
+ out = out.permute(0, 2, 1).unsqueeze(-1).reshape(out.shape[0], -1, height, width)
530
+ x = x + out
531
+
532
+ out = self.out_norm(x, time_embed)
533
+ out = self.feed_forward(out)
534
+ x = x + out
535
+ return x