smoothieAI commited on
Commit
701a6d6
·
verified ·
1 Parent(s): 102ddcf

Upload pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +1179 -0
pipeline.py ADDED
@@ -0,0 +1,1179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from dataclasses import dataclass
17
+ from typing import Any, Callable, Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
22
+
23
+ # Updated to use absolute paths
24
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
25
+ from diffusers.loaders import IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
26
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel, UNetMotionModel
27
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
28
+ from diffusers.models.unet_motion_model import MotionAdapter
29
+ from diffusers.schedulers import (
30
+ DDIMScheduler,
31
+ DPMSolverMultistepScheduler,
32
+ EulerAncestralDiscreteScheduler,
33
+ EulerDiscreteScheduler,
34
+ LMSDiscreteScheduler,
35
+ PNDMScheduler,
36
+ )
37
+ from diffusers.utils import (
38
+ USE_PEFT_BACKEND,
39
+ BaseOutput,
40
+ logging,
41
+ scale_lora_layers,
42
+ unscale_lora_layers,
43
+ )
44
+ from diffusers.utils.torch_utils import is_compiled_module, randn_tensor
45
+
46
+ # Added imports based on the working paths
47
+ from diffusers.models import ControlNetModel
48
+ from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
49
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
50
+ from diffusers.utils import deprecate
51
+
52
+ import torchvision
53
+ import PIL
54
+ import PIL.Image
55
+ import math
56
+
57
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
58
+
59
+ EXAMPLE_DOC_STRING = """
60
+ Examples:
61
+ ```py
62
+ >>> import torch
63
+ >>> from diffusers import MotionAdapter, AnimateDiffPipeline, DDIMScheduler
64
+ >>> from diffusers.utils import export_to_gif
65
+ >>> adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2")
66
+ >>> pipe = AnimateDiffPipeline.from_pretrained("frankjoshua/toonyou_beta6", motion_adapter=adapter)
67
+ >>> pipe.scheduler = DDIMScheduler(beta_schedule="linear", steps_offset=1, clip_sample=False)
68
+ >>> output = pipe(prompt="A corgi walking in the park")
69
+ >>> frames = output.frames[0]
70
+ >>> export_to_gif(frames, "animation.gif")
71
+ ```
72
+ """
73
+
74
+
75
+ def tensor2vid(video: torch.Tensor, processor, output_type="np"):
76
+ # Based on:
77
+ # https://github.com/modelscope/modelscope/blob/1509fdb973e5871f37148a4b5e5964cafd43e64d/modelscope/pipelines/multi_modal/text_to_video_synthesis_pipeline.py#L78
78
+
79
+ batch_size, channels, num_frames, height, width = video.shape
80
+ outputs = []
81
+ for batch_idx in range(batch_size):
82
+ batch_vid = video[batch_idx].permute(1, 0, 2, 3)
83
+ batch_output = processor.postprocess(batch_vid, output_type)
84
+
85
+ outputs.append(batch_output)
86
+
87
+ return outputs
88
+
89
+
90
+ @dataclass
91
+ class AnimateDiffPipelineOutput(BaseOutput):
92
+ frames: Union[torch.Tensor, np.ndarray]
93
+
94
+
95
+ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, IPAdapterMixin, LoraLoaderMixin):
96
+ r"""
97
+ Pipeline for text-to-video generation.
98
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
99
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
100
+ The pipeline also inherits the following loading methods:
101
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
102
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
103
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
104
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
105
+ Args:
106
+ vae ([`AutoencoderKL`]):
107
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
108
+ text_encoder ([`CLIPTextModel`]):
109
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
110
+ tokenizer (`CLIPTokenizer`):
111
+ A [`~transformers.CLIPTokenizer`] to tokenize text.
112
+ unet ([`UNet2DConditionModel`]):
113
+ A [`UNet2DConditionModel`] used to create a UNetMotionModel to denoise the encoded video latents.
114
+ motion_adapter ([`MotionAdapter`]):
115
+ A [`MotionAdapter`] to be used in combination with `unet` to denoise the encoded video latents.
116
+ scheduler ([`SchedulerMixin`]):
117
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
118
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
119
+ """
120
+
121
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
122
+ _optional_components = ["feature_extractor", "image_encoder"]
123
+
124
+ def __init__(
125
+ self,
126
+ vae: AutoencoderKL,
127
+ text_encoder: CLIPTextModel,
128
+ tokenizer: CLIPTokenizer,
129
+ unet: UNet2DConditionModel,
130
+ motion_adapter: MotionAdapter,
131
+ scheduler: Union[
132
+ DDIMScheduler,
133
+ PNDMScheduler,
134
+ LMSDiscreteScheduler,
135
+ EulerDiscreteScheduler,
136
+ EulerAncestralDiscreteScheduler,
137
+ DPMSolverMultistepScheduler,
138
+ ],
139
+ feature_extractor: CLIPImageProcessor = None,
140
+ image_encoder: CLIPVisionModelWithProjection = None,
141
+ ):
142
+ super().__init__()
143
+ unet = UNetMotionModel.from_unet2d(unet, motion_adapter)
144
+
145
+ self.register_modules(
146
+ vae=vae,
147
+ text_encoder=text_encoder,
148
+ tokenizer=tokenizer,
149
+ unet=unet,
150
+ motion_adapter=motion_adapter,
151
+ scheduler=scheduler,
152
+ feature_extractor=feature_extractor,
153
+ image_encoder=image_encoder,
154
+ )
155
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
156
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
157
+
158
+ def load_motion_adapter(self,motion_adapter):
159
+ self.register_modules(motion_adapter=motion_adapter)
160
+
161
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt with num_images_per_prompt -> num_videos_per_prompt
162
+ def encode_prompt(
163
+ self,
164
+ prompt,
165
+ device,
166
+ num_images_per_prompt,
167
+ do_classifier_free_guidance,
168
+ negative_prompt=None,
169
+ prompt_embeds: Optional[torch.FloatTensor] = None,
170
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
171
+ lora_scale: Optional[float] = None,
172
+ clip_skip: Optional[int] = None,
173
+ ):
174
+ r"""
175
+ Encodes the prompt into text encoder hidden states.
176
+ Args:
177
+ prompt (`str` or `List[str]`, *optional*):
178
+ prompt to be encoded
179
+ device: (`torch.device`):
180
+ torch device
181
+ num_images_per_prompt (`int`):
182
+ number of images that should be generated per prompt
183
+ do_classifier_free_guidance (`bool`):
184
+ whether to use classifier free guidance or not
185
+ negative_prompt (`str` or `List[str]`, *optional*):
186
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
187
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
188
+ less than `1`).
189
+ prompt_embeds (`torch.FloatTensor`, *optional*):
190
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
191
+ provided, text embeddings will be generated from `prompt` input argument.
192
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
193
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
194
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
195
+ argument.
196
+ lora_scale (`float`, *optional*):
197
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
198
+ clip_skip (`int`, *optional*):
199
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
200
+ the output of the pre-final layer will be used for computing the prompt embeddings.
201
+ """
202
+ # set lora scale so that monkey patched LoRA
203
+ # function of text encoder can correctly access it
204
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
205
+ self._lora_scale = lora_scale
206
+
207
+ # dynamically adjust the LoRA scale
208
+ if not USE_PEFT_BACKEND:
209
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
210
+ else:
211
+ scale_lora_layers(self.text_encoder, lora_scale)
212
+
213
+ if prompt is not None and isinstance(prompt, str):
214
+ batch_size = 1
215
+ elif prompt is not None and isinstance(prompt, list):
216
+ batch_size = len(prompt)
217
+ else:
218
+ batch_size = prompt_embeds.shape[0]
219
+
220
+ if prompt_embeds is None:
221
+ # textual inversion: procecss multi-vector tokens if necessary
222
+ if isinstance(self, TextualInversionLoaderMixin):
223
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
224
+
225
+ text_inputs = self.tokenizer(
226
+ prompt,
227
+ padding="max_length",
228
+ max_length=self.tokenizer.model_max_length,
229
+ truncation=True,
230
+ return_tensors="pt",
231
+ )
232
+ text_input_ids = text_inputs.input_ids
233
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
234
+
235
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
236
+ text_input_ids, untruncated_ids
237
+ ):
238
+ removed_text = self.tokenizer.batch_decode(
239
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
240
+ )
241
+ logger.warning(
242
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
243
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
244
+ )
245
+
246
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
247
+ attention_mask = text_inputs.attention_mask.to(device)
248
+ else:
249
+ attention_mask = None
250
+
251
+ if clip_skip is None:
252
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
253
+ prompt_embeds = prompt_embeds[0]
254
+ else:
255
+ prompt_embeds = self.text_encoder(
256
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
257
+ )
258
+ # Access the `hidden_states` first, that contains a tuple of
259
+ # all the hidden states from the encoder layers. Then index into
260
+ # the tuple to access the hidden states from the desired layer.
261
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
262
+ # We also need to apply the final LayerNorm here to not mess with the
263
+ # representations. The `last_hidden_states` that we typically use for
264
+ # obtaining the final prompt representations passes through the LayerNorm
265
+ # layer.
266
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
267
+
268
+ if self.text_encoder is not None:
269
+ prompt_embeds_dtype = self.text_encoder.dtype
270
+ elif self.unet is not None:
271
+ prompt_embeds_dtype = self.unet.dtype
272
+ else:
273
+ prompt_embeds_dtype = prompt_embeds.dtype
274
+
275
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
276
+
277
+ bs_embed, seq_len, _ = prompt_embeds.shape
278
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
279
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
280
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
281
+
282
+ # get unconditional embeddings for classifier free guidance
283
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
284
+ uncond_tokens: List[str]
285
+ if negative_prompt is None:
286
+ uncond_tokens = [""] * batch_size
287
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
288
+ raise TypeError(
289
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
290
+ f" {type(prompt)}."
291
+ )
292
+ elif isinstance(negative_prompt, str):
293
+ uncond_tokens = [negative_prompt]
294
+ elif batch_size != len(negative_prompt):
295
+ raise ValueError(
296
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
297
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
298
+ " the batch size of `prompt`."
299
+ )
300
+ else:
301
+ uncond_tokens = negative_prompt
302
+
303
+ # textual inversion: procecss multi-vector tokens if necessary
304
+ if isinstance(self, TextualInversionLoaderMixin):
305
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
306
+
307
+ max_length = prompt_embeds.shape[1]
308
+ uncond_input = self.tokenizer(
309
+ uncond_tokens,
310
+ padding="max_length",
311
+ max_length=max_length,
312
+ truncation=True,
313
+ return_tensors="pt",
314
+ )
315
+
316
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
317
+ attention_mask = uncond_input.attention_mask.to(device)
318
+ else:
319
+ attention_mask = None
320
+
321
+ negative_prompt_embeds = self.text_encoder(
322
+ uncond_input.input_ids.to(device),
323
+ attention_mask=attention_mask,
324
+ )
325
+ negative_prompt_embeds = negative_prompt_embeds[0]
326
+
327
+ if do_classifier_free_guidance:
328
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
329
+ seq_len = negative_prompt_embeds.shape[1]
330
+
331
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
332
+
333
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
334
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
335
+
336
+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
337
+ # Retrieve the original scale by scaling back the LoRA layers
338
+ unscale_lora_layers(self.text_encoder, lora_scale)
339
+
340
+ return prompt_embeds, negative_prompt_embeds
341
+
342
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
343
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
344
+ dtype = next(self.image_encoder.parameters()).dtype
345
+
346
+ if not isinstance(image, torch.Tensor):
347
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
348
+
349
+ image = image.to(device=device, dtype=dtype)
350
+ if output_hidden_states:
351
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
352
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
353
+ uncond_image_enc_hidden_states = self.image_encoder(
354
+ torch.zeros_like(image), output_hidden_states=True
355
+ ).hidden_states[-2]
356
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
357
+ num_images_per_prompt, dim=0
358
+ )
359
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
360
+ else:
361
+ image_embeds = self.image_encoder(image).image_embeds
362
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
363
+ uncond_image_embeds = torch.zeros_like(image_embeds)
364
+
365
+ return image_embeds, uncond_image_embeds
366
+
367
+ # Copied from diffusers.pipelines.text_to_video_synthesis/pipeline_text_to_video_synth.TextToVideoSDPipeline.decode_latents
368
+ def decode_latents(self, latents):
369
+ latents = 1 / self.vae.config.scaling_factor * latents
370
+
371
+ batch_size, channels, num_frames, height, width = latents.shape
372
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
373
+
374
+ image = self.vae.decode(latents).sample
375
+ video = (
376
+ image[None, :]
377
+ .reshape(
378
+ (
379
+ batch_size,
380
+ num_frames,
381
+ -1,
382
+ )
383
+ + image.shape[2:]
384
+ )
385
+ .permute(0, 2, 1, 3, 4)
386
+ )
387
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
388
+ video = video.float()
389
+ return video
390
+
391
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
392
+ def enable_vae_slicing(self):
393
+ r"""
394
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
395
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
396
+ """
397
+ self.vae.enable_slicing()
398
+
399
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
400
+ def disable_vae_slicing(self):
401
+ r"""
402
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
403
+ computing decoding in one step.
404
+ """
405
+ self.vae.disable_slicing()
406
+
407
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
408
+ def enable_vae_tiling(self):
409
+ r"""
410
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
411
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
412
+ processing larger images.
413
+ """
414
+ self.vae.enable_tiling()
415
+
416
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
417
+ def disable_vae_tiling(self):
418
+ r"""
419
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
420
+ computing decoding in one step.
421
+ """
422
+ self.vae.disable_tiling()
423
+
424
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_freeu
425
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
426
+ r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.
427
+ The suffixes after the scaling factors represent the stages where they are being applied.
428
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
429
+ that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
430
+ Args:
431
+ s1 (`float`):
432
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
433
+ mitigate "oversmoothing effect" in the enhanced denoising process.
434
+ s2 (`float`):
435
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
436
+ mitigate "oversmoothing effect" in the enhanced denoising process.
437
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
438
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
439
+ """
440
+ if not hasattr(self, "unet"):
441
+ raise ValueError("The pipeline must have `unet` for using FreeU.")
442
+ self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
443
+
444
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_freeu
445
+ def disable_freeu(self):
446
+ """Disables the FreeU mechanism if enabled."""
447
+ self.unet.disable_freeu()
448
+
449
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
450
+ def prepare_extra_step_kwargs(self, generator, eta):
451
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
452
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
453
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
454
+ # and should be between [0, 1]
455
+
456
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
457
+ extra_step_kwargs = {}
458
+ if accepts_eta:
459
+ extra_step_kwargs["eta"] = eta
460
+
461
+ # check if the scheduler accepts generator
462
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
463
+ if accepts_generator:
464
+ extra_step_kwargs["generator"] = generator
465
+ return extra_step_kwargs
466
+
467
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
468
+ def check_inputs(
469
+ self,
470
+ prompt,
471
+ height,
472
+ width,
473
+ callback_steps,
474
+ negative_prompt=None,
475
+ prompt_embeds=None,
476
+ negative_prompt_embeds=None,
477
+ callback_on_step_end_tensor_inputs=None,
478
+ ):
479
+ if height % 8 != 0 or width % 8 != 0:
480
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
481
+
482
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
483
+ raise ValueError(
484
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
485
+ f" {type(callback_steps)}."
486
+ )
487
+ if callback_on_step_end_tensor_inputs is not None and not all(
488
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
489
+ ):
490
+ raise ValueError(
491
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
492
+ )
493
+
494
+ if prompt is not None and prompt_embeds is not None:
495
+ raise ValueError(
496
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
497
+ " only forward one of the two."
498
+ )
499
+ elif prompt is None and prompt_embeds is None:
500
+ raise ValueError(
501
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
502
+ )
503
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
504
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
505
+
506
+ if negative_prompt is not None and negative_prompt_embeds is not None:
507
+ raise ValueError(
508
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
509
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
510
+ )
511
+
512
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
513
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
514
+ raise ValueError(
515
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
516
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
517
+ f" {negative_prompt_embeds.shape}."
518
+ )
519
+
520
+ # Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_synth.TextToVideoSDPipeline.prepare_latents
521
+ def prepare_latents(self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None):
522
+ shape = (
523
+ batch_size,
524
+ num_channels_latents,
525
+ num_frames,
526
+ height // self.vae_scale_factor,
527
+ width // self.vae_scale_factor,
528
+ )
529
+ if isinstance(generator, list) and len(generator) != batch_size:
530
+ raise ValueError(
531
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
532
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
533
+ )
534
+
535
+ if latents is None:
536
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
537
+ else:
538
+ latents = latents.to(device)
539
+
540
+ # scale the initial noise by the standard deviation required by the scheduler
541
+ latents = latents * self.scheduler.init_noise_sigma
542
+ return latents
543
+
544
+ def prepare_latents_same_start(self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None, context_size=16, overlap=4, strength=0.5):
545
+ shape = (
546
+ batch_size,
547
+ num_channels_latents,
548
+ num_frames,
549
+ height // self.vae_scale_factor,
550
+ width // self.vae_scale_factor,
551
+ )
552
+ if isinstance(generator, list) and len(generator) != batch_size:
553
+ raise ValueError(
554
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
555
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
556
+ )
557
+
558
+ if latents is None:
559
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
560
+ else:
561
+ latents = latents.to(device)
562
+
563
+ # make every (context_size-overlap) frames have the same noise
564
+ loop_size = context_size - overlap
565
+ loop_count = num_frames // loop_size
566
+ for i in range(loop_count):
567
+ # repeat the first frames noise for i*loop_size frame
568
+ # lerp the first frames noise
569
+ latents[:, :, i*loop_size:(i*loop_size)+overlap, :, :] = torch.lerp(latents[:, :, i*loop_size:(i*loop_size)+overlap, :, :], latents[:, :, 0:overlap, :, :], strength)
570
+
571
+ # scale the initial noise by the standard deviation required by the scheduler
572
+ latents = latents * self.scheduler.init_noise_sigma
573
+ return latents
574
+
575
+ def prepare_latents_consistent(self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None,smooth_weight=0.5,smooth_steps=3):
576
+ shape = (
577
+ batch_size,
578
+ num_channels_latents,
579
+ num_frames,
580
+ height // self.vae_scale_factor,
581
+ width // self.vae_scale_factor,
582
+ )
583
+ if isinstance(generator, list) and len(generator) != batch_size:
584
+ raise ValueError(
585
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
586
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
587
+ )
588
+
589
+ if latents is None:
590
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
591
+
592
+ # blend each frame with the surrounding N frames making sure to wrap around at the end
593
+ for i in range(num_frames):
594
+ blended_latent = torch.zeros_like(latents[:, :, i])
595
+ for s in range(-smooth_steps, smooth_steps + 1):
596
+ if s == 0:
597
+ continue
598
+ frame_index = (i + s) % num_frames
599
+ weight = (smooth_steps - abs(s)) / smooth_steps
600
+ blended_latent += latents[:, :, frame_index] * weight
601
+ latents[:, :, i] = blended_latent / (2 * smooth_steps)
602
+
603
+ latents = torch.lerp(randn_tensor(shape, generator=generator, device=device, dtype=dtype),latents, smooth_weight)
604
+ else:
605
+ latents = latents.to(device)
606
+
607
+ # scale the initial noise by the standard deviation required by the scheduler
608
+ latents = latents * self.scheduler.init_noise_sigma
609
+ return latents
610
+
611
+ def prepare_motion_latents(self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator,
612
+ latents=None, x_velocity=0, y_velocity=0, scale_velocity=0):
613
+ shape = (
614
+ batch_size,
615
+ num_channels_latents,
616
+ num_frames,
617
+ height // self.vae_scale_factor,
618
+ width // self.vae_scale_factor,
619
+ )
620
+ if isinstance(generator, list) and len(generator) != batch_size:
621
+ raise ValueError(
622
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
623
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
624
+ )
625
+
626
+ if latents is None:
627
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
628
+ else:
629
+ latents = latents.to(device)
630
+
631
+ # scale the initial noise by the standard deviation required by the scheduler
632
+ latents = latents * self.scheduler.init_noise_sigma
633
+
634
+ for frame in range(num_frames):
635
+ x_offset = int(frame * x_velocity) # Convert to int
636
+ y_offset = int(frame * y_velocity) # Convert to int
637
+ scale_factor = 1 + frame * scale_velocity
638
+
639
+ # Apply offsets
640
+ latents[:, :, frame] = torch.roll(latents[:, :, frame], shifts=(x_offset,), dims=3) # x direction
641
+ latents[:, :, frame] = torch.roll(latents[:, :, frame], shifts=(y_offset,), dims=2) # y direction
642
+
643
+ # Apply scaling - This is a simple approach and might not be ideal for all applications
644
+ if scale_factor != 1:
645
+ scaled_size = (
646
+ int(latents.shape[3] * scale_factor),
647
+ int(latents.shape[4] * scale_factor)
648
+ )
649
+ latents[:, :, frame] = torch.nn.functional.interpolate(
650
+ latents[:, :, frame].unsqueeze(0), size=scaled_size, mode='bilinear', align_corners=False
651
+ ).squeeze(0)
652
+
653
+ return latents
654
+
655
+ def generate_correlated_noise(self, latents, init_noise_correlation):
656
+ cloned_latents = latents.clone()
657
+ p = init_noise_correlation
658
+ flattened_latents = torch.flatten(cloned_latents)
659
+ noise = torch.randn_like(flattened_latents)
660
+ correlated_noise = flattened_latents * p + math.sqrt(1 - p**2) * noise
661
+
662
+ return correlated_noise.reshape(cloned_latents.shape)
663
+
664
+ def generate_correlated_latents(self, latents, init_noise_correlation):
665
+ cloned_latents = latents.clone()
666
+ for i in range(1, cloned_latents.shape[2]):
667
+ p = init_noise_correlation
668
+ flattened_latents = torch.flatten(cloned_latents[:, :, i])
669
+ prev_flattened_latents = torch.flatten(cloned_latents[:, :, i - 1])
670
+ correlated_latents = (prev_flattened_latents * p/math.sqrt((1+p**2))+flattened_latents * math.sqrt(1/(1 + p**2)))
671
+ cloned_latents[:, :, i] = correlated_latents.reshape(cloned_latents[:, :, i].shape)
672
+
673
+ return cloned_latents
674
+
675
+ def generate_correlated_latents_legacy(self, latents, init_noise_correlation):
676
+ cloned_latents = latents.clone()
677
+ for i in range(1, cloned_latents.shape[2]):
678
+ p = init_noise_correlation
679
+ flattened_latents = torch.flatten(cloned_latents[:, :, i])
680
+ prev_flattened_latents = torch.flatten(cloned_latents[:, :, i - 1])
681
+ correlated_latents = (
682
+ prev_flattened_latents * p
683
+ +
684
+ flattened_latents * math.sqrt(1 - p**2)
685
+ )
686
+ cloned_latents[:, :, i] = correlated_latents.reshape(
687
+ cloned_latents[:, :, i].shape
688
+ )
689
+
690
+ return cloned_latents
691
+
692
+ def generate_mixed_noise(self, noise, init_noise_correlation):
693
+ shared_noise = torch.randn_like(noise[0, :, 0])
694
+ for b in range(noise.shape[0]):
695
+ for f in range(noise.shape[2]):
696
+ p = init_noise_correlation
697
+ flattened_latents = torch.flatten(noise[b, :, f])
698
+ shared_latents = torch.flatten(shared_noise)
699
+ correlated_latents = (
700
+ shared_latents * math.sqrt(p**2/(1+p**2)) +
701
+ flattened_latents * math.sqrt(1/(1+p**2))
702
+ )
703
+ noise[b, :, f] = correlated_latents.reshape(noise[b, :, f].shape)
704
+
705
+ return noise
706
+
707
+ def prepare_correlated_latents(
708
+ self,
709
+ init_image,
710
+ init_image_strength,
711
+ init_noise_correlation,
712
+ batch_size,
713
+ num_channels_latents,
714
+ video_length,
715
+ height,
716
+ width,
717
+ dtype,
718
+ device,
719
+ generator,
720
+ latents=None,
721
+ ):
722
+ shape = (
723
+ batch_size,
724
+ num_channels_latents,
725
+ video_length,
726
+ height // self.vae_scale_factor,
727
+ width // self.vae_scale_factor,
728
+ )
729
+
730
+ if init_image is not None:
731
+ start_image = ((torchvision.transforms.functional.pil_to_tensor(init_image))/ 255 )[:3, :, :].to("cuda").to(dtype).unsqueeze(0)
732
+ start_image = (
733
+ self.vae.encode(start_image.mul(2).sub(1))
734
+ .latent_dist.sample()
735
+ .view(1, 4, height // 8, width // 8)
736
+ * 0.18215
737
+ )
738
+ init_latents = start_image.unsqueeze(2).repeat(1, 1, video_length, 1, 1)
739
+ else:
740
+ init_latents = None
741
+
742
+ if isinstance(generator, list) and len(generator) != batch_size:
743
+ raise ValueError(
744
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
745
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
746
+ )
747
+ if latents is None:
748
+ rand_device = "cpu" if device.type == "mps" else device
749
+ if isinstance(generator, list):
750
+ shape = shape
751
+ # shape = (1,) + shape[1:]
752
+ # ignore init latents for batch model
753
+ latents = [torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype)for i in range(batch_size)]
754
+ latents = torch.cat(latents, dim=0).to(device)
755
+ else:
756
+ if init_latents is not None:
757
+ offset = int(
758
+ init_image_strength * (len(self.scheduler.timesteps) - 1)
759
+ )
760
+ noise = torch.randn_like(init_latents)
761
+ noise = self.generate_correlated_latents(noise, init_noise_correlation)
762
+
763
+ # Eric - some black magic here
764
+ # We should be only adding the noise at timestep[offset], but I noticed that
765
+ # we get more motion and cooler motion if we add the noise at timestep[offset - 1]
766
+ # or offset - 2. However, this breaks the fewer timesteps there are, so let's interpolate
767
+ timesteps = self.scheduler.timesteps
768
+ average_timestep = None
769
+ if offset == 0:
770
+ average_timestep = timesteps[0]
771
+ elif offset == 1:
772
+ average_timestep = (
773
+ timesteps[offset - 1] * (1 - init_image_strength)
774
+ + timesteps[offset] * init_image_strength
775
+ )
776
+ else:
777
+ average_timestep = timesteps[offset - 1]
778
+
779
+ latents = self.scheduler.add_noise(
780
+ init_latents, noise, average_timestep.long()
781
+ )
782
+
783
+ latents = self.scheduler.add_noise(
784
+ latents, torch.randn_like(init_latents), timesteps[-2]
785
+ )
786
+ else:
787
+ latents = torch.randn(
788
+ shape, generator=generator, device=rand_device, dtype=dtype
789
+ ).to(device)
790
+ latents = self.generate_correlated_latents(
791
+ latents, init_noise_correlation
792
+ )
793
+ else:
794
+ if latents.shape != shape:
795
+ raise ValueError(
796
+ f"Unexpected latents shape, got {latents.shape}, expected {shape}"
797
+ )
798
+ latents = latents.to(device)
799
+
800
+ # scale the initial noise by the standard deviation required by the scheduler
801
+ if init_latents is None:
802
+ latents = latents * self.scheduler.init_noise_sigma
803
+ # elif self.unet.trained_initial_frames and init_latents is not None:
804
+ # # we only want to use this as the first frame
805
+ # init_latents[:, :, 1:] = torch.zeros_like(init_latents[:, :, 1:])
806
+
807
+ latents = latents.to(device)
808
+ return latents, init_latents
809
+
810
+
811
+ @torch.no_grad()
812
+ # @replace_example_docstring(EXAMPLE_DOC_STRING)
813
+ def __call__(
814
+ self,
815
+ prompt: Union[str, List[str]] = None,
816
+ num_frames: Optional[int] = 16,
817
+ context_size=16,
818
+ overlap=2,
819
+ step=1,
820
+ height: Optional[int] = None,
821
+ width: Optional[int] = None,
822
+ num_inference_steps: int = 50,
823
+ guidance_scale: float = 7.5,
824
+ negative_prompt: Optional[Union[str, List[str]]] = None,
825
+ num_videos_per_prompt: Optional[int] = 1,
826
+ eta: float = 0.0,
827
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
828
+ latents: Optional[torch.FloatTensor] = None,
829
+ prompt_embeds: Optional[torch.FloatTensor] = None,
830
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
831
+ ip_adapter_image: Optional[PipelineImageInput] = None,
832
+ output_type: Optional[str] = "pil",
833
+ output_path: Optional[str] = None,
834
+ return_dict: bool = True,
835
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
836
+ callback_steps: Optional[int] = 1,
837
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
838
+ clip_skip: Optional[int] = None,
839
+ x_velocity: Optional[float] = 0,
840
+ y_velocity: Optional[float] = 0,
841
+ scale_velocity: Optional[float] = 0,
842
+ init_image: Optional[PipelineImageInput] = None,
843
+ init_image_strength: Optional[float] = 1.0,
844
+ init_noise_correlation: Optional[float] = 0.0,
845
+ latent_mode: Optional[str] = "normal",
846
+ smooth_weight: Optional[float] = 0.5,
847
+ smooth_steps: Optional[int] = 3,
848
+ initial_context_scale: Optional[float] = 1.0,
849
+ ):
850
+ r"""
851
+ The call function to the pipeline for generation.
852
+ Args:
853
+ prompt (`str` or `List[str]`, *optional*):
854
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
855
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
856
+ The height in pixels of the generated video.
857
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
858
+ The width in pixels of the generated video.
859
+ num_frames (`int`, *optional*, defaults to 16):
860
+ The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
861
+ amounts to 2 seconds of video.
862
+ num_inference_steps (`int`, *optional*, defaults to 50):
863
+ The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
864
+ expense of slower inference.
865
+ guidance_scale (`float`, *optional*, defaults to 7.5):
866
+ A higher guidance scale value encourages the model to generate images closely linked to the text
867
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
868
+ negative_prompt (`str` or `List[str]`, *optional*):
869
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
870
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
871
+ eta (`float`, *optional*, defaults to 0.0):
872
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
873
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
874
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
875
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
876
+ generation deterministic.
877
+ latents (`torch.FloatTensor`, *optional*):
878
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for video
879
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
880
+ tensor is generated by sampling using the supplied random `generator`. Latents should be of shape
881
+ `(batch_size, num_channel, num_frames, height, width)`.
882
+ prompt_embeds (`torch.FloatTensor`, *optional*):
883
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
884
+ provided, text embeddings are generated from the `prompt` input argument.
885
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
886
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
887
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
888
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
889
+ output_type (`str`, *optional*, defaults to `"pil"`):
890
+ The output format of the generated video. Choose between `torch.FloatTensor`, `PIL.Image` or
891
+ `np.array`.
892
+ return_dict (`bool`, *optional*, defaults to `True`):
893
+ Whether or not to return a [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] instead
894
+ of a plain tuple.
895
+ callback (`Callable`, *optional*):
896
+ A function that calls every `callback_steps` steps during inference. The function is called with the
897
+ following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
898
+ callback_steps (`int`, *optional*, defaults to 1):
899
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
900
+ every step.
901
+ cross_attention_kwargs (`dict`, *optional*):
902
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
903
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
904
+ clip_skip (`int`, *optional*):
905
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
906
+ the output of the pre-final layer will be used for computing the prompt embeddings.
907
+ Examples:
908
+ Returns:
909
+ [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] or `tuple`:
910
+ If `return_dict` is `True`, [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] is
911
+ returned, otherwise a `tuple` is returned where the first element is a list with the generated frames.
912
+ """
913
+ # 0. Default height and width to unet
914
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
915
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
916
+
917
+ num_videos_per_prompt = 1
918
+
919
+ # 1. Check inputs. Raise error if not correct
920
+ self.check_inputs(
921
+ prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
922
+ )
923
+
924
+ # 2. Define call parameters
925
+ if prompt is not None and isinstance(prompt, str):
926
+ batch_size = 1
927
+ elif prompt is not None and isinstance(prompt, list):
928
+ batch_size = len(prompt)
929
+ else:
930
+ batch_size = prompt_embeds.shape[0]
931
+
932
+ device = self._execution_device
933
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
934
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
935
+ # corresponds to doing no classifier free guidance.
936
+ do_classifier_free_guidance = guidance_scale > 1.0
937
+
938
+ # 3. Encode input prompt
939
+ text_encoder_lora_scale = (
940
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
941
+ )
942
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
943
+ prompt,
944
+ device,
945
+ num_videos_per_prompt,
946
+ do_classifier_free_guidance,
947
+ negative_prompt,
948
+ prompt_embeds=prompt_embeds,
949
+ negative_prompt_embeds=negative_prompt_embeds,
950
+ lora_scale=text_encoder_lora_scale,
951
+ clip_skip=clip_skip,
952
+ )
953
+ # For classifier free guidance, we need to do two forward passes.
954
+ # Here we concatenate the unconditional and text embeddings into a single batch
955
+ # to avoid doing two forward passes
956
+ if do_classifier_free_guidance:
957
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
958
+
959
+ if ip_adapter_image is not None:
960
+ output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
961
+ image_embeds, negative_image_embeds = self.encode_image(
962
+ ip_adapter_image, device, num_videos_per_prompt, output_hidden_state
963
+ )
964
+ if do_classifier_free_guidance:
965
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
966
+
967
+ # 4. Prepare timesteps
968
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
969
+ timesteps = self.scheduler.timesteps
970
+
971
+ # round num frames to the nearest multiple of context size - overlap
972
+ num_frames = (num_frames // (context_size - overlap)) * (context_size - overlap)
973
+ print(f"Num frames: {num_frames}")
974
+
975
+ # 5. Prepare latent variables
976
+ num_channels_latents = self.unet.config.in_channels
977
+ if(latent_mode == "normal"):
978
+ latents = self.prepare_latents(
979
+ batch_size * num_videos_per_prompt,
980
+ num_channels_latents,
981
+ num_frames,
982
+ height,
983
+ width,
984
+ prompt_embeds.dtype,
985
+ device,
986
+ generator,
987
+ latents,
988
+ )
989
+ if(latent_mode == "same_start"):
990
+ latents = self.prepare_latents_same_start(
991
+ batch_size * num_videos_per_prompt,
992
+ num_channels_latents,
993
+ num_frames,
994
+ height,
995
+ width,
996
+ prompt_embeds.dtype,
997
+ device,
998
+ generator,
999
+ latents,
1000
+ context_size=context_size,
1001
+ overlap=overlap,
1002
+ strength=init_image_strength,
1003
+ )
1004
+ elif(latent_mode == "motion"):
1005
+ latents = self.prepare_motion_latents(
1006
+ batch_size * num_videos_per_prompt,
1007
+ num_channels_latents,
1008
+ num_frames,
1009
+ height,
1010
+ width,
1011
+ prompt_embeds.dtype,
1012
+ device,
1013
+ generator,
1014
+ latents,
1015
+ x_velocity=x_velocity,
1016
+ y_velocity=y_velocity,
1017
+ scale_velocity=scale_velocity,
1018
+ )
1019
+ elif(latent_mode == "correlated"):
1020
+ latents, init_latents = self.prepare_correlated_latents(
1021
+ init_image,
1022
+ init_image_strength,
1023
+ init_noise_correlation,
1024
+ batch_size,
1025
+ num_channels_latents,
1026
+ num_frames,
1027
+ height,
1028
+ width,
1029
+ prompt_embeds.dtype,
1030
+ device,
1031
+ generator,
1032
+ )
1033
+ elif(latent_mode == "consistent"):
1034
+ latents = self.prepare_latents_consistent(
1035
+ batch_size * num_videos_per_prompt,
1036
+ num_channels_latents,
1037
+ num_frames,
1038
+ height,
1039
+ width,
1040
+ prompt_embeds.dtype,
1041
+ device,
1042
+ generator,
1043
+ latents,
1044
+ smooth_weight,
1045
+ smooth_steps,
1046
+ )
1047
+
1048
+
1049
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1050
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1051
+ # 7 Add image embeds for IP-Adapter
1052
+ added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
1053
+
1054
+ # divide the initial latents into context groups
1055
+
1056
+ def context_scheduler(context_size, overlap, offset, total_frames, total_timesteps):
1057
+ # Calculate the number of context groups based on frame count and context size
1058
+ number_of_context_groups = (total_frames // (context_size - overlap))
1059
+ # Initialize a list to store context indexes for all timesteps
1060
+ all_context_indexes = []
1061
+ # Iterate over each timestep
1062
+ for timestep in range(total_timesteps):
1063
+ # Initialize a list to store groups of context indexes for this timestep
1064
+ timestep_context_groups = []
1065
+ # Iterate over each context group
1066
+ for group_index in range(number_of_context_groups):
1067
+ # Initialize a list to store context indexes for this group
1068
+ context_group_indexes = []
1069
+ # Iterate over each index in the context group
1070
+ local_context_size = context_size
1071
+ if timestep <= 1:
1072
+ local_context_size = int(context_size * initial_context_scale)
1073
+ for index in range(local_context_size):
1074
+ # if its the first timestep, spread the indexes out evenly over the full frame range, offset by the group index
1075
+ frame_index = (group_index * (local_context_size - overlap)) + (offset * timestep) + index
1076
+ # If frame index exceeds total frames, wrap around
1077
+ if frame_index >= total_frames:
1078
+ frame_index %= total_frames
1079
+ # Add the frame index to the group's list
1080
+ context_group_indexes.append(frame_index)
1081
+ # Add the group's indexes to the timestep's list
1082
+ timestep_context_groups.append(context_group_indexes)
1083
+ # Add the timestep's context groups to the overall list
1084
+ all_context_indexes.append(timestep_context_groups)
1085
+ return all_context_indexes
1086
+
1087
+ context_indexes = context_scheduler(context_size, overlap, step, num_frames, len(timesteps))
1088
+
1089
+ # Denoising loop
1090
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1091
+ with self.progress_bar(total=len(timesteps)) as progress_bar:
1092
+ for i, t in enumerate(timesteps):
1093
+ noise_pred_uncond_sum = torch.zeros_like(latents).to(device).to(dtype=torch.float16)
1094
+ noise_pred_text_sum = torch.zeros_like(latents).to(device).to(dtype=torch.float16)
1095
+ latent_counter = torch.zeros(num_frames).to(device).to(dtype=torch.float16)
1096
+
1097
+ # foreach context group seperately denoise the current timestep
1098
+ for context_group in range(len(context_indexes[i])):
1099
+ # calculate to current indexes, considering overlap
1100
+ current_context_indexes = context_indexes[i][context_group]
1101
+
1102
+ # select the relevent context from the latents
1103
+ current_context_latents = latents[:, :, current_context_indexes, :, :]
1104
+
1105
+ # expand the latents if we are doing classifier free guidance
1106
+ latent_model_input = torch.cat([current_context_latents] * 2) if do_classifier_free_guidance else current_context_latents
1107
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1108
+
1109
+ # predict the noise residual
1110
+ noise_pred = self.unet(
1111
+ latent_model_input,
1112
+ t,
1113
+ encoder_hidden_states=prompt_embeds,
1114
+ cross_attention_kwargs=cross_attention_kwargs,
1115
+ added_cond_kwargs=added_cond_kwargs,
1116
+ ).sample
1117
+
1118
+ # sum the noise predictions for the unconditional and text conditioned noise
1119
+ if do_classifier_free_guidance:
1120
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1121
+
1122
+ # add the ending frames from noise_pred_uncond to the start of the noise_pred_uncond_sum
1123
+ noise_pred_uncond_sum[:, :,current_context_indexes, :, :] += noise_pred_uncond
1124
+ noise_pred_text_sum[:, :,current_context_indexes, :, :] += noise_pred_text
1125
+ #increase the counter for the ending frames
1126
+ latent_counter[current_context_indexes] += 1
1127
+
1128
+ # set the step index to the current batch
1129
+ self.scheduler._step_index = i
1130
+
1131
+ # perform guidance
1132
+ if do_classifier_free_guidance:
1133
+ latent_counter = latent_counter.reshape(1, 1, num_frames, 1, 1)
1134
+ noise_pred_uncond = noise_pred_uncond_sum / latent_counter
1135
+ noise_pred_text = noise_pred_text_sum / latent_counter
1136
+
1137
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1138
+
1139
+ # compute the previous noisy sample x_t -> x_t-1
1140
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1141
+
1142
+ # call the callback, if provided
1143
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1144
+ progress_bar.update()
1145
+ if callback is not None and i % callback_steps == 0:
1146
+ callback(i, t, None)
1147
+
1148
+ if output_type == "latent":
1149
+ return AnimateDiffPipelineOutput(frames=latents)
1150
+
1151
+ # save frames
1152
+ if output_path is not None:
1153
+ output_batch_size = 2 # prevents out of memory errors with large videos
1154
+ num_digits = output_path.count('#') # count the number of '#' characters
1155
+ frame_format = output_path.replace('#' * num_digits, '{:0' + str(num_digits) + 'd}')
1156
+ for batch in range((num_frames + output_batch_size - 1) // output_batch_size):
1157
+ start_id = batch * output_batch_size
1158
+ end_id = min((batch + 1) * output_batch_size, num_frames)
1159
+ video_tensor = self.decode_latents(latents[:, :, start_id:end_id, :, :])
1160
+ video = tensor2vid(video_tensor, self.image_processor, output_type=output_type)
1161
+ for f_id, frame in enumerate(video[0]):
1162
+ frame.save(frame_format.format(start_id + f_id))
1163
+ return output_path
1164
+
1165
+ # Post-processing
1166
+ video_tensor = self.decode_latents(latents)
1167
+
1168
+ if output_type == "pt":
1169
+ video = video_tensor
1170
+ else:
1171
+ video = tensor2vid(video_tensor, self.image_processor, output_type=output_type)
1172
+
1173
+ # Offload all models
1174
+ self.maybe_free_model_hooks()
1175
+
1176
+ if not return_dict:
1177
+ return (video,)
1178
+
1179
+ return AnimateDiffPipelineOutput(frames=video)