diffusers 0.29.2__py3-none-any.whl → 0.30.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 (220) hide show
  1. diffusers/__init__.py +94 -3
  2. diffusers/commands/env.py +1 -5
  3. diffusers/configuration_utils.py +4 -9
  4. diffusers/dependency_versions_table.py +2 -2
  5. diffusers/image_processor.py +1 -2
  6. diffusers/loaders/__init__.py +17 -2
  7. diffusers/loaders/ip_adapter.py +10 -7
  8. diffusers/loaders/lora_base.py +752 -0
  9. diffusers/loaders/lora_pipeline.py +2252 -0
  10. diffusers/loaders/peft.py +213 -5
  11. diffusers/loaders/single_file.py +3 -14
  12. diffusers/loaders/single_file_model.py +31 -10
  13. diffusers/loaders/single_file_utils.py +293 -8
  14. diffusers/loaders/textual_inversion.py +1 -6
  15. diffusers/loaders/unet.py +23 -208
  16. diffusers/models/__init__.py +20 -0
  17. diffusers/models/activations.py +22 -0
  18. diffusers/models/attention.py +386 -7
  19. diffusers/models/attention_processor.py +1937 -629
  20. diffusers/models/autoencoders/__init__.py +2 -0
  21. diffusers/models/autoencoders/autoencoder_kl.py +14 -3
  22. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1271 -0
  23. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +1 -1
  24. diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
  25. diffusers/models/autoencoders/autoencoder_tiny.py +1 -0
  26. diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
  27. diffusers/models/autoencoders/vq_model.py +4 -4
  28. diffusers/models/controlnet.py +2 -3
  29. diffusers/models/controlnet_hunyuan.py +401 -0
  30. diffusers/models/controlnet_sd3.py +11 -11
  31. diffusers/models/controlnet_sparsectrl.py +789 -0
  32. diffusers/models/controlnet_xs.py +40 -10
  33. diffusers/models/downsampling.py +68 -0
  34. diffusers/models/embeddings.py +403 -36
  35. diffusers/models/model_loading_utils.py +1 -3
  36. diffusers/models/modeling_flax_utils.py +1 -6
  37. diffusers/models/modeling_utils.py +4 -16
  38. diffusers/models/normalization.py +203 -12
  39. diffusers/models/transformers/__init__.py +6 -0
  40. diffusers/models/transformers/auraflow_transformer_2d.py +543 -0
  41. diffusers/models/transformers/cogvideox_transformer_3d.py +485 -0
  42. diffusers/models/transformers/hunyuan_transformer_2d.py +19 -15
  43. diffusers/models/transformers/latte_transformer_3d.py +327 -0
  44. diffusers/models/transformers/lumina_nextdit2d.py +340 -0
  45. diffusers/models/transformers/pixart_transformer_2d.py +102 -1
  46. diffusers/models/transformers/prior_transformer.py +1 -1
  47. diffusers/models/transformers/stable_audio_transformer.py +458 -0
  48. diffusers/models/transformers/transformer_flux.py +455 -0
  49. diffusers/models/transformers/transformer_sd3.py +18 -4
  50. diffusers/models/unets/unet_1d_blocks.py +1 -1
  51. diffusers/models/unets/unet_2d_condition.py +8 -1
  52. diffusers/models/unets/unet_3d_blocks.py +51 -920
  53. diffusers/models/unets/unet_3d_condition.py +4 -1
  54. diffusers/models/unets/unet_i2vgen_xl.py +4 -1
  55. diffusers/models/unets/unet_kandinsky3.py +1 -1
  56. diffusers/models/unets/unet_motion_model.py +1330 -84
  57. diffusers/models/unets/unet_spatio_temporal_condition.py +1 -1
  58. diffusers/models/unets/unet_stable_cascade.py +1 -3
  59. diffusers/models/unets/uvit_2d.py +1 -1
  60. diffusers/models/upsampling.py +64 -0
  61. diffusers/models/vq_model.py +8 -4
  62. diffusers/optimization.py +1 -1
  63. diffusers/pipelines/__init__.py +100 -3
  64. diffusers/pipelines/animatediff/__init__.py +4 -0
  65. diffusers/pipelines/animatediff/pipeline_animatediff.py +50 -40
  66. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1076 -0
  67. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +17 -27
  68. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1008 -0
  69. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +51 -38
  70. diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
  71. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +1 -0
  72. diffusers/pipelines/aura_flow/__init__.py +48 -0
  73. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +591 -0
  74. diffusers/pipelines/auto_pipeline.py +97 -19
  75. diffusers/pipelines/cogvideo/__init__.py +48 -0
  76. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +746 -0
  77. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
  78. diffusers/pipelines/controlnet/pipeline_controlnet.py +24 -30
  79. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +31 -30
  80. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +24 -153
  81. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +19 -28
  82. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +18 -28
  83. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +29 -32
  84. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
  85. diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
  86. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1042 -0
  87. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +35 -0
  88. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +10 -6
  89. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +0 -4
  90. diffusers/pipelines/deepfloyd_if/pipeline_if.py +2 -2
  91. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +2 -2
  92. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +2 -2
  93. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +2 -2
  94. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +2 -2
  95. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +2 -2
  96. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +11 -6
  97. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +11 -6
  98. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +6 -6
  99. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +6 -6
  100. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -10
  101. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +10 -6
  102. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +3 -3
  103. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +1 -1
  104. diffusers/pipelines/flux/__init__.py +47 -0
  105. diffusers/pipelines/flux/pipeline_flux.py +749 -0
  106. diffusers/pipelines/flux/pipeline_output.py +21 -0
  107. diffusers/pipelines/free_init_utils.py +2 -0
  108. diffusers/pipelines/free_noise_utils.py +236 -0
  109. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +2 -2
  110. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +2 -2
  111. diffusers/pipelines/kolors/__init__.py +54 -0
  112. diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
  113. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1247 -0
  114. diffusers/pipelines/kolors/pipeline_output.py +21 -0
  115. diffusers/pipelines/kolors/text_encoder.py +889 -0
  116. diffusers/pipelines/kolors/tokenizer.py +334 -0
  117. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +30 -29
  118. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +23 -29
  119. diffusers/pipelines/latte/__init__.py +48 -0
  120. diffusers/pipelines/latte/pipeline_latte.py +881 -0
  121. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +4 -4
  122. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +0 -4
  123. diffusers/pipelines/lumina/__init__.py +48 -0
  124. diffusers/pipelines/lumina/pipeline_lumina.py +897 -0
  125. diffusers/pipelines/pag/__init__.py +67 -0
  126. diffusers/pipelines/pag/pag_utils.py +237 -0
  127. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1329 -0
  128. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1612 -0
  129. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +953 -0
  130. diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
  131. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +872 -0
  132. diffusers/pipelines/pag/pipeline_pag_sd.py +1050 -0
  133. diffusers/pipelines/pag/pipeline_pag_sd_3.py +985 -0
  134. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +862 -0
  135. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1333 -0
  136. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1529 -0
  137. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1753 -0
  138. diffusers/pipelines/pia/pipeline_pia.py +30 -37
  139. diffusers/pipelines/pipeline_flax_utils.py +4 -9
  140. diffusers/pipelines/pipeline_loading_utils.py +0 -3
  141. diffusers/pipelines/pipeline_utils.py +2 -14
  142. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +0 -1
  143. diffusers/pipelines/stable_audio/__init__.py +50 -0
  144. diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
  145. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +745 -0
  146. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +2 -0
  147. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
  148. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +23 -29
  149. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +15 -8
  150. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +30 -29
  151. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +23 -152
  152. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +8 -4
  153. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +11 -11
  154. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +8 -6
  155. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +6 -6
  156. diffusers/pipelines/stable_diffusion_3/__init__.py +2 -0
  157. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +34 -3
  158. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +33 -7
  159. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1201 -0
  160. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +3 -3
  161. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +6 -6
  162. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +5 -5
  163. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +5 -5
  164. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +6 -6
  165. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +0 -4
  166. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +23 -29
  167. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +27 -29
  168. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +3 -3
  169. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +17 -27
  170. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +26 -29
  171. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +17 -145
  172. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +0 -4
  173. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +6 -6
  174. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -28
  175. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +8 -6
  176. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +8 -6
  177. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +6 -4
  178. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +0 -4
  179. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +3 -3
  180. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
  181. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -4
  182. diffusers/schedulers/__init__.py +8 -0
  183. diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
  184. diffusers/schedulers/scheduling_ddim.py +1 -1
  185. diffusers/schedulers/scheduling_ddim_cogvideox.py +449 -0
  186. diffusers/schedulers/scheduling_ddpm.py +1 -1
  187. diffusers/schedulers/scheduling_ddpm_parallel.py +1 -1
  188. diffusers/schedulers/scheduling_deis_multistep.py +2 -2
  189. diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
  190. diffusers/schedulers/scheduling_dpmsolver_multistep.py +1 -1
  191. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +1 -1
  192. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +64 -19
  193. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +2 -2
  194. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +63 -39
  195. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +321 -0
  196. diffusers/schedulers/scheduling_ipndm.py +1 -1
  197. diffusers/schedulers/scheduling_unipc_multistep.py +1 -1
  198. diffusers/schedulers/scheduling_utils.py +1 -3
  199. diffusers/schedulers/scheduling_utils_flax.py +1 -3
  200. diffusers/training_utils.py +99 -14
  201. diffusers/utils/__init__.py +2 -2
  202. diffusers/utils/dummy_pt_objects.py +210 -0
  203. diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
  204. diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
  205. diffusers/utils/dummy_torch_and_transformers_objects.py +315 -0
  206. diffusers/utils/dynamic_modules_utils.py +1 -11
  207. diffusers/utils/export_utils.py +50 -6
  208. diffusers/utils/hub_utils.py +45 -42
  209. diffusers/utils/import_utils.py +37 -15
  210. diffusers/utils/loading_utils.py +80 -3
  211. diffusers/utils/testing_utils.py +11 -8
  212. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/METADATA +73 -83
  213. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/RECORD +217 -164
  214. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/WHEEL +1 -1
  215. diffusers/loaders/autoencoder.py +0 -146
  216. diffusers/loaders/controlnet.py +0 -136
  217. diffusers/loaders/lora.py +0 -1728
  218. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/LICENSE +0 -0
  219. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/entry_points.txt +0 -0
  220. {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,543 @@
1
+ # Copyright 2024 AuraFlow Authors, 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
+
16
+ from typing import Any, Dict, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...utils import is_torch_version, logging
24
+ from ...utils.torch_utils import maybe_allow_in_graph
25
+ from ..attention_processor import (
26
+ Attention,
27
+ AttentionProcessor,
28
+ AuraFlowAttnProcessor2_0,
29
+ FusedAuraFlowAttnProcessor2_0,
30
+ )
31
+ from ..embeddings import TimestepEmbedding, Timesteps
32
+ from ..modeling_outputs import Transformer2DModelOutput
33
+ from ..modeling_utils import ModelMixin
34
+ from ..normalization import AdaLayerNormZero, FP32LayerNorm
35
+
36
+
37
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
38
+
39
+
40
+ # Taken from the original aura flow inference code.
41
+ def find_multiple(n: int, k: int) -> int:
42
+ if n % k == 0:
43
+ return n
44
+ return n + k - (n % k)
45
+
46
+
47
+ # Aura Flow patch embed doesn't use convs for projections.
48
+ # Additionally, it uses learned positional embeddings.
49
+ class AuraFlowPatchEmbed(nn.Module):
50
+ def __init__(
51
+ self,
52
+ height=224,
53
+ width=224,
54
+ patch_size=16,
55
+ in_channels=3,
56
+ embed_dim=768,
57
+ pos_embed_max_size=None,
58
+ ):
59
+ super().__init__()
60
+
61
+ self.num_patches = (height // patch_size) * (width // patch_size)
62
+ self.pos_embed_max_size = pos_embed_max_size
63
+
64
+ self.proj = nn.Linear(patch_size * patch_size * in_channels, embed_dim)
65
+ self.pos_embed = nn.Parameter(torch.randn(1, pos_embed_max_size, embed_dim) * 0.1)
66
+
67
+ self.patch_size = patch_size
68
+ self.height, self.width = height // patch_size, width // patch_size
69
+ self.base_size = height // patch_size
70
+
71
+ def pe_selection_index_based_on_dim(self, h, w):
72
+ # select subset of positional embedding based on H, W, where H, W is size of latent
73
+ # PE will be viewed as 2d-grid, and H/p x W/p of the PE will be selected
74
+ # because original input are in flattened format, we have to flatten this 2d grid as well.
75
+ h_p, w_p = h // self.patch_size, w // self.patch_size
76
+ original_pe_indexes = torch.arange(self.pos_embed.shape[1])
77
+ h_max, w_max = int(self.pos_embed_max_size**0.5), int(self.pos_embed_max_size**0.5)
78
+ original_pe_indexes = original_pe_indexes.view(h_max, w_max)
79
+ starth = h_max // 2 - h_p // 2
80
+ endh = starth + h_p
81
+ startw = w_max // 2 - w_p // 2
82
+ endw = startw + w_p
83
+ original_pe_indexes = original_pe_indexes[starth:endh, startw:endw]
84
+ return original_pe_indexes.flatten()
85
+
86
+ def forward(self, latent):
87
+ batch_size, num_channels, height, width = latent.size()
88
+ latent = latent.view(
89
+ batch_size,
90
+ num_channels,
91
+ height // self.patch_size,
92
+ self.patch_size,
93
+ width // self.patch_size,
94
+ self.patch_size,
95
+ )
96
+ latent = latent.permute(0, 2, 4, 1, 3, 5).flatten(-3).flatten(1, 2)
97
+ latent = self.proj(latent)
98
+ pe_index = self.pe_selection_index_based_on_dim(height, width)
99
+ return latent + self.pos_embed[:, pe_index]
100
+
101
+
102
+ # Taken from the original Aura flow inference code.
103
+ # Our feedforward only has GELU but Aura uses SiLU.
104
+ class AuraFlowFeedForward(nn.Module):
105
+ def __init__(self, dim, hidden_dim=None) -> None:
106
+ super().__init__()
107
+ if hidden_dim is None:
108
+ hidden_dim = 4 * dim
109
+
110
+ final_hidden_dim = int(2 * hidden_dim / 3)
111
+ final_hidden_dim = find_multiple(final_hidden_dim, 256)
112
+
113
+ self.linear_1 = nn.Linear(dim, final_hidden_dim, bias=False)
114
+ self.linear_2 = nn.Linear(dim, final_hidden_dim, bias=False)
115
+ self.out_projection = nn.Linear(final_hidden_dim, dim, bias=False)
116
+
117
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
118
+ x = F.silu(self.linear_1(x)) * self.linear_2(x)
119
+ x = self.out_projection(x)
120
+ return x
121
+
122
+
123
+ class AuraFlowPreFinalBlock(nn.Module):
124
+ def __init__(self, embedding_dim: int, conditioning_embedding_dim: int):
125
+ super().__init__()
126
+
127
+ self.silu = nn.SiLU()
128
+ self.linear = nn.Linear(conditioning_embedding_dim, embedding_dim * 2, bias=False)
129
+
130
+ def forward(self, x: torch.Tensor, conditioning_embedding: torch.Tensor) -> torch.Tensor:
131
+ emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))
132
+ scale, shift = torch.chunk(emb, 2, dim=1)
133
+ x = x * (1 + scale)[:, None, :] + shift[:, None, :]
134
+ return x
135
+
136
+
137
+ @maybe_allow_in_graph
138
+ class AuraFlowSingleTransformerBlock(nn.Module):
139
+ """Similar to `AuraFlowJointTransformerBlock` with a single DiT instead of an MMDiT."""
140
+
141
+ def __init__(self, dim, num_attention_heads, attention_head_dim):
142
+ super().__init__()
143
+
144
+ self.norm1 = AdaLayerNormZero(dim, bias=False, norm_type="fp32_layer_norm")
145
+
146
+ processor = AuraFlowAttnProcessor2_0()
147
+ self.attn = Attention(
148
+ query_dim=dim,
149
+ cross_attention_dim=None,
150
+ dim_head=attention_head_dim,
151
+ heads=num_attention_heads,
152
+ qk_norm="fp32_layer_norm",
153
+ out_dim=dim,
154
+ bias=False,
155
+ out_bias=False,
156
+ processor=processor,
157
+ )
158
+
159
+ self.norm2 = FP32LayerNorm(dim, elementwise_affine=False, bias=False)
160
+ self.ff = AuraFlowFeedForward(dim, dim * 4)
161
+
162
+ def forward(self, hidden_states: torch.FloatTensor, temb: torch.FloatTensor):
163
+ residual = hidden_states
164
+
165
+ # Norm + Projection.
166
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
167
+
168
+ # Attention.
169
+ attn_output = self.attn(hidden_states=norm_hidden_states)
170
+
171
+ # Process attention outputs for the `hidden_states`.
172
+ hidden_states = self.norm2(residual + gate_msa.unsqueeze(1) * attn_output)
173
+ hidden_states = hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
174
+ ff_output = self.ff(hidden_states)
175
+ hidden_states = gate_mlp.unsqueeze(1) * ff_output
176
+ hidden_states = residual + hidden_states
177
+
178
+ return hidden_states
179
+
180
+
181
+ @maybe_allow_in_graph
182
+ class AuraFlowJointTransformerBlock(nn.Module):
183
+ r"""
184
+ Transformer block for Aura Flow. Similar to SD3 MMDiT. Differences (non-exhaustive):
185
+
186
+ * QK Norm in the attention blocks
187
+ * No bias in the attention blocks
188
+ * Most LayerNorms are in FP32
189
+
190
+ Parameters:
191
+ dim (`int`): The number of channels in the input and output.
192
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
193
+ attention_head_dim (`int`): The number of channels in each head.
194
+ is_last (`bool`): Boolean to determine if this is the last block in the model.
195
+ """
196
+
197
+ def __init__(self, dim, num_attention_heads, attention_head_dim):
198
+ super().__init__()
199
+
200
+ self.norm1 = AdaLayerNormZero(dim, bias=False, norm_type="fp32_layer_norm")
201
+ self.norm1_context = AdaLayerNormZero(dim, bias=False, norm_type="fp32_layer_norm")
202
+
203
+ processor = AuraFlowAttnProcessor2_0()
204
+ self.attn = Attention(
205
+ query_dim=dim,
206
+ cross_attention_dim=None,
207
+ added_kv_proj_dim=dim,
208
+ added_proj_bias=False,
209
+ dim_head=attention_head_dim,
210
+ heads=num_attention_heads,
211
+ qk_norm="fp32_layer_norm",
212
+ out_dim=dim,
213
+ bias=False,
214
+ out_bias=False,
215
+ processor=processor,
216
+ context_pre_only=False,
217
+ )
218
+
219
+ self.norm2 = FP32LayerNorm(dim, elementwise_affine=False, bias=False)
220
+ self.ff = AuraFlowFeedForward(dim, dim * 4)
221
+ self.norm2_context = FP32LayerNorm(dim, elementwise_affine=False, bias=False)
222
+ self.ff_context = AuraFlowFeedForward(dim, dim * 4)
223
+
224
+ def forward(
225
+ self, hidden_states: torch.FloatTensor, encoder_hidden_states: torch.FloatTensor, temb: torch.FloatTensor
226
+ ):
227
+ residual = hidden_states
228
+ residual_context = encoder_hidden_states
229
+
230
+ # Norm + Projection.
231
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
232
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
233
+ encoder_hidden_states, emb=temb
234
+ )
235
+
236
+ # Attention.
237
+ attn_output, context_attn_output = self.attn(
238
+ hidden_states=norm_hidden_states, encoder_hidden_states=norm_encoder_hidden_states
239
+ )
240
+
241
+ # Process attention outputs for the `hidden_states`.
242
+ hidden_states = self.norm2(residual + gate_msa.unsqueeze(1) * attn_output)
243
+ hidden_states = hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
244
+ hidden_states = gate_mlp.unsqueeze(1) * self.ff(hidden_states)
245
+ hidden_states = residual + hidden_states
246
+
247
+ # Process attention outputs for the `encoder_hidden_states`.
248
+ encoder_hidden_states = self.norm2_context(residual_context + c_gate_msa.unsqueeze(1) * context_attn_output)
249
+ encoder_hidden_states = encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
250
+ encoder_hidden_states = c_gate_mlp.unsqueeze(1) * self.ff_context(encoder_hidden_states)
251
+ encoder_hidden_states = residual_context + encoder_hidden_states
252
+
253
+ return encoder_hidden_states, hidden_states
254
+
255
+
256
+ class AuraFlowTransformer2DModel(ModelMixin, ConfigMixin):
257
+ r"""
258
+ A 2D Transformer model as introduced in AuraFlow (https://blog.fal.ai/auraflow/).
259
+
260
+ Parameters:
261
+ sample_size (`int`): The width of the latent images. This is fixed during training since
262
+ it is used to learn a number of position embeddings.
263
+ patch_size (`int`): Patch size to turn the input data into small patches.
264
+ in_channels (`int`, *optional*, defaults to 16): The number of channels in the input.
265
+ num_mmdit_layers (`int`, *optional*, defaults to 4): The number of layers of MMDiT Transformer blocks to use.
266
+ num_single_dit_layers (`int`, *optional*, defaults to 4):
267
+ The number of layers of Transformer blocks to use. These blocks use concatenated image and text
268
+ representations.
269
+ attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head.
270
+ num_attention_heads (`int`, *optional*, defaults to 18): The number of heads to use for multi-head attention.
271
+ joint_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
272
+ caption_projection_dim (`int`): Number of dimensions to use when projecting the `encoder_hidden_states`.
273
+ out_channels (`int`, defaults to 16): Number of output channels.
274
+ pos_embed_max_size (`int`, defaults to 4096): Maximum positions to embed from the image latents.
275
+ """
276
+
277
+ _supports_gradient_checkpointing = True
278
+
279
+ @register_to_config
280
+ def __init__(
281
+ self,
282
+ sample_size: int = 64,
283
+ patch_size: int = 2,
284
+ in_channels: int = 4,
285
+ num_mmdit_layers: int = 4,
286
+ num_single_dit_layers: int = 32,
287
+ attention_head_dim: int = 256,
288
+ num_attention_heads: int = 12,
289
+ joint_attention_dim: int = 2048,
290
+ caption_projection_dim: int = 3072,
291
+ out_channels: int = 4,
292
+ pos_embed_max_size: int = 1024,
293
+ ):
294
+ super().__init__()
295
+ default_out_channels = in_channels
296
+ self.out_channels = out_channels if out_channels is not None else default_out_channels
297
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
298
+
299
+ self.pos_embed = AuraFlowPatchEmbed(
300
+ height=self.config.sample_size,
301
+ width=self.config.sample_size,
302
+ patch_size=self.config.patch_size,
303
+ in_channels=self.config.in_channels,
304
+ embed_dim=self.inner_dim,
305
+ pos_embed_max_size=pos_embed_max_size,
306
+ )
307
+
308
+ self.context_embedder = nn.Linear(
309
+ self.config.joint_attention_dim, self.config.caption_projection_dim, bias=False
310
+ )
311
+ self.time_step_embed = Timesteps(num_channels=256, downscale_freq_shift=0, scale=1000, flip_sin_to_cos=True)
312
+ self.time_step_proj = TimestepEmbedding(in_channels=256, time_embed_dim=self.inner_dim)
313
+
314
+ self.joint_transformer_blocks = nn.ModuleList(
315
+ [
316
+ AuraFlowJointTransformerBlock(
317
+ dim=self.inner_dim,
318
+ num_attention_heads=self.config.num_attention_heads,
319
+ attention_head_dim=self.config.attention_head_dim,
320
+ )
321
+ for i in range(self.config.num_mmdit_layers)
322
+ ]
323
+ )
324
+ self.single_transformer_blocks = nn.ModuleList(
325
+ [
326
+ AuraFlowSingleTransformerBlock(
327
+ dim=self.inner_dim,
328
+ num_attention_heads=self.config.num_attention_heads,
329
+ attention_head_dim=self.config.attention_head_dim,
330
+ )
331
+ for _ in range(self.config.num_single_dit_layers)
332
+ ]
333
+ )
334
+
335
+ self.norm_out = AuraFlowPreFinalBlock(self.inner_dim, self.inner_dim)
336
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=False)
337
+
338
+ # https://arxiv.org/abs/2309.16588
339
+ # prevents artifacts in the attention maps
340
+ self.register_tokens = nn.Parameter(torch.randn(1, 8, self.inner_dim) * 0.02)
341
+
342
+ self.gradient_checkpointing = False
343
+
344
+ @property
345
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
346
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
347
+ r"""
348
+ Returns:
349
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
350
+ indexed by its weight name.
351
+ """
352
+ # set recursively
353
+ processors = {}
354
+
355
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
356
+ if hasattr(module, "get_processor"):
357
+ processors[f"{name}.processor"] = module.get_processor()
358
+
359
+ for sub_name, child in module.named_children():
360
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
361
+
362
+ return processors
363
+
364
+ for name, module in self.named_children():
365
+ fn_recursive_add_processors(name, module, processors)
366
+
367
+ return processors
368
+
369
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
370
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
371
+ r"""
372
+ Sets the attention processor to use to compute attention.
373
+
374
+ Parameters:
375
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
376
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
377
+ for **all** `Attention` layers.
378
+
379
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
380
+ processor. This is strongly recommended when setting trainable attention processors.
381
+
382
+ """
383
+ count = len(self.attn_processors.keys())
384
+
385
+ if isinstance(processor, dict) and len(processor) != count:
386
+ raise ValueError(
387
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
388
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
389
+ )
390
+
391
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
392
+ if hasattr(module, "set_processor"):
393
+ if not isinstance(processor, dict):
394
+ module.set_processor(processor)
395
+ else:
396
+ module.set_processor(processor.pop(f"{name}.processor"))
397
+
398
+ for sub_name, child in module.named_children():
399
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
400
+
401
+ for name, module in self.named_children():
402
+ fn_recursive_attn_processor(name, module, processor)
403
+
404
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedAuraFlowAttnProcessor2_0
405
+ def fuse_qkv_projections(self):
406
+ """
407
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
408
+ are fused. For cross-attention modules, key and value projection matrices are fused.
409
+
410
+ <Tip warning={true}>
411
+
412
+ This API is 🧪 experimental.
413
+
414
+ </Tip>
415
+ """
416
+ self.original_attn_processors = None
417
+
418
+ for _, attn_processor in self.attn_processors.items():
419
+ if "Added" in str(attn_processor.__class__.__name__):
420
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
421
+
422
+ self.original_attn_processors = self.attn_processors
423
+
424
+ for module in self.modules():
425
+ if isinstance(module, Attention):
426
+ module.fuse_projections(fuse=True)
427
+
428
+ self.set_attn_processor(FusedAuraFlowAttnProcessor2_0())
429
+
430
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
431
+ def unfuse_qkv_projections(self):
432
+ """Disables the fused QKV projection if enabled.
433
+
434
+ <Tip warning={true}>
435
+
436
+ This API is 🧪 experimental.
437
+
438
+ </Tip>
439
+
440
+ """
441
+ if self.original_attn_processors is not None:
442
+ self.set_attn_processor(self.original_attn_processors)
443
+
444
+ def _set_gradient_checkpointing(self, module, value=False):
445
+ if hasattr(module, "gradient_checkpointing"):
446
+ module.gradient_checkpointing = value
447
+
448
+ def forward(
449
+ self,
450
+ hidden_states: torch.FloatTensor,
451
+ encoder_hidden_states: torch.FloatTensor = None,
452
+ timestep: torch.LongTensor = None,
453
+ return_dict: bool = True,
454
+ ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
455
+ height, width = hidden_states.shape[-2:]
456
+
457
+ # Apply patch embedding, timestep embedding, and project the caption embeddings.
458
+ hidden_states = self.pos_embed(hidden_states) # takes care of adding positional embeddings too.
459
+ temb = self.time_step_embed(timestep).to(dtype=next(self.parameters()).dtype)
460
+ temb = self.time_step_proj(temb)
461
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
462
+ encoder_hidden_states = torch.cat(
463
+ [self.register_tokens.repeat(encoder_hidden_states.size(0), 1, 1), encoder_hidden_states], dim=1
464
+ )
465
+
466
+ # MMDiT blocks.
467
+ for index_block, block in enumerate(self.joint_transformer_blocks):
468
+ if self.training and self.gradient_checkpointing:
469
+
470
+ def create_custom_forward(module, return_dict=None):
471
+ def custom_forward(*inputs):
472
+ if return_dict is not None:
473
+ return module(*inputs, return_dict=return_dict)
474
+ else:
475
+ return module(*inputs)
476
+
477
+ return custom_forward
478
+
479
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
480
+ encoder_hidden_states, hidden_states = torch.utils.checkpoint.checkpoint(
481
+ create_custom_forward(block),
482
+ hidden_states,
483
+ encoder_hidden_states,
484
+ temb,
485
+ **ckpt_kwargs,
486
+ )
487
+
488
+ else:
489
+ encoder_hidden_states, hidden_states = block(
490
+ hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states, temb=temb
491
+ )
492
+
493
+ # Single DiT blocks that combine the `hidden_states` (image) and `encoder_hidden_states` (text)
494
+ if len(self.single_transformer_blocks) > 0:
495
+ encoder_seq_len = encoder_hidden_states.size(1)
496
+ combined_hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
497
+
498
+ for index_block, block in enumerate(self.single_transformer_blocks):
499
+ if self.training and self.gradient_checkpointing:
500
+
501
+ def create_custom_forward(module, return_dict=None):
502
+ def custom_forward(*inputs):
503
+ if return_dict is not None:
504
+ return module(*inputs, return_dict=return_dict)
505
+ else:
506
+ return module(*inputs)
507
+
508
+ return custom_forward
509
+
510
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
511
+ combined_hidden_states = torch.utils.checkpoint.checkpoint(
512
+ create_custom_forward(block),
513
+ combined_hidden_states,
514
+ temb,
515
+ **ckpt_kwargs,
516
+ )
517
+
518
+ else:
519
+ combined_hidden_states = block(hidden_states=combined_hidden_states, temb=temb)
520
+
521
+ hidden_states = combined_hidden_states[:, encoder_seq_len:]
522
+
523
+ hidden_states = self.norm_out(hidden_states, temb)
524
+ hidden_states = self.proj_out(hidden_states)
525
+
526
+ # unpatchify
527
+ patch_size = self.config.patch_size
528
+ out_channels = self.config.out_channels
529
+ height = height // patch_size
530
+ width = width // patch_size
531
+
532
+ hidden_states = hidden_states.reshape(
533
+ shape=(hidden_states.shape[0], height, width, patch_size, patch_size, out_channels)
534
+ )
535
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
536
+ output = hidden_states.reshape(
537
+ shape=(hidden_states.shape[0], out_channels, height * patch_size, width * patch_size)
538
+ )
539
+
540
+ if not return_dict:
541
+ return (output,)
542
+
543
+ return Transformer2DModelOutput(sample=output)