diffusers 0.24.0__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 (174) hide show
  1. diffusers/__init__.py +11 -1
  2. diffusers/commands/fp16_safetensors.py +10 -11
  3. diffusers/configuration_utils.py +12 -8
  4. diffusers/dependency_versions_table.py +2 -1
  5. diffusers/experimental/rl/value_guided_sampling.py +1 -1
  6. diffusers/image_processor.py +286 -46
  7. diffusers/loaders/ip_adapter.py +11 -9
  8. diffusers/loaders/lora.py +198 -60
  9. diffusers/loaders/single_file.py +24 -18
  10. diffusers/loaders/textual_inversion.py +10 -14
  11. diffusers/loaders/unet.py +130 -37
  12. diffusers/models/__init__.py +18 -12
  13. diffusers/models/activations.py +9 -6
  14. diffusers/models/attention.py +137 -16
  15. diffusers/models/attention_processor.py +133 -46
  16. diffusers/models/autoencoders/__init__.py +5 -0
  17. diffusers/models/{autoencoder_asym_kl.py → autoencoders/autoencoder_asym_kl.py} +4 -4
  18. diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +45 -6
  19. diffusers/models/{autoencoder_kl_temporal_decoder.py → autoencoders/autoencoder_kl_temporal_decoder.py} +8 -8
  20. diffusers/models/{autoencoder_tiny.py → autoencoders/autoencoder_tiny.py} +4 -4
  21. diffusers/models/{consistency_decoder_vae.py → autoencoders/consistency_decoder_vae.py} +14 -14
  22. diffusers/models/{vae.py → autoencoders/vae.py} +9 -5
  23. diffusers/models/downsampling.py +338 -0
  24. diffusers/models/embeddings.py +112 -29
  25. diffusers/models/modeling_flax_utils.py +12 -7
  26. diffusers/models/modeling_utils.py +10 -10
  27. diffusers/models/normalization.py +108 -2
  28. diffusers/models/resnet.py +15 -699
  29. diffusers/models/transformer_2d.py +2 -2
  30. diffusers/models/unet_2d_condition.py +37 -0
  31. diffusers/models/{unet_kandi3.py → unet_kandinsky3.py} +105 -159
  32. diffusers/models/upsampling.py +454 -0
  33. diffusers/models/uvit_2d.py +471 -0
  34. diffusers/models/vq_model.py +9 -2
  35. diffusers/pipelines/__init__.py +81 -73
  36. diffusers/pipelines/amused/__init__.py +62 -0
  37. diffusers/pipelines/amused/pipeline_amused.py +328 -0
  38. diffusers/pipelines/amused/pipeline_amused_img2img.py +347 -0
  39. diffusers/pipelines/amused/pipeline_amused_inpaint.py +378 -0
  40. diffusers/pipelines/animatediff/pipeline_animatediff.py +38 -10
  41. diffusers/pipelines/auto_pipeline.py +17 -13
  42. diffusers/pipelines/controlnet/pipeline_controlnet.py +27 -10
  43. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +47 -5
  44. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +25 -8
  45. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +4 -6
  46. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +26 -10
  47. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +4 -3
  48. diffusers/pipelines/deprecated/__init__.py +153 -0
  49. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/__init__.py +3 -3
  50. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion.py +91 -18
  51. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion_img2img.py +91 -18
  52. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_output.py +1 -1
  53. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/__init__.py +1 -1
  54. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/mel.py +2 -2
  55. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/pipeline_audio_diffusion.py +4 -4
  56. diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/__init__.py +1 -1
  57. diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/pipeline_latent_diffusion_uncond.py +4 -4
  58. diffusers/pipelines/{pndm → deprecated/pndm}/__init__.py +1 -1
  59. diffusers/pipelines/{pndm → deprecated/pndm}/pipeline_pndm.py +4 -4
  60. diffusers/pipelines/{repaint → deprecated/repaint}/__init__.py +1 -1
  61. diffusers/pipelines/{repaint → deprecated/repaint}/pipeline_repaint.py +5 -5
  62. diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/__init__.py +1 -1
  63. diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/pipeline_score_sde_ve.py +4 -4
  64. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/__init__.py +6 -6
  65. diffusers/pipelines/{spectrogram_diffusion/continous_encoder.py → deprecated/spectrogram_diffusion/continuous_encoder.py} +2 -2
  66. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/midi_utils.py +1 -1
  67. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/notes_encoder.py +2 -2
  68. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/pipeline_spectrogram_diffusion.py +7 -7
  69. diffusers/pipelines/deprecated/stable_diffusion_variants/__init__.py +55 -0
  70. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_cycle_diffusion.py +16 -11
  71. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_onnx_stable_diffusion_inpaint_legacy.py +6 -6
  72. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_inpaint_legacy.py +11 -11
  73. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_model_editing.py +16 -11
  74. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_paradigms.py +10 -10
  75. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_pix2pix_zero.py +13 -13
  76. diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/__init__.py +1 -1
  77. diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/pipeline_stochastic_karras_ve.py +4 -4
  78. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/__init__.py +3 -3
  79. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/modeling_text_unet.py +54 -11
  80. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion.py +4 -4
  81. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_dual_guided.py +6 -6
  82. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_image_variation.py +6 -6
  83. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_text_to_image.py +6 -6
  84. diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/__init__.py +3 -3
  85. diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/pipeline_vq_diffusion.py +5 -5
  86. diffusers/pipelines/kandinsky3/__init__.py +4 -4
  87. diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +98 -0
  88. diffusers/pipelines/kandinsky3/{kandinsky3_pipeline.py → pipeline_kandinsky3.py} +172 -35
  89. diffusers/pipelines/kandinsky3/{kandinsky3img2img_pipeline.py → pipeline_kandinsky3_img2img.py} +228 -34
  90. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +46 -5
  91. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +47 -6
  92. diffusers/pipelines/onnx_utils.py +8 -5
  93. diffusers/pipelines/pipeline_flax_utils.py +7 -6
  94. diffusers/pipelines/pipeline_utils.py +30 -29
  95. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +51 -2
  96. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +3 -3
  97. diffusers/pipelines/stable_diffusion/__init__.py +1 -72
  98. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +67 -75
  99. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +92 -8
  100. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +92 -8
  101. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +138 -10
  102. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +57 -7
  103. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +3 -0
  104. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +6 -0
  105. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +5 -0
  106. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -0
  107. diffusers/pipelines/stable_diffusion_attend_and_excite/__init__.py +48 -0
  108. diffusers/pipelines/{stable_diffusion → stable_diffusion_attend_and_excite}/pipeline_stable_diffusion_attend_and_excite.py +5 -2
  109. diffusers/pipelines/stable_diffusion_diffedit/__init__.py +48 -0
  110. diffusers/pipelines/{stable_diffusion → stable_diffusion_diffedit}/pipeline_stable_diffusion_diffedit.py +2 -3
  111. diffusers/pipelines/stable_diffusion_gligen/__init__.py +50 -0
  112. diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen.py +2 -2
  113. diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen_text_image.py +3 -3
  114. diffusers/pipelines/stable_diffusion_k_diffusion/__init__.py +60 -0
  115. diffusers/pipelines/{stable_diffusion → stable_diffusion_k_diffusion}/pipeline_stable_diffusion_k_diffusion.py +6 -1
  116. diffusers/pipelines/stable_diffusion_ldm3d/__init__.py +48 -0
  117. diffusers/pipelines/{stable_diffusion → stable_diffusion_ldm3d}/pipeline_stable_diffusion_ldm3d.py +50 -7
  118. diffusers/pipelines/stable_diffusion_panorama/__init__.py +48 -0
  119. diffusers/pipelines/{stable_diffusion → stable_diffusion_panorama}/pipeline_stable_diffusion_panorama.py +56 -8
  120. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +58 -6
  121. diffusers/pipelines/stable_diffusion_sag/__init__.py +48 -0
  122. diffusers/pipelines/{stable_diffusion → stable_diffusion_sag}/pipeline_stable_diffusion_sag.py +67 -10
  123. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +97 -15
  124. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +98 -14
  125. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +97 -14
  126. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +7 -5
  127. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +12 -9
  128. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +6 -0
  129. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +5 -0
  130. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +5 -0
  131. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +331 -9
  132. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +468 -9
  133. diffusers/pipelines/unclip/pipeline_unclip.py +2 -1
  134. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +1 -0
  135. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
  136. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +4 -0
  137. diffusers/schedulers/__init__.py +2 -0
  138. diffusers/schedulers/scheduling_amused.py +162 -0
  139. diffusers/schedulers/scheduling_consistency_models.py +2 -0
  140. diffusers/schedulers/scheduling_ddim_inverse.py +1 -4
  141. diffusers/schedulers/scheduling_ddpm.py +46 -0
  142. diffusers/schedulers/scheduling_ddpm_parallel.py +46 -0
  143. diffusers/schedulers/scheduling_deis_multistep.py +13 -1
  144. diffusers/schedulers/scheduling_dpmsolver_multistep.py +13 -1
  145. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +13 -1
  146. diffusers/schedulers/scheduling_dpmsolver_sde.py +2 -0
  147. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +13 -1
  148. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +58 -0
  149. diffusers/schedulers/scheduling_euler_discrete.py +62 -3
  150. diffusers/schedulers/scheduling_heun_discrete.py +2 -0
  151. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +2 -0
  152. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +2 -0
  153. diffusers/schedulers/scheduling_lms_discrete.py +2 -0
  154. diffusers/schedulers/scheduling_unipc_multistep.py +13 -1
  155. diffusers/schedulers/scheduling_utils.py +3 -1
  156. diffusers/schedulers/scheduling_utils_flax.py +3 -1
  157. diffusers/training_utils.py +1 -1
  158. diffusers/utils/__init__.py +0 -2
  159. diffusers/utils/constants.py +2 -5
  160. diffusers/utils/dummy_pt_objects.py +30 -0
  161. diffusers/utils/dummy_torch_and_transformers_objects.py +45 -0
  162. diffusers/utils/dynamic_modules_utils.py +14 -18
  163. diffusers/utils/hub_utils.py +24 -36
  164. diffusers/utils/logging.py +1 -1
  165. diffusers/utils/state_dict_utils.py +8 -0
  166. diffusers/utils/testing_utils.py +199 -1
  167. diffusers/utils/torch_utils.py +3 -3
  168. {diffusers-0.24.0.dist-info → diffusers-0.25.0.dist-info}/METADATA +54 -53
  169. {diffusers-0.24.0.dist-info → diffusers-0.25.0.dist-info}/RECORD +174 -155
  170. {diffusers-0.24.0.dist-info → diffusers-0.25.0.dist-info}/WHEEL +1 -1
  171. {diffusers-0.24.0.dist-info → diffusers-0.25.0.dist-info}/entry_points.txt +0 -1
  172. /diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/modeling_roberta_series.py +0 -0
  173. {diffusers-0.24.0.dist-info → diffusers-0.25.0.dist-info}/LICENSE +0 -0
  174. {diffusers-0.24.0.dist-info → diffusers-0.25.0.dist-info}/top_level.txt +0 -0
@@ -18,20 +18,20 @@ import torch
18
18
  import torch.nn.functional as F
19
19
  from torch import nn
20
20
 
21
- from ..configuration_utils import ConfigMixin, register_to_config
22
- from ..schedulers import ConsistencyDecoderScheduler
23
- from ..utils import BaseOutput
24
- from ..utils.accelerate_utils import apply_forward_hook
25
- from ..utils.torch_utils import randn_tensor
26
- from .attention_processor import (
21
+ from ...configuration_utils import ConfigMixin, register_to_config
22
+ from ...schedulers import ConsistencyDecoderScheduler
23
+ from ...utils import BaseOutput
24
+ from ...utils.accelerate_utils import apply_forward_hook
25
+ from ...utils.torch_utils import randn_tensor
26
+ from ..attention_processor import (
27
27
  ADDED_KV_ATTENTION_PROCESSORS,
28
28
  CROSS_ATTENTION_PROCESSORS,
29
29
  AttentionProcessor,
30
30
  AttnAddedKVProcessor,
31
31
  AttnProcessor,
32
32
  )
33
- from .modeling_utils import ModelMixin
34
- from .unet_2d import UNet2DModel
33
+ from ..modeling_utils import ModelMixin
34
+ from ..unet_2d import UNet2DModel
35
35
  from .vae import DecoderOutput, DiagonalGaussianDistribution, Encoder
36
36
 
37
37
 
@@ -153,7 +153,7 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
153
153
  self.use_slicing = False
154
154
  self.use_tiling = False
155
155
 
156
- # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.enable_tiling
156
+ # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.enable_tiling
157
157
  def enable_tiling(self, use_tiling: bool = True):
158
158
  r"""
159
159
  Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
@@ -162,7 +162,7 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
162
162
  """
163
163
  self.use_tiling = use_tiling
164
164
 
165
- # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.disable_tiling
165
+ # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.disable_tiling
166
166
  def disable_tiling(self):
167
167
  r"""
168
168
  Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
@@ -170,7 +170,7 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
170
170
  """
171
171
  self.enable_tiling(False)
172
172
 
173
- # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.enable_slicing
173
+ # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.enable_slicing
174
174
  def enable_slicing(self):
175
175
  r"""
176
176
  Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
@@ -178,7 +178,7 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
178
178
  """
179
179
  self.use_slicing = True
180
180
 
181
- # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.disable_slicing
181
+ # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.disable_slicing
182
182
  def disable_slicing(self):
183
183
  r"""
184
184
  Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
@@ -333,14 +333,14 @@ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
333
333
 
334
334
  return DecoderOutput(sample=x_0)
335
335
 
336
- # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.blend_v
336
+ # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.blend_v
337
337
  def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
338
338
  blend_extent = min(a.shape[2], b.shape[2], blend_extent)
339
339
  for y in range(blend_extent):
340
340
  b[:, :, y, :] = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
341
341
  return b
342
342
 
343
- # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.blend_h
343
+ # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.blend_h
344
344
  def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
345
345
  blend_extent = min(a.shape[3], b.shape[3], blend_extent)
346
346
  for x in range(blend_extent):
@@ -18,11 +18,11 @@ import numpy as np
18
18
  import torch
19
19
  import torch.nn as nn
20
20
 
21
- from ..utils import BaseOutput, is_torch_version
22
- from ..utils.torch_utils import randn_tensor
23
- from .activations import get_activation
24
- from .attention_processor import SpatialNorm
25
- from .unet_2d_blocks import (
21
+ from ...utils import BaseOutput, is_torch_version
22
+ from ...utils.torch_utils import randn_tensor
23
+ from ..activations import get_activation
24
+ from ..attention_processor import SpatialNorm
25
+ from ..unet_2d_blocks import (
26
26
  AutoencoderTinyBlock,
27
27
  UNetMidBlock2D,
28
28
  get_down_block,
@@ -77,6 +77,7 @@ class Encoder(nn.Module):
77
77
  norm_num_groups: int = 32,
78
78
  act_fn: str = "silu",
79
79
  double_z: bool = True,
80
+ mid_block_add_attention=True,
80
81
  ):
81
82
  super().__init__()
82
83
  self.layers_per_block = layers_per_block
@@ -124,6 +125,7 @@ class Encoder(nn.Module):
124
125
  attention_head_dim=block_out_channels[-1],
125
126
  resnet_groups=norm_num_groups,
126
127
  temb_channels=None,
128
+ add_attention=mid_block_add_attention,
127
129
  )
128
130
 
129
131
  # out
@@ -213,6 +215,7 @@ class Decoder(nn.Module):
213
215
  norm_num_groups: int = 32,
214
216
  act_fn: str = "silu",
215
217
  norm_type: str = "group", # group, spatial
218
+ mid_block_add_attention=True,
216
219
  ):
217
220
  super().__init__()
218
221
  self.layers_per_block = layers_per_block
@@ -240,6 +243,7 @@ class Decoder(nn.Module):
240
243
  attention_head_dim=block_out_channels[-1],
241
244
  resnet_groups=norm_num_groups,
242
245
  temb_channels=temb_channels,
246
+ add_attention=mid_block_add_attention,
243
247
  )
244
248
 
245
249
  # up
@@ -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)