diffusers 0.23.0__py3-none-any.whl → 0.24.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 +16 -2
- diffusers/configuration_utils.py +1 -0
- diffusers/dependency_versions_check.py +1 -14
- diffusers/dependency_versions_table.py +5 -4
- diffusers/image_processor.py +186 -14
- diffusers/loaders/__init__.py +82 -0
- diffusers/loaders/ip_adapter.py +157 -0
- diffusers/loaders/lora.py +1415 -0
- diffusers/loaders/lora_conversion_utils.py +284 -0
- diffusers/loaders/single_file.py +631 -0
- diffusers/loaders/textual_inversion.py +459 -0
- diffusers/loaders/unet.py +735 -0
- diffusers/loaders/utils.py +59 -0
- diffusers/models/__init__.py +12 -1
- diffusers/models/attention.py +165 -14
- diffusers/models/attention_flax.py +9 -1
- diffusers/models/attention_processor.py +286 -1
- diffusers/models/autoencoder_asym_kl.py +14 -9
- diffusers/models/autoencoder_kl.py +3 -18
- diffusers/models/autoencoder_kl_temporal_decoder.py +402 -0
- diffusers/models/autoencoder_tiny.py +20 -24
- diffusers/models/consistency_decoder_vae.py +37 -30
- diffusers/models/controlnet.py +59 -39
- diffusers/models/controlnet_flax.py +19 -18
- diffusers/models/embeddings_flax.py +2 -0
- diffusers/models/lora.py +131 -1
- diffusers/models/modeling_flax_utils.py +2 -1
- diffusers/models/modeling_outputs.py +17 -0
- diffusers/models/modeling_utils.py +27 -19
- diffusers/models/normalization.py +2 -2
- diffusers/models/resnet.py +390 -59
- diffusers/models/transformer_2d.py +20 -3
- diffusers/models/transformer_temporal.py +183 -1
- diffusers/models/unet_2d_blocks_flax.py +5 -0
- diffusers/models/unet_2d_condition.py +9 -0
- diffusers/models/unet_2d_condition_flax.py +13 -13
- diffusers/models/unet_3d_blocks.py +957 -173
- diffusers/models/unet_3d_condition.py +16 -8
- diffusers/models/unet_kandi3.py +589 -0
- diffusers/models/unet_motion_model.py +48 -33
- diffusers/models/unet_spatio_temporal_condition.py +489 -0
- diffusers/models/vae.py +63 -13
- diffusers/models/vae_flax.py +7 -0
- diffusers/models/vq_model.py +3 -1
- diffusers/optimization.py +16 -9
- diffusers/pipelines/__init__.py +65 -12
- diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py +93 -23
- diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py +97 -25
- diffusers/pipelines/animatediff/pipeline_animatediff.py +34 -4
- diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
- diffusers/pipelines/auto_pipeline.py +6 -0
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
- diffusers/pipelines/controlnet/pipeline_controlnet.py +217 -31
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +101 -32
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +136 -39
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +119 -37
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +196 -35
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +102 -31
- diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
- diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
- diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
- diffusers/pipelines/dit/pipeline_dit.py +1 -0
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
- diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
- diffusers/pipelines/kandinsky3/__init__.py +49 -0
- diffusers/pipelines/kandinsky3/kandinsky3_pipeline.py +452 -0
- diffusers/pipelines/kandinsky3/kandinsky3img2img_pipeline.py +460 -0
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +65 -6
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +55 -3
- diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
- diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
- diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
- diffusers/pipelines/pipeline_flax_utils.py +4 -2
- diffusers/pipelines/pipeline_utils.py +33 -13
- diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +196 -36
- diffusers/pipelines/score_sde_ve/pipeline_score_sde_ve.py +1 -0
- diffusers/pipelines/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -0
- diffusers/pipelines/stable_diffusion/__init__.py +64 -21
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +8 -3
- diffusers/pipelines/stable_diffusion/pipeline_cycle_diffusion.py +18 -2
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint_legacy.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +88 -9
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_attend_and_excite.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_diffedit.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen_text_image.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +92 -9
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +92 -9
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint_legacy.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +17 -13
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_model_editing.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_panorama.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_paradigms.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_pix2pix_zero.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py +1 -0
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +1 -0
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +103 -8
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +113 -8
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +115 -9
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +16 -12
- diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
- diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +649 -0
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +109 -14
- diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +1 -0
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +18 -3
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +4 -2
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +872 -0
- diffusers/pipelines/versatile_diffusion/modeling_text_unet.py +29 -40
- diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +1 -0
- diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +1 -0
- diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +1 -0
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +1 -1
- diffusers/schedulers/__init__.py +2 -4
- diffusers/schedulers/deprecated/__init__.py +50 -0
- diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
- diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
- diffusers/schedulers/scheduling_ddim.py +1 -3
- diffusers/schedulers/scheduling_ddim_inverse.py +1 -3
- diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
- diffusers/schedulers/scheduling_ddpm.py +1 -3
- diffusers/schedulers/scheduling_ddpm_parallel.py +1 -3
- diffusers/schedulers/scheduling_deis_multistep.py +15 -5
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +15 -5
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +15 -5
- diffusers/schedulers/scheduling_dpmsolver_sde.py +1 -3
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +15 -5
- diffusers/schedulers/scheduling_euler_ancestral_discrete.py +1 -3
- diffusers/schedulers/scheduling_euler_discrete.py +40 -13
- diffusers/schedulers/scheduling_heun_discrete.py +15 -5
- diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +15 -5
- diffusers/schedulers/scheduling_k_dpm_2_discrete.py +15 -5
- diffusers/schedulers/scheduling_lcm.py +123 -29
- diffusers/schedulers/scheduling_lms_discrete.py +1 -3
- diffusers/schedulers/scheduling_pndm.py +1 -3
- diffusers/schedulers/scheduling_repaint.py +1 -3
- diffusers/schedulers/scheduling_unipc_multistep.py +15 -5
- diffusers/utils/__init__.py +1 -0
- diffusers/utils/constants.py +11 -6
- diffusers/utils/dummy_pt_objects.py +45 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +60 -0
- diffusers/utils/dynamic_modules_utils.py +4 -4
- diffusers/utils/export_utils.py +8 -3
- diffusers/utils/logging.py +10 -10
- diffusers/utils/outputs.py +5 -5
- diffusers/utils/peft_utils.py +88 -44
- diffusers/utils/torch_utils.py +2 -2
- diffusers/utils/versions.py +117 -0
- {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/METADATA +83 -64
- {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/RECORD +176 -157
- {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/WHEEL +1 -1
- {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/entry_points.txt +1 -0
- diffusers/loaders.py +0 -3336
- {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/LICENSE +0 -0
- {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,872 @@
|
|
1
|
+
import copy
|
2
|
+
from dataclasses import dataclass
|
3
|
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
4
|
+
|
5
|
+
import numpy as np
|
6
|
+
import PIL
|
7
|
+
import torch
|
8
|
+
import torch.nn.functional as F
|
9
|
+
from torch.nn.functional import grid_sample
|
10
|
+
from transformers import (
|
11
|
+
CLIPImageProcessor,
|
12
|
+
CLIPTextModel,
|
13
|
+
CLIPTextModelWithProjection,
|
14
|
+
CLIPTokenizer,
|
15
|
+
CLIPVisionModelWithProjection,
|
16
|
+
)
|
17
|
+
|
18
|
+
from diffusers.models import AutoencoderKL, UNet2DConditionModel
|
19
|
+
from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipeline
|
20
|
+
from diffusers.schedulers import KarrasDiffusionSchedulers
|
21
|
+
from diffusers.utils import BaseOutput
|
22
|
+
from diffusers.utils.torch_utils import randn_tensor
|
23
|
+
|
24
|
+
|
25
|
+
# Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.rearrange_0
|
26
|
+
def rearrange_0(tensor, f):
|
27
|
+
F, C, H, W = tensor.size()
|
28
|
+
tensor = torch.permute(torch.reshape(tensor, (F // f, f, C, H, W)), (0, 2, 1, 3, 4))
|
29
|
+
return tensor
|
30
|
+
|
31
|
+
|
32
|
+
# Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.rearrange_1
|
33
|
+
def rearrange_1(tensor):
|
34
|
+
B, C, F, H, W = tensor.size()
|
35
|
+
return torch.reshape(torch.permute(tensor, (0, 2, 1, 3, 4)), (B * F, C, H, W))
|
36
|
+
|
37
|
+
|
38
|
+
# Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.rearrange_3
|
39
|
+
def rearrange_3(tensor, f):
|
40
|
+
F, D, C = tensor.size()
|
41
|
+
return torch.reshape(tensor, (F // f, f, D, C))
|
42
|
+
|
43
|
+
|
44
|
+
# Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.rearrange_4
|
45
|
+
def rearrange_4(tensor):
|
46
|
+
B, F, D, C = tensor.size()
|
47
|
+
return torch.reshape(tensor, (B * F, D, C))
|
48
|
+
|
49
|
+
|
50
|
+
# Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.CrossFrameAttnProcessor
|
51
|
+
class CrossFrameAttnProcessor:
|
52
|
+
"""
|
53
|
+
Cross frame attention processor. Each frame attends the first frame.
|
54
|
+
|
55
|
+
Args:
|
56
|
+
batch_size: The number that represents actual batch size, other than the frames.
|
57
|
+
For example, calling unet with a single prompt and num_images_per_prompt=1, batch_size should be equal to
|
58
|
+
2, due to classifier-free guidance.
|
59
|
+
"""
|
60
|
+
|
61
|
+
def __init__(self, batch_size=2):
|
62
|
+
self.batch_size = batch_size
|
63
|
+
|
64
|
+
def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None):
|
65
|
+
batch_size, sequence_length, _ = hidden_states.shape
|
66
|
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
67
|
+
query = attn.to_q(hidden_states)
|
68
|
+
|
69
|
+
is_cross_attention = encoder_hidden_states is not None
|
70
|
+
if encoder_hidden_states is None:
|
71
|
+
encoder_hidden_states = hidden_states
|
72
|
+
elif attn.norm_cross:
|
73
|
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
74
|
+
|
75
|
+
key = attn.to_k(encoder_hidden_states)
|
76
|
+
value = attn.to_v(encoder_hidden_states)
|
77
|
+
|
78
|
+
# Cross Frame Attention
|
79
|
+
if not is_cross_attention:
|
80
|
+
video_length = key.size()[0] // self.batch_size
|
81
|
+
first_frame_index = [0] * video_length
|
82
|
+
|
83
|
+
# rearrange keys to have batch and frames in the 1st and 2nd dims respectively
|
84
|
+
key = rearrange_3(key, video_length)
|
85
|
+
key = key[:, first_frame_index]
|
86
|
+
# rearrange values to have batch and frames in the 1st and 2nd dims respectively
|
87
|
+
value = rearrange_3(value, video_length)
|
88
|
+
value = value[:, first_frame_index]
|
89
|
+
|
90
|
+
# rearrange back to original shape
|
91
|
+
key = rearrange_4(key)
|
92
|
+
value = rearrange_4(value)
|
93
|
+
|
94
|
+
query = attn.head_to_batch_dim(query)
|
95
|
+
key = attn.head_to_batch_dim(key)
|
96
|
+
value = attn.head_to_batch_dim(value)
|
97
|
+
|
98
|
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
99
|
+
hidden_states = torch.bmm(attention_probs, value)
|
100
|
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
101
|
+
|
102
|
+
# linear proj
|
103
|
+
hidden_states = attn.to_out[0](hidden_states)
|
104
|
+
# dropout
|
105
|
+
hidden_states = attn.to_out[1](hidden_states)
|
106
|
+
|
107
|
+
return hidden_states
|
108
|
+
|
109
|
+
|
110
|
+
# Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.CrossFrameAttnProcessor2_0
|
111
|
+
class CrossFrameAttnProcessor2_0:
|
112
|
+
"""
|
113
|
+
Cross frame attention processor with scaled_dot_product attention of Pytorch 2.0.
|
114
|
+
|
115
|
+
Args:
|
116
|
+
batch_size: The number that represents actual batch size, other than the frames.
|
117
|
+
For example, calling unet with a single prompt and num_images_per_prompt=1, batch_size should be equal to
|
118
|
+
2, due to classifier-free guidance.
|
119
|
+
"""
|
120
|
+
|
121
|
+
def __init__(self, batch_size=2):
|
122
|
+
if not hasattr(F, "scaled_dot_product_attention"):
|
123
|
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
124
|
+
self.batch_size = batch_size
|
125
|
+
|
126
|
+
def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None):
|
127
|
+
batch_size, sequence_length, _ = (
|
128
|
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
129
|
+
)
|
130
|
+
inner_dim = hidden_states.shape[-1]
|
131
|
+
|
132
|
+
if attention_mask is not None:
|
133
|
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
134
|
+
# scaled_dot_product_attention expects attention_mask shape to be
|
135
|
+
# (batch, heads, source_length, target_length)
|
136
|
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
137
|
+
|
138
|
+
query = attn.to_q(hidden_states)
|
139
|
+
|
140
|
+
is_cross_attention = encoder_hidden_states is not None
|
141
|
+
if encoder_hidden_states is None:
|
142
|
+
encoder_hidden_states = hidden_states
|
143
|
+
elif attn.norm_cross:
|
144
|
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
145
|
+
|
146
|
+
key = attn.to_k(encoder_hidden_states)
|
147
|
+
value = attn.to_v(encoder_hidden_states)
|
148
|
+
|
149
|
+
# Cross Frame Attention
|
150
|
+
if not is_cross_attention:
|
151
|
+
video_length = max(1, key.size()[0] // self.batch_size)
|
152
|
+
first_frame_index = [0] * video_length
|
153
|
+
|
154
|
+
# rearrange keys to have batch and frames in the 1st and 2nd dims respectively
|
155
|
+
key = rearrange_3(key, video_length)
|
156
|
+
key = key[:, first_frame_index]
|
157
|
+
# rearrange values to have batch and frames in the 1st and 2nd dims respectively
|
158
|
+
value = rearrange_3(value, video_length)
|
159
|
+
value = value[:, first_frame_index]
|
160
|
+
|
161
|
+
# rearrange back to original shape
|
162
|
+
key = rearrange_4(key)
|
163
|
+
value = rearrange_4(value)
|
164
|
+
|
165
|
+
head_dim = inner_dim // attn.heads
|
166
|
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
167
|
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
168
|
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
169
|
+
|
170
|
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
171
|
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
172
|
+
hidden_states = F.scaled_dot_product_attention(
|
173
|
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
174
|
+
)
|
175
|
+
|
176
|
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
177
|
+
hidden_states = hidden_states.to(query.dtype)
|
178
|
+
|
179
|
+
# linear proj
|
180
|
+
hidden_states = attn.to_out[0](hidden_states)
|
181
|
+
# dropout
|
182
|
+
hidden_states = attn.to_out[1](hidden_states)
|
183
|
+
return hidden_states
|
184
|
+
|
185
|
+
|
186
|
+
@dataclass
|
187
|
+
class TextToVideoSDXLPipelineOutput(BaseOutput):
|
188
|
+
"""
|
189
|
+
Output class for zero-shot text-to-video pipeline.
|
190
|
+
|
191
|
+
Args:
|
192
|
+
images (`List[PIL.Image.Image]` or `np.ndarray`)
|
193
|
+
List of denoised PIL images of length `batch_size` or numpy array of shape `(batch_size, height, width,
|
194
|
+
num_channels)`. PIL images or numpy array present the denoised images of the diffusion pipeline.
|
195
|
+
"""
|
196
|
+
|
197
|
+
images: Union[List[PIL.Image.Image], np.ndarray]
|
198
|
+
|
199
|
+
|
200
|
+
# Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.coords_grid
|
201
|
+
def coords_grid(batch, ht, wd, device):
|
202
|
+
# Adapted from https://github.com/princeton-vl/RAFT/blob/master/core/utils/utils.py
|
203
|
+
coords = torch.meshgrid(torch.arange(ht, device=device), torch.arange(wd, device=device))
|
204
|
+
coords = torch.stack(coords[::-1], dim=0).float()
|
205
|
+
return coords[None].repeat(batch, 1, 1, 1)
|
206
|
+
|
207
|
+
|
208
|
+
# Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.warp_single_latent
|
209
|
+
def warp_single_latent(latent, reference_flow):
|
210
|
+
"""
|
211
|
+
Warp latent of a single frame with given flow
|
212
|
+
|
213
|
+
Args:
|
214
|
+
latent: latent code of a single frame
|
215
|
+
reference_flow: flow which to warp the latent with
|
216
|
+
|
217
|
+
Returns:
|
218
|
+
warped: warped latent
|
219
|
+
"""
|
220
|
+
_, _, H, W = reference_flow.size()
|
221
|
+
_, _, h, w = latent.size()
|
222
|
+
coords0 = coords_grid(1, H, W, device=latent.device).to(latent.dtype)
|
223
|
+
|
224
|
+
coords_t0 = coords0 + reference_flow
|
225
|
+
coords_t0[:, 0] /= W
|
226
|
+
coords_t0[:, 1] /= H
|
227
|
+
|
228
|
+
coords_t0 = coords_t0 * 2.0 - 1.0
|
229
|
+
coords_t0 = F.interpolate(coords_t0, size=(h, w), mode="bilinear")
|
230
|
+
coords_t0 = torch.permute(coords_t0, (0, 2, 3, 1))
|
231
|
+
|
232
|
+
warped = grid_sample(latent, coords_t0, mode="nearest", padding_mode="reflection")
|
233
|
+
return warped
|
234
|
+
|
235
|
+
|
236
|
+
# Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.create_motion_field
|
237
|
+
def create_motion_field(motion_field_strength_x, motion_field_strength_y, frame_ids, device, dtype):
|
238
|
+
"""
|
239
|
+
Create translation motion field
|
240
|
+
|
241
|
+
Args:
|
242
|
+
motion_field_strength_x: motion strength along x-axis
|
243
|
+
motion_field_strength_y: motion strength along y-axis
|
244
|
+
frame_ids: indexes of the frames the latents of which are being processed.
|
245
|
+
This is needed when we perform chunk-by-chunk inference
|
246
|
+
device: device
|
247
|
+
dtype: dtype
|
248
|
+
|
249
|
+
Returns:
|
250
|
+
|
251
|
+
"""
|
252
|
+
seq_length = len(frame_ids)
|
253
|
+
reference_flow = torch.zeros((seq_length, 2, 512, 512), device=device, dtype=dtype)
|
254
|
+
for fr_idx in range(seq_length):
|
255
|
+
reference_flow[fr_idx, 0, :, :] = motion_field_strength_x * (frame_ids[fr_idx])
|
256
|
+
reference_flow[fr_idx, 1, :, :] = motion_field_strength_y * (frame_ids[fr_idx])
|
257
|
+
return reference_flow
|
258
|
+
|
259
|
+
|
260
|
+
# Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.create_motion_field_and_warp_latents
|
261
|
+
def create_motion_field_and_warp_latents(motion_field_strength_x, motion_field_strength_y, frame_ids, latents):
|
262
|
+
"""
|
263
|
+
Creates translation motion and warps the latents accordingly
|
264
|
+
|
265
|
+
Args:
|
266
|
+
motion_field_strength_x: motion strength along x-axis
|
267
|
+
motion_field_strength_y: motion strength along y-axis
|
268
|
+
frame_ids: indexes of the frames the latents of which are being processed.
|
269
|
+
This is needed when we perform chunk-by-chunk inference
|
270
|
+
latents: latent codes of frames
|
271
|
+
|
272
|
+
Returns:
|
273
|
+
warped_latents: warped latents
|
274
|
+
"""
|
275
|
+
motion_field = create_motion_field(
|
276
|
+
motion_field_strength_x=motion_field_strength_x,
|
277
|
+
motion_field_strength_y=motion_field_strength_y,
|
278
|
+
frame_ids=frame_ids,
|
279
|
+
device=latents.device,
|
280
|
+
dtype=latents.dtype,
|
281
|
+
)
|
282
|
+
warped_latents = latents.clone().detach()
|
283
|
+
for i in range(len(warped_latents)):
|
284
|
+
warped_latents[i] = warp_single_latent(latents[i][None], motion_field[i][None])
|
285
|
+
return warped_latents
|
286
|
+
|
287
|
+
|
288
|
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
|
289
|
+
def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
|
290
|
+
"""
|
291
|
+
Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
|
292
|
+
Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
|
293
|
+
"""
|
294
|
+
std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
|
295
|
+
std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
|
296
|
+
# rescale the results from guidance (fixes overexposure)
|
297
|
+
noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
|
298
|
+
# mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
|
299
|
+
noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
|
300
|
+
return noise_cfg
|
301
|
+
|
302
|
+
|
303
|
+
class TextToVideoZeroSDXLPipeline(StableDiffusionXLPipeline):
|
304
|
+
r"""
|
305
|
+
Pipeline for zero-shot text-to-video generation using Stable Diffusion XL.
|
306
|
+
|
307
|
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
308
|
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
309
|
+
|
310
|
+
Args:
|
311
|
+
vae ([`AutoencoderKL`]):
|
312
|
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
313
|
+
text_encoder ([`CLIPTextModel`]):
|
314
|
+
Frozen text-encoder. Stable Diffusion XL uses the text portion of
|
315
|
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
316
|
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
317
|
+
text_encoder_2 ([` CLIPTextModelWithProjection`]):
|
318
|
+
Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
|
319
|
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
|
320
|
+
specifically the
|
321
|
+
[laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
|
322
|
+
variant.
|
323
|
+
tokenizer (`CLIPTokenizer`):
|
324
|
+
Tokenizer of class
|
325
|
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
326
|
+
tokenizer_2 (`CLIPTokenizer`):
|
327
|
+
Second Tokenizer of class
|
328
|
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
329
|
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
330
|
+
scheduler ([`SchedulerMixin`]):
|
331
|
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
332
|
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
333
|
+
"""
|
334
|
+
|
335
|
+
def __init__(
|
336
|
+
self,
|
337
|
+
vae: AutoencoderKL,
|
338
|
+
text_encoder: CLIPTextModel,
|
339
|
+
text_encoder_2: CLIPTextModelWithProjection,
|
340
|
+
tokenizer: CLIPTokenizer,
|
341
|
+
tokenizer_2: CLIPTokenizer,
|
342
|
+
unet: UNet2DConditionModel,
|
343
|
+
scheduler: KarrasDiffusionSchedulers,
|
344
|
+
image_encoder: CLIPVisionModelWithProjection = None,
|
345
|
+
feature_extractor: CLIPImageProcessor = None,
|
346
|
+
force_zeros_for_empty_prompt: bool = True,
|
347
|
+
add_watermarker: Optional[bool] = None,
|
348
|
+
):
|
349
|
+
super().__init__(
|
350
|
+
vae=vae,
|
351
|
+
text_encoder=text_encoder,
|
352
|
+
text_encoder_2=text_encoder_2,
|
353
|
+
tokenizer=tokenizer,
|
354
|
+
tokenizer_2=tokenizer_2,
|
355
|
+
unet=unet,
|
356
|
+
scheduler=scheduler,
|
357
|
+
image_encoder=image_encoder,
|
358
|
+
feature_extractor=feature_extractor,
|
359
|
+
force_zeros_for_empty_prompt=force_zeros_for_empty_prompt,
|
360
|
+
add_watermarker=add_watermarker,
|
361
|
+
)
|
362
|
+
processor = (
|
363
|
+
CrossFrameAttnProcessor2_0(batch_size=2)
|
364
|
+
if hasattr(F, "scaled_dot_product_attention")
|
365
|
+
else CrossFrameAttnProcessor(batch_size=2)
|
366
|
+
)
|
367
|
+
self.unet.set_attn_processor(processor)
|
368
|
+
|
369
|
+
# Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.TextToVideoZeroPipeline.forward_loop
|
370
|
+
def forward_loop(self, x_t0, t0, t1, generator):
|
371
|
+
"""
|
372
|
+
Perform DDPM forward process from time t0 to t1. This is the same as adding noise with corresponding variance.
|
373
|
+
|
374
|
+
Args:
|
375
|
+
x_t0:
|
376
|
+
Latent code at time t0.
|
377
|
+
t0:
|
378
|
+
Timestep at t0.
|
379
|
+
t1:
|
380
|
+
Timestamp at t1.
|
381
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
382
|
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
383
|
+
generation deterministic.
|
384
|
+
|
385
|
+
Returns:
|
386
|
+
x_t1:
|
387
|
+
Forward process applied to x_t0 from time t0 to t1.
|
388
|
+
"""
|
389
|
+
eps = randn_tensor(x_t0.size(), generator=generator, dtype=x_t0.dtype, device=x_t0.device)
|
390
|
+
alpha_vec = torch.prod(self.scheduler.alphas[t0:t1])
|
391
|
+
x_t1 = torch.sqrt(alpha_vec) * x_t0 + torch.sqrt(1 - alpha_vec) * eps
|
392
|
+
return x_t1
|
393
|
+
|
394
|
+
def backward_loop(
|
395
|
+
self,
|
396
|
+
latents,
|
397
|
+
timesteps,
|
398
|
+
prompt_embeds,
|
399
|
+
guidance_scale,
|
400
|
+
callback,
|
401
|
+
callback_steps,
|
402
|
+
num_warmup_steps,
|
403
|
+
extra_step_kwargs,
|
404
|
+
add_text_embeds,
|
405
|
+
add_time_ids,
|
406
|
+
cross_attention_kwargs=None,
|
407
|
+
guidance_rescale: float = 0.0,
|
408
|
+
):
|
409
|
+
"""
|
410
|
+
Perform backward process given list of time steps
|
411
|
+
|
412
|
+
Args:
|
413
|
+
latents:
|
414
|
+
Latents at time timesteps[0].
|
415
|
+
timesteps:
|
416
|
+
Time steps along which to perform backward process.
|
417
|
+
prompt_embeds:
|
418
|
+
Pre-generated text embeddings.
|
419
|
+
guidance_scale:
|
420
|
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
421
|
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
422
|
+
callback (`Callable`, *optional*):
|
423
|
+
A function that calls every `callback_steps` steps during inference. The function is called with the
|
424
|
+
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
425
|
+
callback_steps (`int`, *optional*, defaults to 1):
|
426
|
+
The frequency at which the `callback` function is called. If not specified, the callback is called at
|
427
|
+
every step.
|
428
|
+
extra_step_kwargs:
|
429
|
+
Extra_step_kwargs.
|
430
|
+
cross_attention_kwargs:
|
431
|
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
432
|
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
433
|
+
num_warmup_steps:
|
434
|
+
number of warmup steps.
|
435
|
+
|
436
|
+
Returns:
|
437
|
+
latents: latents of backward process output at time timesteps[-1]
|
438
|
+
"""
|
439
|
+
|
440
|
+
do_classifier_free_guidance = guidance_scale > 1.0
|
441
|
+
num_steps = (len(timesteps) - num_warmup_steps) // self.scheduler.order
|
442
|
+
|
443
|
+
with self.progress_bar(total=num_steps) as progress_bar:
|
444
|
+
for i, t in enumerate(timesteps):
|
445
|
+
# expand the latents if we are doing classifier free guidance
|
446
|
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
447
|
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
448
|
+
|
449
|
+
# predict the noise residual
|
450
|
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
451
|
+
noise_pred = self.unet(
|
452
|
+
latent_model_input,
|
453
|
+
t,
|
454
|
+
encoder_hidden_states=prompt_embeds,
|
455
|
+
cross_attention_kwargs=cross_attention_kwargs,
|
456
|
+
added_cond_kwargs=added_cond_kwargs,
|
457
|
+
return_dict=False,
|
458
|
+
)[0]
|
459
|
+
|
460
|
+
# perform guidance
|
461
|
+
if do_classifier_free_guidance:
|
462
|
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
463
|
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
464
|
+
|
465
|
+
if do_classifier_free_guidance and guidance_rescale > 0.0:
|
466
|
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
467
|
+
noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
|
468
|
+
|
469
|
+
# compute the previous noisy sample x_t -> x_t-1
|
470
|
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
|
471
|
+
|
472
|
+
# call the callback, if provided
|
473
|
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
474
|
+
progress_bar.update()
|
475
|
+
if callback is not None and i % callback_steps == 0:
|
476
|
+
callback(i, t, latents)
|
477
|
+
return latents.clone().detach()
|
478
|
+
|
479
|
+
@torch.no_grad()
|
480
|
+
def __call__(
|
481
|
+
self,
|
482
|
+
prompt: Union[str, List[str]],
|
483
|
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
484
|
+
video_length: Optional[int] = 8,
|
485
|
+
height: Optional[int] = None,
|
486
|
+
width: Optional[int] = None,
|
487
|
+
num_inference_steps: int = 50,
|
488
|
+
denoising_end: Optional[float] = None,
|
489
|
+
guidance_scale: float = 7.5,
|
490
|
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
491
|
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
492
|
+
num_videos_per_prompt: Optional[int] = 1,
|
493
|
+
eta: float = 0.0,
|
494
|
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
495
|
+
frame_ids: Optional[List[int]] = None,
|
496
|
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
497
|
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
498
|
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
499
|
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
500
|
+
latents: Optional[torch.FloatTensor] = None,
|
501
|
+
motion_field_strength_x: float = 12,
|
502
|
+
motion_field_strength_y: float = 12,
|
503
|
+
output_type: Optional[str] = "tensor",
|
504
|
+
return_dict: bool = True,
|
505
|
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
506
|
+
callback_steps: int = 1,
|
507
|
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
508
|
+
guidance_rescale: float = 0.0,
|
509
|
+
original_size: Optional[Tuple[int, int]] = None,
|
510
|
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
511
|
+
target_size: Optional[Tuple[int, int]] = None,
|
512
|
+
t0: int = 44,
|
513
|
+
t1: int = 47,
|
514
|
+
):
|
515
|
+
"""
|
516
|
+
Function invoked when calling the pipeline for generation.
|
517
|
+
|
518
|
+
Args:
|
519
|
+
prompt (`str` or `List[str]`, *optional*):
|
520
|
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
521
|
+
instead.
|
522
|
+
prompt_2 (`str` or `List[str]`, *optional*):
|
523
|
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
524
|
+
used in both text-encoders
|
525
|
+
video_length (`int`, *optional*, defaults to 8):
|
526
|
+
The number of generated video frames.
|
527
|
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
528
|
+
The height in pixels of the generated image.
|
529
|
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
530
|
+
The width in pixels of the generated image.
|
531
|
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
532
|
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
533
|
+
expense of slower inference.
|
534
|
+
denoising_end (`float`, *optional*):
|
535
|
+
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
|
536
|
+
completed before it is intentionally prematurely terminated. As a result, the returned sample will
|
537
|
+
still retain a substantial amount of noise as determined by the discrete timesteps selected by the
|
538
|
+
scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
|
539
|
+
"Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
|
540
|
+
Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
|
541
|
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
542
|
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
543
|
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
544
|
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
545
|
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
546
|
+
usually at the expense of lower image quality.
|
547
|
+
negative_prompt (`str` or `List[str]`, *optional*):
|
548
|
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
549
|
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
550
|
+
less than `1`).
|
551
|
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
552
|
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
553
|
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
554
|
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
555
|
+
The number of videos to generate per prompt.
|
556
|
+
eta (`float`, *optional*, defaults to 0.0):
|
557
|
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
558
|
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
559
|
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
560
|
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
561
|
+
to make generation deterministic.
|
562
|
+
frame_ids (`List[int]`, *optional*):
|
563
|
+
Indexes of the frames that are being generated. This is used when generating longer videos
|
564
|
+
chunk-by-chunk.
|
565
|
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
566
|
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
567
|
+
provided, text embeddings will be generated from `prompt` input argument.
|
568
|
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
569
|
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
570
|
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
571
|
+
argument.
|
572
|
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
573
|
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
574
|
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
575
|
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
576
|
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
577
|
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
578
|
+
input argument.
|
579
|
+
latents (`torch.FloatTensor`, *optional*):
|
580
|
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
581
|
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
582
|
+
tensor will ge generated by sampling using the supplied random `generator`.
|
583
|
+
motion_field_strength_x (`float`, *optional*, defaults to 12):
|
584
|
+
Strength of motion in generated video along x-axis. See the [paper](https://arxiv.org/abs/2303.13439),
|
585
|
+
Sect. 3.3.1.
|
586
|
+
motion_field_strength_y (`float`, *optional*, defaults to 12):
|
587
|
+
Strength of motion in generated video along y-axis. See the [paper](https://arxiv.org/abs/2303.13439),
|
588
|
+
Sect. 3.3.1.
|
589
|
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
590
|
+
The output format of the generate image. Choose between
|
591
|
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
592
|
+
return_dict (`bool`, *optional*, defaults to `True`):
|
593
|
+
Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
|
594
|
+
of a plain tuple.
|
595
|
+
callback (`Callable`, *optional*):
|
596
|
+
A function that will be called every `callback_steps` steps during inference. The function will be
|
597
|
+
called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
598
|
+
callback_steps (`int`, *optional*, defaults to 1):
|
599
|
+
The frequency at which the `callback` function will be called. If not specified, the callback will be
|
600
|
+
called at every step.
|
601
|
+
cross_attention_kwargs (`dict`, *optional*):
|
602
|
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
603
|
+
`self.processor` in
|
604
|
+
[diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
|
605
|
+
guidance_rescale (`float`, *optional*, defaults to 0.7):
|
606
|
+
Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
|
607
|
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
|
608
|
+
[Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
609
|
+
Guidance rescale factor should fix overexposure when using zero terminal SNR.
|
610
|
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
611
|
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
612
|
+
`original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
|
613
|
+
explained in section 2.2 of
|
614
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
615
|
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
616
|
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
617
|
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
618
|
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
619
|
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
620
|
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
621
|
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
622
|
+
not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
|
623
|
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
624
|
+
t0 (`int`, *optional*, defaults to 44):
|
625
|
+
Timestep t0. Should be in the range [0, num_inference_steps - 1]. See the
|
626
|
+
[paper](https://arxiv.org/abs/2303.13439), Sect. 3.3.1.
|
627
|
+
t1 (`int`, *optional*, defaults to 47):
|
628
|
+
Timestep t0. Should be in the range [t0 + 1, num_inference_steps - 1]. See the
|
629
|
+
[paper](https://arxiv.org/abs/2303.13439), Sect. 3.3.1.
|
630
|
+
|
631
|
+
Returns:
|
632
|
+
[`~pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.TextToVideoSDXLPipelineOutput`] or
|
633
|
+
`tuple`: [`~pipelines.text_to_video_synthesis.pipeline_text_to_video_zero.TextToVideoSDXLPipelineOutput`]
|
634
|
+
if `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the
|
635
|
+
generated images.
|
636
|
+
"""
|
637
|
+
assert video_length > 0
|
638
|
+
if frame_ids is None:
|
639
|
+
frame_ids = list(range(video_length))
|
640
|
+
assert len(frame_ids) == video_length
|
641
|
+
|
642
|
+
assert num_videos_per_prompt == 1
|
643
|
+
|
644
|
+
if isinstance(prompt, str):
|
645
|
+
prompt = [prompt]
|
646
|
+
if isinstance(negative_prompt, str):
|
647
|
+
negative_prompt = [negative_prompt]
|
648
|
+
|
649
|
+
# 0. Default height and width to unet
|
650
|
+
height = height or self.default_sample_size * self.vae_scale_factor
|
651
|
+
width = width or self.default_sample_size * self.vae_scale_factor
|
652
|
+
|
653
|
+
original_size = original_size or (height, width)
|
654
|
+
target_size = target_size or (height, width)
|
655
|
+
|
656
|
+
# 1. Check inputs. Raise error if not correct
|
657
|
+
self.check_inputs(
|
658
|
+
prompt,
|
659
|
+
prompt_2,
|
660
|
+
height,
|
661
|
+
width,
|
662
|
+
callback_steps,
|
663
|
+
negative_prompt,
|
664
|
+
negative_prompt_2,
|
665
|
+
prompt_embeds,
|
666
|
+
negative_prompt_embeds,
|
667
|
+
pooled_prompt_embeds,
|
668
|
+
negative_pooled_prompt_embeds,
|
669
|
+
)
|
670
|
+
|
671
|
+
# 2. Define call parameters
|
672
|
+
batch_size = (
|
673
|
+
1 if isinstance(prompt, str) else len(prompt) if isinstance(prompt, list) else prompt_embeds.shape[0]
|
674
|
+
)
|
675
|
+
device = self._execution_device
|
676
|
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
677
|
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
678
|
+
# corresponds to doing no classifier free guidance.
|
679
|
+
do_classifier_free_guidance = guidance_scale > 1.0
|
680
|
+
|
681
|
+
# 3. Encode input prompt
|
682
|
+
text_encoder_lora_scale = (
|
683
|
+
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
684
|
+
)
|
685
|
+
(
|
686
|
+
prompt_embeds,
|
687
|
+
negative_prompt_embeds,
|
688
|
+
pooled_prompt_embeds,
|
689
|
+
negative_pooled_prompt_embeds,
|
690
|
+
) = self.encode_prompt(
|
691
|
+
prompt=prompt,
|
692
|
+
prompt_2=prompt_2,
|
693
|
+
device=device,
|
694
|
+
num_images_per_prompt=num_videos_per_prompt,
|
695
|
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
696
|
+
negative_prompt=negative_prompt,
|
697
|
+
negative_prompt_2=negative_prompt_2,
|
698
|
+
prompt_embeds=prompt_embeds,
|
699
|
+
negative_prompt_embeds=negative_prompt_embeds,
|
700
|
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
701
|
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
702
|
+
lora_scale=text_encoder_lora_scale,
|
703
|
+
)
|
704
|
+
|
705
|
+
# 4. Prepare timesteps
|
706
|
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
707
|
+
timesteps = self.scheduler.timesteps
|
708
|
+
|
709
|
+
# 5. Prepare latent variables
|
710
|
+
num_channels_latents = self.unet.config.in_channels
|
711
|
+
|
712
|
+
latents = self.prepare_latents(
|
713
|
+
batch_size * num_videos_per_prompt,
|
714
|
+
num_channels_latents,
|
715
|
+
height,
|
716
|
+
width,
|
717
|
+
prompt_embeds.dtype,
|
718
|
+
device,
|
719
|
+
generator,
|
720
|
+
latents,
|
721
|
+
)
|
722
|
+
|
723
|
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
724
|
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
725
|
+
|
726
|
+
# 7. Prepare added time ids & embeddings
|
727
|
+
add_text_embeds = pooled_prompt_embeds
|
728
|
+
if self.text_encoder_2 is None:
|
729
|
+
text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
|
730
|
+
else:
|
731
|
+
text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
|
732
|
+
|
733
|
+
add_time_ids = self._get_add_time_ids(
|
734
|
+
original_size,
|
735
|
+
crops_coords_top_left,
|
736
|
+
target_size,
|
737
|
+
dtype=prompt_embeds.dtype,
|
738
|
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
739
|
+
)
|
740
|
+
|
741
|
+
if do_classifier_free_guidance:
|
742
|
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
743
|
+
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
744
|
+
add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
|
745
|
+
|
746
|
+
prompt_embeds = prompt_embeds.to(device)
|
747
|
+
add_text_embeds = add_text_embeds.to(device)
|
748
|
+
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_videos_per_prompt, 1)
|
749
|
+
|
750
|
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
751
|
+
|
752
|
+
# Perform the first backward process up to time T_1
|
753
|
+
x_1_t1 = self.backward_loop(
|
754
|
+
timesteps=timesteps[: -t1 - 1],
|
755
|
+
prompt_embeds=prompt_embeds,
|
756
|
+
latents=latents,
|
757
|
+
guidance_scale=guidance_scale,
|
758
|
+
callback=callback,
|
759
|
+
callback_steps=callback_steps,
|
760
|
+
extra_step_kwargs=extra_step_kwargs,
|
761
|
+
num_warmup_steps=num_warmup_steps,
|
762
|
+
add_text_embeds=add_text_embeds,
|
763
|
+
add_time_ids=add_time_ids,
|
764
|
+
)
|
765
|
+
|
766
|
+
scheduler_copy = copy.deepcopy(self.scheduler)
|
767
|
+
|
768
|
+
# Perform the second backward process up to time T_0
|
769
|
+
x_1_t0 = self.backward_loop(
|
770
|
+
timesteps=timesteps[-t1 - 1 : -t0 - 1],
|
771
|
+
prompt_embeds=prompt_embeds,
|
772
|
+
latents=x_1_t1,
|
773
|
+
guidance_scale=guidance_scale,
|
774
|
+
callback=callback,
|
775
|
+
callback_steps=callback_steps,
|
776
|
+
extra_step_kwargs=extra_step_kwargs,
|
777
|
+
num_warmup_steps=0,
|
778
|
+
add_text_embeds=add_text_embeds,
|
779
|
+
add_time_ids=add_time_ids,
|
780
|
+
)
|
781
|
+
|
782
|
+
# Propagate first frame latents at time T_0 to remaining frames
|
783
|
+
x_2k_t0 = x_1_t0.repeat(video_length - 1, 1, 1, 1)
|
784
|
+
|
785
|
+
# Add motion in latents at time T_0
|
786
|
+
x_2k_t0 = create_motion_field_and_warp_latents(
|
787
|
+
motion_field_strength_x=motion_field_strength_x,
|
788
|
+
motion_field_strength_y=motion_field_strength_y,
|
789
|
+
latents=x_2k_t0,
|
790
|
+
frame_ids=frame_ids[1:],
|
791
|
+
)
|
792
|
+
|
793
|
+
# Perform forward process up to time T_1
|
794
|
+
x_2k_t1 = self.forward_loop(
|
795
|
+
x_t0=x_2k_t0,
|
796
|
+
t0=timesteps[-t0 - 1].to(torch.long),
|
797
|
+
t1=timesteps[-t1 - 1].to(torch.long),
|
798
|
+
generator=generator,
|
799
|
+
)
|
800
|
+
|
801
|
+
# Perform backward process from time T_1 to 0
|
802
|
+
latents = torch.cat([x_1_t1, x_2k_t1])
|
803
|
+
|
804
|
+
self.scheduler = scheduler_copy
|
805
|
+
timesteps = timesteps[-t1 - 1 :]
|
806
|
+
|
807
|
+
b, l, d = prompt_embeds.size()
|
808
|
+
prompt_embeds = prompt_embeds[:, None].repeat(1, video_length, 1, 1).reshape(b * video_length, l, d)
|
809
|
+
|
810
|
+
b, k = add_text_embeds.size()
|
811
|
+
add_text_embeds = add_text_embeds[:, None].repeat(1, video_length, 1).reshape(b * video_length, k)
|
812
|
+
|
813
|
+
b, k = add_time_ids.size()
|
814
|
+
add_time_ids = add_time_ids[:, None].repeat(1, video_length, 1).reshape(b * video_length, k)
|
815
|
+
|
816
|
+
# 7.1 Apply denoising_end
|
817
|
+
if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
|
818
|
+
discrete_timestep_cutoff = int(
|
819
|
+
round(
|
820
|
+
self.scheduler.config.num_train_timesteps
|
821
|
+
- (denoising_end * self.scheduler.config.num_train_timesteps)
|
822
|
+
)
|
823
|
+
)
|
824
|
+
num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
|
825
|
+
timesteps = timesteps[:num_inference_steps]
|
826
|
+
|
827
|
+
x_1k_0 = self.backward_loop(
|
828
|
+
timesteps=timesteps,
|
829
|
+
prompt_embeds=prompt_embeds,
|
830
|
+
latents=latents,
|
831
|
+
guidance_scale=guidance_scale,
|
832
|
+
callback=callback,
|
833
|
+
callback_steps=callback_steps,
|
834
|
+
extra_step_kwargs=extra_step_kwargs,
|
835
|
+
num_warmup_steps=0,
|
836
|
+
add_text_embeds=add_text_embeds,
|
837
|
+
add_time_ids=add_time_ids,
|
838
|
+
)
|
839
|
+
|
840
|
+
latents = x_1k_0
|
841
|
+
|
842
|
+
if not output_type == "latent":
|
843
|
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
844
|
+
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
845
|
+
|
846
|
+
if needs_upcasting:
|
847
|
+
self.upcast_vae()
|
848
|
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
849
|
+
|
850
|
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
851
|
+
|
852
|
+
# cast back to fp16 if needed
|
853
|
+
if needs_upcasting:
|
854
|
+
self.vae.to(dtype=torch.float16)
|
855
|
+
else:
|
856
|
+
image = latents
|
857
|
+
return TextToVideoSDXLPipelineOutput(images=image)
|
858
|
+
|
859
|
+
# apply watermark if available
|
860
|
+
if self.watermark is not None:
|
861
|
+
image = self.watermark.apply_watermark(image)
|
862
|
+
|
863
|
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
864
|
+
|
865
|
+
# Offload last model to CPU manually for max memory savings
|
866
|
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
867
|
+
self.final_offload_hook.offload()
|
868
|
+
|
869
|
+
if not return_dict:
|
870
|
+
return (image,)
|
871
|
+
|
872
|
+
return TextToVideoSDXLPipelineOutput(images=image)
|