Sapir commited on
Commit
ebaff66
1 Parent(s): 8aab836
eval.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from vae.causal_video_autoencoder import CausalVideoAutoencoder
3
+ from transformer.transformer3d import Trasformer3D
4
+ from patchify.symmetric import SymmetricPatchifier
5
+
6
+
7
+ model_name_or_path = "PixArt-alpha/PixArt-XL-2-1024-MS"
8
+ vae_path = "/opt/models/checkpoints/vae_training/causal_vvae_32x32x8_420m_cont_32/step_2296000"
9
+ dtype = torch.float32
10
+ vae = CausalVideoAutoencoder.from_pretrained(
11
+ pretrained_model_name_or_path=vae_local_path,
12
+ revision=False,
13
+ torch_dtype=torch.bfloat16,
14
+ load_in_8bit=False,
15
+ )
16
+ transformer_config_path = "/opt/txt2img/txt2img/config/transformer3d/xora_v1.2-L.json"
17
+ transformer_config = Transformer3D.load_config(config_local_path)
18
+ transformer = Transformer3D.from_config(config)
19
+ transformer_local_path = "/opt/models/logs/v1.2-vae-mf-medHR-mr-cvae-nl/ckpt/01760000/model.p"
20
+ transformer_ckpt_state_dict = torch.load(transformer_local_path)
21
+ transformer.load_state_dict(transformer_ckpt_state_dict, True)
22
+ unet = transformer
23
+ scheduler_config_path = "/opt/txt2img/txt2img/config/scheduler/RF_SD3_shifted.json"
24
+ scheduler_config = RectifiedFlowScheduler.load_config(config_local_path)
25
+ scheduler = RectifiedFlowScheduler.from_config(config)
26
+ patchifier = SymmetricPatchifier(patch_size=1)
27
+
28
+
29
+
30
+ pipeline = VideoPixArtAlphaPipeline.from_pretrained(model_name_or_path,
31
+ safety_checker=None,
32
+ revision=None,
33
+ torch_dtype=dtype,
34
+ **submodel_dict,
35
+ )
36
+
37
+ num_inference_steps=20
38
+ num_images_per_prompt=2
39
+ guidance_scale=3
40
+ height=512
41
+ width=768
42
+ num_frames=57
43
+ frame_rate=25
44
+ sample = {
45
+ "prompt_embeds": None, # (B, L, E)
46
+ 'prompt_attention_mask': None, # (B , L)
47
+ 'negative_prompt_embeds': None,' # (B, L, E)
48
+ 'negative_prompt': None,
49
+ 'negative_prompt_attention_mask': None # (B , L)
50
+ }
51
+
52
+
53
+
54
+ images = pipeline(
55
+ num_inference_steps=num_inference_steps,
56
+ num_images_per_prompt=num_images_per_prompt,
57
+ guidance_scale=guidance_scale,
58
+ generator=None,
59
+ output_type="pt",
60
+ callback_on_step_end=None,
61
+ height=height,
62
+ width=width,
63
+ num_frames=num_frames,
64
+ frame_rate=frame_rate,
65
+ **sample,
66
+ is_video=True,
67
+ vae_per_channel_noramlize=True,
68
+ ).images
patchify/symmetric.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from typing import Tuple
3
+
4
+ import torch
5
+ from diffusers.configuration_utils import ConfigMixin
6
+ from einops import rearrange
7
+ from torch import Tensor
8
+
9
+ from txt2img.common.torch_utils import append_dims
10
+ from txt2img.config.diffusion_parts import PatchifierConfig, PatchifierName
11
+
12
+
13
+ def pixart_alpha_patchify(
14
+ latents: Tensor,
15
+ patch_size: int,
16
+ ) -> Tuple[Tensor, Tensor]:
17
+ latents = rearrange(
18
+ latents,
19
+ "b c (f p1) (h p2) (w p3) -> b (f h w) (c p1 p2 p3)",
20
+ p1=patch_size[0],
21
+ p2=patch_size[1],
22
+ p3=patch_size[2],
23
+ )
24
+ return latents
25
+
26
+ class SymmetricPatchifier(Patchifier):
27
+ def patchify(
28
+ self,
29
+ latents: Tensor,
30
+ ) -> Tuple[Tensor, Tensor]:
31
+ return pixart_alpha_patchify(latents, self._patch_size)
32
+
33
+ def unpatchify(
34
+ self, latents: Tensor, output_height: int, output_width: int, output_num_frames: int, out_channels: int
35
+ ) -> Tuple[Tensor, Tensor]:
36
+ output_height = output_height // self._patch_size[1]
37
+ output_width = output_width // self._patch_size[2]
38
+ latents = rearrange(
39
+ latents,
40
+ "b (f h w) (c p q) -> b c f (h p) (w q) ",
41
+ f=output_num_frames,
42
+ h=output_height,
43
+ w=output_width,
44
+ p=self._patch_size[1],
45
+ q=self._patch_size[2],
46
+ )
47
+ return latents
pipeline/pipeline_video_pixart_alpha.py ADDED
@@ -0,0 +1,929 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # Adapted from: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py
2
+ import html
3
+ import inspect
4
+ import math
5
+ import re
6
+ import urllib.parse as ul
7
+ from typing import Callable, Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from diffusers.image_processor import VaeImageProcessor
12
+ from diffusers.models import AutoencoderKL
13
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
14
+ from diffusers.schedulers import DPMSolverMultistepScheduler
15
+ from diffusers.utils import (
16
+ BACKENDS_MAPPING,
17
+ deprecate,
18
+ is_bs4_available,
19
+ is_ftfy_available,
20
+ logging,
21
+ replace_example_docstring,
22
+ )
23
+ from diffusers.utils.torch_utils import randn_tensor
24
+ from einops import rearrange
25
+ from transformers import T5EncoderModel, T5Tokenizer
26
+
27
+ from dataset_metadata.data_field_name import DataFieldName
28
+ from txt2img.config.eval import ValLossConfig
29
+ from txt2img.diffusers_schedulers.rf_scheduler import TimestepShifter
30
+ from txt2img.diffusion.loss.losses import DiffusionLoss
31
+ from txt2img.diffusion.models.pixart.transformer_3d import Transformer3DModel
32
+ from txt2img.diffusion.patchify import Patchifier
33
+ from txt2img.diffusion.vae_encode import get_vae_size_scale_factor, vae_decode, vae_encode
34
+ from txt2img.vae.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
35
+
36
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
37
+
38
+ if is_bs4_available():
39
+ from bs4 import BeautifulSoup
40
+
41
+ if is_ftfy_available():
42
+ import ftfy
43
+
44
+ def retrieve_timesteps(
45
+ scheduler,
46
+ num_inference_steps: Optional[int] = None,
47
+ device: Optional[Union[str, torch.device]] = None,
48
+ timesteps: Optional[List[int]] = None,
49
+ **kwargs,
50
+ ):
51
+ """
52
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
53
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
54
+
55
+ Args:
56
+ scheduler (`SchedulerMixin`):
57
+ The scheduler to get timesteps from.
58
+ num_inference_steps (`int`):
59
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
60
+ `timesteps` must be `None`.
61
+ device (`str` or `torch.device`, *optional*):
62
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
63
+ timesteps (`List[int]`, *optional*):
64
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
65
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
66
+ must be `None`.
67
+
68
+ Returns:
69
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
70
+ second element is the number of inference steps.
71
+ """
72
+ if timesteps is not None:
73
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
74
+ if not accepts_timesteps:
75
+ raise ValueError(
76
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
77
+ f" timestep schedules. Please check whether you are using the correct scheduler."
78
+ )
79
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
80
+ timesteps = scheduler.timesteps
81
+ num_inference_steps = len(timesteps)
82
+ else:
83
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
84
+ timesteps = scheduler.timesteps
85
+ return timesteps, num_inference_steps
86
+
87
+
88
+ class VideoPixArtAlphaPipeline(DiffusionPipeline):
89
+ r"""
90
+ Pipeline for text-to-image generation using PixArt-Alpha.
91
+
92
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
93
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
94
+
95
+ Args:
96
+ vae ([`AutoencoderKL`]):
97
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
98
+ text_encoder ([`T5EncoderModel`]):
99
+ Frozen text-encoder. PixArt-Alpha uses
100
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
101
+ [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
102
+ tokenizer (`T5Tokenizer`):
103
+ Tokenizer of class
104
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
105
+ transformer ([`Transformer2DModel`]):
106
+ A text conditioned `Transformer2DModel` to denoise the encoded image latents.
107
+ scheduler ([`SchedulerMixin`]):
108
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
109
+ """
110
+
111
+ bad_punct_regex = re.compile(
112
+ r"["
113
+ + "#®•©™&@·º½¾¿¡§~"
114
+ + r"\)"
115
+ + r"\("
116
+ + r"\]"
117
+ + r"\["
118
+ + r"\}"
119
+ + r"\{"
120
+ + r"\|"
121
+ + "\\"
122
+ + r"\/"
123
+ + r"\*"
124
+ + r"]{1,}"
125
+ ) # noqa
126
+
127
+ _optional_components = ["tokenizer", "text_encoder"]
128
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
129
+
130
+ def __init__(
131
+ self,
132
+ tokenizer: T5Tokenizer,
133
+ text_encoder: T5EncoderModel,
134
+ vae: AutoencoderKL,
135
+ transformer: Transformer3DModel,
136
+ scheduler: DPMSolverMultistepScheduler,
137
+ patchifier: Patchifier,
138
+ ):
139
+ super().__init__()
140
+
141
+ self.register_modules(
142
+ tokenizer=tokenizer,
143
+ text_encoder=text_encoder,
144
+ vae=vae,
145
+ transformer=transformer,
146
+ scheduler=scheduler,
147
+ patchifier=patchifier,
148
+ )
149
+
150
+ self.video_scale_factor, self.vae_scale_factor, _ = get_vae_size_scale_factor(self.vae)
151
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
152
+
153
+ # Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/utils.py
154
+ def mask_text_embeddings(self, emb, mask):
155
+ if emb.shape[0] == 1:
156
+ keep_index = mask.sum().item()
157
+ return emb[:, :, :keep_index, :], keep_index
158
+ else:
159
+ masked_feature = emb * mask[:, None, :, None]
160
+ return masked_feature, emb.shape[2]
161
+
162
+ # Adapted from diffusers.pipelines.deepfloyd_if.pipeline_if.encode_prompt
163
+ def encode_prompt(
164
+ self,
165
+ prompt: Union[str, List[str]],
166
+ do_classifier_free_guidance: bool = True,
167
+ negative_prompt: str = "",
168
+ num_images_per_prompt: int = 1,
169
+ device: Optional[torch.device] = None,
170
+ prompt_embeds: Optional[torch.FloatTensor] = None,
171
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
172
+ prompt_attention_mask: Optional[torch.FloatTensor] = None,
173
+ negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
174
+ clean_caption: bool = False,
175
+ **kwargs,
176
+ ):
177
+ r"""
178
+ Encodes the prompt into text encoder hidden states.
179
+
180
+ Args:
181
+ prompt (`str` or `List[str]`, *optional*):
182
+ prompt to be encoded
183
+ negative_prompt (`str` or `List[str]`, *optional*):
184
+ The prompt not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`
185
+ instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). For
186
+ PixArt-Alpha, this should be "".
187
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
188
+ whether to use classifier free guidance or not
189
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
190
+ number of images that should be generated per prompt
191
+ device: (`torch.device`, *optional*):
192
+ torch device to place the resulting embeddings on
193
+ prompt_embeds (`torch.FloatTensor`, *optional*):
194
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
195
+ provided, text embeddings will be generated from `prompt` input argument.
196
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
197
+ Pre-generated negative text embeddings. For PixArt-Alpha, it's should be the embeddings of the ""
198
+ string.
199
+ clean_caption (bool, defaults to `False`):
200
+ If `True`, the function will preprocess and clean the provided caption before encoding.
201
+ """
202
+
203
+ if "mask_feature" in kwargs:
204
+ deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
205
+ deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
206
+
207
+ if device is None:
208
+ device = self._execution_device
209
+
210
+ if prompt is not None and isinstance(prompt, str):
211
+ batch_size = 1
212
+ elif prompt is not None and isinstance(prompt, list):
213
+ batch_size = len(prompt)
214
+ else:
215
+ batch_size = prompt_embeds.shape[0]
216
+
217
+ # See Section 3.1. of the paper.
218
+ # FIXME: to be configured in config not hardecoded. Fix in separate PR with rest of config
219
+ max_length = 128 # TPU supports only lengths multiple of 128
220
+
221
+ if prompt_embeds is None:
222
+ prompt = self._text_preprocessing(prompt, clean_caption=clean_caption)
223
+ text_inputs = self.tokenizer(
224
+ prompt,
225
+ padding="max_length",
226
+ max_length=max_length,
227
+ truncation=True,
228
+ add_special_tokens=True,
229
+ return_tensors="pt",
230
+ )
231
+ text_input_ids = text_inputs.input_ids
232
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
233
+
234
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
235
+ text_input_ids, untruncated_ids
236
+ ):
237
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_length - 1 : -1])
238
+ logger.warning(
239
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
240
+ f" {max_length} tokens: {removed_text}"
241
+ )
242
+
243
+ prompt_attention_mask = text_inputs.attention_mask
244
+ prompt_attention_mask = prompt_attention_mask.to(device)
245
+
246
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=prompt_attention_mask)
247
+ prompt_embeds = prompt_embeds[0]
248
+
249
+ if self.text_encoder is not None:
250
+ dtype = self.text_encoder.dtype
251
+ elif self.transformer is not None:
252
+ dtype = self.transformer.dtype
253
+ else:
254
+ dtype = None
255
+
256
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
257
+
258
+ bs_embed, seq_len, _ = prompt_embeds.shape
259
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
260
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
261
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
262
+ prompt_attention_mask = prompt_attention_mask.repeat(1, num_images_per_prompt)
263
+ prompt_attention_mask = prompt_attention_mask.view(bs_embed * num_images_per_prompt, -1)
264
+
265
+ # get unconditional embeddings for classifier free guidance
266
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
267
+ uncond_tokens = [negative_prompt] * batch_size
268
+ uncond_tokens = self._text_preprocessing(uncond_tokens, clean_caption=clean_caption)
269
+ max_length = prompt_embeds.shape[1]
270
+ uncond_input = self.tokenizer(
271
+ uncond_tokens,
272
+ padding="max_length",
273
+ max_length=max_length,
274
+ truncation=True,
275
+ return_attention_mask=True,
276
+ add_special_tokens=True,
277
+ return_tensors="pt",
278
+ )
279
+ negative_prompt_attention_mask = uncond_input.attention_mask
280
+ negative_prompt_attention_mask = negative_prompt_attention_mask.to(device)
281
+
282
+ negative_prompt_embeds = self.text_encoder(
283
+ uncond_input.input_ids.to(device), attention_mask=negative_prompt_attention_mask
284
+ )
285
+ negative_prompt_embeds = negative_prompt_embeds[0]
286
+
287
+ if do_classifier_free_guidance:
288
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
289
+ seq_len = negative_prompt_embeds.shape[1]
290
+
291
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
292
+
293
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
294
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
295
+
296
+ negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(1, num_images_per_prompt)
297
+ negative_prompt_attention_mask = negative_prompt_attention_mask.view(bs_embed * num_images_per_prompt, -1)
298
+ else:
299
+ negative_prompt_embeds = None
300
+ negative_prompt_attention_mask = None
301
+
302
+ return prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask
303
+
304
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
305
+ def prepare_extra_step_kwargs(self, generator, eta):
306
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
307
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
308
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
309
+ # and should be between [0, 1]
310
+
311
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
312
+ extra_step_kwargs = {}
313
+ if accepts_eta:
314
+ extra_step_kwargs["eta"] = eta
315
+
316
+ # check if the scheduler accepts generator
317
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
318
+ if accepts_generator:
319
+ extra_step_kwargs["generator"] = generator
320
+ return extra_step_kwargs
321
+
322
+ def check_inputs(
323
+ self,
324
+ prompt,
325
+ height,
326
+ width,
327
+ negative_prompt,
328
+ prompt_embeds=None,
329
+ negative_prompt_embeds=None,
330
+ prompt_attention_mask=None,
331
+ negative_prompt_attention_mask=None,
332
+ ):
333
+ if height % 8 != 0 or width % 8 != 0:
334
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
335
+
336
+ if prompt is not None and prompt_embeds is not None:
337
+ raise ValueError(
338
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
339
+ " only forward one of the two."
340
+ )
341
+ elif prompt is None and prompt_embeds is None:
342
+ raise ValueError(
343
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
344
+ )
345
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
346
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
347
+
348
+ if prompt is not None and negative_prompt_embeds is not None:
349
+ raise ValueError(
350
+ f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
351
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
352
+ )
353
+
354
+ if negative_prompt is not None and negative_prompt_embeds is not None:
355
+ raise ValueError(
356
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
357
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
358
+ )
359
+
360
+ if prompt_embeds is not None and prompt_attention_mask is None:
361
+ raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
362
+
363
+ if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
364
+ raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
365
+
366
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
367
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
368
+ raise ValueError(
369
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
370
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
371
+ f" {negative_prompt_embeds.shape}."
372
+ )
373
+ if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
374
+ raise ValueError(
375
+ "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
376
+ f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
377
+ f" {negative_prompt_attention_mask.shape}."
378
+ )
379
+
380
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._text_preprocessing
381
+ def _text_preprocessing(self, text, clean_caption=False):
382
+ if clean_caption and not is_bs4_available():
383
+ logger.warn(BACKENDS_MAPPING["bs4"][-1].format("Setting `clean_caption=True`"))
384
+ logger.warn("Setting `clean_caption` to False...")
385
+ clean_caption = False
386
+
387
+ if clean_caption and not is_ftfy_available():
388
+ logger.warn(BACKENDS_MAPPING["ftfy"][-1].format("Setting `clean_caption=True`"))
389
+ logger.warn("Setting `clean_caption` to False...")
390
+ clean_caption = False
391
+
392
+ if not isinstance(text, (tuple, list)):
393
+ text = [text]
394
+
395
+ def process(text: str):
396
+ if clean_caption:
397
+ text = self._clean_caption(text)
398
+ text = self._clean_caption(text)
399
+ else:
400
+ text = text.lower().strip()
401
+ return text
402
+
403
+ return [process(t) for t in text]
404
+
405
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._clean_caption
406
+ def _clean_caption(self, caption):
407
+ caption = str(caption)
408
+ caption = ul.unquote_plus(caption)
409
+ caption = caption.strip().lower()
410
+ caption = re.sub("<person>", "person", caption)
411
+ # urls:
412
+ caption = re.sub(
413
+ r"\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
414
+ "",
415
+ caption,
416
+ ) # regex for urls
417
+ caption = re.sub(
418
+ r"\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
419
+ "",
420
+ caption,
421
+ ) # regex for urls
422
+ # html:
423
+ caption = BeautifulSoup(caption, features="html.parser").text
424
+
425
+ # @<nickname>
426
+ caption = re.sub(r"@[\w\d]+\b", "", caption)
427
+
428
+ # 31C0—31EF CJK Strokes
429
+ # 31F0—31FF Katakana Phonetic Extensions
430
+ # 3200—32FF Enclosed CJK Letters and Months
431
+ # 3300—33FF CJK Compatibility
432
+ # 3400—4DBF CJK Unified Ideographs Extension A
433
+ # 4DC0—4DFF Yijing Hexagram Symbols
434
+ # 4E00—9FFF CJK Unified Ideographs
435
+ caption = re.sub(r"[\u31c0-\u31ef]+", "", caption)
436
+ caption = re.sub(r"[\u31f0-\u31ff]+", "", caption)
437
+ caption = re.sub(r"[\u3200-\u32ff]+", "", caption)
438
+ caption = re.sub(r"[\u3300-\u33ff]+", "", caption)
439
+ caption = re.sub(r"[\u3400-\u4dbf]+", "", caption)
440
+ caption = re.sub(r"[\u4dc0-\u4dff]+", "", caption)
441
+ caption = re.sub(r"[\u4e00-\u9fff]+", "", caption)
442
+ #######################################################
443
+
444
+ # все виды тире / all types of dash --> "-"
445
+ caption = re.sub(
446
+ r"[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+", # noqa
447
+ "-",
448
+ caption,
449
+ )
450
+
451
+ # кавычки к одному стандарту
452
+ caption = re.sub(r"[`´«»“”¨]", '"', caption)
453
+ caption = re.sub(r"[‘’]", "'", caption)
454
+
455
+ # &quot;
456
+ caption = re.sub(r"&quot;?", "", caption)
457
+ # &amp
458
+ caption = re.sub(r"&amp", "", caption)
459
+
460
+ # ip adresses:
461
+ caption = re.sub(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", " ", caption)
462
+
463
+ # article ids:
464
+ caption = re.sub(r"\d:\d\d\s+$", "", caption)
465
+
466
+ # \n
467
+ caption = re.sub(r"\\n", " ", caption)
468
+
469
+ # "#123"
470
+ caption = re.sub(r"#\d{1,3}\b", "", caption)
471
+ # "#12345.."
472
+ caption = re.sub(r"#\d{5,}\b", "", caption)
473
+ # "123456.."
474
+ caption = re.sub(r"\b\d{6,}\b", "", caption)
475
+ # filenames:
476
+ caption = re.sub(r"[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)", "", caption)
477
+
478
+ #
479
+ caption = re.sub(r"[\"\']{2,}", r'"', caption) # """AUSVERKAUFT"""
480
+ caption = re.sub(r"[\.]{2,}", r" ", caption) # """AUSVERKAUFT"""
481
+
482
+ caption = re.sub(self.bad_punct_regex, r" ", caption) # ***AUSVERKAUFT***, #AUSVERKAUFT
483
+ caption = re.sub(r"\s+\.\s+", r" ", caption) # " . "
484
+
485
+ # this-is-my-cute-cat / this_is_my_cute_cat
486
+ regex2 = re.compile(r"(?:\-|\_)")
487
+ if len(re.findall(regex2, caption)) > 3:
488
+ caption = re.sub(regex2, " ", caption)
489
+
490
+ caption = ftfy.fix_text(caption)
491
+ caption = html.unescape(html.unescape(caption))
492
+
493
+ caption = re.sub(r"\b[a-zA-Z]{1,3}\d{3,15}\b", "", caption) # jc6640
494
+ caption = re.sub(r"\b[a-zA-Z]+\d+[a-zA-Z]+\b", "", caption) # jc6640vc
495
+ caption = re.sub(r"\b\d+[a-zA-Z]+\d+\b", "", caption) # 6640vc231
496
+
497
+ caption = re.sub(r"(worldwide\s+)?(free\s+)?shipping", "", caption)
498
+ caption = re.sub(r"(free\s)?download(\sfree)?", "", caption)
499
+ caption = re.sub(r"\bclick\b\s(?:for|on)\s\w+", "", caption)
500
+ caption = re.sub(r"\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?", "", caption)
501
+ caption = re.sub(r"\bpage\s+\d+\b", "", caption)
502
+
503
+ caption = re.sub(r"\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b", r" ", caption) # j2d1a2a...
504
+
505
+ caption = re.sub(r"\b\d+\.?\d*[xх×]\d+\.?\d*\b", "", caption)
506
+
507
+ caption = re.sub(r"\b\s+\:\s+", r": ", caption)
508
+ caption = re.sub(r"(\D[,\./])\b", r"\1 ", caption)
509
+ caption = re.sub(r"\s+", " ", caption)
510
+
511
+ caption.strip()
512
+
513
+ caption = re.sub(r"^[\"\']([\w\W]+)[\"\']$", r"\1", caption)
514
+ caption = re.sub(r"^[\'\_,\-\:;]", r"", caption)
515
+ caption = re.sub(r"[\'\_,\-\:\-\+]$", r"", caption)
516
+ caption = re.sub(r"^\.\S+$", "", caption)
517
+
518
+ return caption.strip()
519
+
520
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
521
+ def prepare_latents(
522
+ self,
523
+ batch_size,
524
+ num_latent_channels,
525
+ num_patches,
526
+ dtype,
527
+ device,
528
+ generator,
529
+ latents=None,
530
+ ):
531
+ shape = (
532
+ batch_size,
533
+ num_patches // math.prod(self.patchifier.patch_size),
534
+ num_latent_channels,
535
+ )
536
+
537
+ if isinstance(generator, list) and len(generator) != batch_size:
538
+ raise ValueError(
539
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
540
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
541
+ )
542
+
543
+ if latents is None:
544
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
545
+ else:
546
+ latents = latents.to(device)
547
+
548
+ # scale the initial noise by the standard deviation required by the scheduler
549
+ latents = latents * self.scheduler.init_noise_sigma
550
+ return latents
551
+
552
+ @staticmethod
553
+ def classify_height_width_bin(height: int, width: int, ratios: dict) -> Tuple[int, int]:
554
+ """Returns binned height and width."""
555
+ ar = float(height / width)
556
+ closest_ratio = min(ratios.keys(), key=lambda ratio: abs(float(ratio) - ar))
557
+ default_hw = ratios[closest_ratio]
558
+ return int(default_hw[0]), int(default_hw[1])
559
+
560
+ @staticmethod
561
+ def resize_and_crop_tensor(samples: torch.Tensor, new_width: int, new_height: int) -> torch.Tensor:
562
+ n_frames, orig_height, orig_width = samples.shape[-3:]
563
+
564
+ # Check if resizing is needed
565
+ if orig_height != new_height or orig_width != new_width:
566
+ ratio = max(new_height / orig_height, new_width / orig_width)
567
+ resized_width = int(orig_width * ratio)
568
+ resized_height = int(orig_height * ratio)
569
+
570
+ # Resize
571
+ samples = rearrange(samples, "b c n h w -> (b n) c h w")
572
+ samples = F.interpolate(samples, size=(resized_height, resized_width), mode="bilinear", align_corners=False)
573
+ samples = rearrange(samples, "(b n) c h w -> b c n h w", n=n_frames)
574
+
575
+ # Center Crop
576
+ start_x = (resized_width - new_width) // 2
577
+ end_x = start_x + new_width
578
+ start_y = (resized_height - new_height) // 2
579
+ end_y = start_y + new_height
580
+ samples = samples[..., start_y:end_y, start_x:end_x]
581
+
582
+ return samples
583
+
584
+ @torch.no_grad()
585
+ def calculate_val_loss(
586
+ self,
587
+ batch: Dict[str, torch.Tensor],
588
+ loss_obj: DiffusionLoss,
589
+ val_loss_config: ValLossConfig,
590
+ vae_per_channel_normalize: bool,
591
+ ) -> torch.Tensor:
592
+ if DataFieldName.VIDEO in batch:
593
+ media_items = batch[DataFieldName.VIDEO]
594
+ else:
595
+ media_items = batch[DataFieldName.IMAGE]
596
+ media_items = media_items.to(dtype=self.vae.dtype)
597
+
598
+ if DataFieldName.VIDEO_AVERAGE_FPS in batch:
599
+ frame_rates = batch[DataFieldName.VIDEO_AVERAGE_FPS]
600
+ else:
601
+ frame_rates = torch.ones(media_items.shape[0], 1, device=media_items.device) * 25.0
602
+ frame_rates = frame_rates / self.video_scale_factor
603
+
604
+ if DataFieldName.T5_EMBEDDING in batch:
605
+ prompt_embeds = batch[DataFieldName.T5_EMBEDDING].to(dtype=self.transformer.dtype)
606
+ prompt_attn_mask = batch[DataFieldName.T5_EMBEDDING_MASK]
607
+
608
+ else:
609
+ text = batch[DataFieldName.CAPTION]
610
+ prompt_embeds, prompt_attn_mask, _, _ = self.encode_prompt(text)
611
+
612
+ latents = vae_encode(media_items, self.vae, vae_per_channel_normalize=vae_per_channel_normalize).float()
613
+ b, _, f, h, w = latents.shape
614
+ if self.patchifier:
615
+ scale_grid = (
616
+ (1 / frame_rates, self.vae_scale_factor, self.vae_scale_factor) if self.transformer.use_rope else None
617
+ )
618
+ indices_grid = self.patchifier.get_grid(
619
+ orig_num_frames=f,
620
+ orig_height=h,
621
+ orig_width=w,
622
+ batch_size=b,
623
+ scale_grid=scale_grid,
624
+ device=self.device,
625
+ )
626
+ latents = self.patchifier.patchify(latents=latents)
627
+
628
+ noise = torch.randn_like(latents)
629
+ noise_cond = torch.linspace(val_loss_config.min_step, val_loss_config.max_step, b, device=latents.device)
630
+
631
+ if isinstance(self.scheduler, TimestepShifter):
632
+ noise_cond = self.scheduler.shift_timesteps(latents, noise_cond)
633
+
634
+ noise_cond = noise_cond[:, None]
635
+ noisy_latents = self.scheduler.add_noise(latents, noise, noise_cond)
636
+
637
+ pred_mean = self.transformer(
638
+ hidden_states=noisy_latents.to(self.transformer.dtype),
639
+ timestep=noise_cond,
640
+ encoder_hidden_states=prompt_embeds,
641
+ encoder_attention_mask=prompt_attn_mask,
642
+ indices_grid=indices_grid,
643
+ ).sample.float()
644
+
645
+ loss = loss_obj(
646
+ pred_mean=pred_mean,
647
+ x_start=latents,
648
+ noise=noise,
649
+ x_t=noisy_latents,
650
+ noise_cond=noise_cond,
651
+ )
652
+
653
+ return loss
654
+
655
+ @torch.no_grad()
656
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
657
+ def __call__(
658
+ self,
659
+ height: int,
660
+ width: int,
661
+ num_frames: int,
662
+ frame_rate: float,
663
+ prompt: Union[str, List[str]] = None,
664
+ negative_prompt: str = "",
665
+ num_inference_steps: int = 20,
666
+ timesteps: List[int] = None,
667
+ guidance_scale: float = 4.5,
668
+ num_images_per_prompt: Optional[int] = 1,
669
+ eta: float = 0.0,
670
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
671
+ latents: Optional[torch.FloatTensor] = None,
672
+ prompt_embeds: Optional[torch.FloatTensor] = None,
673
+ prompt_attention_mask: Optional[torch.FloatTensor] = None,
674
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
675
+ negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
676
+ output_type: Optional[str] = "pil",
677
+ return_dict: bool = True,
678
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
679
+ clean_caption: bool = True,
680
+ **kwargs,
681
+ ) -> Union[ImagePipelineOutput, Tuple]:
682
+ """
683
+ Function invoked when calling the pipeline for generation.
684
+
685
+ Args:
686
+ prompt (`str` or `List[str]`, *optional*):
687
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
688
+ instead.
689
+ negative_prompt (`str` or `List[str]`, *optional*):
690
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
691
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
692
+ less than `1`).
693
+ num_inference_steps (`int`, *optional*, defaults to 100):
694
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
695
+ expense of slower inference.
696
+ timesteps (`List[int]`, *optional*):
697
+ Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
698
+ timesteps are used. Must be in descending order.
699
+ guidance_scale (`float`, *optional*, defaults to 4.5):
700
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
701
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
702
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
703
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
704
+ usually at the expense of lower image quality.
705
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
706
+ The number of images to generate per prompt.
707
+ height (`int`, *optional*, defaults to self.unet.config.sample_size):
708
+ The height in pixels of the generated image.
709
+ width (`int`, *optional*, defaults to self.unet.config.sample_size):
710
+ The width in pixels of the generated image.
711
+ eta (`float`, *optional*, defaults to 0.0):
712
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
713
+ [`schedulers.DDIMScheduler`], will be ignored for others.
714
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
715
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
716
+ to make generation deterministic.
717
+ latents (`torch.FloatTensor`, *optional*):
718
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
719
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
720
+ tensor will ge generated by sampling using the supplied random `generator`.
721
+ prompt_embeds (`torch.FloatTensor`, *optional*):
722
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
723
+ provided, text embeddings will be generated from `prompt` input argument.
724
+ prompt_attention_mask (`torch.FloatTensor`, *optional*): Pre-generated attention mask for text embeddings.
725
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
726
+ Pre-generated negative text embeddings. For PixArt-Alpha this negative prompt should be "". If not
727
+ provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
728
+ negative_prompt_attention_mask (`torch.FloatTensor`, *optional*):
729
+ Pre-generated attention mask for negative text embeddings.
730
+ output_type (`str`, *optional*, defaults to `"pil"`):
731
+ The output format of the generate image. Choose between
732
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
733
+ return_dict (`bool`, *optional*, defaults to `True`):
734
+ Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
735
+ callback_on_step_end (`Callable`, *optional*):
736
+ A function that calls at the end of each denoising steps during the inference. The function is called
737
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
738
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
739
+ `callback_on_step_end_tensor_inputs`.
740
+ clean_caption (`bool`, *optional*, defaults to `True`):
741
+ Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
742
+ be installed. If the dependencies are not installed, the embeddings will be created from the raw
743
+ prompt.
744
+ use_resolution_binning (`bool` defaults to `True`):
745
+ If set to `True`, the requested height and width are first mapped to the closest resolutions using
746
+ `ASPECT_RATIO_1024_BIN`. After the produced latents are decoded into images, they are resized back to
747
+ the requested resolution. Useful for generating non-square images.
748
+
749
+ Examples:
750
+
751
+ Returns:
752
+ [`~pipelines.ImagePipelineOutput`] or `tuple`:
753
+ If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
754
+ returned where the first element is a list with the generated images
755
+ """
756
+ if "mask_feature" in kwargs:
757
+ deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
758
+ deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
759
+
760
+ is_video = kwargs.get("is_video", False)
761
+ self.check_inputs(
762
+ prompt,
763
+ height,
764
+ width,
765
+ negative_prompt,
766
+ prompt_embeds,
767
+ negative_prompt_embeds,
768
+ prompt_attention_mask,
769
+ negative_prompt_attention_mask,
770
+ )
771
+
772
+ # 2. Default height and width to transformer
773
+ if prompt is not None and isinstance(prompt, str):
774
+ batch_size = 1
775
+ elif prompt is not None and isinstance(prompt, list):
776
+ batch_size = len(prompt)
777
+ else:
778
+ batch_size = prompt_embeds.shape[0]
779
+
780
+ device = self._execution_device
781
+
782
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
783
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
784
+ # corresponds to doing no classifier free guidance.
785
+ do_classifier_free_guidance = guidance_scale > 1.0
786
+
787
+ # 3. Encode input prompt
788
+ (
789
+ prompt_embeds,
790
+ prompt_attention_mask,
791
+ negative_prompt_embeds,
792
+ negative_prompt_attention_mask,
793
+ ) = self.encode_prompt(
794
+ prompt,
795
+ do_classifier_free_guidance,
796
+ negative_prompt=negative_prompt,
797
+ num_images_per_prompt=num_images_per_prompt,
798
+ device=device,
799
+ prompt_embeds=prompt_embeds,
800
+ negative_prompt_embeds=negative_prompt_embeds,
801
+ prompt_attention_mask=prompt_attention_mask,
802
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
803
+ clean_caption=clean_caption,
804
+ )
805
+ if do_classifier_free_guidance:
806
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
807
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask], dim=0)
808
+
809
+ # 4. Prepare latents.
810
+ self.video_scale_factor = self.video_scale_factor if is_video else 1
811
+ latent_height = height // self.vae_scale_factor
812
+ latent_width = width // self.vae_scale_factor
813
+ latent_num_frames = num_frames // self.video_scale_factor
814
+ if isinstance(self.vae, CausalVideoAutoencoder) and is_video:
815
+ latent_num_frames += 1
816
+ latent_frame_rate = frame_rate / self.video_scale_factor
817
+ num_latent_patches = latent_height * latent_width * latent_num_frames
818
+ latents = self.prepare_latents(
819
+ batch_size=batch_size * num_images_per_prompt,
820
+ num_latent_channels=self.transformer.config.in_channels,
821
+ num_patches=num_latent_patches,
822
+ dtype=prompt_embeds.dtype,
823
+ device=device,
824
+ generator=generator,
825
+ )
826
+
827
+ # 5. Prepare timesteps
828
+ retrieve_timesteps_kwargs = {}
829
+ if isinstance(self.scheduler, TimestepShifter):
830
+ retrieve_timesteps_kwargs["samples"] = latents
831
+ timesteps, num_inference_steps = retrieve_timesteps(
832
+ self.scheduler, num_inference_steps, device, timesteps, **retrieve_timesteps_kwargs
833
+ )
834
+
835
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
836
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
837
+
838
+ # 7. Denoising loop
839
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
840
+
841
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
842
+ for i, t in enumerate(timesteps):
843
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
844
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
845
+
846
+ latent_frame_rates = (
847
+ torch.ones(latent_model_input.shape[0], 1, device=latent_model_input.device) * latent_frame_rate
848
+ )
849
+
850
+ current_timestep = t
851
+ if not torch.is_tensor(current_timestep):
852
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
853
+ # This would be a good case for the `match` statement (Python 3.10+)
854
+ is_mps = latent_model_input.device.type == "mps"
855
+ if isinstance(current_timestep, float):
856
+ dtype = torch.float32 if is_mps else torch.float64
857
+ else:
858
+ dtype = torch.int32 if is_mps else torch.int64
859
+ current_timestep = torch.tensor([current_timestep], dtype=dtype, device=latent_model_input.device)
860
+ elif len(current_timestep.shape) == 0:
861
+ current_timestep = current_timestep[None].to(latent_model_input.device)
862
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
863
+ current_timestep = current_timestep.expand(latent_model_input.shape[0])
864
+ scale_grid = (
865
+ (1 / latent_frame_rates, self.vae_scale_factor, self.vae_scale_factor)
866
+ if self.transformer.use_rope
867
+ else None
868
+ )
869
+ indices_grid = self.patchifier.get_grid(
870
+ orig_num_frames=latent_num_frames,
871
+ orig_height=latent_height,
872
+ orig_width=latent_width,
873
+ batch_size=latent_model_input.shape[0],
874
+ scale_grid=scale_grid,
875
+ device=latents.device,
876
+ )
877
+
878
+ # predict noise model_output
879
+ noise_pred = self.transformer(
880
+ latent_model_input.to(self.transformer.dtype),
881
+ indices_grid,
882
+ encoder_hidden_states=prompt_embeds.to(self.transformer.dtype),
883
+ encoder_attention_mask=prompt_attention_mask,
884
+ timestep=current_timestep,
885
+ return_dict=False,
886
+ )[0]
887
+
888
+ # perform guidance
889
+ if do_classifier_free_guidance:
890
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
891
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
892
+
893
+ # learned sigma
894
+ if self.transformer.config.out_channels // 2 == self.transformer.config.in_channels:
895
+ noise_pred = noise_pred.chunk(2, dim=1)[0]
896
+
897
+ # compute previous image: x_t -> x_t-1
898
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
899
+
900
+ # call the callback, if provided
901
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
902
+ progress_bar.update()
903
+
904
+ if callback_on_step_end is not None:
905
+ callback_on_step_end(self, i, t, {})
906
+
907
+ latents = self.patchifier.unpatchify(
908
+ latents=latents,
909
+ output_height=latent_height,
910
+ output_width=latent_width,
911
+ output_num_frames=latent_num_frames,
912
+ out_channels=self.transformer.in_channels // math.prod(self.patchifier.patch_size),
913
+ )
914
+ if output_type != "latent":
915
+ image = vae_decode(
916
+ latents, self.vae, is_video, vae_per_channel_normalize=kwargs["vae_per_channel_normalize"]
917
+ )
918
+ image = self.image_processor.postprocess(image, output_type=output_type)
919
+
920
+ else:
921
+ image = latents
922
+
923
+ # Offload all models
924
+ self.maybe_free_model_hooks()
925
+
926
+ if not return_dict:
927
+ return (image,)
928
+
929
+ return ImagePipelineOutput(images=image)
scheduler/rf.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from abc import ABC, abstractmethod
3
+ from dataclasses import dataclass
4
+ from typing import Callable, Optional, Tuple, Union
5
+
6
+ import torch
7
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
8
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
9
+ from diffusers.utils import BaseOutput
10
+ from torch import Tensor
11
+
12
+ from txt2img.common.torch_utils import append_dims
13
+
14
+
15
+ def simple_diffusion_resolution_dependent_timestep_shift(
16
+ samples: Tensor,
17
+ timesteps: Tensor,
18
+ n: int = 32 * 32,
19
+ ) -> Tensor:
20
+ if len(samples.shape) == 3:
21
+ _, m, _ = samples.shape
22
+ elif len(samples.shape) in [4, 5]:
23
+ m = math.prod(samples.shape[2:])
24
+ else:
25
+ raise ValueError("Samples must have shape (b, t, c), (b, c, h, w) or (b, c, f, h, w)")
26
+ snr = (timesteps / (1 - timesteps)) ** 2
27
+ shift_snr = torch.log(snr) + 2 * math.log(m / n)
28
+ shifted_timesteps = torch.sigmoid(0.5 * shift_snr)
29
+
30
+ return shifted_timesteps
31
+
32
+
33
+ def time_shift(mu: float, sigma: float, t: Tensor):
34
+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
35
+
36
+
37
+ def get_normal_shift(
38
+ n_tokens: int,
39
+ min_tokens: int = 1024,
40
+ max_tokens: int = 4096,
41
+ min_shift: float = 0.95,
42
+ max_shift: float = 2.05,
43
+ ) -> Callable[[float], float]:
44
+ m = (max_shift - min_shift) / (max_tokens - min_tokens)
45
+ b = min_shift - m * min_tokens
46
+ return m * n_tokens + b
47
+
48
+
49
+ def sd3_resolution_dependent_timestep_shift(samples: Tensor, timesteps: Tensor) -> Tensor:
50
+ """
51
+ Shifts the timestep schedule as a function of the generated resolution.
52
+
53
+ In the SD3 paper, the authors empirically how to shift the timesteps based on the resolution of the target images.
54
+ For more details: https://arxiv.org/pdf/2403.03206
55
+
56
+ In Flux they later propose a more dynamic resolution dependent timestep shift, see:
57
+ https://github.com/black-forest-labs/flux/blob/87f6fff727a377ea1c378af692afb41ae84cbe04/src/flux/sampling.py#L66
58
+
59
+
60
+ Args:
61
+ samples (Tensor): A batch of samples with shape (batch_size, channels, height, width) or
62
+ (batch_size, channels, frame, height, width).
63
+ timesteps (Tensor): A batch of timesteps with shape (batch_size,).
64
+
65
+ Returns:
66
+ Tensor: The shifted timesteps.
67
+ """
68
+ if len(samples.shape) == 3:
69
+ _, m, _ = samples.shape
70
+ elif len(samples.shape) in [4, 5]:
71
+ m = math.prod(samples.shape[2:])
72
+ else:
73
+ raise ValueError("Samples must have shape (b, t, c), (b, c, h, w) or (b, c, f, h, w)")
74
+
75
+ shift = get_normal_shift(m)
76
+ return time_shift(shift, 1, timesteps)
77
+
78
+
79
+ class TimestepShifter(ABC):
80
+ @abstractmethod
81
+ def shift_timesteps(self, samples: Tensor, timesteps: Tensor) -> Tensor:
82
+ pass
83
+
84
+
85
+ @dataclass
86
+ class RectifiedFlowSchedulerOutput(BaseOutput):
87
+ """
88
+ Output class for the scheduler's step function output.
89
+
90
+ Args:
91
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
92
+ Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the
93
+ denoising loop.
94
+ pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
95
+ The predicted denoised sample (x_{0}) based on the model output from the current timestep.
96
+ `pred_original_sample` can be used to preview progress or for guidance.
97
+ """
98
+
99
+ prev_sample: torch.FloatTensor
100
+ pred_original_sample: Optional[torch.FloatTensor] = None
101
+
102
+
103
+ class RectifiedFlowScheduler(SchedulerMixin, ConfigMixin, TimestepShifter):
104
+ order = 1
105
+
106
+ @register_to_config
107
+ def __init__(self, num_train_timesteps=1000, shifting: Optional[str] = None, base_resolution: int = 32**2):
108
+ super().__init__()
109
+ self.init_noise_sigma = 1.0
110
+ self.num_inference_steps = None
111
+ self.timesteps = self.sigmas = torch.linspace(1, 1 / num_train_timesteps, num_train_timesteps)
112
+ self.delta_timesteps = self.timesteps - torch.cat([self.timesteps[1:], torch.zeros_like(self.timesteps[-1:])])
113
+ self.shifting = shifting
114
+ self.base_resolution = base_resolution
115
+
116
+ def shift_timesteps(self, samples: Tensor, timesteps: Tensor) -> Tensor:
117
+ if self.shifting == "SD3":
118
+ return sd3_resolution_dependent_timestep_shift(samples, timesteps)
119
+ elif self.shifting == "SimpleDiffusion":
120
+ return simple_diffusion_resolution_dependent_timestep_shift(samples, timesteps, self.base_resolution)
121
+ return timesteps
122
+
123
+ def set_timesteps(self, num_inference_steps: int, samples: Tensor, device: Union[str, torch.device] = None):
124
+ """
125
+ Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.
126
+
127
+ Args:
128
+ num_inference_steps (`int`): The number of diffusion steps used when generating samples.
129
+ samples (`Tensor`): A batch of samples with shape.
130
+ device (`Union[str, torch.device]`, *optional*): The device to which the timesteps tensor will be moved.
131
+ """
132
+ num_inference_steps = min(self.config.num_train_timesteps, num_inference_steps)
133
+ timesteps = torch.linspace(1, 1 / num_inference_steps, num_inference_steps).to(device)
134
+ self.timesteps = self.shift_timesteps(samples, timesteps)
135
+ self.delta_timesteps = self.timesteps - torch.cat([self.timesteps[1:], torch.zeros_like(self.timesteps[-1:])])
136
+ self.num_inference_steps = num_inference_steps
137
+ self.sigmas = self.timesteps
138
+
139
+ def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:
140
+ # pylint: disable=unused-argument
141
+ """
142
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
143
+ current timestep.
144
+
145
+ Args:
146
+ sample (`torch.FloatTensor`): input sample
147
+ timestep (`int`, optional): current timestep
148
+
149
+ Returns:
150
+ `torch.FloatTensor`: scaled input sample
151
+ """
152
+ return sample
153
+
154
+ def step(
155
+ self,
156
+ model_output: torch.FloatTensor,
157
+ timestep: torch.FloatTensor,
158
+ sample: torch.FloatTensor,
159
+ eta: float = 0.0,
160
+ use_clipped_model_output: bool = False,
161
+ generator=None,
162
+ variance_noise: Optional[torch.FloatTensor] = None,
163
+ return_dict: bool = True,
164
+ ) -> Union[RectifiedFlowSchedulerOutput, Tuple]:
165
+ # pylint: disable=unused-argument
166
+ """
167
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
168
+ process from the learned model outputs (most often the predicted noise).
169
+
170
+ Args:
171
+ model_output (`torch.FloatTensor`):
172
+ The direct output from learned diffusion model.
173
+ timestep (`float`):
174
+ The current discrete timestep in the diffusion chain.
175
+ sample (`torch.FloatTensor`):
176
+ A current instance of a sample created by the diffusion process.
177
+ eta (`float`):
178
+ The weight of noise for added noise in diffusion step.
179
+ use_clipped_model_output (`bool`, defaults to `False`):
180
+ If `True`, computes "corrected" `model_output` from the clipped predicted original sample. Necessary
181
+ because predicted original sample is clipped to [-1, 1] when `self.config.clip_sample` is `True`. If no
182
+ clipping has happened, "corrected" `model_output` would coincide with the one provided as input and
183
+ `use_clipped_model_output` has no effect.
184
+ generator (`torch.Generator`, *optional*):
185
+ A random number generator.
186
+ variance_noise (`torch.FloatTensor`):
187
+ Alternative to generating noise with `generator` by directly providing the noise for the variance
188
+ itself. Useful for methods such as [`CycleDiffusion`].
189
+ return_dict (`bool`, *optional*, defaults to `True`):
190
+ Whether or not to return a [`~schedulers.scheduling_ddim.DDIMSchedulerOutput`] or `tuple`.
191
+
192
+ Returns:
193
+ [`~schedulers.scheduling_utils.RectifiedFlowSchedulerOutput`] or `tuple`:
194
+ If return_dict is `True`, [`~schedulers.rf_scheduler.RectifiedFlowSchedulerOutput`] is returned,
195
+ otherwise a tuple is returned where the first element is the sample tensor.
196
+ """
197
+ if self.num_inference_steps is None:
198
+ raise ValueError(
199
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
200
+ )
201
+
202
+ current_index = (self.timesteps - timestep).abs().argmin()
203
+ dt = self.delta_timesteps.gather(0, current_index.unsqueeze(0))
204
+
205
+ prev_sample = sample - dt * model_output
206
+
207
+ if not return_dict:
208
+ return (prev_sample,)
209
+
210
+ return RectifiedFlowSchedulerOutput(prev_sample=prev_sample)
211
+
212
+ def add_noise(
213
+ self,
214
+ original_samples: torch.FloatTensor,
215
+ noise: torch.FloatTensor,
216
+ timesteps: torch.FloatTensor,
217
+ ) -> torch.FloatTensor:
218
+ sigmas = timesteps
219
+ sigmas = append_dims(sigmas, original_samples.ndim)
220
+ alphas = 1 - sigmas
221
+ noisy_samples = alphas * original_samples + sigmas * noise
222
+ return noisy_samples
transformer/transformer3d.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from: https://github.com/huggingface/diffusers/blob/v0.26.3/src/diffusers/models/transformers/transformer_2d.py
2
+ import math
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ import torch
7
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
8
+ from diffusers.models.embeddings import PixArtAlphaTextProjection
9
+ from diffusers.models.modeling_utils import ModelMixin
10
+ from diffusers.models.normalization import AdaLayerNormSingle
11
+ from diffusers.utils import BaseOutput, is_torch_version
12
+ from torch import nn
13
+
14
+ from txt2img.common import dist_util, logger
15
+ from txt2img.config.weights_init_config import WeightsInitConfig, WeightsInitModeName
16
+ from txt2img.diffusion.models.pixart.attention import BasicTransformerBlock
17
+ from txt2img.diffusion.models.pixart.embeddings import get_3d_sincos_pos_embed
18
+
19
+
20
+ @dataclass
21
+ class Transformer3DModelOutput(BaseOutput):
22
+ """
23
+ The output of [`Transformer2DModel`].
24
+
25
+ Args:
26
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
27
+ The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability
28
+ distributions for the unnoised latent pixels.
29
+ """
30
+
31
+ sample: torch.FloatTensor
32
+
33
+
34
+ class Transformer3DModel(ModelMixin, ConfigMixin):
35
+ _supports_gradient_checkpointing = True
36
+
37
+ @register_to_config
38
+ def __init__(
39
+ self,
40
+ num_attention_heads: int = 16,
41
+ attention_head_dim: int = 88,
42
+ in_channels: Optional[int] = None,
43
+ out_channels: Optional[int] = None,
44
+ num_layers: int = 1,
45
+ dropout: float = 0.0,
46
+ norm_num_groups: int = 32,
47
+ cross_attention_dim: Optional[int] = None,
48
+ attention_bias: bool = False,
49
+ num_vector_embeds: Optional[int] = None,
50
+ activation_fn: str = "geglu",
51
+ num_embeds_ada_norm: Optional[int] = None,
52
+ use_linear_projection: bool = False,
53
+ only_cross_attention: bool = False,
54
+ double_self_attention: bool = False,
55
+ upcast_attention: bool = False,
56
+ adaptive_norm: str = "single_scale_shift", # 'single_scale_shift' or 'single_scale'
57
+ standardization_norm: str = "layer_norm", # 'layer_norm' or 'rms_norm'
58
+ norm_elementwise_affine: bool = True,
59
+ norm_eps: float = 1e-5,
60
+ attention_type: str = "default",
61
+ caption_channels: int = None,
62
+ project_to_2d_pos: bool = False,
63
+ use_tpu_flash_attention: bool = False, # if True uses the TPU attention offload ('flash attention')
64
+ qk_norm: Optional[str] = None,
65
+ positional_embedding_type: str = "absolute",
66
+ positional_embedding_theta: Optional[float] = None,
67
+ positional_embedding_max_pos: Optional[List[int]] = None,
68
+ timestep_scale_multiplier: Optional[float] = None,
69
+ ):
70
+ super().__init__()
71
+ self.use_tpu_flash_attention = use_tpu_flash_attention # FIXME: push config down to the attention modules
72
+ self.use_linear_projection = use_linear_projection
73
+ self.num_attention_heads = num_attention_heads
74
+ self.attention_head_dim = attention_head_dim
75
+ inner_dim = num_attention_heads * attention_head_dim
76
+ self.inner_dim = inner_dim
77
+
78
+ self.project_to_2d_pos = project_to_2d_pos
79
+
80
+ self.patchify_proj = nn.Linear(in_channels, inner_dim, bias=True)
81
+
82
+ self.positional_embedding_type = positional_embedding_type
83
+ self.positional_embedding_theta = positional_embedding_theta
84
+ self.positional_embedding_max_pos = positional_embedding_max_pos
85
+ self.use_rope = self.positional_embedding_type == "rope"
86
+ self.timestep_scale_multiplier = timestep_scale_multiplier
87
+
88
+ if self.positional_embedding_type == "absolute":
89
+ embed_dim_3d = math.ceil((inner_dim / 2) * 3) if project_to_2d_pos else inner_dim
90
+ if self.project_to_2d_pos:
91
+ self.to_2d_proj = torch.nn.Linear(embed_dim_3d, inner_dim, bias=False)
92
+ self._init_to_2d_proj_weights(self.to_2d_proj)
93
+ elif self.positional_embedding_type == "rope":
94
+ if positional_embedding_theta is None:
95
+ raise ValueError(
96
+ "If `positional_embedding_type` type is rope, `positional_embedding_theta` must also be defined"
97
+ )
98
+ if positional_embedding_max_pos is None:
99
+ raise ValueError(
100
+ "If `positional_embedding_type` type is rope, `positional_embedding_max_pos` must also be defined"
101
+ )
102
+
103
+ # 3. Define transformers blocks
104
+ self.transformer_blocks = nn.ModuleList(
105
+ [
106
+ BasicTransformerBlock(
107
+ inner_dim,
108
+ num_attention_heads,
109
+ attention_head_dim,
110
+ dropout=dropout,
111
+ cross_attention_dim=cross_attention_dim,
112
+ activation_fn=activation_fn,
113
+ num_embeds_ada_norm=num_embeds_ada_norm,
114
+ attention_bias=attention_bias,
115
+ only_cross_attention=only_cross_attention,
116
+ double_self_attention=double_self_attention,
117
+ upcast_attention=upcast_attention,
118
+ adaptive_norm=adaptive_norm,
119
+ standardization_norm=standardization_norm,
120
+ norm_elementwise_affine=norm_elementwise_affine,
121
+ norm_eps=norm_eps,
122
+ attention_type=attention_type,
123
+ use_tpu_flash_attention=use_tpu_flash_attention,
124
+ qk_norm=qk_norm,
125
+ use_rope=self.use_rope,
126
+ )
127
+ for d in range(num_layers)
128
+ ]
129
+ )
130
+
131
+ # 4. Define output layers
132
+ self.out_channels = in_channels if out_channels is None else out_channels
133
+ self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
134
+ self.scale_shift_table = nn.Parameter(torch.randn(2, inner_dim) / inner_dim**0.5)
135
+ self.proj_out = nn.Linear(inner_dim, self.out_channels)
136
+
137
+ # 5. PixArt-Alpha blocks.
138
+ self.adaln_single = AdaLayerNormSingle(inner_dim, use_additional_conditions=False)
139
+ if adaptive_norm == "single_scale":
140
+ # Use 4 channels instead of the 6 for the PixArt-Alpha scale + shift ada norm.
141
+ self.adaln_single.linear = nn.Linear(inner_dim, 4 * inner_dim, bias=True)
142
+
143
+ self.caption_projection = None
144
+ if caption_channels is not None:
145
+ self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim)
146
+
147
+ self.gradient_checkpointing = False
148
+
149
+ def set_use_tpu_flash_attention(self):
150
+ r"""
151
+ Function sets the flag in this object and propagates down the children. The flag will enforce the usage of TPU
152
+ attention kernel.
153
+ """
154
+ logger.info(" ENABLE TPU FLASH ATTENTION -> TRUE")
155
+ # if using TPU -> configure components to use TPU flash attention
156
+ if dist_util.acceleration_type() == dist_util.AccelerationType.TPU:
157
+ self.use_tpu_flash_attention = True
158
+ # push config down to the attention modules
159
+ for block in self.transformer_blocks:
160
+ block.set_use_tpu_flash_attention()
161
+
162
+ def initialize(self, weights_init: WeightsInitConfig):
163
+ if weights_init.mode != WeightsInitModeName.PixArt and weights_init.mode != WeightsInitModeName.Xora:
164
+ return
165
+
166
+ def _basic_init(module):
167
+ if isinstance(module, nn.Linear):
168
+ torch.nn.init.xavier_uniform_(module.weight)
169
+ if module.bias is not None:
170
+ nn.init.constant_(module.bias, 0)
171
+
172
+ self.apply(_basic_init)
173
+
174
+ # Initialize timestep embedding MLP:
175
+ nn.init.normal_(self.adaln_single.emb.timestep_embedder.linear_1.weight, std=weights_init.embedding_std)
176
+ nn.init.normal_(self.adaln_single.emb.timestep_embedder.linear_2.weight, std=weights_init.embedding_std)
177
+ nn.init.normal_(self.adaln_single.linear.weight, std=weights_init.embedding_std)
178
+
179
+ if hasattr(self.adaln_single.emb, "resolution_embedder"):
180
+ nn.init.normal_(self.adaln_single.emb.resolution_embedder.linear_1.weight, std=weights_init.embedding_std)
181
+ nn.init.normal_(self.adaln_single.emb.resolution_embedder.linear_2.weight, std=weights_init.embedding_std)
182
+ if hasattr(self.adaln_single.emb, "aspect_ratio_embedder"):
183
+ nn.init.normal_(self.adaln_single.emb.aspect_ratio_embedder.linear_1.weight, std=weights_init.embedding_std)
184
+ nn.init.normal_(self.adaln_single.emb.aspect_ratio_embedder.linear_2.weight, std=weights_init.embedding_std)
185
+
186
+ # Initialize caption embedding MLP:
187
+ nn.init.normal_(self.caption_projection.linear_1.weight, std=weights_init.embedding_std)
188
+ nn.init.normal_(self.caption_projection.linear_1.weight, std=weights_init.embedding_std)
189
+
190
+ # Zero-out adaLN modulation layers in PixArt blocks:
191
+ for block in self.transformer_blocks:
192
+ if weights_init.mode == WeightsInitModeName.Xora:
193
+ nn.init.constant_(block.attn1.to_out[0].weight, 0)
194
+ nn.init.constant_(block.attn1.to_out[0].bias, 0)
195
+
196
+ nn.init.constant_(block.attn2.to_out[0].weight, 0)
197
+ nn.init.constant_(block.attn2.to_out[0].bias, 0)
198
+
199
+ if weights_init.mode == WeightsInitModeName.Xora:
200
+ nn.init.constant_(block.ff.net[2].weight, 0)
201
+ nn.init.constant_(block.ff.net[2].bias, 0)
202
+
203
+ # Zero-out output layers:
204
+ nn.init.constant_(self.proj_out.weight, 0)
205
+ nn.init.constant_(self.proj_out.bias, 0)
206
+
207
+ def _set_gradient_checkpointing(self, module, value=False):
208
+ if hasattr(module, "gradient_checkpointing"):
209
+ module.gradient_checkpointing = value
210
+
211
+ @staticmethod
212
+ def _init_to_2d_proj_weights(linear_layer):
213
+ input_features = linear_layer.weight.data.size(1)
214
+ output_features = linear_layer.weight.data.size(0)
215
+
216
+ # Start with a zero matrix
217
+ identity_like = torch.zeros((output_features, input_features))
218
+
219
+ # Fill the diagonal with 1's as much as possible
220
+ min_features = min(output_features, input_features)
221
+ identity_like[:min_features, :min_features] = torch.eye(min_features)
222
+ linear_layer.weight.data = identity_like.to(linear_layer.weight.data.device)
223
+
224
+ def get_fractional_positions(self, indices_grid):
225
+ fractional_positions = torch.stack(
226
+ [indices_grid[:, i] / self.positional_embedding_max_pos[i] for i in range(3)], dim=-1
227
+ )
228
+ return fractional_positions
229
+
230
+ def precompute_freqs_cis(self, indices_grid, spacing="exp"):
231
+ dtype = self.dtype
232
+ dim = self.inner_dim
233
+ theta = self.positional_embedding_theta
234
+
235
+ fractional_positions = self.get_fractional_positions(indices_grid)
236
+
237
+ start = 1
238
+ end = theta
239
+ device = fractional_positions.device
240
+ if spacing == "exp":
241
+ indices = theta ** (
242
+ torch.linspace(math.log(start, theta), math.log(end, theta), dim // 6, device=device, dtype=dtype)
243
+ )
244
+ indices = indices.to(dtype=dtype)
245
+ elif spacing == "exp_2":
246
+ indices = 1.0 / theta ** (torch.arange(0, dim, 6, device=device) / dim)
247
+ indices = indices.to(dtype=dtype)
248
+ elif spacing == "linear":
249
+ indices = torch.linspace(start, end, dim // 6, device=device, dtype=dtype)
250
+ elif spacing == "sqrt":
251
+ indices = torch.linspace(start**2, end**2, dim // 6, device=device, dtype=dtype).sqrt()
252
+
253
+ indices = indices * math.pi / 2
254
+
255
+ if spacing == "exp_2":
256
+ freqs = (indices * fractional_positions.unsqueeze(-1)).transpose(-1, -2).flatten(2)
257
+ else:
258
+ freqs = (indices * (fractional_positions.unsqueeze(-1) * 2 - 1)).transpose(-1, -2).flatten(2)
259
+
260
+ cos_freq = freqs.cos().repeat_interleave(2, dim=-1)
261
+ sin_freq = freqs.sin().repeat_interleave(2, dim=-1)
262
+ if dim % 6 != 0:
263
+ cos_padding = torch.ones_like(cos_freq[:, :, : dim % 6])
264
+ sin_padding = torch.zeros_like(cos_freq[:, :, : dim % 6])
265
+ cos_freq = torch.cat([cos_padding, cos_freq], dim=-1)
266
+ sin_freq = torch.cat([sin_padding, sin_freq], dim=-1)
267
+ return cos_freq, sin_freq
268
+
269
+ def forward(
270
+ self,
271
+ hidden_states: torch.Tensor,
272
+ indices_grid: torch.Tensor,
273
+ encoder_hidden_states: Optional[torch.Tensor] = None,
274
+ timestep: Optional[torch.LongTensor] = None,
275
+ class_labels: Optional[torch.LongTensor] = None,
276
+ cross_attention_kwargs: Dict[str, Any] = None,
277
+ attention_mask: Optional[torch.Tensor] = None,
278
+ encoder_attention_mask: Optional[torch.Tensor] = None,
279
+ return_dict: bool = True,
280
+ ):
281
+ """
282
+ The [`Transformer2DModel`] forward method.
283
+
284
+ Args:
285
+ hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
286
+ Input `hidden_states`.
287
+ indices_grid (`torch.LongTensor` of shape `(batch size, 3, num latent pixels)`):
288
+ encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
289
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
290
+ self-attention.
291
+ timestep ( `torch.LongTensor`, *optional*):
292
+ Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
293
+ class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
294
+ Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
295
+ `AdaLayerZeroNorm`.
296
+ cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
297
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
298
+ `self.processor` in
299
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
300
+ attention_mask ( `torch.Tensor`, *optional*):
301
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
302
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
303
+ negative values to the attention scores corresponding to "discard" tokens.
304
+ encoder_attention_mask ( `torch.Tensor`, *optional*):
305
+ Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
306
+
307
+ * Mask `(batch, sequence_length)` True = keep, False = discard.
308
+ * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
309
+
310
+ If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
311
+ above. This bias will be added to the cross-attention scores.
312
+ return_dict (`bool`, *optional*, defaults to `True`):
313
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
314
+ tuple.
315
+
316
+ Returns:
317
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
318
+ `tuple` where the first element is the sample tensor.
319
+ """
320
+ # for tpu attention offload 2d token masks are used. No need to transform.
321
+ if not self.use_tpu_flash_attention:
322
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
323
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
324
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
325
+ # expects mask of shape:
326
+ # [batch, key_tokens]
327
+ # adds singleton query_tokens dimension:
328
+ # [batch, 1, key_tokens]
329
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
330
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
331
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
332
+ if attention_mask is not None and attention_mask.ndim == 2:
333
+ # assume that mask is expressed as:
334
+ # (1 = keep, 0 = discard)
335
+ # convert mask into a bias that can be added to attention scores:
336
+ # (keep = +0, discard = -10000.0)
337
+ attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
338
+ attention_mask = attention_mask.unsqueeze(1)
339
+
340
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
341
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
342
+ encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
343
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
344
+
345
+ # 1. Input
346
+ hidden_states = self.patchify_proj(hidden_states)
347
+
348
+ if self.timestep_scale_multiplier:
349
+ timestep = self.timestep_scale_multiplier * timestep
350
+
351
+ if self.positional_embedding_type == "absolute":
352
+ pos_embed_3d = self.get_absolute_pos_embed(indices_grid).to(hidden_states.device)
353
+ if self.project_to_2d_pos:
354
+ pos_embed = self.to_2d_proj(pos_embed_3d)
355
+ hidden_states = (hidden_states + pos_embed).to(hidden_states.dtype)
356
+ freqs_cis = None
357
+ elif self.positional_embedding_type == "rope":
358
+ freqs_cis = self.precompute_freqs_cis(indices_grid)
359
+
360
+ batch_size = hidden_states.shape[0]
361
+ timestep, embedded_timestep = self.adaln_single(
362
+ timestep.flatten(),
363
+ {"resolution": None, "aspect_ratio": None},
364
+ batch_size=batch_size,
365
+ hidden_dtype=hidden_states.dtype,
366
+ )
367
+ # Second dimension is 1 or number of tokens (if timestep_per_token)
368
+ timestep = timestep.view(batch_size, -1, timestep.shape[-1])
369
+ embedded_timestep = embedded_timestep.view(batch_size, -1, embedded_timestep.shape[-1])
370
+
371
+ # 2. Blocks
372
+ if self.caption_projection is not None:
373
+ batch_size = hidden_states.shape[0]
374
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states)
375
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
376
+
377
+ for block in self.transformer_blocks:
378
+ if self.training and self.gradient_checkpointing:
379
+
380
+ def create_custom_forward(module, return_dict=None):
381
+ def custom_forward(*inputs):
382
+ if return_dict is not None:
383
+ return module(*inputs, return_dict=return_dict)
384
+ else:
385
+ return module(*inputs)
386
+
387
+ return custom_forward
388
+
389
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
390
+ hidden_states = torch.utils.checkpoint.checkpoint(
391
+ create_custom_forward(block),
392
+ hidden_states,
393
+ freqs_cis,
394
+ attention_mask,
395
+ encoder_hidden_states,
396
+ encoder_attention_mask,
397
+ timestep,
398
+ cross_attention_kwargs,
399
+ class_labels,
400
+ **ckpt_kwargs,
401
+ )
402
+ else:
403
+ hidden_states = block(
404
+ hidden_states,
405
+ freqs_cis=freqs_cis,
406
+ attention_mask=attention_mask,
407
+ encoder_hidden_states=encoder_hidden_states,
408
+ encoder_attention_mask=encoder_attention_mask,
409
+ timestep=timestep,
410
+ cross_attention_kwargs=cross_attention_kwargs,
411
+ class_labels=class_labels,
412
+ )
413
+
414
+ # 3. Output
415
+ scale_shift_values = self.scale_shift_table[None, None] + embedded_timestep[:, :, None]
416
+ shift, scale = scale_shift_values[:, :, 0], scale_shift_values[:, :, 1]
417
+ hidden_states = self.norm_out(hidden_states)
418
+ # Modulation
419
+ hidden_states = hidden_states * (1 + scale) + shift
420
+ hidden_states = self.proj_out(hidden_states)
421
+ if not return_dict:
422
+ return (hidden_states,)
423
+
424
+ return Transformer3DModelOutput(sample=hidden_states)
425
+
426
+ def get_absolute_pos_embed(self, grid):
427
+ grid_np = grid[0].cpu().numpy()
428
+ embed_dim_3d = math.ceil((self.inner_dim / 2) * 3) if self.project_to_2d_pos else self.inner_dim
429
+ pos_embed = get_3d_sincos_pos_embed( # (f h w)
430
+ embed_dim_3d,
431
+ grid_np,
432
+ h=int(max(grid_np[1]) + 1),
433
+ w=int(max(grid_np[2]) + 1),
434
+ f=int(max(grid_np[0] + 1)),
435
+ )
436
+ return torch.from_numpy(pos_embed).float().unsqueeze(0)
vae/causal_video_encoder.py ADDED
@@ -0,0 +1,764 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from functools import partial
4
+ from types import SimpleNamespace
5
+ from typing import Any, Mapping, Optional, Tuple, Union, List
6
+
7
+ import torch
8
+ import numpy as np
9
+ from einops import rearrange
10
+ from torch import nn
11
+
12
+ from txt2img.common import logger
13
+ from txt2img.vae.layers.conv_nd_factory import make_conv_nd, make_linear_nd
14
+ from txt2img.vae.layers.pixel_norm import PixelNorm
15
+ from txt2img.vae.vae import AutoencoderKLWrapper
16
+
17
+
18
+ class CausalVideoAutoencoder(AutoencoderKLWrapper):
19
+ @classmethod
20
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *args, **kwargs):
21
+ config_local_path = pretrained_model_name_or_path / "config.json"
22
+ config = cls.load_config(config_local_path, **kwargs)
23
+ video_vae = cls.from_config(config)
24
+ video_vae.to(kwargs["torch_dtype"])
25
+
26
+ model_local_path = pretrained_model_name_or_path / "autoencoder.pth"
27
+ ckpt_state_dict = torch.load(model_local_path, map_location=torch.device("cpu"))
28
+ video_vae.load_state_dict(ckpt_state_dict)
29
+
30
+ statistics_local_path = pretrained_model_name_or_path / "per_channel_statistics.json"
31
+ if statistics_local_path.exists():
32
+ with open(statistics_local_path, "r") as file:
33
+ data = json.load(file)
34
+ transposed_data = list(zip(*data["data"]))
35
+ data_dict = {col: torch.tensor(vals) for col, vals in zip(data["columns"], transposed_data)}
36
+ video_vae.register_buffer("std_of_means", data_dict["std-of-means"])
37
+ video_vae.register_buffer(
38
+ "mean_of_means", data_dict.get("mean-of-means", torch.zeros_like(data_dict["std-of-means"]))
39
+ )
40
+
41
+ return video_vae
42
+
43
+ @staticmethod
44
+ def from_config(config):
45
+ assert config["_class_name"] == "CausalVideoAutoencoder", "config must have _class_name=CausalVideoAutoencoder"
46
+ if isinstance(config["dims"], list):
47
+ config["dims"] = tuple(config["dims"])
48
+
49
+ assert config["dims"] in [2, 3, (2, 1)], "dims must be 2, 3 or (2, 1)"
50
+
51
+ double_z = config.get("double_z", True)
52
+ latent_log_var = config.get("latent_log_var", "per_channel" if double_z else "none")
53
+ use_quant_conv = config.get("use_quant_conv", True)
54
+
55
+ if use_quant_conv and latent_log_var == "uniform":
56
+ raise ValueError("uniform latent_log_var requires use_quant_conv=False")
57
+
58
+ encoder = Encoder(
59
+ dims=config["dims"],
60
+ in_channels=config.get("in_channels", 3),
61
+ out_channels=config["latent_channels"],
62
+ blocks=config["blocks"],
63
+ patch_size=config.get("patch_size", 1),
64
+ latent_log_var=latent_log_var,
65
+ norm_layer=config.get("norm_layer", "group_norm"),
66
+ )
67
+
68
+ decoder = Decoder(
69
+ dims=config["dims"],
70
+ in_channels=config["latent_channels"],
71
+ out_channels=config.get("out_channels", 3),
72
+ blocks=config["blocks"],
73
+ patch_size=config.get("patch_size", 1),
74
+ norm_layer=config.get("norm_layer", "group_norm"),
75
+ causal=config.get("causal_decoder", False),
76
+ )
77
+
78
+ dims = config["dims"]
79
+ return CausalVideoAutoencoder(
80
+ encoder=encoder,
81
+ decoder=decoder,
82
+ latent_channels=config["latent_channels"],
83
+ dims=dims,
84
+ use_quant_conv=use_quant_conv,
85
+ )
86
+
87
+ @property
88
+ def config(self):
89
+ return SimpleNamespace(
90
+ _class_name="CausalVideoAutoencoder",
91
+ dims=self.dims,
92
+ in_channels=self.encoder.conv_in.in_channels // self.encoder.patch_size**2,
93
+ out_channels=self.decoder.conv_out.out_channels // self.decoder.patch_size**2,
94
+ latent_channels=self.decoder.conv_in.in_channels,
95
+ blocks=self.encoder.blocks_desc,
96
+ scaling_factor=1.0,
97
+ norm_layer=self.encoder.norm_layer,
98
+ patch_size=self.encoder.patch_size,
99
+ latent_log_var=self.encoder.latent_log_var,
100
+ use_quant_conv=self.use_quant_conv,
101
+ causal_decoder=self.decoder.causal,
102
+ )
103
+
104
+ @property
105
+ def is_video_supported(self):
106
+ """
107
+ Check if the model supports video inputs of shape (B, C, F, H, W). Otherwise, the model only supports 2D images.
108
+ """
109
+ return self.dims != 2
110
+
111
+ @property
112
+ def spatial_downscale_factor(self):
113
+ return (
114
+ 2 ** len([block for block in self.encoder.blocks_desc if block[0] in ["compress_space", "compress_all"]])
115
+ * self.encoder.patch_size
116
+ )
117
+
118
+ @property
119
+ def temporal_downscale_factor(self):
120
+ return 2 ** len([block for block in self.encoder.blocks_desc if block[0] in ["compress_time", "compress_all"]])
121
+
122
+ def to_json_string(self) -> str:
123
+ import json
124
+
125
+ return json.dumps(self.config.__dict__)
126
+
127
+ def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True):
128
+ model_keys = set(name for name, _ in self.named_parameters())
129
+
130
+ key_mapping = {
131
+ ".resnets.": ".res_blocks.",
132
+ "downsamplers.0": "downsample",
133
+ "upsamplers.0": "upsample",
134
+ }
135
+
136
+ converted_state_dict = {}
137
+ for key, value in state_dict.items():
138
+ for k, v in key_mapping.items():
139
+ key = key.replace(k, v)
140
+
141
+ if "norm" in key and key not in model_keys:
142
+ logger.info(f"Removing key {key} from state_dict as it is not present in the model")
143
+ continue
144
+
145
+ converted_state_dict[key] = value
146
+
147
+ super().load_state_dict(converted_state_dict, strict=strict)
148
+
149
+ def last_layer(self):
150
+ if hasattr(self.decoder, "conv_out"):
151
+ if isinstance(self.decoder.conv_out, nn.Sequential):
152
+ last_layer = self.decoder.conv_out[-1]
153
+ else:
154
+ last_layer = self.decoder.conv_out
155
+ else:
156
+ last_layer = self.decoder.layers[-1]
157
+ return last_layer
158
+
159
+
160
+ class Encoder(nn.Module):
161
+ r"""
162
+ The `Encoder` layer of a variational autoencoder that encodes its input into a latent representation.
163
+
164
+ Args:
165
+ dims (`int` or `Tuple[int, int]`, *optional*, defaults to 3):
166
+ The number of dimensions to use in convolutions.
167
+ in_channels (`int`, *optional*, defaults to 3):
168
+ The number of input channels.
169
+ out_channels (`int`, *optional*, defaults to 3):
170
+ The number of output channels.
171
+ blocks (`List[Tuple[str, int]]`, *optional*, defaults to `[("res_x", 1)]`):
172
+ The blocks to use. Each block is a tuple of the block name and the number of layers.
173
+ base_channels (`int`, *optional*, defaults to 128):
174
+ The number of output channels for the first convolutional layer.
175
+ norm_num_groups (`int`, *optional*, defaults to 32):
176
+ The number of groups for normalization.
177
+ patch_size (`int`, *optional*, defaults to 1):
178
+ The patch size to use. Should be a power of 2.
179
+ norm_layer (`str`, *optional*, defaults to `group_norm`):
180
+ The normalization layer to use. Can be either `group_norm` or `pixel_norm`.
181
+ latent_log_var (`str`, *optional*, defaults to `per_channel`):
182
+ The number of channels for the log variance. Can be either `per_channel`, `uniform`, or `none`.
183
+ """
184
+
185
+ def __init__(
186
+ self,
187
+ dims: Union[int, Tuple[int, int]] = 3,
188
+ in_channels: int = 3,
189
+ out_channels: int = 3,
190
+ blocks: List[Tuple[str, int]] = [("res_x", 1)],
191
+ base_channels: int = 128,
192
+ norm_num_groups: int = 32,
193
+ patch_size: Union[int, Tuple[int]] = 1,
194
+ norm_layer: str = "group_norm", # group_norm, pixel_norm
195
+ latent_log_var: str = "per_channel",
196
+ ):
197
+ super().__init__()
198
+ self.patch_size = patch_size
199
+ self.norm_layer = norm_layer
200
+ self.latent_channels = out_channels
201
+ self.latent_log_var = latent_log_var
202
+ self.blocks_desc = blocks
203
+
204
+ in_channels = in_channels * patch_size**2
205
+ output_channel = base_channels
206
+
207
+ self.conv_in = make_conv_nd(
208
+ dims=dims,
209
+ in_channels=in_channels,
210
+ out_channels=output_channel,
211
+ kernel_size=3,
212
+ stride=1,
213
+ padding=1,
214
+ causal=True,
215
+ )
216
+
217
+ self.down_blocks = nn.ModuleList([])
218
+
219
+ for block_name, num_layers in blocks:
220
+ input_channel = output_channel
221
+
222
+ if block_name == "res_x":
223
+ block = UNetMidBlock3D(
224
+ dims=dims,
225
+ in_channels=input_channel,
226
+ num_layers=num_layers,
227
+ resnet_eps=1e-6,
228
+ resnet_groups=norm_num_groups,
229
+ norm_layer=norm_layer,
230
+ )
231
+ elif block_name == "res_x_y":
232
+ output_channel = 2 * output_channel
233
+ block = ResnetBlock3D(
234
+ dims=dims,
235
+ in_channels=input_channel,
236
+ out_channels=output_channel,
237
+ eps=1e-6,
238
+ groups=norm_num_groups,
239
+ norm_layer=norm_layer,
240
+ )
241
+ elif block_name == "compress_time":
242
+ block = make_conv_nd(
243
+ dims=dims,
244
+ in_channels=input_channel,
245
+ out_channels=output_channel,
246
+ kernel_size=3,
247
+ stride=(2, 1, 1),
248
+ causal=True,
249
+ )
250
+ elif block_name == "compress_space":
251
+ block = make_conv_nd(
252
+ dims=dims,
253
+ in_channels=input_channel,
254
+ out_channels=output_channel,
255
+ kernel_size=3,
256
+ stride=(1, 2, 2),
257
+ causal=True,
258
+ )
259
+ elif block_name == "compress_all":
260
+ block = make_conv_nd(
261
+ dims=dims,
262
+ in_channels=input_channel,
263
+ out_channels=output_channel,
264
+ kernel_size=3,
265
+ stride=(2, 2, 2),
266
+ causal=True,
267
+ )
268
+ else:
269
+ raise ValueError(f"unknown block: {block_name}")
270
+
271
+ self.down_blocks.append(block)
272
+
273
+ # out
274
+ if norm_layer == "group_norm":
275
+ self.conv_norm_out = nn.GroupNorm(num_channels=output_channel, num_groups=norm_num_groups, eps=1e-6)
276
+ elif norm_layer == "pixel_norm":
277
+ self.conv_norm_out = PixelNorm()
278
+ elif norm_layer == "layer_norm":
279
+ self.conv_norm_out = LayerNorm(output_channel, eps=1e-6)
280
+
281
+ self.conv_act = nn.SiLU()
282
+
283
+ conv_out_channels = out_channels
284
+ if latent_log_var == "per_channel":
285
+ conv_out_channels *= 2
286
+ elif latent_log_var == "uniform":
287
+ conv_out_channels += 1
288
+ elif latent_log_var != "none":
289
+ raise ValueError(f"Invalid latent_log_var: {latent_log_var}")
290
+ self.conv_out = make_conv_nd(dims, output_channel, conv_out_channels, 3, padding=1, causal=True)
291
+
292
+ self.gradient_checkpointing = False
293
+
294
+ def forward(self, sample: torch.FloatTensor) -> torch.FloatTensor:
295
+ r"""The forward method of the `Encoder` class."""
296
+
297
+ sample = patchify(sample, patch_size_hw=self.patch_size, patch_size_t=1)
298
+ sample = self.conv_in(sample)
299
+
300
+ checkpoint_fn = (
301
+ partial(torch.utils.checkpoint.checkpoint, use_reentrant=False)
302
+ if self.gradient_checkpointing and self.training
303
+ else lambda x: x
304
+ )
305
+
306
+ for down_block in self.down_blocks:
307
+ sample = checkpoint_fn(down_block)(sample)
308
+
309
+ sample = self.conv_norm_out(sample)
310
+ sample = self.conv_act(sample)
311
+ sample = self.conv_out(sample)
312
+
313
+ if self.latent_log_var == "uniform":
314
+ last_channel = sample[:, -1:, ...]
315
+ num_dims = sample.dim()
316
+
317
+ if num_dims == 4:
318
+ # For shape (B, C, H, W)
319
+ repeated_last_channel = last_channel.repeat(1, sample.shape[1] - 2, 1, 1)
320
+ sample = torch.cat([sample, repeated_last_channel], dim=1)
321
+ elif num_dims == 5:
322
+ # For shape (B, C, F, H, W)
323
+ repeated_last_channel = last_channel.repeat(1, sample.shape[1] - 2, 1, 1, 1)
324
+ sample = torch.cat([sample, repeated_last_channel], dim=1)
325
+ else:
326
+ raise ValueError(f"Invalid input shape: {sample.shape}")
327
+
328
+ return sample
329
+
330
+
331
+ class Decoder(nn.Module):
332
+ r"""
333
+ The `Decoder` layer of a variational autoencoder that decodes its latent representation into an output sample.
334
+
335
+ Args:
336
+ dims (`int` or `Tuple[int, int]`, *optional*, defaults to 3):
337
+ The number of dimensions to use in convolutions.
338
+ in_channels (`int`, *optional*, defaults to 3):
339
+ The number of input channels.
340
+ out_channels (`int`, *optional*, defaults to 3):
341
+ The number of output channels.
342
+ blocks (`List[Tuple[str, int]]`, *optional*, defaults to `[("res_x", 1)]`):
343
+ The blocks to use. Each block is a tuple of the block name and the number of layers.
344
+ base_channels (`int`, *optional*, defaults to 128):
345
+ The number of output channels for the first convolutional layer.
346
+ norm_num_groups (`int`, *optional*, defaults to 32):
347
+ The number of groups for normalization.
348
+ patch_size (`int`, *optional*, defaults to 1):
349
+ The patch size to use. Should be a power of 2.
350
+ norm_layer (`str`, *optional*, defaults to `group_norm`):
351
+ The normalization layer to use. Can be either `group_norm` or `pixel_norm`.
352
+ causal (`bool`, *optional*, defaults to `True`):
353
+ Whether to use causal convolutions or not.
354
+ """
355
+
356
+ def __init__(
357
+ self,
358
+ dims,
359
+ in_channels: int = 3,
360
+ out_channels: int = 3,
361
+ blocks: List[Tuple[str, int]] = [("res_x", 1)],
362
+ base_channels: int = 128,
363
+ layers_per_block: int = 2,
364
+ norm_num_groups: int = 32,
365
+ patch_size: int = 1,
366
+ norm_layer: str = "group_norm",
367
+ causal: bool = True,
368
+ ):
369
+ super().__init__()
370
+ self.patch_size = patch_size
371
+ self.layers_per_block = layers_per_block
372
+ out_channels = out_channels * patch_size**2
373
+ num_channel_doubles = len([x for x in blocks if x[0] == "res_x_y"])
374
+ output_channel = base_channels * 2**num_channel_doubles
375
+ self.causal = causal
376
+
377
+ self.conv_in = make_conv_nd(
378
+ dims,
379
+ in_channels,
380
+ output_channel,
381
+ kernel_size=3,
382
+ stride=1,
383
+ padding=1,
384
+ causal=True,
385
+ )
386
+
387
+ self.up_blocks = nn.ModuleList([])
388
+
389
+ for block_name, num_layers in list(reversed(blocks)):
390
+ input_channel = output_channel
391
+
392
+ if block_name == "res_x":
393
+ block = UNetMidBlock3D(
394
+ dims=dims,
395
+ in_channels=input_channel,
396
+ num_layers=num_layers,
397
+ resnet_eps=1e-6,
398
+ resnet_groups=norm_num_groups,
399
+ norm_layer=norm_layer,
400
+ )
401
+ elif block_name == "res_x_y":
402
+ output_channel = output_channel // 2
403
+ block = ResnetBlock3D(
404
+ dims=dims,
405
+ in_channels=input_channel,
406
+ out_channels=output_channel,
407
+ eps=1e-6,
408
+ groups=norm_num_groups,
409
+ norm_layer=norm_layer,
410
+ )
411
+ elif block_name == "compress_time":
412
+ block = DepthToSpaceUpsample(dims=dims, in_channels=input_channel, stride=(2, 1, 1))
413
+ elif block_name == "compress_space":
414
+ block = DepthToSpaceUpsample(dims=dims, in_channels=input_channel, stride=(1, 2, 2))
415
+ elif block_name == "compress_all":
416
+ block = DepthToSpaceUpsample(dims=dims, in_channels=input_channel, stride=(2, 2, 2))
417
+ else:
418
+ raise ValueError(f"unknown layer: {block_name}")
419
+
420
+ self.up_blocks.append(block)
421
+
422
+ if norm_layer == "group_norm":
423
+ self.conv_norm_out = nn.GroupNorm(num_channels=output_channel, num_groups=norm_num_groups, eps=1e-6)
424
+ elif norm_layer == "pixel_norm":
425
+ self.conv_norm_out = PixelNorm()
426
+ elif norm_layer == "layer_norm":
427
+ self.conv_norm_out = LayerNorm(output_channel, eps=1e-6)
428
+
429
+ self.conv_act = nn.SiLU()
430
+ self.conv_out = make_conv_nd(dims, output_channel, out_channels, 3, padding=1, causal=True)
431
+
432
+ self.gradient_checkpointing = False
433
+
434
+ def forward(self, sample: torch.FloatTensor, target_shape) -> torch.FloatTensor:
435
+ r"""The forward method of the `Decoder` class."""
436
+ assert target_shape is not None, "target_shape must be provided"
437
+
438
+ sample = self.conv_in(sample, causal=self.causal)
439
+
440
+ upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
441
+
442
+ checkpoint_fn = (
443
+ partial(torch.utils.checkpoint.checkpoint, use_reentrant=False)
444
+ if self.gradient_checkpointing and self.training
445
+ else lambda x: x
446
+ )
447
+
448
+ sample = sample.to(upscale_dtype)
449
+
450
+ for up_block in self.up_blocks:
451
+ sample = checkpoint_fn(up_block)(sample, causal=self.causal)
452
+
453
+ sample = self.conv_norm_out(sample)
454
+ sample = self.conv_act(sample)
455
+ sample = self.conv_out(sample, causal=self.causal)
456
+
457
+ sample = unpatchify(sample, patch_size_hw=self.patch_size, patch_size_t=1)
458
+
459
+ return sample
460
+
461
+
462
+ class UNetMidBlock3D(nn.Module):
463
+ """
464
+ A 3D UNet mid-block [`UNetMidBlock3D`] with multiple residual blocks.
465
+
466
+ Args:
467
+ in_channels (`int`): The number of input channels.
468
+ dropout (`float`, *optional*, defaults to 0.0): The dropout rate.
469
+ num_layers (`int`, *optional*, defaults to 1): The number of residual blocks.
470
+ resnet_eps (`float`, *optional*, 1e-6 ): The epsilon value for the resnet blocks.
471
+ resnet_groups (`int`, *optional*, defaults to 32):
472
+ The number of groups to use in the group normalization layers of the resnet blocks.
473
+
474
+ Returns:
475
+ `torch.FloatTensor`: The output of the last residual block, which is a tensor of shape `(batch_size,
476
+ in_channels, height, width)`.
477
+
478
+ """
479
+
480
+ def __init__(
481
+ self,
482
+ dims: Union[int, Tuple[int, int]],
483
+ in_channels: int,
484
+ dropout: float = 0.0,
485
+ num_layers: int = 1,
486
+ resnet_eps: float = 1e-6,
487
+ resnet_groups: int = 32,
488
+ norm_layer: str = "group_norm",
489
+ ):
490
+ super().__init__()
491
+ resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
492
+
493
+ self.res_blocks = nn.ModuleList(
494
+ [
495
+ ResnetBlock3D(
496
+ dims=dims,
497
+ in_channels=in_channels,
498
+ out_channels=in_channels,
499
+ eps=resnet_eps,
500
+ groups=resnet_groups,
501
+ dropout=dropout,
502
+ norm_layer=norm_layer,
503
+ )
504
+ for _ in range(num_layers)
505
+ ]
506
+ )
507
+
508
+ def forward(self, hidden_states: torch.FloatTensor, causal: bool = True) -> torch.FloatTensor:
509
+ for resnet in self.res_blocks:
510
+ hidden_states = resnet(hidden_states, causal=causal)
511
+
512
+ return hidden_states
513
+
514
+
515
+ class DepthToSpaceUpsample(nn.Module):
516
+ def __init__(self, dims, in_channels, stride):
517
+ super().__init__()
518
+ self.stride = stride
519
+ self.out_channels = np.prod(stride) * in_channels
520
+ self.conv = make_conv_nd(
521
+ dims=dims,
522
+ in_channels=in_channels,
523
+ out_channels=self.out_channels,
524
+ kernel_size=3,
525
+ stride=1,
526
+ causal=True,
527
+ )
528
+
529
+ def forward(self, x, causal: bool = True):
530
+ x = self.conv(x, causal=causal)
531
+ x = rearrange(
532
+ x,
533
+ "b (c p1 p2 p3) d h w -> b c (d p1) (h p2) (w p3)",
534
+ p1=self.stride[0],
535
+ p2=self.stride[1],
536
+ p3=self.stride[2],
537
+ )
538
+ if self.stride[0] == 2:
539
+ x = x[:, :, 1:, :, :]
540
+ return x
541
+
542
+
543
+ class LayerNorm(nn.Module):
544
+ def __init__(self, dim, eps, elementwise_affine=True) -> None:
545
+ super().__init__()
546
+ self.norm = nn.LayerNorm(dim, eps=eps, elementwise_affine=elementwise_affine)
547
+
548
+ def forward(self, x):
549
+ x = rearrange(x, "b c d h w -> b d h w c")
550
+ x = self.norm(x)
551
+ x = rearrange(x, "b d h w c -> b c d h w")
552
+ return x
553
+
554
+
555
+ class ResnetBlock3D(nn.Module):
556
+ r"""
557
+ A Resnet block.
558
+
559
+ Parameters:
560
+ in_channels (`int`): The number of channels in the input.
561
+ out_channels (`int`, *optional*, default to be `None`):
562
+ The number of output channels for the first conv layer. If None, same as `in_channels`.
563
+ dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
564
+ groups (`int`, *optional*, default to `32`): The number of groups to use for the first normalization layer.
565
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
566
+ """
567
+
568
+ def __init__(
569
+ self,
570
+ dims: Union[int, Tuple[int, int]],
571
+ in_channels: int,
572
+ out_channels: Optional[int] = None,
573
+ conv_shortcut: bool = False,
574
+ dropout: float = 0.0,
575
+ groups: int = 32,
576
+ eps: float = 1e-6,
577
+ norm_layer: str = "group_norm",
578
+ ):
579
+ super().__init__()
580
+ self.in_channels = in_channels
581
+ out_channels = in_channels if out_channels is None else out_channels
582
+ self.out_channels = out_channels
583
+ self.use_conv_shortcut = conv_shortcut
584
+
585
+ if norm_layer == "group_norm":
586
+ self.norm1 = nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)
587
+ elif norm_layer == "pixel_norm":
588
+ self.norm1 = PixelNorm()
589
+ elif norm_layer == "layer_norm":
590
+ self.norm1 = LayerNorm(in_channels, eps=eps, elementwise_affine=True)
591
+
592
+ self.non_linearity = nn.SiLU()
593
+
594
+ self.conv1 = make_conv_nd(dims, in_channels, out_channels, kernel_size=3, stride=1, padding=1, causal=True)
595
+
596
+ if norm_layer == "group_norm":
597
+ self.norm2 = nn.GroupNorm(num_groups=groups, num_channels=out_channels, eps=eps, affine=True)
598
+ elif norm_layer == "pixel_norm":
599
+ self.norm2 = PixelNorm()
600
+ elif norm_layer == "layer_norm":
601
+ self.norm2 = LayerNorm(out_channels, eps=eps, elementwise_affine=True)
602
+
603
+ self.dropout = torch.nn.Dropout(dropout)
604
+
605
+ self.conv2 = make_conv_nd(dims, out_channels, out_channels, kernel_size=3, stride=1, padding=1, causal=True)
606
+
607
+ self.conv_shortcut = (
608
+ make_linear_nd(dims=dims, in_channels=in_channels, out_channels=out_channels)
609
+ if in_channels != out_channels
610
+ else nn.Identity()
611
+ )
612
+
613
+ self.norm3 = (
614
+ LayerNorm(in_channels, eps=eps, elementwise_affine=True) if in_channels != out_channels else nn.Identity()
615
+ )
616
+
617
+ def forward(
618
+ self,
619
+ input_tensor: torch.FloatTensor,
620
+ causal: bool = True,
621
+ ) -> torch.FloatTensor:
622
+ hidden_states = input_tensor
623
+
624
+ hidden_states = self.norm1(hidden_states)
625
+
626
+ hidden_states = self.non_linearity(hidden_states)
627
+
628
+ hidden_states = self.conv1(hidden_states, causal=causal)
629
+
630
+ hidden_states = self.norm2(hidden_states)
631
+
632
+ hidden_states = self.non_linearity(hidden_states)
633
+
634
+ hidden_states = self.dropout(hidden_states)
635
+
636
+ hidden_states = self.conv2(hidden_states, causal=causal)
637
+
638
+ input_tensor = self.norm3(input_tensor)
639
+
640
+ input_tensor = self.conv_shortcut(input_tensor)
641
+
642
+ output_tensor = input_tensor + hidden_states
643
+
644
+ return output_tensor
645
+
646
+
647
+ def patchify(x, patch_size_hw, patch_size_t=1):
648
+ if patch_size_hw == 1 and patch_size_t == 1:
649
+ return x
650
+ if x.dim() == 4:
651
+ x = rearrange(x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size_hw, r=patch_size_hw)
652
+ elif x.dim() == 5:
653
+ x = rearrange(x, "b c (f p) (h q) (w r) -> b (c p r q) f h w", p=patch_size_t, q=patch_size_hw, r=patch_size_hw)
654
+ else:
655
+ raise ValueError(f"Invalid input shape: {x.shape}")
656
+
657
+ return x
658
+
659
+
660
+ def unpatchify(x, patch_size_hw, patch_size_t=1):
661
+ if patch_size_hw == 1 and patch_size_t == 1:
662
+ return x
663
+
664
+ if x.dim() == 4:
665
+ x = rearrange(x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size_hw, r=patch_size_hw)
666
+ elif x.dim() == 5:
667
+ x = rearrange(x, "b (c p r q) f h w -> b c (f p) (h q) (w r)", p=patch_size_t, q=patch_size_hw, r=patch_size_hw)
668
+
669
+ return x
670
+
671
+
672
+ def create_video_autoencoder_config(
673
+ latent_channels: int = 64,
674
+ ):
675
+ config = {
676
+ "_class_name": "CausalVideoAutoencoder",
677
+ "dims": 3, # (2, 1), # 2 for Conv2, 3 for Conv3d, (2, 1) for Conv2d followed by Conv1d
678
+ "in_channels": 3, # Number of input color channels (e.g., RGB)
679
+ "out_channels": 3, # Number of output color channels
680
+ "latent_channels": latent_channels, # Number of channels in the latent space representation
681
+ "blocks": [
682
+ ("res_x", 4),
683
+ ("compress_space", 1),
684
+ ("res_x_y", 1),
685
+ ("res_x", 2),
686
+ ("compress_all", 1),
687
+ ("res_x", 3),
688
+ ("compress_all", 1),
689
+ ("res_x_y", 1),
690
+ ("res_x", 2),
691
+ ("compress_time", 1),
692
+ ("res_x", 3),
693
+ ("res_x", 3),
694
+ ],
695
+ "patch_size": 4,
696
+ "latent_log_var": "uniform",
697
+ "use_quant_conv": False,
698
+ "norm_layer": "layer_norm",
699
+ "causal_decoder": True,
700
+ }
701
+
702
+ return config
703
+
704
+
705
+ def test_vae_patchify_unpatchify():
706
+ import torch
707
+
708
+ x = torch.randn(2, 3, 8, 64, 64)
709
+ x_patched = patchify(x, patch_size_hw=4, patch_size_t=4)
710
+ x_unpatched = unpatchify(x_patched, patch_size_hw=4, patch_size_t=4)
711
+ assert torch.allclose(x, x_unpatched)
712
+
713
+
714
+ def demo_video_autoencoder_forward_backward():
715
+ # Configuration for the VideoAutoencoder
716
+ config = create_video_autoencoder_config()
717
+
718
+ # Instantiate the VideoAutoencoder with the specified configuration
719
+ video_autoencoder = CausalVideoAutoencoder.from_config(config)
720
+
721
+ print(video_autoencoder)
722
+ video_autoencoder.eval()
723
+ # Print the total number of parameters in the video autoencoder
724
+ total_params = sum(p.numel() for p in video_autoencoder.parameters())
725
+ print(f"Total number of parameters in VideoAutoencoder: {total_params:,}")
726
+
727
+ # Create a mock input tensor simulating a batch of videos
728
+ # Shape: (batch_size, channels, depth, height, width)
729
+ # E.g., 4 videos, each with 3 color channels, 16 frames, and 64x64 pixels per frame
730
+ input_videos = torch.randn(2, 3, 17, 64, 64)
731
+
732
+ # Forward pass: encode and decode the input videos
733
+ latent = video_autoencoder.encode(input_videos).latent_dist.mode()
734
+ print(f"input shape={input_videos.shape}")
735
+ print(f"latent shape={latent.shape}")
736
+
737
+ reconstructed_videos = video_autoencoder.decode(latent, target_shape=input_videos.shape).sample
738
+
739
+ print(f"reconstructed shape={reconstructed_videos.shape}")
740
+
741
+ # Validate that single image gets treated the same way as first frame
742
+ input_image = input_videos[:, :, :1, :, :]
743
+ image_latent = video_autoencoder.encode(input_image).latent_dist.mode()
744
+ reconstructed_image = video_autoencoder.decode(image_latent, target_shape=image_latent.shape).sample
745
+
746
+ first_frame_latent = latent[:, :, :1, :, :]
747
+
748
+ # assert torch.allclose(image_latent, first_frame_latent, atol=1e-6)
749
+ # assert torch.allclose(reconstructed_image, reconstructed_videos[:, :, :1, :, :], atol=1e-6)
750
+ assert (image_latent == first_frame_latent).all()
751
+ assert (reconstructed_image == reconstructed_videos[:, :, :1, :, :]).all()
752
+
753
+ # Calculate the loss (e.g., mean squared error)
754
+ loss = torch.nn.functional.mse_loss(input_videos, reconstructed_videos)
755
+
756
+ # Perform backward pass
757
+ loss.backward()
758
+
759
+ print(f"Demo completed with loss: {loss.item()}")
760
+
761
+
762
+ # Ensure to call the demo function to execute the forward and backward pass
763
+ if __name__ == "__main__":
764
+ demo_video_autoencoder_forward_backward()