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.
- diffusers/__init__.py +11 -1
- diffusers/commands/fp16_safetensors.py +10 -11
- diffusers/configuration_utils.py +12 -8
- diffusers/dependency_versions_table.py +2 -1
- diffusers/experimental/rl/value_guided_sampling.py +1 -1
- diffusers/image_processor.py +286 -46
- diffusers/loaders/ip_adapter.py +11 -9
- diffusers/loaders/lora.py +198 -60
- diffusers/loaders/single_file.py +24 -18
- diffusers/loaders/textual_inversion.py +10 -14
- diffusers/loaders/unet.py +130 -37
- diffusers/models/__init__.py +18 -12
- diffusers/models/activations.py +9 -6
- diffusers/models/attention.py +137 -16
- diffusers/models/attention_processor.py +133 -46
- diffusers/models/autoencoders/__init__.py +5 -0
- diffusers/models/{autoencoder_asym_kl.py → autoencoders/autoencoder_asym_kl.py} +4 -4
- diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +45 -6
- diffusers/models/{autoencoder_kl_temporal_decoder.py → autoencoders/autoencoder_kl_temporal_decoder.py} +8 -8
- diffusers/models/{autoencoder_tiny.py → autoencoders/autoencoder_tiny.py} +4 -4
- diffusers/models/{consistency_decoder_vae.py → autoencoders/consistency_decoder_vae.py} +14 -14
- diffusers/models/{vae.py → autoencoders/vae.py} +9 -5
- diffusers/models/downsampling.py +338 -0
- diffusers/models/embeddings.py +112 -29
- diffusers/models/modeling_flax_utils.py +12 -7
- diffusers/models/modeling_utils.py +10 -10
- diffusers/models/normalization.py +108 -2
- diffusers/models/resnet.py +15 -699
- diffusers/models/transformer_2d.py +2 -2
- diffusers/models/unet_2d_condition.py +37 -0
- diffusers/models/{unet_kandi3.py → unet_kandinsky3.py} +105 -159
- diffusers/models/upsampling.py +454 -0
- diffusers/models/uvit_2d.py +471 -0
- diffusers/models/vq_model.py +9 -2
- diffusers/pipelines/__init__.py +81 -73
- diffusers/pipelines/amused/__init__.py +62 -0
- diffusers/pipelines/amused/pipeline_amused.py +328 -0
- diffusers/pipelines/amused/pipeline_amused_img2img.py +347 -0
- diffusers/pipelines/amused/pipeline_amused_inpaint.py +378 -0
- diffusers/pipelines/animatediff/pipeline_animatediff.py +38 -10
- diffusers/pipelines/auto_pipeline.py +17 -13
- diffusers/pipelines/controlnet/pipeline_controlnet.py +27 -10
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +47 -5
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +25 -8
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +4 -6
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +26 -10
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +4 -3
- diffusers/pipelines/deprecated/__init__.py +153 -0
- diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/__init__.py +3 -3
- diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion.py +91 -18
- diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion_img2img.py +91 -18
- diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_output.py +1 -1
- diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/__init__.py +1 -1
- diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/mel.py +2 -2
- diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/pipeline_audio_diffusion.py +4 -4
- diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/__init__.py +1 -1
- diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/pipeline_latent_diffusion_uncond.py +4 -4
- diffusers/pipelines/{pndm → deprecated/pndm}/__init__.py +1 -1
- diffusers/pipelines/{pndm → deprecated/pndm}/pipeline_pndm.py +4 -4
- diffusers/pipelines/{repaint → deprecated/repaint}/__init__.py +1 -1
- diffusers/pipelines/{repaint → deprecated/repaint}/pipeline_repaint.py +5 -5
- diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/__init__.py +1 -1
- diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/pipeline_score_sde_ve.py +4 -4
- diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/__init__.py +6 -6
- diffusers/pipelines/{spectrogram_diffusion/continous_encoder.py → deprecated/spectrogram_diffusion/continuous_encoder.py} +2 -2
- diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/midi_utils.py +1 -1
- diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/notes_encoder.py +2 -2
- diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/pipeline_spectrogram_diffusion.py +7 -7
- diffusers/pipelines/deprecated/stable_diffusion_variants/__init__.py +55 -0
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_cycle_diffusion.py +16 -11
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_onnx_stable_diffusion_inpaint_legacy.py +6 -6
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_inpaint_legacy.py +11 -11
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_model_editing.py +16 -11
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_paradigms.py +10 -10
- diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_pix2pix_zero.py +13 -13
- diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/__init__.py +1 -1
- diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/pipeline_stochastic_karras_ve.py +4 -4
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/__init__.py +3 -3
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/modeling_text_unet.py +54 -11
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion.py +4 -4
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_dual_guided.py +6 -6
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_image_variation.py +6 -6
- diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_text_to_image.py +6 -6
- diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/__init__.py +3 -3
- diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/pipeline_vq_diffusion.py +5 -5
- diffusers/pipelines/kandinsky3/__init__.py +4 -4
- diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +98 -0
- diffusers/pipelines/kandinsky3/{kandinsky3_pipeline.py → pipeline_kandinsky3.py} +172 -35
- diffusers/pipelines/kandinsky3/{kandinsky3img2img_pipeline.py → pipeline_kandinsky3_img2img.py} +228 -34
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +46 -5
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +47 -6
- diffusers/pipelines/onnx_utils.py +8 -5
- diffusers/pipelines/pipeline_flax_utils.py +7 -6
- diffusers/pipelines/pipeline_utils.py +30 -29
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +51 -2
- diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +3 -3
- diffusers/pipelines/stable_diffusion/__init__.py +1 -72
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +67 -75
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +92 -8
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +92 -8
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +138 -10
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +57 -7
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +3 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +6 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +5 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -0
- diffusers/pipelines/stable_diffusion_attend_and_excite/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_attend_and_excite}/pipeline_stable_diffusion_attend_and_excite.py +5 -2
- diffusers/pipelines/stable_diffusion_diffedit/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_diffedit}/pipeline_stable_diffusion_diffedit.py +2 -3
- diffusers/pipelines/stable_diffusion_gligen/__init__.py +50 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen.py +2 -2
- diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen_text_image.py +3 -3
- diffusers/pipelines/stable_diffusion_k_diffusion/__init__.py +60 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_k_diffusion}/pipeline_stable_diffusion_k_diffusion.py +6 -1
- diffusers/pipelines/stable_diffusion_ldm3d/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_ldm3d}/pipeline_stable_diffusion_ldm3d.py +50 -7
- diffusers/pipelines/stable_diffusion_panorama/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_panorama}/pipeline_stable_diffusion_panorama.py +56 -8
- diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +58 -6
- diffusers/pipelines/stable_diffusion_sag/__init__.py +48 -0
- diffusers/pipelines/{stable_diffusion → stable_diffusion_sag}/pipeline_stable_diffusion_sag.py +67 -10
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +97 -15
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +98 -14
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +97 -14
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +7 -5
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +12 -9
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +6 -0
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +5 -0
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +5 -0
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +331 -9
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +468 -9
- diffusers/pipelines/unclip/pipeline_unclip.py +2 -1
- diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +1 -0
- diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +4 -0
- diffusers/schedulers/__init__.py +2 -0
- diffusers/schedulers/scheduling_amused.py +162 -0
- diffusers/schedulers/scheduling_consistency_models.py +2 -0
- diffusers/schedulers/scheduling_ddim_inverse.py +1 -4
- diffusers/schedulers/scheduling_ddpm.py +46 -0
- diffusers/schedulers/scheduling_ddpm_parallel.py +46 -0
- diffusers/schedulers/scheduling_deis_multistep.py +13 -1
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +13 -1
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +13 -1
- diffusers/schedulers/scheduling_dpmsolver_sde.py +2 -0
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +13 -1
- diffusers/schedulers/scheduling_euler_ancestral_discrete.py +58 -0
- diffusers/schedulers/scheduling_euler_discrete.py +62 -3
- diffusers/schedulers/scheduling_heun_discrete.py +2 -0
- diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +2 -0
- diffusers/schedulers/scheduling_k_dpm_2_discrete.py +2 -0
- diffusers/schedulers/scheduling_lms_discrete.py +2 -0
- diffusers/schedulers/scheduling_unipc_multistep.py +13 -1
- diffusers/schedulers/scheduling_utils.py +3 -1
- diffusers/schedulers/scheduling_utils_flax.py +3 -1
- diffusers/training_utils.py +1 -1
- diffusers/utils/__init__.py +0 -2
- diffusers/utils/constants.py +2 -5
- diffusers/utils/dummy_pt_objects.py +30 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +45 -0
- diffusers/utils/dynamic_modules_utils.py +14 -18
- diffusers/utils/hub_utils.py +24 -36
- diffusers/utils/logging.py +1 -1
- diffusers/utils/state_dict_utils.py +8 -0
- diffusers/utils/testing_utils.py +199 -1
- diffusers/utils/torch_utils.py +3 -3
- {diffusers-0.24.0.dist-info → diffusers-0.25.0.dist-info}/METADATA +54 -53
- {diffusers-0.24.0.dist-info → diffusers-0.25.0.dist-info}/RECORD +174 -155
- {diffusers-0.24.0.dist-info → diffusers-0.25.0.dist-info}/WHEEL +1 -1
- {diffusers-0.24.0.dist-info → diffusers-0.25.0.dist-info}/entry_points.txt +0 -1
- /diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/modeling_roberta_series.py +0 -0
- {diffusers-0.24.0.dist-info → diffusers-0.25.0.dist-info}/LICENSE +0 -0
- {diffusers-0.24.0.dist-info → diffusers-0.25.0.dist-info}/top_level.txt +0 -0
diffusers/models/attention.py
CHANGED
@@ -14,6 +14,7 @@
|
|
14
14
|
from typing import Any, Dict, Optional
|
15
15
|
|
16
16
|
import torch
|
17
|
+
import torch.nn.functional as F
|
17
18
|
from torch import nn
|
18
19
|
|
19
20
|
from ..utils import USE_PEFT_BACKEND
|
@@ -22,7 +23,7 @@ from .activations import GEGLU, GELU, ApproximateGELU
|
|
22
23
|
from .attention_processor import Attention
|
23
24
|
from .embeddings import SinusoidalPositionalEmbedding
|
24
25
|
from .lora import LoRACompatibleLinear
|
25
|
-
from .normalization import AdaLayerNorm, AdaLayerNormZero
|
26
|
+
from .normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm
|
26
27
|
|
27
28
|
|
28
29
|
def _chunked_feed_forward(
|
@@ -148,6 +149,11 @@ class BasicTransformerBlock(nn.Module):
|
|
148
149
|
attention_type: str = "default",
|
149
150
|
positional_embeddings: Optional[str] = None,
|
150
151
|
num_positional_embeddings: Optional[int] = None,
|
152
|
+
ada_norm_continous_conditioning_embedding_dim: Optional[int] = None,
|
153
|
+
ada_norm_bias: Optional[int] = None,
|
154
|
+
ff_inner_dim: Optional[int] = None,
|
155
|
+
ff_bias: bool = True,
|
156
|
+
attention_out_bias: bool = True,
|
151
157
|
):
|
152
158
|
super().__init__()
|
153
159
|
self.only_cross_attention = only_cross_attention
|
@@ -156,6 +162,7 @@ class BasicTransformerBlock(nn.Module):
|
|
156
162
|
self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
|
157
163
|
self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
|
158
164
|
self.use_layer_norm = norm_type == "layer_norm"
|
165
|
+
self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous"
|
159
166
|
|
160
167
|
if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
|
161
168
|
raise ValueError(
|
@@ -179,6 +186,15 @@ class BasicTransformerBlock(nn.Module):
|
|
179
186
|
self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
|
180
187
|
elif self.use_ada_layer_norm_zero:
|
181
188
|
self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
|
189
|
+
elif self.use_ada_layer_norm_continuous:
|
190
|
+
self.norm1 = AdaLayerNormContinuous(
|
191
|
+
dim,
|
192
|
+
ada_norm_continous_conditioning_embedding_dim,
|
193
|
+
norm_elementwise_affine,
|
194
|
+
norm_eps,
|
195
|
+
ada_norm_bias,
|
196
|
+
"rms_norm",
|
197
|
+
)
|
182
198
|
else:
|
183
199
|
self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
|
184
200
|
|
@@ -190,6 +206,7 @@ class BasicTransformerBlock(nn.Module):
|
|
190
206
|
bias=attention_bias,
|
191
207
|
cross_attention_dim=cross_attention_dim if only_cross_attention else None,
|
192
208
|
upcast_attention=upcast_attention,
|
209
|
+
out_bias=attention_out_bias,
|
193
210
|
)
|
194
211
|
|
195
212
|
# 2. Cross-Attn
|
@@ -197,11 +214,20 @@ class BasicTransformerBlock(nn.Module):
|
|
197
214
|
# We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
|
198
215
|
# I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
|
199
216
|
# the second cross attention block.
|
200
|
-
self.
|
201
|
-
AdaLayerNorm(dim, num_embeds_ada_norm)
|
202
|
-
|
203
|
-
|
204
|
-
|
217
|
+
if self.use_ada_layer_norm:
|
218
|
+
self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm)
|
219
|
+
elif self.use_ada_layer_norm_continuous:
|
220
|
+
self.norm2 = AdaLayerNormContinuous(
|
221
|
+
dim,
|
222
|
+
ada_norm_continous_conditioning_embedding_dim,
|
223
|
+
norm_elementwise_affine,
|
224
|
+
norm_eps,
|
225
|
+
ada_norm_bias,
|
226
|
+
"rms_norm",
|
227
|
+
)
|
228
|
+
else:
|
229
|
+
self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
|
230
|
+
|
205
231
|
self.attn2 = Attention(
|
206
232
|
query_dim=dim,
|
207
233
|
cross_attention_dim=cross_attention_dim if not double_self_attention else None,
|
@@ -210,20 +236,32 @@ class BasicTransformerBlock(nn.Module):
|
|
210
236
|
dropout=dropout,
|
211
237
|
bias=attention_bias,
|
212
238
|
upcast_attention=upcast_attention,
|
239
|
+
out_bias=attention_out_bias,
|
213
240
|
) # is self-attn if encoder_hidden_states is none
|
214
241
|
else:
|
215
242
|
self.norm2 = None
|
216
243
|
self.attn2 = None
|
217
244
|
|
218
245
|
# 3. Feed-forward
|
219
|
-
if
|
220
|
-
self.norm3 =
|
246
|
+
if self.use_ada_layer_norm_continuous:
|
247
|
+
self.norm3 = AdaLayerNormContinuous(
|
248
|
+
dim,
|
249
|
+
ada_norm_continous_conditioning_embedding_dim,
|
250
|
+
norm_elementwise_affine,
|
251
|
+
norm_eps,
|
252
|
+
ada_norm_bias,
|
253
|
+
"layer_norm",
|
254
|
+
)
|
255
|
+
elif not self.use_ada_layer_norm_single:
|
256
|
+
self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
|
221
257
|
|
222
258
|
self.ff = FeedForward(
|
223
259
|
dim,
|
224
260
|
dropout=dropout,
|
225
261
|
activation_fn=activation_fn,
|
226
262
|
final_dropout=final_dropout,
|
263
|
+
inner_dim=ff_inner_dim,
|
264
|
+
bias=ff_bias,
|
227
265
|
)
|
228
266
|
|
229
267
|
# 4. Fuser
|
@@ -252,6 +290,7 @@ class BasicTransformerBlock(nn.Module):
|
|
252
290
|
timestep: Optional[torch.LongTensor] = None,
|
253
291
|
cross_attention_kwargs: Dict[str, Any] = None,
|
254
292
|
class_labels: Optional[torch.LongTensor] = None,
|
293
|
+
added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
|
255
294
|
) -> torch.FloatTensor:
|
256
295
|
# Notice that normalization is always applied before the real computation in the following blocks.
|
257
296
|
# 0. Self-Attention
|
@@ -265,6 +304,8 @@ class BasicTransformerBlock(nn.Module):
|
|
265
304
|
)
|
266
305
|
elif self.use_layer_norm:
|
267
306
|
norm_hidden_states = self.norm1(hidden_states)
|
307
|
+
elif self.use_ada_layer_norm_continuous:
|
308
|
+
norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
|
268
309
|
elif self.use_ada_layer_norm_single:
|
269
310
|
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
270
311
|
self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
|
@@ -314,6 +355,8 @@ class BasicTransformerBlock(nn.Module):
|
|
314
355
|
# For PixArt norm2 isn't applied here:
|
315
356
|
# https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
|
316
357
|
norm_hidden_states = hidden_states
|
358
|
+
elif self.use_ada_layer_norm_continuous:
|
359
|
+
norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
|
317
360
|
else:
|
318
361
|
raise ValueError("Incorrect norm")
|
319
362
|
|
@@ -329,7 +372,9 @@ class BasicTransformerBlock(nn.Module):
|
|
329
372
|
hidden_states = attn_output + hidden_states
|
330
373
|
|
331
374
|
# 4. Feed-forward
|
332
|
-
if
|
375
|
+
if self.use_ada_layer_norm_continuous:
|
376
|
+
norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
|
377
|
+
elif not self.use_ada_layer_norm_single:
|
333
378
|
norm_hidden_states = self.norm3(hidden_states)
|
334
379
|
|
335
380
|
if self.use_ada_layer_norm_zero:
|
@@ -453,7 +498,7 @@ class TemporalBasicTransformerBlock(nn.Module):
|
|
453
498
|
hidden_states = self.norm_in(hidden_states)
|
454
499
|
|
455
500
|
if self._chunk_size is not None:
|
456
|
-
hidden_states = _chunked_feed_forward(self.
|
501
|
+
hidden_states = _chunked_feed_forward(self.ff_in, hidden_states, self._chunk_dim, self._chunk_size)
|
457
502
|
else:
|
458
503
|
hidden_states = self.ff_in(hidden_states)
|
459
504
|
|
@@ -490,6 +535,78 @@ class TemporalBasicTransformerBlock(nn.Module):
|
|
490
535
|
return hidden_states
|
491
536
|
|
492
537
|
|
538
|
+
class SkipFFTransformerBlock(nn.Module):
|
539
|
+
def __init__(
|
540
|
+
self,
|
541
|
+
dim: int,
|
542
|
+
num_attention_heads: int,
|
543
|
+
attention_head_dim: int,
|
544
|
+
kv_input_dim: int,
|
545
|
+
kv_input_dim_proj_use_bias: bool,
|
546
|
+
dropout=0.0,
|
547
|
+
cross_attention_dim: Optional[int] = None,
|
548
|
+
attention_bias: bool = False,
|
549
|
+
attention_out_bias: bool = True,
|
550
|
+
):
|
551
|
+
super().__init__()
|
552
|
+
if kv_input_dim != dim:
|
553
|
+
self.kv_mapper = nn.Linear(kv_input_dim, dim, kv_input_dim_proj_use_bias)
|
554
|
+
else:
|
555
|
+
self.kv_mapper = None
|
556
|
+
|
557
|
+
self.norm1 = RMSNorm(dim, 1e-06)
|
558
|
+
|
559
|
+
self.attn1 = Attention(
|
560
|
+
query_dim=dim,
|
561
|
+
heads=num_attention_heads,
|
562
|
+
dim_head=attention_head_dim,
|
563
|
+
dropout=dropout,
|
564
|
+
bias=attention_bias,
|
565
|
+
cross_attention_dim=cross_attention_dim,
|
566
|
+
out_bias=attention_out_bias,
|
567
|
+
)
|
568
|
+
|
569
|
+
self.norm2 = RMSNorm(dim, 1e-06)
|
570
|
+
|
571
|
+
self.attn2 = Attention(
|
572
|
+
query_dim=dim,
|
573
|
+
cross_attention_dim=cross_attention_dim,
|
574
|
+
heads=num_attention_heads,
|
575
|
+
dim_head=attention_head_dim,
|
576
|
+
dropout=dropout,
|
577
|
+
bias=attention_bias,
|
578
|
+
out_bias=attention_out_bias,
|
579
|
+
)
|
580
|
+
|
581
|
+
def forward(self, hidden_states, encoder_hidden_states, cross_attention_kwargs):
|
582
|
+
cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
|
583
|
+
|
584
|
+
if self.kv_mapper is not None:
|
585
|
+
encoder_hidden_states = self.kv_mapper(F.silu(encoder_hidden_states))
|
586
|
+
|
587
|
+
norm_hidden_states = self.norm1(hidden_states)
|
588
|
+
|
589
|
+
attn_output = self.attn1(
|
590
|
+
norm_hidden_states,
|
591
|
+
encoder_hidden_states=encoder_hidden_states,
|
592
|
+
**cross_attention_kwargs,
|
593
|
+
)
|
594
|
+
|
595
|
+
hidden_states = attn_output + hidden_states
|
596
|
+
|
597
|
+
norm_hidden_states = self.norm2(hidden_states)
|
598
|
+
|
599
|
+
attn_output = self.attn2(
|
600
|
+
norm_hidden_states,
|
601
|
+
encoder_hidden_states=encoder_hidden_states,
|
602
|
+
**cross_attention_kwargs,
|
603
|
+
)
|
604
|
+
|
605
|
+
hidden_states = attn_output + hidden_states
|
606
|
+
|
607
|
+
return hidden_states
|
608
|
+
|
609
|
+
|
493
610
|
class FeedForward(nn.Module):
|
494
611
|
r"""
|
495
612
|
A feed-forward layer.
|
@@ -501,6 +618,7 @@ class FeedForward(nn.Module):
|
|
501
618
|
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
|
502
619
|
activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
|
503
620
|
final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
|
621
|
+
bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
|
504
622
|
"""
|
505
623
|
|
506
624
|
def __init__(
|
@@ -511,20 +629,23 @@ class FeedForward(nn.Module):
|
|
511
629
|
dropout: float = 0.0,
|
512
630
|
activation_fn: str = "geglu",
|
513
631
|
final_dropout: bool = False,
|
632
|
+
inner_dim=None,
|
633
|
+
bias: bool = True,
|
514
634
|
):
|
515
635
|
super().__init__()
|
516
|
-
inner_dim
|
636
|
+
if inner_dim is None:
|
637
|
+
inner_dim = int(dim * mult)
|
517
638
|
dim_out = dim_out if dim_out is not None else dim
|
518
639
|
linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
|
519
640
|
|
520
641
|
if activation_fn == "gelu":
|
521
|
-
act_fn = GELU(dim, inner_dim)
|
642
|
+
act_fn = GELU(dim, inner_dim, bias=bias)
|
522
643
|
if activation_fn == "gelu-approximate":
|
523
|
-
act_fn = GELU(dim, inner_dim, approximate="tanh")
|
644
|
+
act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
|
524
645
|
elif activation_fn == "geglu":
|
525
|
-
act_fn = GEGLU(dim, inner_dim)
|
646
|
+
act_fn = GEGLU(dim, inner_dim, bias=bias)
|
526
647
|
elif activation_fn == "geglu-approximate":
|
527
|
-
act_fn = ApproximateGELU(dim, inner_dim)
|
648
|
+
act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
|
528
649
|
|
529
650
|
self.net = nn.ModuleList([])
|
530
651
|
# project in
|
@@ -532,7 +653,7 @@ class FeedForward(nn.Module):
|
|
532
653
|
# project dropout
|
533
654
|
self.net.append(nn.Dropout(dropout))
|
534
655
|
# project out
|
535
|
-
self.net.append(linear_cls(inner_dim, dim_out))
|
656
|
+
self.net.append(linear_cls(inner_dim, dim_out, bias=bias))
|
536
657
|
# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
|
537
658
|
if final_dropout:
|
538
659
|
self.net.append(nn.Dropout(dropout))
|
@@ -16,7 +16,7 @@ from typing import Callable, Optional, Union
|
|
16
16
|
|
17
17
|
import torch
|
18
18
|
import torch.nn.functional as F
|
19
|
-
from torch import
|
19
|
+
from torch import nn
|
20
20
|
|
21
21
|
from ..utils import USE_PEFT_BACKEND, deprecate, logging
|
22
22
|
from ..utils.import_utils import is_xformers_available
|
@@ -109,15 +109,19 @@ class Attention(nn.Module):
|
|
109
109
|
residual_connection: bool = False,
|
110
110
|
_from_deprecated_attn_block: bool = False,
|
111
111
|
processor: Optional["AttnProcessor"] = None,
|
112
|
+
out_dim: int = None,
|
112
113
|
):
|
113
114
|
super().__init__()
|
114
|
-
self.inner_dim = dim_head * heads
|
115
|
+
self.inner_dim = out_dim if out_dim is not None else dim_head * heads
|
116
|
+
self.query_dim = query_dim
|
115
117
|
self.cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim
|
116
118
|
self.upcast_attention = upcast_attention
|
117
119
|
self.upcast_softmax = upcast_softmax
|
118
120
|
self.rescale_output_factor = rescale_output_factor
|
119
121
|
self.residual_connection = residual_connection
|
120
122
|
self.dropout = dropout
|
123
|
+
self.fused_projections = False
|
124
|
+
self.out_dim = out_dim if out_dim is not None else query_dim
|
121
125
|
|
122
126
|
# we make use of this private variable to know whether this class is loaded
|
123
127
|
# with an deprecated state dict so that we can convert it on the fly
|
@@ -126,7 +130,7 @@ class Attention(nn.Module):
|
|
126
130
|
self.scale_qk = scale_qk
|
127
131
|
self.scale = dim_head**-0.5 if self.scale_qk else 1.0
|
128
132
|
|
129
|
-
self.heads = heads
|
133
|
+
self.heads = out_dim // dim_head if out_dim is not None else heads
|
130
134
|
# for slice_size > 0 the attention score computation
|
131
135
|
# is split across the batch axis to save memory
|
132
136
|
# You can set slice_size with `set_attention_slice`
|
@@ -178,6 +182,7 @@ class Attention(nn.Module):
|
|
178
182
|
else:
|
179
183
|
linear_cls = LoRACompatibleLinear
|
180
184
|
|
185
|
+
self.linear_cls = linear_cls
|
181
186
|
self.to_q = linear_cls(query_dim, self.inner_dim, bias=bias)
|
182
187
|
|
183
188
|
if not self.only_cross_attention:
|
@@ -193,7 +198,7 @@ class Attention(nn.Module):
|
|
193
198
|
self.add_v_proj = linear_cls(added_kv_proj_dim, self.inner_dim)
|
194
199
|
|
195
200
|
self.to_out = nn.ModuleList([])
|
196
|
-
self.to_out.append(linear_cls(self.inner_dim,
|
201
|
+
self.to_out.append(linear_cls(self.inner_dim, self.out_dim, bias=out_bias))
|
197
202
|
self.to_out.append(nn.Dropout(dropout))
|
198
203
|
|
199
204
|
# set attention processor
|
@@ -690,6 +695,32 @@ class Attention(nn.Module):
|
|
690
695
|
|
691
696
|
return encoder_hidden_states
|
692
697
|
|
698
|
+
@torch.no_grad()
|
699
|
+
def fuse_projections(self, fuse=True):
|
700
|
+
is_cross_attention = self.cross_attention_dim != self.query_dim
|
701
|
+
device = self.to_q.weight.data.device
|
702
|
+
dtype = self.to_q.weight.data.dtype
|
703
|
+
|
704
|
+
if not is_cross_attention:
|
705
|
+
# fetch weight matrices.
|
706
|
+
concatenated_weights = torch.cat([self.to_q.weight.data, self.to_k.weight.data, self.to_v.weight.data])
|
707
|
+
in_features = concatenated_weights.shape[1]
|
708
|
+
out_features = concatenated_weights.shape[0]
|
709
|
+
|
710
|
+
# create a new single projection layer and copy over the weights.
|
711
|
+
self.to_qkv = self.linear_cls(in_features, out_features, bias=False, device=device, dtype=dtype)
|
712
|
+
self.to_qkv.weight.copy_(concatenated_weights)
|
713
|
+
|
714
|
+
else:
|
715
|
+
concatenated_weights = torch.cat([self.to_k.weight.data, self.to_v.weight.data])
|
716
|
+
in_features = concatenated_weights.shape[1]
|
717
|
+
out_features = concatenated_weights.shape[0]
|
718
|
+
|
719
|
+
self.to_kv = self.linear_cls(in_features, out_features, bias=False, device=device, dtype=dtype)
|
720
|
+
self.to_kv.weight.copy_(concatenated_weights)
|
721
|
+
|
722
|
+
self.fused_projections = fuse
|
723
|
+
|
693
724
|
|
694
725
|
class AttnProcessor:
|
695
726
|
r"""
|
@@ -1182,9 +1213,6 @@ class AttnProcessor2_0:
|
|
1182
1213
|
scale: float = 1.0,
|
1183
1214
|
) -> torch.FloatTensor:
|
1184
1215
|
residual = hidden_states
|
1185
|
-
|
1186
|
-
args = () if USE_PEFT_BACKEND else (scale,)
|
1187
|
-
|
1188
1216
|
if attn.spatial_norm is not None:
|
1189
1217
|
hidden_states = attn.spatial_norm(hidden_states, temb)
|
1190
1218
|
|
@@ -1251,6 +1279,103 @@ class AttnProcessor2_0:
|
|
1251
1279
|
return hidden_states
|
1252
1280
|
|
1253
1281
|
|
1282
|
+
class FusedAttnProcessor2_0:
|
1283
|
+
r"""
|
1284
|
+
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
|
1285
|
+
It uses fused projection layers. For self-attention modules, all projection matrices (i.e., query,
|
1286
|
+
key, value) are fused. For cross-attention modules, key and value projection matrices are fused.
|
1287
|
+
|
1288
|
+
<Tip warning={true}>
|
1289
|
+
|
1290
|
+
This API is currently 🧪 experimental in nature and can change in future.
|
1291
|
+
|
1292
|
+
</Tip>
|
1293
|
+
"""
|
1294
|
+
|
1295
|
+
def __init__(self):
|
1296
|
+
if not hasattr(F, "scaled_dot_product_attention"):
|
1297
|
+
raise ImportError(
|
1298
|
+
"FusedAttnProcessor2_0 requires at least PyTorch 2.0, to use it. Please upgrade PyTorch to > 2.0."
|
1299
|
+
)
|
1300
|
+
|
1301
|
+
def __call__(
|
1302
|
+
self,
|
1303
|
+
attn: Attention,
|
1304
|
+
hidden_states: torch.FloatTensor,
|
1305
|
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
1306
|
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1307
|
+
temb: Optional[torch.FloatTensor] = None,
|
1308
|
+
scale: float = 1.0,
|
1309
|
+
) -> torch.FloatTensor:
|
1310
|
+
residual = hidden_states
|
1311
|
+
if attn.spatial_norm is not None:
|
1312
|
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
1313
|
+
|
1314
|
+
input_ndim = hidden_states.ndim
|
1315
|
+
|
1316
|
+
if input_ndim == 4:
|
1317
|
+
batch_size, channel, height, width = hidden_states.shape
|
1318
|
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
1319
|
+
|
1320
|
+
batch_size, sequence_length, _ = (
|
1321
|
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
1322
|
+
)
|
1323
|
+
|
1324
|
+
if attention_mask is not None:
|
1325
|
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
1326
|
+
# scaled_dot_product_attention expects attention_mask shape to be
|
1327
|
+
# (batch, heads, source_length, target_length)
|
1328
|
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
1329
|
+
|
1330
|
+
if attn.group_norm is not None:
|
1331
|
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
1332
|
+
|
1333
|
+
args = () if USE_PEFT_BACKEND else (scale,)
|
1334
|
+
if encoder_hidden_states is None:
|
1335
|
+
qkv = attn.to_qkv(hidden_states, *args)
|
1336
|
+
split_size = qkv.shape[-1] // 3
|
1337
|
+
query, key, value = torch.split(qkv, split_size, dim=-1)
|
1338
|
+
else:
|
1339
|
+
if attn.norm_cross:
|
1340
|
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
1341
|
+
query = attn.to_q(hidden_states, *args)
|
1342
|
+
|
1343
|
+
kv = attn.to_kv(encoder_hidden_states, *args)
|
1344
|
+
split_size = kv.shape[-1] // 2
|
1345
|
+
key, value = torch.split(kv, split_size, dim=-1)
|
1346
|
+
|
1347
|
+
inner_dim = key.shape[-1]
|
1348
|
+
head_dim = inner_dim // attn.heads
|
1349
|
+
|
1350
|
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
1351
|
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
1352
|
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
1353
|
+
|
1354
|
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
1355
|
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
1356
|
+
hidden_states = F.scaled_dot_product_attention(
|
1357
|
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
1358
|
+
)
|
1359
|
+
|
1360
|
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
1361
|
+
hidden_states = hidden_states.to(query.dtype)
|
1362
|
+
|
1363
|
+
# linear proj
|
1364
|
+
hidden_states = attn.to_out[0](hidden_states, *args)
|
1365
|
+
# dropout
|
1366
|
+
hidden_states = attn.to_out[1](hidden_states)
|
1367
|
+
|
1368
|
+
if input_ndim == 4:
|
1369
|
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
1370
|
+
|
1371
|
+
if attn.residual_connection:
|
1372
|
+
hidden_states = hidden_states + residual
|
1373
|
+
|
1374
|
+
hidden_states = hidden_states / attn.rescale_output_factor
|
1375
|
+
|
1376
|
+
return hidden_states
|
1377
|
+
|
1378
|
+
|
1254
1379
|
class CustomDiffusionXFormersAttnProcessor(nn.Module):
|
1255
1380
|
r"""
|
1256
1381
|
Processor for implementing memory efficient attention using xFormers for the Custom Diffusion method.
|
@@ -2219,44 +2344,6 @@ class IPAdapterAttnProcessor2_0(torch.nn.Module):
|
|
2219
2344
|
return hidden_states
|
2220
2345
|
|
2221
2346
|
|
2222
|
-
# TODO(Yiyi): This class should not exist, we can replace it with a normal attention processor I believe
|
2223
|
-
# this way torch.compile and co. will work as well
|
2224
|
-
class Kandi3AttnProcessor:
|
2225
|
-
r"""
|
2226
|
-
Default kandinsky3 proccesor for performing attention-related computations.
|
2227
|
-
"""
|
2228
|
-
|
2229
|
-
@staticmethod
|
2230
|
-
def _reshape(hid_states, h):
|
2231
|
-
b, n, f = hid_states.shape
|
2232
|
-
d = f // h
|
2233
|
-
return hid_states.unsqueeze(-1).reshape(b, n, h, d).permute(0, 2, 1, 3)
|
2234
|
-
|
2235
|
-
def __call__(
|
2236
|
-
self,
|
2237
|
-
attn,
|
2238
|
-
x,
|
2239
|
-
context,
|
2240
|
-
context_mask=None,
|
2241
|
-
):
|
2242
|
-
query = self._reshape(attn.to_q(x), h=attn.num_heads)
|
2243
|
-
key = self._reshape(attn.to_k(context), h=attn.num_heads)
|
2244
|
-
value = self._reshape(attn.to_v(context), h=attn.num_heads)
|
2245
|
-
|
2246
|
-
attention_matrix = einsum("b h i d, b h j d -> b h i j", query, key)
|
2247
|
-
|
2248
|
-
if context_mask is not None:
|
2249
|
-
max_neg_value = -torch.finfo(attention_matrix.dtype).max
|
2250
|
-
context_mask = context_mask.unsqueeze(1).unsqueeze(1)
|
2251
|
-
attention_matrix = attention_matrix.masked_fill(~(context_mask != 0), max_neg_value)
|
2252
|
-
attention_matrix = (attention_matrix * attn.scale).softmax(dim=-1)
|
2253
|
-
|
2254
|
-
out = einsum("b h i j, b h j d -> b h i d", attention_matrix, value)
|
2255
|
-
out = out.permute(0, 2, 1, 3).reshape(out.shape[0], out.shape[2], -1)
|
2256
|
-
out = attn.to_out[0](out)
|
2257
|
-
return out
|
2258
|
-
|
2259
|
-
|
2260
2347
|
LORA_ATTENTION_PROCESSORS = (
|
2261
2348
|
LoRAAttnProcessor,
|
2262
2349
|
LoRAAttnProcessor2_0,
|
@@ -2282,12 +2369,12 @@ CROSS_ATTENTION_PROCESSORS = (
|
|
2282
2369
|
LoRAXFormersAttnProcessor,
|
2283
2370
|
IPAdapterAttnProcessor,
|
2284
2371
|
IPAdapterAttnProcessor2_0,
|
2285
|
-
Kandi3AttnProcessor,
|
2286
2372
|
)
|
2287
2373
|
|
2288
2374
|
AttentionProcessor = Union[
|
2289
2375
|
AttnProcessor,
|
2290
2376
|
AttnProcessor2_0,
|
2377
|
+
FusedAttnProcessor2_0,
|
2291
2378
|
XFormersAttnProcessor,
|
2292
2379
|
SlicedAttnProcessor,
|
2293
2380
|
AttnAddedKVProcessor,
|
@@ -0,0 +1,5 @@
|
|
1
|
+
from .autoencoder_asym_kl import AsymmetricAutoencoderKL
|
2
|
+
from .autoencoder_kl import AutoencoderKL
|
3
|
+
from .autoencoder_kl_temporal_decoder import AutoencoderKLTemporalDecoder
|
4
|
+
from .autoencoder_tiny import AutoencoderTiny
|
5
|
+
from .consistency_decoder_vae import ConsistencyDecoderVAE
|
@@ -16,10 +16,10 @@ from typing import Optional, Tuple, Union
|
|
16
16
|
import torch
|
17
17
|
import torch.nn as nn
|
18
18
|
|
19
|
-
from
|
20
|
-
from
|
21
|
-
from
|
22
|
-
from
|
19
|
+
from ...configuration_utils import ConfigMixin, register_to_config
|
20
|
+
from ...utils.accelerate_utils import apply_forward_hook
|
21
|
+
from ..modeling_outputs import AutoencoderKLOutput
|
22
|
+
from ..modeling_utils import ModelMixin
|
23
23
|
from .vae import DecoderOutput, DiagonalGaussianDistribution, Encoder, MaskConditionDecoder
|
24
24
|
|
25
25
|
|
@@ -16,18 +16,19 @@ from typing import Dict, Optional, Tuple, Union
|
|
16
16
|
import torch
|
17
17
|
import torch.nn as nn
|
18
18
|
|
19
|
-
from
|
20
|
-
from
|
21
|
-
from
|
22
|
-
from
|
19
|
+
from ...configuration_utils import ConfigMixin, register_to_config
|
20
|
+
from ...loaders import FromOriginalVAEMixin
|
21
|
+
from ...utils.accelerate_utils import apply_forward_hook
|
22
|
+
from ..attention_processor import (
|
23
23
|
ADDED_KV_ATTENTION_PROCESSORS,
|
24
24
|
CROSS_ATTENTION_PROCESSORS,
|
25
|
+
Attention,
|
25
26
|
AttentionProcessor,
|
26
27
|
AttnAddedKVProcessor,
|
27
28
|
AttnProcessor,
|
28
29
|
)
|
29
|
-
from
|
30
|
-
from
|
30
|
+
from ..modeling_outputs import AutoencoderKLOutput
|
31
|
+
from ..modeling_utils import ModelMixin
|
31
32
|
from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder
|
32
33
|
|
33
34
|
|
@@ -448,3 +449,41 @@ class AutoencoderKL(ModelMixin, ConfigMixin, FromOriginalVAEMixin):
|
|
448
449
|
return (dec,)
|
449
450
|
|
450
451
|
return DecoderOutput(sample=dec)
|
452
|
+
|
453
|
+
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
|
454
|
+
def fuse_qkv_projections(self):
|
455
|
+
"""
|
456
|
+
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query,
|
457
|
+
key, value) are fused. For cross-attention modules, key and value projection matrices are fused.
|
458
|
+
|
459
|
+
<Tip warning={true}>
|
460
|
+
|
461
|
+
This API is 🧪 experimental.
|
462
|
+
|
463
|
+
</Tip>
|
464
|
+
"""
|
465
|
+
self.original_attn_processors = None
|
466
|
+
|
467
|
+
for _, attn_processor in self.attn_processors.items():
|
468
|
+
if "Added" in str(attn_processor.__class__.__name__):
|
469
|
+
raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
|
470
|
+
|
471
|
+
self.original_attn_processors = self.attn_processors
|
472
|
+
|
473
|
+
for module in self.modules():
|
474
|
+
if isinstance(module, Attention):
|
475
|
+
module.fuse_projections(fuse=True)
|
476
|
+
|
477
|
+
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
|
478
|
+
def unfuse_qkv_projections(self):
|
479
|
+
"""Disables the fused QKV projection if enabled.
|
480
|
+
|
481
|
+
<Tip warning={true}>
|
482
|
+
|
483
|
+
This API is 🧪 experimental.
|
484
|
+
|
485
|
+
</Tip>
|
486
|
+
|
487
|
+
"""
|
488
|
+
if self.original_attn_processors is not None:
|
489
|
+
self.set_attn_processor(self.original_attn_processors)
|
@@ -16,14 +16,14 @@ from typing import Dict, Optional, Tuple, Union
|
|
16
16
|
import torch
|
17
17
|
import torch.nn as nn
|
18
18
|
|
19
|
-
from
|
20
|
-
from
|
21
|
-
from
|
22
|
-
from
|
23
|
-
from
|
24
|
-
from
|
25
|
-
from
|
26
|
-
from
|
19
|
+
from ...configuration_utils import ConfigMixin, register_to_config
|
20
|
+
from ...loaders import FromOriginalVAEMixin
|
21
|
+
from ...utils import is_torch_version
|
22
|
+
from ...utils.accelerate_utils import apply_forward_hook
|
23
|
+
from ..attention_processor import CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnProcessor
|
24
|
+
from ..modeling_outputs import AutoencoderKLOutput
|
25
|
+
from ..modeling_utils import ModelMixin
|
26
|
+
from ..unet_3d_blocks import MidBlockTemporalDecoder, UpBlockTemporalDecoder
|
27
27
|
from .vae import DecoderOutput, DiagonalGaussianDistribution, Encoder
|
28
28
|
|
29
29
|
|
@@ -18,10 +18,10 @@ from typing import Optional, Tuple, Union
|
|
18
18
|
|
19
19
|
import torch
|
20
20
|
|
21
|
-
from
|
22
|
-
from
|
23
|
-
from
|
24
|
-
from
|
21
|
+
from ...configuration_utils import ConfigMixin, register_to_config
|
22
|
+
from ...utils import BaseOutput
|
23
|
+
from ...utils.accelerate_utils import apply_forward_hook
|
24
|
+
from ..modeling_utils import ModelMixin
|
25
25
|
from .vae import DecoderOutput, DecoderTiny, EncoderTiny
|
26
26
|
|
27
27
|
|