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
@@ -46,10 +46,10 @@ class FlaxControlNetOutput(BaseOutput):
46
46
 
47
47
  class FlaxControlNetConditioningEmbedding(nn.Module):
48
48
  conditioning_embedding_channels: int
49
- block_out_channels: Tuple[int] = (16, 32, 96, 256)
49
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256)
50
50
  dtype: jnp.dtype = jnp.float32
51
51
 
52
- def setup(self):
52
+ def setup(self) -> None:
53
53
  self.conv_in = nn.Conv(
54
54
  self.block_out_channels[0],
55
55
  kernel_size=(3, 3),
@@ -87,7 +87,7 @@ class FlaxControlNetConditioningEmbedding(nn.Module):
87
87
  dtype=self.dtype,
88
88
  )
89
89
 
90
- def __call__(self, conditioning):
90
+ def __call__(self, conditioning: jnp.ndarray) -> jnp.ndarray:
91
91
  embedding = self.conv_in(conditioning)
92
92
  embedding = nn.silu(embedding)
93
93
 
@@ -146,19 +146,20 @@ class FlaxControlNetModel(nn.Module, FlaxModelMixin, ConfigMixin):
146
146
  conditioning_embedding_out_channels (`tuple`, *optional*, defaults to `(16, 32, 96, 256)`):
147
147
  The tuple of output channel for each block in the `conditioning_embedding` layer.
148
148
  """
149
+
149
150
  sample_size: int = 32
150
151
  in_channels: int = 4
151
- down_block_types: Tuple[str] = (
152
+ down_block_types: Tuple[str, ...] = (
152
153
  "CrossAttnDownBlock2D",
153
154
  "CrossAttnDownBlock2D",
154
155
  "CrossAttnDownBlock2D",
155
156
  "DownBlock2D",
156
157
  )
157
- only_cross_attention: Union[bool, Tuple[bool]] = False
158
- block_out_channels: Tuple[int] = (320, 640, 1280, 1280)
158
+ only_cross_attention: Union[bool, Tuple[bool, ...]] = False
159
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280)
159
160
  layers_per_block: int = 2
160
- attention_head_dim: Union[int, Tuple[int]] = 8
161
- num_attention_heads: Optional[Union[int, Tuple[int]]] = None
161
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8
162
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None
162
163
  cross_attention_dim: int = 1280
163
164
  dropout: float = 0.0
164
165
  use_linear_projection: bool = False
@@ -166,7 +167,7 @@ class FlaxControlNetModel(nn.Module, FlaxModelMixin, ConfigMixin):
166
167
  flip_sin_to_cos: bool = True
167
168
  freq_shift: int = 0
168
169
  controlnet_conditioning_channel_order: str = "rgb"
169
- conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256)
170
+ conditioning_embedding_out_channels: Tuple[int, ...] = (16, 32, 96, 256)
170
171
 
171
172
  def init_weights(self, rng: jax.Array) -> FrozenDict:
172
173
  # init input tensors
@@ -182,7 +183,7 @@ class FlaxControlNetModel(nn.Module, FlaxModelMixin, ConfigMixin):
182
183
 
183
184
  return self.init(rngs, sample, timesteps, encoder_hidden_states, controlnet_cond)["params"]
184
185
 
185
- def setup(self):
186
+ def setup(self) -> None:
186
187
  block_out_channels = self.block_out_channels
187
188
  time_embed_dim = block_out_channels[0] * 4
188
189
 
@@ -312,21 +313,21 @@ class FlaxControlNetModel(nn.Module, FlaxModelMixin, ConfigMixin):
312
313
 
313
314
  def __call__(
314
315
  self,
315
- sample,
316
- timesteps,
317
- encoder_hidden_states,
318
- controlnet_cond,
316
+ sample: jnp.ndarray,
317
+ timesteps: Union[jnp.ndarray, float, int],
318
+ encoder_hidden_states: jnp.ndarray,
319
+ controlnet_cond: jnp.ndarray,
319
320
  conditioning_scale: float = 1.0,
320
321
  return_dict: bool = True,
321
322
  train: bool = False,
322
- ) -> Union[FlaxControlNetOutput, Tuple]:
323
+ ) -> Union[FlaxControlNetOutput, Tuple[Tuple[jnp.ndarray, ...], jnp.ndarray]]:
323
324
  r"""
324
325
  Args:
325
326
  sample (`jnp.ndarray`): (batch, channel, height, width) noisy inputs tensor
326
327
  timestep (`jnp.ndarray` or `float` or `int`): timesteps
327
328
  encoder_hidden_states (`jnp.ndarray`): (batch_size, sequence_length, hidden_size) encoder hidden states
328
329
  controlnet_cond (`jnp.ndarray`): (batch, channel, height, width) the conditional input tensor
329
- conditioning_scale: (`float`) the scale factor for controlnet outputs
330
+ conditioning_scale (`float`, *optional*, defaults to `1.0`): the scale factor for controlnet outputs
330
331
  return_dict (`bool`, *optional*, defaults to `True`):
331
332
  Whether or not to return a [`models.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] instead of a
332
333
  plain tuple.
@@ -335,8 +336,8 @@ class FlaxControlNetModel(nn.Module, FlaxModelMixin, ConfigMixin):
335
336
 
336
337
  Returns:
337
338
  [`~models.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] or `tuple`:
338
- [`~models.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`.
339
- When returning a tuple, the first element is the sample tensor.
339
+ [`~models.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] if `return_dict` is True, otherwise a
340
+ `tuple`. When returning a tuple, the first element is the sample tensor.
340
341
  """
341
342
  channel_order = self.controlnet_conditioning_channel_order
342
343
  if channel_order == "bgr":
@@ -0,0 +1,338 @@
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 typing import Optional, Tuple
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+
21
+ from ..utils import USE_PEFT_BACKEND
22
+ from .lora import LoRACompatibleConv
23
+ from .normalization import RMSNorm
24
+ from .upsampling import upfirdn2d_native
25
+
26
+
27
+ class Downsample1D(nn.Module):
28
+ """A 1D downsampling layer with an optional convolution.
29
+
30
+ Parameters:
31
+ channels (`int`):
32
+ number of channels in the inputs and outputs.
33
+ use_conv (`bool`, default `False`):
34
+ option to use a convolution.
35
+ out_channels (`int`, optional):
36
+ number of output channels. Defaults to `channels`.
37
+ padding (`int`, default `1`):
38
+ padding for the convolution.
39
+ name (`str`, default `conv`):
40
+ name of the downsampling 1D layer.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ channels: int,
46
+ use_conv: bool = False,
47
+ out_channels: Optional[int] = None,
48
+ padding: int = 1,
49
+ name: str = "conv",
50
+ ):
51
+ super().__init__()
52
+ self.channels = channels
53
+ self.out_channels = out_channels or channels
54
+ self.use_conv = use_conv
55
+ self.padding = padding
56
+ stride = 2
57
+ self.name = name
58
+
59
+ if use_conv:
60
+ self.conv = nn.Conv1d(self.channels, self.out_channels, 3, stride=stride, padding=padding)
61
+ else:
62
+ assert self.channels == self.out_channels
63
+ self.conv = nn.AvgPool1d(kernel_size=stride, stride=stride)
64
+
65
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
66
+ assert inputs.shape[1] == self.channels
67
+ return self.conv(inputs)
68
+
69
+
70
+ class Downsample2D(nn.Module):
71
+ """A 2D downsampling layer with an optional convolution.
72
+
73
+ Parameters:
74
+ channels (`int`):
75
+ number of channels in the inputs and outputs.
76
+ use_conv (`bool`, default `False`):
77
+ option to use a convolution.
78
+ out_channels (`int`, optional):
79
+ number of output channels. Defaults to `channels`.
80
+ padding (`int`, default `1`):
81
+ padding for the convolution.
82
+ name (`str`, default `conv`):
83
+ name of the downsampling 2D layer.
84
+ """
85
+
86
+ def __init__(
87
+ self,
88
+ channels: int,
89
+ use_conv: bool = False,
90
+ out_channels: Optional[int] = None,
91
+ padding: int = 1,
92
+ name: str = "conv",
93
+ kernel_size=3,
94
+ norm_type=None,
95
+ eps=None,
96
+ elementwise_affine=None,
97
+ bias=True,
98
+ ):
99
+ super().__init__()
100
+ self.channels = channels
101
+ self.out_channels = out_channels or channels
102
+ self.use_conv = use_conv
103
+ self.padding = padding
104
+ stride = 2
105
+ self.name = name
106
+ conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
107
+
108
+ if norm_type == "ln_norm":
109
+ self.norm = nn.LayerNorm(channels, eps, elementwise_affine)
110
+ elif norm_type == "rms_norm":
111
+ self.norm = RMSNorm(channels, eps, elementwise_affine)
112
+ elif norm_type is None:
113
+ self.norm = None
114
+ else:
115
+ raise ValueError(f"unknown norm_type: {norm_type}")
116
+
117
+ if use_conv:
118
+ conv = conv_cls(
119
+ self.channels, self.out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias
120
+ )
121
+ else:
122
+ assert self.channels == self.out_channels
123
+ conv = nn.AvgPool2d(kernel_size=stride, stride=stride)
124
+
125
+ # TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
126
+ if name == "conv":
127
+ self.Conv2d_0 = conv
128
+ self.conv = conv
129
+ elif name == "Conv2d_0":
130
+ self.conv = conv
131
+ else:
132
+ self.conv = conv
133
+
134
+ def forward(self, hidden_states: torch.FloatTensor, scale: float = 1.0) -> torch.FloatTensor:
135
+ assert hidden_states.shape[1] == self.channels
136
+
137
+ if self.norm is not None:
138
+ hidden_states = self.norm(hidden_states.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
139
+
140
+ if self.use_conv and self.padding == 0:
141
+ pad = (0, 1, 0, 1)
142
+ hidden_states = F.pad(hidden_states, pad, mode="constant", value=0)
143
+
144
+ assert hidden_states.shape[1] == self.channels
145
+
146
+ if not USE_PEFT_BACKEND:
147
+ if isinstance(self.conv, LoRACompatibleConv):
148
+ hidden_states = self.conv(hidden_states, scale)
149
+ else:
150
+ hidden_states = self.conv(hidden_states)
151
+ else:
152
+ hidden_states = self.conv(hidden_states)
153
+
154
+ return hidden_states
155
+
156
+
157
+ class FirDownsample2D(nn.Module):
158
+ """A 2D FIR downsampling layer with an optional convolution.
159
+
160
+ Parameters:
161
+ channels (`int`):
162
+ number of channels in the inputs and outputs.
163
+ use_conv (`bool`, default `False`):
164
+ option to use a convolution.
165
+ out_channels (`int`, optional):
166
+ number of output channels. Defaults to `channels`.
167
+ fir_kernel (`tuple`, default `(1, 3, 3, 1)`):
168
+ kernel for the FIR filter.
169
+ """
170
+
171
+ def __init__(
172
+ self,
173
+ channels: Optional[int] = None,
174
+ out_channels: Optional[int] = None,
175
+ use_conv: bool = False,
176
+ fir_kernel: Tuple[int, int, int, int] = (1, 3, 3, 1),
177
+ ):
178
+ super().__init__()
179
+ out_channels = out_channels if out_channels else channels
180
+ if use_conv:
181
+ self.Conv2d_0 = nn.Conv2d(channels, out_channels, kernel_size=3, stride=1, padding=1)
182
+ self.fir_kernel = fir_kernel
183
+ self.use_conv = use_conv
184
+ self.out_channels = out_channels
185
+
186
+ def _downsample_2d(
187
+ self,
188
+ hidden_states: torch.FloatTensor,
189
+ weight: Optional[torch.FloatTensor] = None,
190
+ kernel: Optional[torch.FloatTensor] = None,
191
+ factor: int = 2,
192
+ gain: float = 1,
193
+ ) -> torch.FloatTensor:
194
+ """Fused `Conv2d()` followed by `downsample_2d()`.
195
+ Padding is performed only once at the beginning, not between the operations. The fused op is considerably more
196
+ efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of
197
+ arbitrary order.
198
+
199
+ Args:
200
+ hidden_states (`torch.FloatTensor`):
201
+ Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
202
+ weight (`torch.FloatTensor`, *optional*):
203
+ Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be
204
+ performed by `inChannels = x.shape[0] // numGroups`.
205
+ kernel (`torch.FloatTensor`, *optional*):
206
+ FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
207
+ corresponds to average pooling.
208
+ factor (`int`, *optional*, default to `2`):
209
+ Integer downsampling factor.
210
+ gain (`float`, *optional*, default to `1.0`):
211
+ Scaling factor for signal magnitude.
212
+
213
+ Returns:
214
+ output (`torch.FloatTensor`):
215
+ Tensor of the shape `[N, C, H // factor, W // factor]` or `[N, H // factor, W // factor, C]`, and same
216
+ datatype as `x`.
217
+ """
218
+
219
+ assert isinstance(factor, int) and factor >= 1
220
+ if kernel is None:
221
+ kernel = [1] * factor
222
+
223
+ # setup kernel
224
+ kernel = torch.tensor(kernel, dtype=torch.float32)
225
+ if kernel.ndim == 1:
226
+ kernel = torch.outer(kernel, kernel)
227
+ kernel /= torch.sum(kernel)
228
+
229
+ kernel = kernel * gain
230
+
231
+ if self.use_conv:
232
+ _, _, convH, convW = weight.shape
233
+ pad_value = (kernel.shape[0] - factor) + (convW - 1)
234
+ stride_value = [factor, factor]
235
+ upfirdn_input = upfirdn2d_native(
236
+ hidden_states,
237
+ torch.tensor(kernel, device=hidden_states.device),
238
+ pad=((pad_value + 1) // 2, pad_value // 2),
239
+ )
240
+ output = F.conv2d(upfirdn_input, weight, stride=stride_value, padding=0)
241
+ else:
242
+ pad_value = kernel.shape[0] - factor
243
+ output = upfirdn2d_native(
244
+ hidden_states,
245
+ torch.tensor(kernel, device=hidden_states.device),
246
+ down=factor,
247
+ pad=((pad_value + 1) // 2, pad_value // 2),
248
+ )
249
+
250
+ return output
251
+
252
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
253
+ if self.use_conv:
254
+ downsample_input = self._downsample_2d(hidden_states, weight=self.Conv2d_0.weight, kernel=self.fir_kernel)
255
+ hidden_states = downsample_input + self.Conv2d_0.bias.reshape(1, -1, 1, 1)
256
+ else:
257
+ hidden_states = self._downsample_2d(hidden_states, kernel=self.fir_kernel, factor=2)
258
+
259
+ return hidden_states
260
+
261
+
262
+ # downsample/upsample layer used in k-upscaler, might be able to use FirDownsample2D/DirUpsample2D instead
263
+ class KDownsample2D(nn.Module):
264
+ r"""A 2D K-downsampling layer.
265
+
266
+ Parameters:
267
+ pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
268
+ """
269
+
270
+ def __init__(self, pad_mode: str = "reflect"):
271
+ super().__init__()
272
+ self.pad_mode = pad_mode
273
+ kernel_1d = torch.tensor([[1 / 8, 3 / 8, 3 / 8, 1 / 8]])
274
+ self.pad = kernel_1d.shape[1] // 2 - 1
275
+ self.register_buffer("kernel", kernel_1d.T @ kernel_1d, persistent=False)
276
+
277
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
278
+ inputs = F.pad(inputs, (self.pad,) * 4, self.pad_mode)
279
+ weight = inputs.new_zeros(
280
+ [
281
+ inputs.shape[1],
282
+ inputs.shape[1],
283
+ self.kernel.shape[0],
284
+ self.kernel.shape[1],
285
+ ]
286
+ )
287
+ indices = torch.arange(inputs.shape[1], device=inputs.device)
288
+ kernel = self.kernel.to(weight)[None, :].expand(inputs.shape[1], -1, -1)
289
+ weight[indices, indices] = kernel
290
+ return F.conv2d(inputs, weight, stride=2)
291
+
292
+
293
+ def downsample_2d(
294
+ hidden_states: torch.FloatTensor,
295
+ kernel: Optional[torch.FloatTensor] = None,
296
+ factor: int = 2,
297
+ gain: float = 1,
298
+ ) -> torch.FloatTensor:
299
+ r"""Downsample2D a batch of 2D images with the given filter.
300
+ Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and downsamples each image with the
301
+ given filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the
302
+ specified `gain`. Pixels outside the image are assumed to be zero, and the filter is padded with zeros so that its
303
+ shape is a multiple of the downsampling factor.
304
+
305
+ Args:
306
+ hidden_states (`torch.FloatTensor`)
307
+ Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
308
+ kernel (`torch.FloatTensor`, *optional*):
309
+ FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
310
+ corresponds to average pooling.
311
+ factor (`int`, *optional*, default to `2`):
312
+ Integer downsampling factor.
313
+ gain (`float`, *optional*, default to `1.0`):
314
+ Scaling factor for signal magnitude.
315
+
316
+ Returns:
317
+ output (`torch.FloatTensor`):
318
+ Tensor of the shape `[N, C, H // factor, W // factor]`
319
+ """
320
+
321
+ assert isinstance(factor, int) and factor >= 1
322
+ if kernel is None:
323
+ kernel = [1] * factor
324
+
325
+ kernel = torch.tensor(kernel, dtype=torch.float32)
326
+ if kernel.ndim == 1:
327
+ kernel = torch.outer(kernel, kernel)
328
+ kernel /= torch.sum(kernel)
329
+
330
+ kernel = kernel * gain
331
+ pad_value = kernel.shape[0] - factor
332
+ output = upfirdn2d_native(
333
+ hidden_states,
334
+ kernel.to(device=hidden_states.device),
335
+ down=factor,
336
+ pad=((pad_value + 1) // 2, pad_value // 2),
337
+ )
338
+ return output
@@ -20,6 +20,7 @@ from torch import nn
20
20
 
21
21
  from ..utils import USE_PEFT_BACKEND
22
22
  from .activations import get_activation
23
+ from .attention_processor import Attention
23
24
  from .lora import LoRACompatibleLinear
24
25
 
25
26
 
@@ -196,11 +197,12 @@ class TimestepEmbedding(nn.Module):
196
197
  out_dim: int = None,
197
198
  post_act_fn: Optional[str] = None,
198
199
  cond_proj_dim=None,
200
+ sample_proj_bias=True,
199
201
  ):
200
202
  super().__init__()
201
203
  linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear
202
204
 
203
- self.linear_1 = linear_cls(in_channels, time_embed_dim)
205
+ self.linear_1 = linear_cls(in_channels, time_embed_dim, sample_proj_bias)
204
206
 
205
207
  if cond_proj_dim is not None:
206
208
  self.cond_proj = nn.Linear(cond_proj_dim, in_channels, bias=False)
@@ -213,7 +215,7 @@ class TimestepEmbedding(nn.Module):
213
215
  time_embed_dim_out = out_dim
214
216
  else:
215
217
  time_embed_dim_out = time_embed_dim
216
- self.linear_2 = linear_cls(time_embed_dim, time_embed_dim_out)
218
+ self.linear_2 = linear_cls(time_embed_dim, time_embed_dim_out, sample_proj_bias)
217
219
 
218
220
  if post_act_fn is None:
219
221
  self.post_act = None
@@ -460,6 +462,18 @@ class ImageProjection(nn.Module):
460
462
  return image_embeds
461
463
 
462
464
 
465
+ class MLPProjection(nn.Module):
466
+ def __init__(self, image_embed_dim=1024, cross_attention_dim=1024):
467
+ super().__init__()
468
+ from .attention import FeedForward
469
+
470
+ self.ff = FeedForward(image_embed_dim, cross_attention_dim, mult=1, activation_fn="gelu")
471
+ self.norm = nn.LayerNorm(cross_attention_dim)
472
+
473
+ def forward(self, image_embeds: torch.FloatTensor):
474
+ return self.norm(self.ff(image_embeds))
475
+
476
+
463
477
  class CombinedTimestepLabelEmbeddings(nn.Module):
464
478
  def __init__(self, num_classes, embedding_dim, class_dropout_prob=0.1):
465
479
  super().__init__()
@@ -716,7 +730,7 @@ class PositionNet(nn.Module):
716
730
  return objs
717
731
 
718
732
 
719
- class CombinedTimestepSizeEmbeddings(nn.Module):
733
+ class PixArtAlphaCombinedTimestepSizeEmbeddings(nn.Module):
720
734
  """
721
735
  For PixArt-Alpha.
722
736
 
@@ -733,45 +747,27 @@ class CombinedTimestepSizeEmbeddings(nn.Module):
733
747
 
734
748
  self.use_additional_conditions = use_additional_conditions
735
749
  if use_additional_conditions:
736
- self.use_additional_conditions = True
737
750
  self.additional_condition_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
738
751
  self.resolution_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
739
752
  self.aspect_ratio_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
740
753
 
741
- def apply_condition(self, size: torch.Tensor, batch_size: int, embedder: nn.Module):
742
- if size.ndim == 1:
743
- size = size[:, None]
744
-
745
- if size.shape[0] != batch_size:
746
- size = size.repeat(batch_size // size.shape[0], 1)
747
- if size.shape[0] != batch_size:
748
- raise ValueError(f"`batch_size` should be {size.shape[0]} but found {batch_size}.")
749
-
750
- current_batch_size, dims = size.shape[0], size.shape[1]
751
- size = size.reshape(-1)
752
- size_freq = self.additional_condition_proj(size).to(size.dtype)
753
-
754
- size_emb = embedder(size_freq)
755
- size_emb = size_emb.reshape(current_batch_size, dims * self.outdim)
756
- return size_emb
757
-
758
754
  def forward(self, timestep, resolution, aspect_ratio, batch_size, hidden_dtype):
759
755
  timesteps_proj = self.time_proj(timestep)
760
756
  timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
761
757
 
762
758
  if self.use_additional_conditions:
763
- resolution = self.apply_condition(resolution, batch_size=batch_size, embedder=self.resolution_embedder)
764
- aspect_ratio = self.apply_condition(
765
- aspect_ratio, batch_size=batch_size, embedder=self.aspect_ratio_embedder
766
- )
767
- conditioning = timesteps_emb + torch.cat([resolution, aspect_ratio], dim=1)
759
+ resolution_emb = self.additional_condition_proj(resolution.flatten()).to(hidden_dtype)
760
+ resolution_emb = self.resolution_embedder(resolution_emb).reshape(batch_size, -1)
761
+ aspect_ratio_emb = self.additional_condition_proj(aspect_ratio.flatten()).to(hidden_dtype)
762
+ aspect_ratio_emb = self.aspect_ratio_embedder(aspect_ratio_emb).reshape(batch_size, -1)
763
+ conditioning = timesteps_emb + torch.cat([resolution_emb, aspect_ratio_emb], dim=1)
768
764
  else:
769
765
  conditioning = timesteps_emb
770
766
 
771
767
  return conditioning
772
768
 
773
769
 
774
- class CaptionProjection(nn.Module):
770
+ class PixArtAlphaTextProjection(nn.Module):
775
771
  """
776
772
  Projects caption embeddings. Also handles dropout for classifier-free guidance.
777
773
 
@@ -783,10 +779,97 @@ class CaptionProjection(nn.Module):
783
779
  self.linear_1 = nn.Linear(in_features=in_features, out_features=hidden_size, bias=True)
784
780
  self.act_1 = nn.GELU(approximate="tanh")
785
781
  self.linear_2 = nn.Linear(in_features=hidden_size, out_features=hidden_size, bias=True)
786
- self.register_buffer("y_embedding", nn.Parameter(torch.randn(num_tokens, in_features) / in_features**0.5))
787
782
 
788
- def forward(self, caption, force_drop_ids=None):
783
+ def forward(self, caption):
789
784
  hidden_states = self.linear_1(caption)
790
785
  hidden_states = self.act_1(hidden_states)
791
786
  hidden_states = self.linear_2(hidden_states)
792
787
  return hidden_states
788
+
789
+
790
+ class Resampler(nn.Module):
791
+ """Resampler of IP-Adapter Plus.
792
+
793
+ Args:
794
+ ----
795
+ embed_dims (int): The feature dimension. Defaults to 768.
796
+ output_dims (int): The number of output channels, that is the same
797
+ number of the channels in the
798
+ `unet.config.cross_attention_dim`. Defaults to 1024.
799
+ hidden_dims (int): The number of hidden channels. Defaults to 1280.
800
+ depth (int): The number of blocks. Defaults to 8.
801
+ dim_head (int): The number of head channels. Defaults to 64.
802
+ heads (int): Parallel attention heads. Defaults to 16.
803
+ num_queries (int): The number of queries. Defaults to 8.
804
+ ffn_ratio (float): The expansion ratio of feedforward network hidden
805
+ layer channels. Defaults to 4.
806
+ """
807
+
808
+ def __init__(
809
+ self,
810
+ embed_dims: int = 768,
811
+ output_dims: int = 1024,
812
+ hidden_dims: int = 1280,
813
+ depth: int = 4,
814
+ dim_head: int = 64,
815
+ heads: int = 16,
816
+ num_queries: int = 8,
817
+ ffn_ratio: float = 4,
818
+ ) -> None:
819
+ super().__init__()
820
+ from .attention import FeedForward # Lazy import to avoid circular import
821
+
822
+ self.latents = nn.Parameter(torch.randn(1, num_queries, hidden_dims) / hidden_dims**0.5)
823
+
824
+ self.proj_in = nn.Linear(embed_dims, hidden_dims)
825
+
826
+ self.proj_out = nn.Linear(hidden_dims, output_dims)
827
+ self.norm_out = nn.LayerNorm(output_dims)
828
+
829
+ self.layers = nn.ModuleList([])
830
+ for _ in range(depth):
831
+ self.layers.append(
832
+ nn.ModuleList(
833
+ [
834
+ nn.LayerNorm(hidden_dims),
835
+ nn.LayerNorm(hidden_dims),
836
+ Attention(
837
+ query_dim=hidden_dims,
838
+ dim_head=dim_head,
839
+ heads=heads,
840
+ out_bias=False,
841
+ ),
842
+ nn.Sequential(
843
+ nn.LayerNorm(hidden_dims),
844
+ FeedForward(hidden_dims, hidden_dims, activation_fn="gelu", mult=ffn_ratio, bias=False),
845
+ ),
846
+ ]
847
+ )
848
+ )
849
+
850
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
851
+ """Forward pass.
852
+
853
+ Args:
854
+ ----
855
+ x (torch.Tensor): Input Tensor.
856
+
857
+ Returns:
858
+ -------
859
+ torch.Tensor: Output Tensor.
860
+ """
861
+ latents = self.latents.repeat(x.size(0), 1, 1)
862
+
863
+ x = self.proj_in(x)
864
+
865
+ for ln0, ln1, attn, ff in self.layers:
866
+ residual = latents
867
+
868
+ encoder_hidden_states = ln0(x)
869
+ latents = ln1(latents)
870
+ encoder_hidden_states = torch.cat([encoder_hidden_states, latents], dim=-2)
871
+ latents = attn(latents, encoder_hidden_states) + residual
872
+ latents = ff(latents) + latents
873
+
874
+ latents = self.proj_out(latents)
875
+ return self.norm_out(latents)
@@ -65,6 +65,7 @@ class FlaxTimestepEmbedding(nn.Module):
65
65
  dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
66
66
  Parameters `dtype`
67
67
  """
68
+
68
69
  time_embed_dim: int = 32
69
70
  dtype: jnp.dtype = jnp.float32
70
71
 
@@ -84,6 +85,7 @@ class FlaxTimesteps(nn.Module):
84
85
  dim (`int`, *optional*, defaults to `32`):
85
86
  Time step embedding dimension
86
87
  """
88
+
87
89
  dim: int = 32
88
90
  flip_sin_to_cos: bool = False
89
91
  freq_shift: float = 1