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
@@ -23,530 +23,23 @@ import torch.nn.functional as F
23
23
  from ..utils import USE_PEFT_BACKEND
24
24
  from .activations import get_activation
25
25
  from .attention_processor import SpatialNorm
26
+ from .downsampling import ( # noqa
27
+ Downsample1D,
28
+ Downsample2D,
29
+ FirDownsample2D,
30
+ KDownsample2D,
31
+ downsample_2d,
32
+ )
26
33
  from .lora import LoRACompatibleConv, LoRACompatibleLinear
27
34
  from .normalization import AdaGroupNorm
28
-
29
-
30
- class Upsample1D(nn.Module):
31
- """A 1D upsampling layer with an optional convolution.
32
-
33
- Parameters:
34
- channels (`int`):
35
- number of channels in the inputs and outputs.
36
- use_conv (`bool`, default `False`):
37
- option to use a convolution.
38
- use_conv_transpose (`bool`, default `False`):
39
- option to use a convolution transpose.
40
- out_channels (`int`, optional):
41
- number of output channels. Defaults to `channels`.
42
- name (`str`, default `conv`):
43
- name of the upsampling 1D layer.
44
- """
45
-
46
- def __init__(
47
- self,
48
- channels: int,
49
- use_conv: bool = False,
50
- use_conv_transpose: bool = False,
51
- out_channels: Optional[int] = None,
52
- name: str = "conv",
53
- ):
54
- super().__init__()
55
- self.channels = channels
56
- self.out_channels = out_channels or channels
57
- self.use_conv = use_conv
58
- self.use_conv_transpose = use_conv_transpose
59
- self.name = name
60
-
61
- self.conv = None
62
- if use_conv_transpose:
63
- self.conv = nn.ConvTranspose1d(channels, self.out_channels, 4, 2, 1)
64
- elif use_conv:
65
- self.conv = nn.Conv1d(self.channels, self.out_channels, 3, padding=1)
66
-
67
- def forward(self, inputs: torch.Tensor) -> torch.Tensor:
68
- assert inputs.shape[1] == self.channels
69
- if self.use_conv_transpose:
70
- return self.conv(inputs)
71
-
72
- outputs = F.interpolate(inputs, scale_factor=2.0, mode="nearest")
73
-
74
- if self.use_conv:
75
- outputs = self.conv(outputs)
76
-
77
- return outputs
78
-
79
-
80
- class Downsample1D(nn.Module):
81
- """A 1D downsampling layer with an optional convolution.
82
-
83
- Parameters:
84
- channels (`int`):
85
- number of channels in the inputs and outputs.
86
- use_conv (`bool`, default `False`):
87
- option to use a convolution.
88
- out_channels (`int`, optional):
89
- number of output channels. Defaults to `channels`.
90
- padding (`int`, default `1`):
91
- padding for the convolution.
92
- name (`str`, default `conv`):
93
- name of the downsampling 1D layer.
94
- """
95
-
96
- def __init__(
97
- self,
98
- channels: int,
99
- use_conv: bool = False,
100
- out_channels: Optional[int] = None,
101
- padding: int = 1,
102
- name: str = "conv",
103
- ):
104
- super().__init__()
105
- self.channels = channels
106
- self.out_channels = out_channels or channels
107
- self.use_conv = use_conv
108
- self.padding = padding
109
- stride = 2
110
- self.name = name
111
-
112
- if use_conv:
113
- self.conv = nn.Conv1d(self.channels, self.out_channels, 3, stride=stride, padding=padding)
114
- else:
115
- assert self.channels == self.out_channels
116
- self.conv = nn.AvgPool1d(kernel_size=stride, stride=stride)
117
-
118
- def forward(self, inputs: torch.Tensor) -> torch.Tensor:
119
- assert inputs.shape[1] == self.channels
120
- return self.conv(inputs)
121
-
122
-
123
- class Upsample2D(nn.Module):
124
- """A 2D upsampling layer with an optional convolution.
125
-
126
- Parameters:
127
- channels (`int`):
128
- number of channels in the inputs and outputs.
129
- use_conv (`bool`, default `False`):
130
- option to use a convolution.
131
- use_conv_transpose (`bool`, default `False`):
132
- option to use a convolution transpose.
133
- out_channels (`int`, optional):
134
- number of output channels. Defaults to `channels`.
135
- name (`str`, default `conv`):
136
- name of the upsampling 2D layer.
137
- """
138
-
139
- def __init__(
140
- self,
141
- channels: int,
142
- use_conv: bool = False,
143
- use_conv_transpose: bool = False,
144
- out_channels: Optional[int] = None,
145
- name: str = "conv",
146
- ):
147
- super().__init__()
148
- self.channels = channels
149
- self.out_channels = out_channels or channels
150
- self.use_conv = use_conv
151
- self.use_conv_transpose = use_conv_transpose
152
- self.name = name
153
- conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
154
-
155
- conv = None
156
- if use_conv_transpose:
157
- conv = nn.ConvTranspose2d(channels, self.out_channels, 4, 2, 1)
158
- elif use_conv:
159
- conv = conv_cls(self.channels, self.out_channels, 3, padding=1)
160
-
161
- # TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
162
- if name == "conv":
163
- self.conv = conv
164
- else:
165
- self.Conv2d_0 = conv
166
-
167
- def forward(self, hidden_states: torch.Tensor, output_size: Optional[int] = None, scale: float = 1.0):
168
- assert hidden_states.shape[1] == self.channels
169
-
170
- if self.use_conv_transpose:
171
- return self.conv(hidden_states)
172
-
173
- # Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16
174
- # TODO(Suraj): Remove this cast once the issue is fixed in PyTorch
175
- # https://github.com/pytorch/pytorch/issues/86679
176
- dtype = hidden_states.dtype
177
- if dtype == torch.bfloat16:
178
- hidden_states = hidden_states.to(torch.float32)
179
-
180
- # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
181
- if hidden_states.shape[0] >= 64:
182
- hidden_states = hidden_states.contiguous()
183
-
184
- # if `output_size` is passed we force the interpolation output
185
- # size and do not make use of `scale_factor=2`
186
- if output_size is None:
187
- hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
188
- else:
189
- hidden_states = F.interpolate(hidden_states, size=output_size, mode="nearest")
190
-
191
- # If the input is bfloat16, we cast back to bfloat16
192
- if dtype == torch.bfloat16:
193
- hidden_states = hidden_states.to(dtype)
194
-
195
- # TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
196
- if self.use_conv:
197
- if self.name == "conv":
198
- if isinstance(self.conv, LoRACompatibleConv) and not USE_PEFT_BACKEND:
199
- hidden_states = self.conv(hidden_states, scale)
200
- else:
201
- hidden_states = self.conv(hidden_states)
202
- else:
203
- if isinstance(self.Conv2d_0, LoRACompatibleConv) and not USE_PEFT_BACKEND:
204
- hidden_states = self.Conv2d_0(hidden_states, scale)
205
- else:
206
- hidden_states = self.Conv2d_0(hidden_states)
207
-
208
- return hidden_states
209
-
210
-
211
- class Downsample2D(nn.Module):
212
- """A 2D downsampling layer with an optional convolution.
213
-
214
- Parameters:
215
- channels (`int`):
216
- number of channels in the inputs and outputs.
217
- use_conv (`bool`, default `False`):
218
- option to use a convolution.
219
- out_channels (`int`, optional):
220
- number of output channels. Defaults to `channels`.
221
- padding (`int`, default `1`):
222
- padding for the convolution.
223
- name (`str`, default `conv`):
224
- name of the downsampling 2D layer.
225
- """
226
-
227
- def __init__(
228
- self,
229
- channels: int,
230
- use_conv: bool = False,
231
- out_channels: Optional[int] = None,
232
- padding: int = 1,
233
- name: str = "conv",
234
- ):
235
- super().__init__()
236
- self.channels = channels
237
- self.out_channels = out_channels or channels
238
- self.use_conv = use_conv
239
- self.padding = padding
240
- stride = 2
241
- self.name = name
242
- conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
243
-
244
- if use_conv:
245
- conv = conv_cls(self.channels, self.out_channels, 3, stride=stride, padding=padding)
246
- else:
247
- assert self.channels == self.out_channels
248
- conv = nn.AvgPool2d(kernel_size=stride, stride=stride)
249
-
250
- # TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
251
- if name == "conv":
252
- self.Conv2d_0 = conv
253
- self.conv = conv
254
- elif name == "Conv2d_0":
255
- self.conv = conv
256
- else:
257
- self.conv = conv
258
-
259
- def forward(self, hidden_states, scale: float = 1.0):
260
- assert hidden_states.shape[1] == self.channels
261
-
262
- if self.use_conv and self.padding == 0:
263
- pad = (0, 1, 0, 1)
264
- hidden_states = F.pad(hidden_states, pad, mode="constant", value=0)
265
-
266
- assert hidden_states.shape[1] == self.channels
267
-
268
- if not USE_PEFT_BACKEND:
269
- if isinstance(self.conv, LoRACompatibleConv):
270
- hidden_states = self.conv(hidden_states, scale)
271
- else:
272
- hidden_states = self.conv(hidden_states)
273
- else:
274
- hidden_states = self.conv(hidden_states)
275
-
276
- return hidden_states
277
-
278
-
279
- class FirUpsample2D(nn.Module):
280
- """A 2D FIR upsampling layer with an optional convolution.
281
-
282
- Parameters:
283
- channels (`int`):
284
- number of channels in the inputs and outputs.
285
- use_conv (`bool`, default `False`):
286
- option to use a convolution.
287
- out_channels (`int`, optional):
288
- number of output channels. Defaults to `channels`.
289
- fir_kernel (`tuple`, default `(1, 3, 3, 1)`):
290
- kernel for the FIR filter.
291
- """
292
-
293
- def __init__(
294
- self,
295
- channels: int = None,
296
- out_channels: Optional[int] = None,
297
- use_conv: bool = False,
298
- fir_kernel: Tuple[int, int, int, int] = (1, 3, 3, 1),
299
- ):
300
- super().__init__()
301
- out_channels = out_channels if out_channels else channels
302
- if use_conv:
303
- self.Conv2d_0 = nn.Conv2d(channels, out_channels, kernel_size=3, stride=1, padding=1)
304
- self.use_conv = use_conv
305
- self.fir_kernel = fir_kernel
306
- self.out_channels = out_channels
307
-
308
- def _upsample_2d(
309
- self,
310
- hidden_states: torch.Tensor,
311
- weight: Optional[torch.Tensor] = None,
312
- kernel: Optional[torch.FloatTensor] = None,
313
- factor: int = 2,
314
- gain: float = 1,
315
- ) -> torch.Tensor:
316
- """Fused `upsample_2d()` followed by `Conv2d()`.
317
-
318
- Padding is performed only once at the beginning, not between the operations. The fused op is considerably more
319
- efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of
320
- arbitrary order.
321
-
322
- Args:
323
- hidden_states: Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
324
- weight: Weight tensor of the shape `[filterH, filterW, inChannels,
325
- outChannels]`. Grouped convolution can be performed by `inChannels = x.shape[0] // numGroups`.
326
- kernel: FIR filter of the shape `[firH, firW]` or `[firN]`
327
- (separable). The default is `[1] * factor`, which corresponds to nearest-neighbor upsampling.
328
- factor: Integer upsampling factor (default: 2).
329
- gain: Scaling factor for signal magnitude (default: 1.0).
330
-
331
- Returns:
332
- output: Tensor of the shape `[N, C, H * factor, W * factor]` or `[N, H * factor, W * factor, C]`, and same
333
- datatype as `hidden_states`.
334
- """
335
-
336
- assert isinstance(factor, int) and factor >= 1
337
-
338
- # Setup filter kernel.
339
- if kernel is None:
340
- kernel = [1] * factor
341
-
342
- # setup kernel
343
- kernel = torch.tensor(kernel, dtype=torch.float32)
344
- if kernel.ndim == 1:
345
- kernel = torch.outer(kernel, kernel)
346
- kernel /= torch.sum(kernel)
347
-
348
- kernel = kernel * (gain * (factor**2))
349
-
350
- if self.use_conv:
351
- convH = weight.shape[2]
352
- convW = weight.shape[3]
353
- inC = weight.shape[1]
354
-
355
- pad_value = (kernel.shape[0] - factor) - (convW - 1)
356
-
357
- stride = (factor, factor)
358
- # Determine data dimensions.
359
- output_shape = (
360
- (hidden_states.shape[2] - 1) * factor + convH,
361
- (hidden_states.shape[3] - 1) * factor + convW,
362
- )
363
- output_padding = (
364
- output_shape[0] - (hidden_states.shape[2] - 1) * stride[0] - convH,
365
- output_shape[1] - (hidden_states.shape[3] - 1) * stride[1] - convW,
366
- )
367
- assert output_padding[0] >= 0 and output_padding[1] >= 0
368
- num_groups = hidden_states.shape[1] // inC
369
-
370
- # Transpose weights.
371
- weight = torch.reshape(weight, (num_groups, -1, inC, convH, convW))
372
- weight = torch.flip(weight, dims=[3, 4]).permute(0, 2, 1, 3, 4)
373
- weight = torch.reshape(weight, (num_groups * inC, -1, convH, convW))
374
-
375
- inverse_conv = F.conv_transpose2d(
376
- hidden_states, weight, stride=stride, output_padding=output_padding, padding=0
377
- )
378
-
379
- output = upfirdn2d_native(
380
- inverse_conv,
381
- torch.tensor(kernel, device=inverse_conv.device),
382
- pad=((pad_value + 1) // 2 + factor - 1, pad_value // 2 + 1),
383
- )
384
- else:
385
- pad_value = kernel.shape[0] - factor
386
- output = upfirdn2d_native(
387
- hidden_states,
388
- torch.tensor(kernel, device=hidden_states.device),
389
- up=factor,
390
- pad=((pad_value + 1) // 2 + factor - 1, pad_value // 2),
391
- )
392
-
393
- return output
394
-
395
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
396
- if self.use_conv:
397
- height = self._upsample_2d(hidden_states, self.Conv2d_0.weight, kernel=self.fir_kernel)
398
- height = height + self.Conv2d_0.bias.reshape(1, -1, 1, 1)
399
- else:
400
- height = self._upsample_2d(hidden_states, kernel=self.fir_kernel, factor=2)
401
-
402
- return height
403
-
404
-
405
- class FirDownsample2D(nn.Module):
406
- """A 2D FIR downsampling layer with an optional convolution.
407
-
408
- Parameters:
409
- channels (`int`):
410
- number of channels in the inputs and outputs.
411
- use_conv (`bool`, default `False`):
412
- option to use a convolution.
413
- out_channels (`int`, optional):
414
- number of output channels. Defaults to `channels`.
415
- fir_kernel (`tuple`, default `(1, 3, 3, 1)`):
416
- kernel for the FIR filter.
417
- """
418
-
419
- def __init__(
420
- self,
421
- channels: int = None,
422
- out_channels: Optional[int] = None,
423
- use_conv: bool = False,
424
- fir_kernel: Tuple[int, int, int, int] = (1, 3, 3, 1),
425
- ):
426
- super().__init__()
427
- out_channels = out_channels if out_channels else channels
428
- if use_conv:
429
- self.Conv2d_0 = nn.Conv2d(channels, out_channels, kernel_size=3, stride=1, padding=1)
430
- self.fir_kernel = fir_kernel
431
- self.use_conv = use_conv
432
- self.out_channels = out_channels
433
-
434
- def _downsample_2d(
435
- self,
436
- hidden_states: torch.Tensor,
437
- weight: Optional[torch.Tensor] = None,
438
- kernel: Optional[torch.FloatTensor] = None,
439
- factor: int = 2,
440
- gain: float = 1,
441
- ) -> torch.Tensor:
442
- """Fused `Conv2d()` followed by `downsample_2d()`.
443
- Padding is performed only once at the beginning, not between the operations. The fused op is considerably more
444
- efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of
445
- arbitrary order.
446
-
447
- Args:
448
- hidden_states: Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
449
- weight:
450
- Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be
451
- performed by `inChannels = x.shape[0] // numGroups`.
452
- kernel: FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] *
453
- factor`, which corresponds to average pooling.
454
- factor: Integer downsampling factor (default: 2).
455
- gain: Scaling factor for signal magnitude (default: 1.0).
456
-
457
- Returns:
458
- output: Tensor of the shape `[N, C, H // factor, W // factor]` or `[N, H // factor, W // factor, C]`, and
459
- same datatype as `x`.
460
- """
461
-
462
- assert isinstance(factor, int) and factor >= 1
463
- if kernel is None:
464
- kernel = [1] * factor
465
-
466
- # setup kernel
467
- kernel = torch.tensor(kernel, dtype=torch.float32)
468
- if kernel.ndim == 1:
469
- kernel = torch.outer(kernel, kernel)
470
- kernel /= torch.sum(kernel)
471
-
472
- kernel = kernel * gain
473
-
474
- if self.use_conv:
475
- _, _, convH, convW = weight.shape
476
- pad_value = (kernel.shape[0] - factor) + (convW - 1)
477
- stride_value = [factor, factor]
478
- upfirdn_input = upfirdn2d_native(
479
- hidden_states,
480
- torch.tensor(kernel, device=hidden_states.device),
481
- pad=((pad_value + 1) // 2, pad_value // 2),
482
- )
483
- output = F.conv2d(upfirdn_input, weight, stride=stride_value, padding=0)
484
- else:
485
- pad_value = kernel.shape[0] - factor
486
- output = upfirdn2d_native(
487
- hidden_states,
488
- torch.tensor(kernel, device=hidden_states.device),
489
- down=factor,
490
- pad=((pad_value + 1) // 2, pad_value // 2),
491
- )
492
-
493
- return output
494
-
495
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
496
- if self.use_conv:
497
- downsample_input = self._downsample_2d(hidden_states, weight=self.Conv2d_0.weight, kernel=self.fir_kernel)
498
- hidden_states = downsample_input + self.Conv2d_0.bias.reshape(1, -1, 1, 1)
499
- else:
500
- hidden_states = self._downsample_2d(hidden_states, kernel=self.fir_kernel, factor=2)
501
-
502
- return hidden_states
503
-
504
-
505
- # downsample/upsample layer used in k-upscaler, might be able to use FirDownsample2D/DirUpsample2D instead
506
- class KDownsample2D(nn.Module):
507
- r"""A 2D K-downsampling layer.
508
-
509
- Parameters:
510
- pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
511
- """
512
-
513
- def __init__(self, pad_mode: str = "reflect"):
514
- super().__init__()
515
- self.pad_mode = pad_mode
516
- kernel_1d = torch.tensor([[1 / 8, 3 / 8, 3 / 8, 1 / 8]])
517
- self.pad = kernel_1d.shape[1] // 2 - 1
518
- self.register_buffer("kernel", kernel_1d.T @ kernel_1d, persistent=False)
519
-
520
- def forward(self, inputs: torch.Tensor) -> torch.Tensor:
521
- inputs = F.pad(inputs, (self.pad,) * 4, self.pad_mode)
522
- weight = inputs.new_zeros([inputs.shape[1], inputs.shape[1], self.kernel.shape[0], self.kernel.shape[1]])
523
- indices = torch.arange(inputs.shape[1], device=inputs.device)
524
- kernel = self.kernel.to(weight)[None, :].expand(inputs.shape[1], -1, -1)
525
- weight[indices, indices] = kernel
526
- return F.conv2d(inputs, weight, stride=2)
527
-
528
-
529
- class KUpsample2D(nn.Module):
530
- r"""A 2D K-upsampling layer.
531
-
532
- Parameters:
533
- pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
534
- """
535
-
536
- def __init__(self, pad_mode: str = "reflect"):
537
- super().__init__()
538
- self.pad_mode = pad_mode
539
- kernel_1d = torch.tensor([[1 / 8, 3 / 8, 3 / 8, 1 / 8]]) * 2
540
- self.pad = kernel_1d.shape[1] // 2 - 1
541
- self.register_buffer("kernel", kernel_1d.T @ kernel_1d, persistent=False)
542
-
543
- def forward(self, inputs: torch.Tensor) -> torch.Tensor:
544
- inputs = F.pad(inputs, ((self.pad + 1) // 2,) * 4, self.pad_mode)
545
- weight = inputs.new_zeros([inputs.shape[1], inputs.shape[1], self.kernel.shape[0], self.kernel.shape[1]])
546
- indices = torch.arange(inputs.shape[1], device=inputs.device)
547
- kernel = self.kernel.to(weight)[None, :].expand(inputs.shape[1], -1, -1)
548
- weight[indices, indices] = kernel
549
- return F.conv_transpose2d(inputs, weight, stride=2, padding=self.pad * 2 + 1)
35
+ from .upsampling import ( # noqa
36
+ FirUpsample2D,
37
+ KUpsample2D,
38
+ Upsample1D,
39
+ Upsample2D,
40
+ upfirdn2d_native,
41
+ upsample_2d,
42
+ )
550
43
 
551
44
 
552
45
  class ResnetBlock2D(nn.Module):
@@ -679,10 +172,20 @@ class ResnetBlock2D(nn.Module):
679
172
  self.conv_shortcut = None
680
173
  if self.use_in_shortcut:
681
174
  self.conv_shortcut = conv_cls(
682
- in_channels, conv_2d_out_channels, kernel_size=1, stride=1, padding=0, bias=conv_shortcut_bias
175
+ in_channels,
176
+ conv_2d_out_channels,
177
+ kernel_size=1,
178
+ stride=1,
179
+ padding=0,
180
+ bias=conv_shortcut_bias,
683
181
  )
684
182
 
685
- def forward(self, input_tensor, temb, scale: float = 1.0):
183
+ def forward(
184
+ self,
185
+ input_tensor: torch.FloatTensor,
186
+ temb: torch.FloatTensor,
187
+ scale: float = 1.0,
188
+ ) -> torch.FloatTensor:
686
189
  hidden_states = input_tensor
687
190
 
688
191
  if self.time_embedding_norm == "ada_group" or self.time_embedding_norm == "spatial":
@@ -778,7 +281,7 @@ class Conv1dBlock(nn.Module):
778
281
  out_channels (`int`): Number of output channels.
779
282
  kernel_size (`int` or `tuple`): Size of the convolving kernel.
780
283
  n_groups (`int`, default `8`): Number of groups to separate the channels into.
781
- activation (`str`, defaults `mish`): Name of the activation function.
284
+ activation (`str`, defaults to `mish`): Name of the activation function.
782
285
  """
783
286
 
784
287
  def __init__(
@@ -852,128 +355,6 @@ class ResidualTemporalBlock1D(nn.Module):
852
355
  return out + self.residual_conv(inputs)
853
356
 
854
357
 
855
- def upsample_2d(
856
- hidden_states: torch.Tensor, kernel: Optional[torch.FloatTensor] = None, factor: int = 2, gain: float = 1
857
- ) -> torch.Tensor:
858
- r"""Upsample2D a batch of 2D images with the given filter.
859
- Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and upsamples each image with the given
860
- filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the specified
861
- `gain`. Pixels outside the image are assumed to be zero, and the filter is padded with zeros so that its shape is
862
- a: multiple of the upsampling factor.
863
-
864
- Args:
865
- hidden_states: Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
866
- kernel: FIR filter of the shape `[firH, firW]` or `[firN]`
867
- (separable). The default is `[1] * factor`, which corresponds to nearest-neighbor upsampling.
868
- factor: Integer upsampling factor (default: 2).
869
- gain: Scaling factor for signal magnitude (default: 1.0).
870
-
871
- Returns:
872
- output: Tensor of the shape `[N, C, H * factor, W * factor]`
873
- """
874
- assert isinstance(factor, int) and factor >= 1
875
- if kernel is None:
876
- kernel = [1] * factor
877
-
878
- kernel = torch.tensor(kernel, dtype=torch.float32)
879
- if kernel.ndim == 1:
880
- kernel = torch.outer(kernel, kernel)
881
- kernel /= torch.sum(kernel)
882
-
883
- kernel = kernel * (gain * (factor**2))
884
- pad_value = kernel.shape[0] - factor
885
- output = upfirdn2d_native(
886
- hidden_states,
887
- kernel.to(device=hidden_states.device),
888
- up=factor,
889
- pad=((pad_value + 1) // 2 + factor - 1, pad_value // 2),
890
- )
891
- return output
892
-
893
-
894
- def downsample_2d(
895
- hidden_states: torch.Tensor, kernel: Optional[torch.FloatTensor] = None, factor: int = 2, gain: float = 1
896
- ) -> torch.Tensor:
897
- r"""Downsample2D a batch of 2D images with the given filter.
898
- Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and downsamples each image with the
899
- given filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the
900
- specified `gain`. Pixels outside the image are assumed to be zero, and the filter is padded with zeros so that its
901
- shape is a multiple of the downsampling factor.
902
-
903
- Args:
904
- hidden_states: Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
905
- kernel: FIR filter of the shape `[firH, firW]` or `[firN]`
906
- (separable). The default is `[1] * factor`, which corresponds to average pooling.
907
- factor: Integer downsampling factor (default: 2).
908
- gain: Scaling factor for signal magnitude (default: 1.0).
909
-
910
- Returns:
911
- output: Tensor of the shape `[N, C, H // factor, W // factor]`
912
- """
913
-
914
- assert isinstance(factor, int) and factor >= 1
915
- if kernel is None:
916
- kernel = [1] * factor
917
-
918
- kernel = torch.tensor(kernel, dtype=torch.float32)
919
- if kernel.ndim == 1:
920
- kernel = torch.outer(kernel, kernel)
921
- kernel /= torch.sum(kernel)
922
-
923
- kernel = kernel * gain
924
- pad_value = kernel.shape[0] - factor
925
- output = upfirdn2d_native(
926
- hidden_states, kernel.to(device=hidden_states.device), down=factor, pad=((pad_value + 1) // 2, pad_value // 2)
927
- )
928
- return output
929
-
930
-
931
- def upfirdn2d_native(
932
- tensor: torch.Tensor, kernel: torch.Tensor, up: int = 1, down: int = 1, pad: Tuple[int, int] = (0, 0)
933
- ) -> torch.Tensor:
934
- up_x = up_y = up
935
- down_x = down_y = down
936
- pad_x0 = pad_y0 = pad[0]
937
- pad_x1 = pad_y1 = pad[1]
938
-
939
- _, channel, in_h, in_w = tensor.shape
940
- tensor = tensor.reshape(-1, in_h, in_w, 1)
941
-
942
- _, in_h, in_w, minor = tensor.shape
943
- kernel_h, kernel_w = kernel.shape
944
-
945
- out = tensor.view(-1, in_h, 1, in_w, 1, minor)
946
- out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1])
947
- out = out.view(-1, in_h * up_y, in_w * up_x, minor)
948
-
949
- out = F.pad(out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)])
950
- out = out.to(tensor.device) # Move back to mps if necessary
951
- out = out[
952
- :,
953
- max(-pad_y0, 0) : out.shape[1] - max(-pad_y1, 0),
954
- max(-pad_x0, 0) : out.shape[2] - max(-pad_x1, 0),
955
- :,
956
- ]
957
-
958
- out = out.permute(0, 3, 1, 2)
959
- out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1])
960
- w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w)
961
- out = F.conv2d(out, w)
962
- out = out.reshape(
963
- -1,
964
- minor,
965
- in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1,
966
- in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1,
967
- )
968
- out = out.permute(0, 2, 3, 1)
969
- out = out[:, ::down_y, ::down_x, :]
970
-
971
- out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
972
- out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
973
-
974
- return out.view(-1, channel, out_h, out_w)
975
-
976
-
977
358
  class TemporalConvLayer(nn.Module):
978
359
  """
979
360
  Temporal convolutional layer that can be used for video (sequence of images) input Code mostly copied from:
@@ -985,7 +366,13 @@ class TemporalConvLayer(nn.Module):
985
366
  dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
986
367
  """
987
368
 
988
- def __init__(self, in_dim: int, out_dim: Optional[int] = None, dropout: float = 0.0):
369
+ def __init__(
370
+ self,
371
+ in_dim: int,
372
+ out_dim: Optional[int] = None,
373
+ dropout: float = 0.0,
374
+ norm_num_groups: int = 32,
375
+ ):
989
376
  super().__init__()
990
377
  out_dim = out_dim or in_dim
991
378
  self.in_dim = in_dim
@@ -993,22 +380,24 @@ class TemporalConvLayer(nn.Module):
993
380
 
994
381
  # conv layers
995
382
  self.conv1 = nn.Sequential(
996
- nn.GroupNorm(32, in_dim), nn.SiLU(), nn.Conv3d(in_dim, out_dim, (3, 1, 1), padding=(1, 0, 0))
383
+ nn.GroupNorm(norm_num_groups, in_dim),
384
+ nn.SiLU(),
385
+ nn.Conv3d(in_dim, out_dim, (3, 1, 1), padding=(1, 0, 0)),
997
386
  )
998
387
  self.conv2 = nn.Sequential(
999
- nn.GroupNorm(32, out_dim),
388
+ nn.GroupNorm(norm_num_groups, out_dim),
1000
389
  nn.SiLU(),
1001
390
  nn.Dropout(dropout),
1002
391
  nn.Conv3d(out_dim, in_dim, (3, 1, 1), padding=(1, 0, 0)),
1003
392
  )
1004
393
  self.conv3 = nn.Sequential(
1005
- nn.GroupNorm(32, out_dim),
394
+ nn.GroupNorm(norm_num_groups, out_dim),
1006
395
  nn.SiLU(),
1007
396
  nn.Dropout(dropout),
1008
397
  nn.Conv3d(out_dim, in_dim, (3, 1, 1), padding=(1, 0, 0)),
1009
398
  )
1010
399
  self.conv4 = nn.Sequential(
1011
- nn.GroupNorm(32, out_dim),
400
+ nn.GroupNorm(norm_num_groups, out_dim),
1012
401
  nn.SiLU(),
1013
402
  nn.Dropout(dropout),
1014
403
  nn.Conv3d(out_dim, in_dim, (3, 1, 1), padding=(1, 0, 0)),
@@ -1035,3 +424,261 @@ class TemporalConvLayer(nn.Module):
1035
424
  (hidden_states.shape[0] * hidden_states.shape[2], -1) + hidden_states.shape[3:]
1036
425
  )
1037
426
  return hidden_states
427
+
428
+
429
+ class TemporalResnetBlock(nn.Module):
430
+ r"""
431
+ A Resnet block.
432
+
433
+ Parameters:
434
+ in_channels (`int`): The number of channels in the input.
435
+ out_channels (`int`, *optional*, default to be `None`):
436
+ The number of output channels for the first conv2d layer. If None, same as `in_channels`.
437
+ temb_channels (`int`, *optional*, default to `512`): the number of channels in timestep embedding.
438
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
439
+ """
440
+
441
+ def __init__(
442
+ self,
443
+ in_channels: int,
444
+ out_channels: Optional[int] = None,
445
+ temb_channels: int = 512,
446
+ eps: float = 1e-6,
447
+ ):
448
+ super().__init__()
449
+ self.in_channels = in_channels
450
+ out_channels = in_channels if out_channels is None else out_channels
451
+ self.out_channels = out_channels
452
+
453
+ kernel_size = (3, 1, 1)
454
+ padding = [k // 2 for k in kernel_size]
455
+
456
+ self.norm1 = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=eps, affine=True)
457
+ self.conv1 = nn.Conv3d(
458
+ in_channels,
459
+ out_channels,
460
+ kernel_size=kernel_size,
461
+ stride=1,
462
+ padding=padding,
463
+ )
464
+
465
+ if temb_channels is not None:
466
+ self.time_emb_proj = nn.Linear(temb_channels, out_channels)
467
+ else:
468
+ self.time_emb_proj = None
469
+
470
+ self.norm2 = torch.nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=eps, affine=True)
471
+
472
+ self.dropout = torch.nn.Dropout(0.0)
473
+ self.conv2 = nn.Conv3d(
474
+ out_channels,
475
+ out_channels,
476
+ kernel_size=kernel_size,
477
+ stride=1,
478
+ padding=padding,
479
+ )
480
+
481
+ self.nonlinearity = get_activation("silu")
482
+
483
+ self.use_in_shortcut = self.in_channels != out_channels
484
+
485
+ self.conv_shortcut = None
486
+ if self.use_in_shortcut:
487
+ self.conv_shortcut = nn.Conv3d(
488
+ in_channels,
489
+ out_channels,
490
+ kernel_size=1,
491
+ stride=1,
492
+ padding=0,
493
+ )
494
+
495
+ def forward(self, input_tensor: torch.FloatTensor, temb: torch.FloatTensor) -> torch.FloatTensor:
496
+ hidden_states = input_tensor
497
+
498
+ hidden_states = self.norm1(hidden_states)
499
+ hidden_states = self.nonlinearity(hidden_states)
500
+ hidden_states = self.conv1(hidden_states)
501
+
502
+ if self.time_emb_proj is not None:
503
+ temb = self.nonlinearity(temb)
504
+ temb = self.time_emb_proj(temb)[:, :, :, None, None]
505
+ temb = temb.permute(0, 2, 1, 3, 4)
506
+ hidden_states = hidden_states + temb
507
+
508
+ hidden_states = self.norm2(hidden_states)
509
+ hidden_states = self.nonlinearity(hidden_states)
510
+ hidden_states = self.dropout(hidden_states)
511
+ hidden_states = self.conv2(hidden_states)
512
+
513
+ if self.conv_shortcut is not None:
514
+ input_tensor = self.conv_shortcut(input_tensor)
515
+
516
+ output_tensor = input_tensor + hidden_states
517
+
518
+ return output_tensor
519
+
520
+
521
+ # VideoResBlock
522
+ class SpatioTemporalResBlock(nn.Module):
523
+ r"""
524
+ A SpatioTemporal Resnet block.
525
+
526
+ Parameters:
527
+ in_channels (`int`): The number of channels in the input.
528
+ out_channels (`int`, *optional*, default to be `None`):
529
+ The number of output channels for the first conv2d layer. If None, same as `in_channels`.
530
+ temb_channels (`int`, *optional*, default to `512`): the number of channels in timestep embedding.
531
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the spatial resenet.
532
+ temporal_eps (`float`, *optional*, defaults to `eps`): The epsilon to use for the temporal resnet.
533
+ merge_factor (`float`, *optional*, defaults to `0.5`): The merge factor to use for the temporal mixing.
534
+ merge_strategy (`str`, *optional*, defaults to `learned_with_images`):
535
+ The merge strategy to use for the temporal mixing.
536
+ switch_spatial_to_temporal_mix (`bool`, *optional*, defaults to `False`):
537
+ If `True`, switch the spatial and temporal mixing.
538
+ """
539
+
540
+ def __init__(
541
+ self,
542
+ in_channels: int,
543
+ out_channels: Optional[int] = None,
544
+ temb_channels: int = 512,
545
+ eps: float = 1e-6,
546
+ temporal_eps: Optional[float] = None,
547
+ merge_factor: float = 0.5,
548
+ merge_strategy="learned_with_images",
549
+ switch_spatial_to_temporal_mix: bool = False,
550
+ ):
551
+ super().__init__()
552
+
553
+ self.spatial_res_block = ResnetBlock2D(
554
+ in_channels=in_channels,
555
+ out_channels=out_channels,
556
+ temb_channels=temb_channels,
557
+ eps=eps,
558
+ )
559
+
560
+ self.temporal_res_block = TemporalResnetBlock(
561
+ in_channels=out_channels if out_channels is not None else in_channels,
562
+ out_channels=out_channels if out_channels is not None else in_channels,
563
+ temb_channels=temb_channels,
564
+ eps=temporal_eps if temporal_eps is not None else eps,
565
+ )
566
+
567
+ self.time_mixer = AlphaBlender(
568
+ alpha=merge_factor,
569
+ merge_strategy=merge_strategy,
570
+ switch_spatial_to_temporal_mix=switch_spatial_to_temporal_mix,
571
+ )
572
+
573
+ def forward(
574
+ self,
575
+ hidden_states: torch.FloatTensor,
576
+ temb: Optional[torch.FloatTensor] = None,
577
+ image_only_indicator: Optional[torch.Tensor] = None,
578
+ ):
579
+ num_frames = image_only_indicator.shape[-1]
580
+ hidden_states = self.spatial_res_block(hidden_states, temb)
581
+
582
+ batch_frames, channels, height, width = hidden_states.shape
583
+ batch_size = batch_frames // num_frames
584
+
585
+ hidden_states_mix = (
586
+ hidden_states[None, :].reshape(batch_size, num_frames, channels, height, width).permute(0, 2, 1, 3, 4)
587
+ )
588
+ hidden_states = (
589
+ hidden_states[None, :].reshape(batch_size, num_frames, channels, height, width).permute(0, 2, 1, 3, 4)
590
+ )
591
+
592
+ if temb is not None:
593
+ temb = temb.reshape(batch_size, num_frames, -1)
594
+
595
+ hidden_states = self.temporal_res_block(hidden_states, temb)
596
+ hidden_states = self.time_mixer(
597
+ x_spatial=hidden_states_mix,
598
+ x_temporal=hidden_states,
599
+ image_only_indicator=image_only_indicator,
600
+ )
601
+
602
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4).reshape(batch_frames, channels, height, width)
603
+ return hidden_states
604
+
605
+
606
+ class AlphaBlender(nn.Module):
607
+ r"""
608
+ A module to blend spatial and temporal features.
609
+
610
+ Parameters:
611
+ alpha (`float`): The initial value of the blending factor.
612
+ merge_strategy (`str`, *optional*, defaults to `learned_with_images`):
613
+ The merge strategy to use for the temporal mixing.
614
+ switch_spatial_to_temporal_mix (`bool`, *optional*, defaults to `False`):
615
+ If `True`, switch the spatial and temporal mixing.
616
+ """
617
+
618
+ strategies = ["learned", "fixed", "learned_with_images"]
619
+
620
+ def __init__(
621
+ self,
622
+ alpha: float,
623
+ merge_strategy: str = "learned_with_images",
624
+ switch_spatial_to_temporal_mix: bool = False,
625
+ ):
626
+ super().__init__()
627
+ self.merge_strategy = merge_strategy
628
+ self.switch_spatial_to_temporal_mix = switch_spatial_to_temporal_mix # For TemporalVAE
629
+
630
+ if merge_strategy not in self.strategies:
631
+ raise ValueError(f"merge_strategy needs to be in {self.strategies}")
632
+
633
+ if self.merge_strategy == "fixed":
634
+ self.register_buffer("mix_factor", torch.Tensor([alpha]))
635
+ elif self.merge_strategy == "learned" or self.merge_strategy == "learned_with_images":
636
+ self.register_parameter("mix_factor", torch.nn.Parameter(torch.Tensor([alpha])))
637
+ else:
638
+ raise ValueError(f"Unknown merge strategy {self.merge_strategy}")
639
+
640
+ def get_alpha(self, image_only_indicator: torch.Tensor, ndims: int) -> torch.Tensor:
641
+ if self.merge_strategy == "fixed":
642
+ alpha = self.mix_factor
643
+
644
+ elif self.merge_strategy == "learned":
645
+ alpha = torch.sigmoid(self.mix_factor)
646
+
647
+ elif self.merge_strategy == "learned_with_images":
648
+ if image_only_indicator is None:
649
+ raise ValueError("Please provide image_only_indicator to use learned_with_images merge strategy")
650
+
651
+ alpha = torch.where(
652
+ image_only_indicator.bool(),
653
+ torch.ones(1, 1, device=image_only_indicator.device),
654
+ torch.sigmoid(self.mix_factor)[..., None],
655
+ )
656
+
657
+ # (batch, channel, frames, height, width)
658
+ if ndims == 5:
659
+ alpha = alpha[:, None, :, None, None]
660
+ # (batch*frames, height*width, channels)
661
+ elif ndims == 3:
662
+ alpha = alpha.reshape(-1)[:, None, None]
663
+ else:
664
+ raise ValueError(f"Unexpected ndims {ndims}. Dimensions should be 3 or 5")
665
+
666
+ else:
667
+ raise NotImplementedError
668
+
669
+ return alpha
670
+
671
+ def forward(
672
+ self,
673
+ x_spatial: torch.Tensor,
674
+ x_temporal: torch.Tensor,
675
+ image_only_indicator: Optional[torch.Tensor] = None,
676
+ ) -> torch.Tensor:
677
+ alpha = self.get_alpha(image_only_indicator, x_spatial.ndim)
678
+ alpha = alpha.to(x_spatial.dtype)
679
+
680
+ if self.switch_spatial_to_temporal_mix:
681
+ alpha = 1.0 - alpha
682
+
683
+ x = alpha * x_spatial + (1.0 - alpha) * x_temporal
684
+ return x