smoothieAI commited on
Commit
7fe1725
·
verified ·
1 Parent(s): 0380582

Create pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +1570 -0
pipeline.py ADDED
@@ -0,0 +1,1570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Tuple
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, ControlNetModel
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
+ import time
57
+
58
+
59
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
60
+
61
+ EXAMPLE_DOC_STRING = """
62
+ Examples:
63
+ ```py
64
+ >>> import torch
65
+ >>> from diffusers import MotionAdapter, AnimateDiffPipeline, DDIMScheduler
66
+ >>> from diffusers.utils import export_to_gif
67
+ >>> adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2")
68
+ >>> pipe = AnimateDiffPipeline.from_pretrained("frankjoshua/toonyou_beta6", motion_adapter=adapter)
69
+ >>> pipe.scheduler = DDIMScheduler(beta_schedule="linear", steps_offset=1, clip_sample=False)
70
+ >>> output = pipe(prompt="A corgi walking in the park")
71
+ >>> frames = output.frames[0]
72
+ >>> export_to_gif(frames, "animation.gif")
73
+ ```
74
+ """
75
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
76
+ def retrieve_latents(
77
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
78
+ ):
79
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
80
+ return encoder_output.latent_dist.sample(generator)
81
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
82
+ return encoder_output.latent_dist.mode()
83
+ elif hasattr(encoder_output, "latents"):
84
+ return encoder_output.latents
85
+ else:
86
+ raise AttributeError("Could not access latents of provided encoder_output")
87
+
88
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
89
+ def retrieve_timesteps(
90
+ scheduler,
91
+ num_inference_steps: Optional[int] = None,
92
+ device: Optional[Union[str, torch.device]] = None,
93
+ timesteps: Optional[List[int]] = None,
94
+ **kwargs,
95
+ ):
96
+ """
97
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
98
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
99
+
100
+ Args:
101
+ scheduler (`SchedulerMixin`):
102
+ The scheduler to get timesteps from.
103
+ num_inference_steps (`int`):
104
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
105
+ `timesteps` must be `None`.
106
+ device (`str` or `torch.device`, *optional*):
107
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
108
+ timesteps (`List[int]`, *optional*):
109
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
110
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
111
+ must be `None`.
112
+
113
+ Returns:
114
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
115
+ second element is the number of inference steps.
116
+ """
117
+ if timesteps is not None:
118
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
119
+ # if not accepts_timesteps:
120
+ # raise ValueError(
121
+ # f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
122
+ # f" timestep schedules. Please check whether you are using the correct scheduler."
123
+ # )
124
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
125
+ timesteps = scheduler.timesteps
126
+ num_inference_steps = len(timesteps)
127
+ else:
128
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
129
+ timesteps = scheduler.timesteps
130
+ return timesteps, num_inference_steps
131
+
132
+ def tensor2vid(video: torch.Tensor, processor, output_type="np"):
133
+ # Based on:
134
+ # https://github.com/modelscope/modelscope/blob/1509fdb973e5871f37148a4b5e5964cafd43e64d/modelscope/pipelines/multi_modal/text_to_video_synthesis_pipeline.py#L78
135
+
136
+ batch_size, channels, num_frames, height, width = video.shape
137
+ outputs = []
138
+ for batch_idx in range(batch_size):
139
+ batch_vid = video[batch_idx].permute(1, 0, 2, 3)
140
+ batch_output = processor.postprocess(batch_vid, output_type)
141
+
142
+ outputs.append(batch_output)
143
+
144
+ return outputs
145
+
146
+ @dataclass
147
+ class AnimateDiffPipelineOutput(BaseOutput):
148
+ frames: Union[torch.Tensor, np.ndarray]
149
+
150
+ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, IPAdapterMixin, LoraLoaderMixin):
151
+ r"""
152
+ Pipeline for text-to-video generation.
153
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
154
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
155
+ The pipeline also inherits the following loading methods:
156
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
157
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
158
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
159
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
160
+ Args:
161
+ vae ([`AutoencoderKL`]):
162
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
163
+ text_encoder ([`CLIPTextModel`]):
164
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
165
+ tokenizer (`CLIPTokenizer`):
166
+ A [`~transformers.CLIPTokenizer`] to tokenize text.
167
+ unet ([`UNet2DConditionModel`]):
168
+ A [`UNet2DConditionModel`] used to create a UNetMotionModel to denoise the encoded video latents.
169
+ motion_adapter ([`MotionAdapter`]):
170
+ A [`MotionAdapter`] to be used in combination with `unet` to denoise the encoded video latents.
171
+ scheduler ([`SchedulerMixin`]):
172
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
173
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
174
+ """
175
+
176
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
177
+ _optional_components = ["feature_extractor", "image_encoder","controlnet"]
178
+
179
+ def __init__(
180
+ self,
181
+ vae: AutoencoderKL,
182
+ text_encoder: CLIPTextModel,
183
+ tokenizer: CLIPTokenizer,
184
+ unet: UNet2DConditionModel,
185
+ motion_adapter: MotionAdapter,
186
+ scheduler: Union[
187
+ DDIMScheduler,
188
+ PNDMScheduler,
189
+ LMSDiscreteScheduler,
190
+ EulerDiscreteScheduler,
191
+ EulerAncestralDiscreteScheduler,
192
+ DPMSolverMultistepScheduler,
193
+ ],
194
+ controlnet: Optional[Union[ControlNetModel, MultiControlNetModel]]=None,
195
+ feature_extractor: Optional[CLIPImageProcessor] = None,
196
+ image_encoder: Optional[CLIPVisionModelWithProjection] = None,
197
+ ):
198
+ super().__init__()
199
+ unet = UNetMotionModel.from_unet2d(unet, motion_adapter)
200
+
201
+ self.register_modules(
202
+ vae=vae,
203
+ text_encoder=text_encoder,
204
+ tokenizer=tokenizer,
205
+ unet=unet,
206
+ motion_adapter=motion_adapter,
207
+ controlnet=controlnet,
208
+ scheduler=scheduler,
209
+ feature_extractor=feature_extractor,
210
+ image_encoder=image_encoder,
211
+ )
212
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
213
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
214
+ self.control_image_processor = VaeImageProcessor(
215
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
216
+ )
217
+
218
+ def load_motion_adapter(self,motion_adapter):
219
+ self.register_modules(motion_adapter=motion_adapter)
220
+
221
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt with num_images_per_prompt -> num_videos_per_prompt
222
+ def encode_prompt(
223
+ self,
224
+ prompt,
225
+ device,
226
+ num_images_per_prompt,
227
+ do_classifier_free_guidance,
228
+ negative_prompt=None,
229
+ prompt_embeds: Optional[torch.FloatTensor] = None,
230
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
231
+ lora_scale: Optional[float] = None,
232
+ clip_skip: Optional[int] = None,
233
+ ):
234
+ r"""
235
+ Encodes the prompt into text encoder hidden states.
236
+ Args:
237
+ prompt (`str` or `List[str]`, *optional*):
238
+ prompt to be encoded
239
+ device: (`torch.device`):
240
+ torch device
241
+ num_images_per_prompt (`int`):
242
+ number of images that should be generated per prompt
243
+ do_classifier_free_guidance (`bool`):
244
+ whether to use classifier free guidance or not
245
+ negative_prompt (`str` or `List[str]`, *optional*):
246
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
247
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
248
+ less than `1`).
249
+ prompt_embeds (`torch.FloatTensor`, *optional*):
250
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
251
+ provided, text embeddings will be generated from `prompt` input argument.
252
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
253
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
254
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
255
+ argument.
256
+ lora_scale (`float`, *optional*):
257
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
258
+ clip_skip (`int`, *optional*):
259
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
260
+ the output of the pre-final layer will be used for computing the prompt embeddings.
261
+ """
262
+ # set lora scale so that monkey patched LoRA
263
+ # function of text encoder can correctly access it
264
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
265
+ self._lora_scale = lora_scale
266
+
267
+ # dynamically adjust the LoRA scale
268
+ if not USE_PEFT_BACKEND:
269
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
270
+ else:
271
+ scale_lora_layers(self.text_encoder, lora_scale)
272
+
273
+ if prompt is not None and isinstance(prompt, str):
274
+ batch_size = 1
275
+ elif prompt is not None and isinstance(prompt, list):
276
+ batch_size = len(prompt)
277
+ else:
278
+ batch_size = prompt_embeds.shape[0]
279
+
280
+ if prompt_embeds is None:
281
+ # textual inversion: procecss multi-vector tokens if necessary
282
+ if isinstance(self, TextualInversionLoaderMixin):
283
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
284
+
285
+ text_inputs = self.tokenizer(
286
+ prompt,
287
+ padding="max_length",
288
+ max_length=self.tokenizer.model_max_length,
289
+ truncation=True,
290
+ return_tensors="pt",
291
+ )
292
+ text_input_ids = text_inputs.input_ids
293
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
294
+
295
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
296
+ text_input_ids, untruncated_ids
297
+ ):
298
+ removed_text = self.tokenizer.batch_decode(
299
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
300
+ )
301
+ logger.warning(
302
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
303
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
304
+ )
305
+
306
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
307
+ attention_mask = text_inputs.attention_mask.to(device)
308
+ else:
309
+ attention_mask = None
310
+
311
+ if clip_skip is None:
312
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
313
+ prompt_embeds = prompt_embeds[0]
314
+ else:
315
+ prompt_embeds = self.text_encoder(
316
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
317
+ )
318
+ # Access the `hidden_states` first, that contains a tuple of
319
+ # all the hidden states from the encoder layers. Then index into
320
+ # the tuple to access the hidden states from the desired layer.
321
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
322
+ # We also need to apply the final LayerNorm here to not mess with the
323
+ # representations. The `last_hidden_states` that we typically use for
324
+ # obtaining the final prompt representations passes through the LayerNorm
325
+ # layer.
326
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
327
+
328
+ if self.text_encoder is not None:
329
+ prompt_embeds_dtype = self.text_encoder.dtype
330
+ elif self.unet is not None:
331
+ prompt_embeds_dtype = self.unet.dtype
332
+ else:
333
+ prompt_embeds_dtype = prompt_embeds.dtype
334
+
335
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
336
+
337
+ bs_embed, seq_len, _ = prompt_embeds.shape
338
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
339
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
340
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
341
+
342
+ # get unconditional embeddings for classifier free guidance
343
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
344
+ uncond_tokens: List[str]
345
+ if negative_prompt is None:
346
+ uncond_tokens = [""] * batch_size
347
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
348
+ raise TypeError(
349
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
350
+ f" {type(prompt)}."
351
+ )
352
+ elif isinstance(negative_prompt, str):
353
+ uncond_tokens = [negative_prompt]
354
+ elif batch_size != len(negative_prompt):
355
+ raise ValueError(
356
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
357
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
358
+ " the batch size of `prompt`."
359
+ )
360
+ else:
361
+ uncond_tokens = negative_prompt
362
+
363
+ # textual inversion: procecss multi-vector tokens if necessary
364
+ if isinstance(self, TextualInversionLoaderMixin):
365
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
366
+
367
+ max_length = prompt_embeds.shape[1]
368
+ uncond_input = self.tokenizer(
369
+ uncond_tokens,
370
+ padding="max_length",
371
+ max_length=max_length,
372
+ truncation=True,
373
+ return_tensors="pt",
374
+ )
375
+
376
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
377
+ attention_mask = uncond_input.attention_mask.to(device)
378
+ else:
379
+ attention_mask = None
380
+
381
+ negative_prompt_embeds = self.text_encoder(
382
+ uncond_input.input_ids.to(device),
383
+ attention_mask=attention_mask,
384
+ )
385
+ negative_prompt_embeds = negative_prompt_embeds[0]
386
+
387
+ if do_classifier_free_guidance:
388
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
389
+ seq_len = negative_prompt_embeds.shape[1]
390
+
391
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
392
+
393
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
394
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
395
+
396
+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
397
+ # Retrieve the original scale by scaling back the LoRA layers
398
+ unscale_lora_layers(self.text_encoder, lora_scale)
399
+
400
+ return prompt_embeds, negative_prompt_embeds
401
+
402
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
403
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
404
+ dtype = next(self.image_encoder.parameters()).dtype
405
+
406
+ if not isinstance(image, torch.Tensor):
407
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
408
+
409
+ image = image.to(device=device, dtype=dtype)
410
+ if output_hidden_states:
411
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
412
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
413
+ uncond_image_enc_hidden_states = self.image_encoder(
414
+ torch.zeros_like(image), output_hidden_states=True
415
+ ).hidden_states[-2]
416
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
417
+ num_images_per_prompt, dim=0
418
+ )
419
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
420
+ else:
421
+ image_embeds = self.image_encoder(image).image_embeds
422
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
423
+ uncond_image_embeds = torch.zeros_like(image_embeds)
424
+
425
+ return image_embeds, uncond_image_embeds
426
+
427
+ # Copied from diffusers.pipelines.text_to_video_synthesis/pipeline_text_to_video_synth.TextToVideoSDPipeline.decode_latents
428
+ def decode_latents(self, latents):
429
+ latents = 1 / self.vae.config.scaling_factor * latents
430
+
431
+ batch_size, channels, num_frames, height, width = latents.shape
432
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
433
+
434
+ image = self.vae.decode(latents).sample
435
+ video = (
436
+ image[None, :]
437
+ .reshape(
438
+ (
439
+ batch_size,
440
+ num_frames,
441
+ -1,
442
+ )
443
+ + image.shape[2:]
444
+ )
445
+ .permute(0, 2, 1, 3, 4)
446
+ )
447
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
448
+ video = video.float()
449
+ return video
450
+
451
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
452
+ def enable_vae_slicing(self):
453
+ r"""
454
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
455
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
456
+ """
457
+ self.vae.enable_slicing()
458
+
459
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
460
+ def disable_vae_slicing(self):
461
+ r"""
462
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
463
+ computing decoding in one step.
464
+ """
465
+ self.vae.disable_slicing()
466
+
467
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
468
+ def enable_vae_tiling(self):
469
+ r"""
470
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
471
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
472
+ processing larger images.
473
+ """
474
+ self.vae.enable_tiling()
475
+
476
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
477
+ def disable_vae_tiling(self):
478
+ r"""
479
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
480
+ computing decoding in one step.
481
+ """
482
+ self.vae.disable_tiling()
483
+
484
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_freeu
485
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
486
+ r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.
487
+ The suffixes after the scaling factors represent the stages where they are being applied.
488
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
489
+ that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
490
+ Args:
491
+ s1 (`float`):
492
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
493
+ mitigate "oversmoothing effect" in the enhanced denoising process.
494
+ s2 (`float`):
495
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
496
+ mitigate "oversmoothing effect" in the enhanced denoising process.
497
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
498
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
499
+ """
500
+ if not hasattr(self, "unet"):
501
+ raise ValueError("The pipeline must have `unet` for using FreeU.")
502
+ self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
503
+
504
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_freeu
505
+ def disable_freeu(self):
506
+ """Disables the FreeU mechanism if enabled."""
507
+ self.unet.disable_freeu()
508
+
509
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
510
+ def prepare_extra_step_kwargs(self, generator, eta):
511
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
512
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
513
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
514
+ # and should be between [0, 1]
515
+
516
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
517
+ extra_step_kwargs = {}
518
+ if accepts_eta:
519
+ extra_step_kwargs["eta"] = eta
520
+
521
+ # check if the scheduler accepts generator
522
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
523
+ if accepts_generator:
524
+ extra_step_kwargs["generator"] = generator
525
+ return extra_step_kwargs
526
+
527
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
528
+ def check_inputs(
529
+ self,
530
+ prompt,
531
+ height,
532
+ width,
533
+ callback_steps,
534
+ negative_prompt=None,
535
+ prompt_embeds=None,
536
+ negative_prompt_embeds=None,
537
+ callback_on_step_end_tensor_inputs=None,
538
+ ):
539
+ if height % 8 != 0 or width % 8 != 0:
540
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
541
+
542
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
543
+ raise ValueError(
544
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
545
+ f" {type(callback_steps)}."
546
+ )
547
+ if callback_on_step_end_tensor_inputs is not None and not all(
548
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
549
+ ):
550
+ raise ValueError(
551
+ 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]}"
552
+ )
553
+
554
+ if prompt is not None and prompt_embeds is not None:
555
+ raise ValueError(
556
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
557
+ " only forward one of the two."
558
+ )
559
+ elif prompt is None and prompt_embeds is None:
560
+ raise ValueError(
561
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
562
+ )
563
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
564
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
565
+
566
+ if negative_prompt is not None and negative_prompt_embeds is not None:
567
+ raise ValueError(
568
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
569
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
570
+ )
571
+
572
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
573
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
574
+ raise ValueError(
575
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
576
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
577
+ f" {negative_prompt_embeds.shape}."
578
+ )
579
+
580
+ # Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_synth.TextToVideoSDPipeline.prepare_latents
581
+ def prepare_latents(self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None):
582
+ shape = (
583
+ batch_size,
584
+ num_channels_latents,
585
+ num_frames,
586
+ height // self.vae_scale_factor,
587
+ width // self.vae_scale_factor,
588
+ )
589
+ if isinstance(generator, list) and len(generator) != batch_size:
590
+ raise ValueError(
591
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
592
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
593
+ )
594
+
595
+ if latents is None:
596
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
597
+ else:
598
+ latents = latents.to(device)
599
+
600
+ # scale the initial noise by the standard deviation required by the scheduler
601
+ latents = latents * self.scheduler.init_noise_sigma
602
+ return latents
603
+
604
+ 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):
605
+ shape = (
606
+ batch_size,
607
+ num_channels_latents,
608
+ num_frames,
609
+ height // self.vae_scale_factor,
610
+ width // self.vae_scale_factor,
611
+ )
612
+ if isinstance(generator, list) and len(generator) != batch_size:
613
+ raise ValueError(
614
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
615
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
616
+ )
617
+
618
+ if latents is None:
619
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
620
+ else:
621
+ latents = latents.to(device)
622
+
623
+ # make every (context_size-overlap) frames have the same noise
624
+ loop_size = context_size - overlap
625
+ loop_count = num_frames // loop_size
626
+ for i in range(loop_count):
627
+ # repeat the first frames noise for i*loop_size frame
628
+ # lerp the first frames noise
629
+ latents[:, :, i*loop_size:(i*loop_size)+overlap, :, :] = torch.lerp(latents[:, :, i*loop_size:(i*loop_size)+overlap, :, :], latents[:, :, 0:overlap, :, :], strength)
630
+
631
+ # scale the initial noise by the standard deviation required by the scheduler
632
+ latents = latents * self.scheduler.init_noise_sigma
633
+ return latents
634
+
635
+ 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):
636
+ shape = (
637
+ batch_size,
638
+ num_channels_latents,
639
+ num_frames,
640
+ height // self.vae_scale_factor,
641
+ width // self.vae_scale_factor,
642
+ )
643
+ if isinstance(generator, list) and len(generator) != batch_size:
644
+ raise ValueError(
645
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
646
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
647
+ )
648
+
649
+ if latents is None:
650
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
651
+
652
+ # blend each frame with the surrounding N frames making sure to wrap around at the end
653
+ for i in range(num_frames):
654
+ blended_latent = torch.zeros_like(latents[:, :, i])
655
+ for s in range(-smooth_steps, smooth_steps + 1):
656
+ if s == 0:
657
+ continue
658
+ frame_index = (i + s) % num_frames
659
+ weight = (smooth_steps - abs(s)) / smooth_steps
660
+ blended_latent += latents[:, :, frame_index] * weight
661
+ latents[:, :, i] = blended_latent / (2 * smooth_steps)
662
+
663
+ latents = torch.lerp(randn_tensor(shape, generator=generator, device=device, dtype=dtype),latents, smooth_weight)
664
+ else:
665
+ latents = latents.to(device)
666
+
667
+ # scale the initial noise by the standard deviation required by the scheduler
668
+ latents = latents * self.scheduler.init_noise_sigma
669
+ return latents
670
+
671
+ def prepare_motion_latents(self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator,
672
+ latents=None, x_velocity=0, y_velocity=0, scale_velocity=0):
673
+ shape = (
674
+ batch_size,
675
+ num_channels_latents,
676
+ num_frames,
677
+ height // self.vae_scale_factor,
678
+ width // self.vae_scale_factor,
679
+ )
680
+ if isinstance(generator, list) and len(generator) != batch_size:
681
+ raise ValueError(
682
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
683
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
684
+ )
685
+
686
+ if latents is None:
687
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
688
+ else:
689
+ latents = latents.to(device)
690
+
691
+ # scale the initial noise by the standard deviation required by the scheduler
692
+ latents = latents * self.scheduler.init_noise_sigma
693
+
694
+ for frame in range(num_frames):
695
+ x_offset = int(frame * x_velocity) # Convert to int
696
+ y_offset = int(frame * y_velocity) # Convert to int
697
+ scale_factor = 1 + frame * scale_velocity
698
+
699
+ # Apply offsets
700
+ latents[:, :, frame] = torch.roll(latents[:, :, frame], shifts=(x_offset,), dims=3) # x direction
701
+ latents[:, :, frame] = torch.roll(latents[:, :, frame], shifts=(y_offset,), dims=2) # y direction
702
+
703
+ # Apply scaling - This is a simple approach and might not be ideal for all applications
704
+ if scale_factor != 1:
705
+ scaled_size = (
706
+ int(latents.shape[3] * scale_factor),
707
+ int(latents.shape[4] * scale_factor)
708
+ )
709
+ latents[:, :, frame] = torch.nn.functional.interpolate(
710
+ latents[:, :, frame].unsqueeze(0), size=scaled_size, mode='bilinear', align_corners=False
711
+ ).squeeze(0)
712
+
713
+ return latents
714
+
715
+ def generate_correlated_noise(self, latents, init_noise_correlation):
716
+ cloned_latents = latents.clone()
717
+ p = init_noise_correlation
718
+ flattened_latents = torch.flatten(cloned_latents)
719
+ noise = torch.randn_like(flattened_latents)
720
+ correlated_noise = flattened_latents * p + math.sqrt(1 - p**2) * noise
721
+
722
+ return correlated_noise.reshape(cloned_latents.shape)
723
+
724
+ def generate_correlated_latents(self, latents, init_noise_correlation):
725
+ cloned_latents = latents.clone()
726
+ for i in range(1, cloned_latents.shape[2]):
727
+ p = init_noise_correlation
728
+ flattened_latents = torch.flatten(cloned_latents[:, :, i])
729
+ prev_flattened_latents = torch.flatten(cloned_latents[:, :, i - 1])
730
+ correlated_latents = (prev_flattened_latents * p/math.sqrt((1+p**2))+flattened_latents * math.sqrt(1/(1 + p**2)))
731
+ cloned_latents[:, :, i] = correlated_latents.reshape(cloned_latents[:, :, i].shape)
732
+
733
+ return cloned_latents
734
+
735
+ def generate_correlated_latents_legacy(self, latents, init_noise_correlation):
736
+ cloned_latents = latents.clone()
737
+ for i in range(1, cloned_latents.shape[2]):
738
+ p = init_noise_correlation
739
+ flattened_latents = torch.flatten(cloned_latents[:, :, i])
740
+ prev_flattened_latents = torch.flatten(cloned_latents[:, :, i - 1])
741
+ correlated_latents = (
742
+ prev_flattened_latents * p
743
+ +
744
+ flattened_latents * math.sqrt(1 - p**2)
745
+ )
746
+ cloned_latents[:, :, i] = correlated_latents.reshape(
747
+ cloned_latents[:, :, i].shape
748
+ )
749
+
750
+ return cloned_latents
751
+
752
+ def generate_mixed_noise(self, noise, init_noise_correlation):
753
+ shared_noise = torch.randn_like(noise[0, :, 0])
754
+ for b in range(noise.shape[0]):
755
+ for f in range(noise.shape[2]):
756
+ p = init_noise_correlation
757
+ flattened_latents = torch.flatten(noise[b, :, f])
758
+ shared_latents = torch.flatten(shared_noise)
759
+ correlated_latents = (
760
+ shared_latents * math.sqrt(p**2/(1+p**2)) +
761
+ flattened_latents * math.sqrt(1/(1+p**2))
762
+ )
763
+ noise[b, :, f] = correlated_latents.reshape(noise[b, :, f].shape)
764
+
765
+ return noise
766
+
767
+ def prepare_correlated_latents(
768
+ self,
769
+ init_image,
770
+ init_image_strength,
771
+ init_noise_correlation,
772
+ batch_size,
773
+ num_channels_latents,
774
+ video_length,
775
+ height,
776
+ width,
777
+ dtype,
778
+ device,
779
+ generator,
780
+ latents=None,
781
+ ):
782
+ shape = (
783
+ batch_size,
784
+ num_channels_latents,
785
+ video_length,
786
+ height // self.vae_scale_factor,
787
+ width // self.vae_scale_factor,
788
+ )
789
+
790
+ if init_image is not None:
791
+ start_image = ((torchvision.transforms.functional.pil_to_tensor(init_image))/ 255 )[:3, :, :].to("cuda").to(dtype).unsqueeze(0)
792
+ start_image = (
793
+ self.vae.encode(start_image.mul(2).sub(1))
794
+ .latent_dist.sample()
795
+ .view(1, 4, height // 8, width // 8)
796
+ * 0.18215
797
+ )
798
+ init_latents = start_image.unsqueeze(2).repeat(1, 1, video_length, 1, 1)
799
+ else:
800
+ init_latents = None
801
+
802
+ if isinstance(generator, list) and len(generator) != batch_size:
803
+ raise ValueError(
804
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
805
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
806
+ )
807
+ if latents is None:
808
+ rand_device = "cpu" if device.type == "mps" else device
809
+ if isinstance(generator, list):
810
+ shape = shape
811
+ # shape = (1,) + shape[1:]
812
+ # ignore init latents for batch model
813
+ latents = [torch.randn(shape, generator=generator[i], device=rand_device, dtype=dtype)for i in range(batch_size)]
814
+ latents = torch.cat(latents, dim=0).to(device)
815
+ else:
816
+ if init_latents is not None:
817
+ offset = int(
818
+ init_image_strength * (len(self.scheduler.timesteps) - 1)
819
+ )
820
+ noise = torch.randn_like(init_latents)
821
+ noise = self.generate_correlated_latents(noise, init_noise_correlation)
822
+
823
+ # Eric - some black magic here
824
+ # We should be only adding the noise at timestep[offset], but I noticed that
825
+ # we get more motion and cooler motion if we add the noise at timestep[offset - 1]
826
+ # or offset - 2. However, this breaks the fewer timesteps there are, so let's interpolate
827
+ timesteps = self.scheduler.timesteps
828
+ average_timestep = None
829
+ if offset == 0:
830
+ average_timestep = timesteps[0]
831
+ elif offset == 1:
832
+ average_timestep = (
833
+ timesteps[offset - 1] * (1 - init_image_strength)
834
+ + timesteps[offset] * init_image_strength
835
+ )
836
+ else:
837
+ average_timestep = timesteps[offset - 1]
838
+
839
+ latents = self.scheduler.add_noise(
840
+ init_latents, noise, average_timestep.long()
841
+ )
842
+
843
+ latents = self.scheduler.add_noise(
844
+ latents, torch.randn_like(init_latents), timesteps[-2]
845
+ )
846
+ else:
847
+ latents = torch.randn(
848
+ shape, generator=generator, device=rand_device, dtype=dtype
849
+ ).to(device)
850
+ latents = self.generate_correlated_latents(
851
+ latents, init_noise_correlation
852
+ )
853
+ else:
854
+ if latents.shape != shape:
855
+ raise ValueError(
856
+ f"Unexpected latents shape, got {latents.shape}, expected {shape}"
857
+ )
858
+ latents = latents.to(device)
859
+
860
+ # scale the initial noise by the standard deviation required by the scheduler
861
+ if init_latents is None:
862
+ latents = latents * self.scheduler.init_noise_sigma
863
+ # elif self.unet.trained_initial_frames and init_latents is not None:
864
+ # # we only want to use this as the first frame
865
+ # init_latents[:, :, 1:] = torch.zeros_like(init_latents[:, :, 1:])
866
+
867
+ latents = latents.to(device)
868
+ return latents, init_latents
869
+
870
+ def prepare_video_latents(
871
+ self,
872
+ video,
873
+ height,
874
+ width,
875
+ num_channels_latents,
876
+ batch_size,
877
+ timestep,
878
+ dtype,
879
+ device,
880
+ generator,
881
+ latents=None,
882
+ ):
883
+ # video must be a list of list of images
884
+ # the outer list denotes having multiple videos as input, whereas inner list means the frames of the video
885
+ # as a list of images
886
+ if not isinstance(video[0], list):
887
+ video = [video]
888
+ if latents is None:
889
+ video = torch.cat(
890
+ [self.image_processor.preprocess(vid, height=height, width=width).unsqueeze(0) for vid in video], dim=0
891
+ )
892
+ video = video.to(device=device, dtype=dtype)
893
+ num_frames = video.shape[1]
894
+ else:
895
+ num_frames = latents.shape[2]
896
+
897
+ shape = (
898
+ batch_size,
899
+ num_channels_latents,
900
+ num_frames,
901
+ height // self.vae_scale_factor,
902
+ width // self.vae_scale_factor,
903
+ )
904
+
905
+ if isinstance(generator, list) and len(generator) != batch_size:
906
+ raise ValueError(
907
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
908
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
909
+ )
910
+
911
+ if latents is None:
912
+ # make sure the VAE is in float32 mode, as it overflows in float16
913
+ if self.vae.config.force_upcast:
914
+ video = video.float()
915
+ self.vae.to(dtype=torch.float32)
916
+
917
+ if isinstance(generator, list):
918
+ if len(generator) != batch_size:
919
+ raise ValueError(
920
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
921
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
922
+ )
923
+
924
+ init_latents = [
925
+ retrieve_latents(self.vae.encode(video[i]), generator=generator[i]).unsqueeze(0)
926
+ for i in range(batch_size)
927
+ ]
928
+ else:
929
+ init_latents = [
930
+ retrieve_latents(self.vae.encode(vid), generator=generator).unsqueeze(0) for vid in video
931
+ ]
932
+
933
+ init_latents = torch.cat(init_latents, dim=0)
934
+
935
+ # restore vae to original dtype
936
+ if self.vae.config.force_upcast:
937
+ self.vae.to(dtype)
938
+
939
+ init_latents = init_latents.to(dtype)
940
+ init_latents = self.vae.config.scaling_factor * init_latents
941
+
942
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
943
+ # expand init_latents for batch_size
944
+ error_message = (
945
+ f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
946
+ " images (`image`). Please make sure to update your script to pass as many initial images as text prompts"
947
+ )
948
+ raise ValueError(error_message)
949
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
950
+ raise ValueError(
951
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
952
+ )
953
+ else:
954
+ init_latents = torch.cat([init_latents], dim=0)
955
+
956
+ noise = randn_tensor(init_latents.shape, generator=generator, device=device, dtype=dtype)
957
+ latents = self.scheduler.add_noise(init_latents, noise, timestep).permute(0, 2, 1, 3, 4)
958
+ else:
959
+ if shape != latents.shape:
960
+ # [B, C, F, H, W]
961
+ raise ValueError(f"`latents` expected to have {shape=}, but found {latents.shape=}")
962
+ latents = latents.to(device, dtype=dtype)
963
+
964
+ return latents
965
+
966
+
967
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
968
+ def prepare_control_frames(
969
+ self,
970
+ image,
971
+ width,
972
+ height,
973
+ batch_size,
974
+ num_images_per_prompt,
975
+ device,
976
+ dtype,
977
+ do_classifier_free_guidance=False,
978
+ guess_mode=False,
979
+ ):
980
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
981
+ # image_batch_size = image.shape[0]
982
+ image_batch_size = len(image)
983
+
984
+ # if image_batch_size == 1:
985
+ # repeat_by = batch_size
986
+ # else:
987
+ # # image batch size is the same as prompt batch size
988
+ # repeat_by = num_images_per_prompt
989
+
990
+ # image = image.repeat_interleave(repeat_by, dim=0)
991
+
992
+ image = image.to(device=device, dtype=dtype)
993
+
994
+ # if do_classifier_free_guidance and not guess_mode:
995
+ # image = torch.cat([image] * 2)
996
+
997
+ return image
998
+
999
+ @torch.no_grad()
1000
+ def __call__(
1001
+ self,
1002
+ prompt: Union[str, List[str]] = None,
1003
+ num_frames: Optional[int] = 16,
1004
+ context_size=16,
1005
+ overlap=2,
1006
+ step=1,
1007
+ height: Optional[int] = None,
1008
+ width: Optional[int] = None,
1009
+ num_inference_steps: int = 50,
1010
+ guidance_scale: float = 7.5,
1011
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1012
+ num_videos_per_prompt: Optional[int] = 1,
1013
+ eta: float = 0.0,
1014
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1015
+ latents: Optional[torch.FloatTensor] = None,
1016
+ prompt_embeds: Optional[torch.FloatTensor] = None,
1017
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
1018
+ ip_adapter_image: Optional[Union[PipelineImageInput, List[PipelineImageInput]]] = None,
1019
+ output_type: Optional[str] = "pil",
1020
+ output_path: Optional[str] = None,
1021
+ return_dict: bool = True,
1022
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
1023
+ callback_steps: Optional[int] = 1,
1024
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1025
+ clip_skip: Optional[int] = None,
1026
+ x_velocity: Optional[float] = 0,
1027
+ y_velocity: Optional[float] = 0,
1028
+ scale_velocity: Optional[float] = 0,
1029
+ init_image: Optional[PipelineImageInput] = None,
1030
+ init_image_strength: Optional[float] = 1.0,
1031
+ init_noise_correlation: Optional[float] = 0.0,
1032
+ latent_mode: Optional[str] = "normal",
1033
+ smooth_weight: Optional[float] = 0.5,
1034
+ smooth_steps: Optional[int] = 3,
1035
+ initial_context_scale: Optional[float] = 1.0,
1036
+ conditioning_frames: Optional[List[PipelineImageInput]] = None,
1037
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
1038
+ control_guidance_start: Union[float, List[float]] = 0.0,
1039
+ control_guidance_end: Union[float, List[float]] = 1.0,
1040
+ guess_mode: bool = False,
1041
+ ):
1042
+ r"""
1043
+ The call function to the pipeline for generation.
1044
+ Args:
1045
+ prompt (`str` or `List[str]`, *optional*):
1046
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
1047
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1048
+ The height in pixels of the generated video.
1049
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1050
+ The width in pixels of the generated video.
1051
+ num_frames (`int`, *optional*, defaults to 16):
1052
+ The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
1053
+ amounts to 2 seconds of video.
1054
+ num_inference_steps (`int`, *optional*, defaults to 50):
1055
+ The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
1056
+ expense of slower inference.
1057
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1058
+ A higher guidance scale value encourages the model to generate images closely linked to the text
1059
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
1060
+ negative_prompt (`str` or `List[str]`, *optional*):
1061
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
1062
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
1063
+ eta (`float`, *optional*, defaults to 0.0):
1064
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
1065
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
1066
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1067
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
1068
+ generation deterministic.
1069
+ latents (`torch.FloatTensor`, *optional*):
1070
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for video
1071
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1072
+ tensor is generated by sampling using the supplied random `generator`. Latents should be of shape
1073
+ `(batch_size, num_channel, num_frames, height, width)`.
1074
+ prompt_embeds (`torch.FloatTensor`, *optional*):
1075
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
1076
+ provided, text embeddings are generated from the `prompt` input argument.
1077
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1078
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1079
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
1080
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1081
+ output_type (`str`, *optional*, defaults to `"pil"`):
1082
+ The output format of the generated video. Choose between `torch.FloatTensor`, `PIL.Image` or
1083
+ `np.array`.
1084
+ return_dict (`bool`, *optional*, defaults to `True`):
1085
+ Whether or not to return a [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] instead
1086
+ of a plain tuple.
1087
+ callback (`Callable`, *optional*):
1088
+ A function that calls every `callback_steps` steps during inference. The function is called with the
1089
+ following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
1090
+ callback_steps (`int`, *optional*, defaults to 1):
1091
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
1092
+ every step.
1093
+ cross_attention_kwargs (`dict`, *optional*):
1094
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
1095
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1096
+ clip_skip (`int`, *optional*):
1097
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1098
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1099
+ Examples:
1100
+ Returns:
1101
+ [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] or `tuple`:
1102
+ If `return_dict` is `True`, [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] is
1103
+ returned, otherwise a `tuple` is returned where the first element is a list with the generated frames.
1104
+ """
1105
+
1106
+ if self.controlnet != None:
1107
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
1108
+
1109
+ # align format for control guidance
1110
+ control_end = control_guidance_end
1111
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
1112
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
1113
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
1114
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1115
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
1116
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
1117
+ control_guidance_start, control_guidance_end = (
1118
+ mult * [control_guidance_start],
1119
+ mult * [control_guidance_end],
1120
+ )
1121
+
1122
+
1123
+ # 0. Default height and width to unet
1124
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
1125
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
1126
+
1127
+ num_videos_per_prompt = 1
1128
+
1129
+ # 1. Check inputs. Raise error if not correct
1130
+ self.check_inputs(
1131
+ prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
1132
+ )
1133
+
1134
+ # 2. Define call parameters
1135
+ if prompt is not None and isinstance(prompt, str):
1136
+ batch_size = 1
1137
+ elif prompt is not None and isinstance(prompt, list):
1138
+ batch_size = len(prompt)
1139
+ else:
1140
+ batch_size = 1
1141
+
1142
+
1143
+ device = self._execution_device
1144
+
1145
+ if self.controlnet != None:
1146
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
1147
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
1148
+
1149
+ global_pool_conditions = (
1150
+ controlnet.config.global_pool_conditions
1151
+ if isinstance(controlnet, ControlNetModel)
1152
+ else controlnet.nets[0].config.global_pool_conditions
1153
+ )
1154
+ guess_mode = guess_mode or global_pool_conditions
1155
+
1156
+
1157
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1158
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1159
+ # corresponds to doing no classifier free guidance.
1160
+ do_classifier_free_guidance = guidance_scale > 1.0
1161
+
1162
+ # 3. Encode input prompt
1163
+ text_encoder_lora_scale = (
1164
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1165
+ )
1166
+
1167
+ # if promptEmbeds size
1168
+ num_prompts = prompt_embeds.size(0) if prompt_embeds is not None else 0
1169
+ # foreach prompt embed
1170
+
1171
+ prompt_embeds_list = []
1172
+ for p in range(num_prompts):
1173
+ single_prompt_embeds, single_negative_prompt_embeds = self.encode_prompt(
1174
+ prompt,
1175
+ device,
1176
+ num_videos_per_prompt,
1177
+ do_classifier_free_guidance,
1178
+ negative_prompt,
1179
+ prompt_embeds=prompt_embeds[p].unsqueeze(0),
1180
+ negative_prompt_embeds=negative_prompt_embeds[p].unsqueeze(0),
1181
+ lora_scale=text_encoder_lora_scale,
1182
+ clip_skip=clip_skip,
1183
+ )
1184
+
1185
+ # For classifier free guidance, we need to do two forward passes.
1186
+ # Here we concatenate the unconditional and text embeddings into a single batch
1187
+ # to avoid doing two forward passes
1188
+ if do_classifier_free_guidance:
1189
+ # concatenate negative prompt embeddings with prompt embeddings on a new dimension after the first batch dimension
1190
+ single_prompt_embeds = torch.cat([single_negative_prompt_embeds, single_prompt_embeds])
1191
+
1192
+ prompt_embeds_list.append(single_prompt_embeds)
1193
+
1194
+ if ip_adapter_image is not None:
1195
+ output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
1196
+ # foreach ip_adapter_image in ip_adapter_image
1197
+ image_embed_list = []
1198
+ # if ip_adapter_image is not list, convert to list
1199
+ ip_adapter_image = [ip_adapter_image] if not isinstance(ip_adapter_image, list) else ip_adapter_image
1200
+ for image in ip_adapter_image:
1201
+ image_embeds, negative_image_embeds = self.encode_image(image, device, num_videos_per_prompt, output_hidden_state)
1202
+ if do_classifier_free_guidance:image_embeds = torch.cat([negative_image_embeds, image_embeds])
1203
+ image_embed_list.append(image_embeds)
1204
+ image_embeds = image_embed_list
1205
+ if self.controlnet != None:
1206
+ if isinstance(controlnet, ControlNetModel):
1207
+ # conditioning_frames = self.prepare_image(
1208
+ # image=conditioning_frames,
1209
+ # width=width,
1210
+ # height=height,
1211
+ # batch_size=batch_size * num_videos_per_prompt * num_frames,
1212
+ # num_images_per_prompt=num_videos_per_prompt,
1213
+ # device=device,
1214
+ # dtype=controlnet.dtype,
1215
+ # do_classifier_free_guidance=self.do_classifier_free_guidance,
1216
+ # guess_mode=guess_mode,
1217
+ # )
1218
+ conditioning_frames = self.prepare_control_frames(
1219
+ image=conditioning_frames,
1220
+ width=width,
1221
+ height=height,
1222
+ batch_size=batch_size * num_videos_per_prompt * num_frames,
1223
+ num_images_per_prompt=num_videos_per_prompt,
1224
+ device=device,
1225
+ dtype=controlnet.dtype,
1226
+ do_classifier_free_guidance=do_classifier_free_guidance,
1227
+ guess_mode=guess_mode,
1228
+ )
1229
+
1230
+ elif isinstance(controlnet, MultiControlNetModel):
1231
+ cond_prepared_frames = []
1232
+ for frame_ in conditioning_frames:
1233
+ # prepared_frame = self.prepare_image(
1234
+ # image=frame_,
1235
+ # width=width,
1236
+ # height=height,
1237
+ # batch_size=batch_size * num_videos_per_prompt * num_frames,
1238
+ # num_images_per_prompt=num_videos_per_prompt,
1239
+ # device=device,
1240
+ # dtype=controlnet.dtype,
1241
+ # do_classifier_free_guidance=self.do_classifier_free_guidance,
1242
+ # guess_mode=guess_mode,
1243
+ # )
1244
+
1245
+ prepared_frame = self.prepare_control_frames(
1246
+ image=frame_,
1247
+ width=width,
1248
+ height=height,
1249
+ batch_size=batch_size * num_videos_per_prompt * num_frames,
1250
+ num_images_per_prompt=num_videos_per_prompt,
1251
+ device=device,
1252
+ dtype=controlnet.dtype,
1253
+ do_classifier_free_guidance=do_classifier_free_guidance,
1254
+ guess_mode=guess_mode,
1255
+ )
1256
+
1257
+ cond_prepared_frames.append(prepared_frame)
1258
+
1259
+ conditioning_frames = cond_prepared_frames
1260
+ else:
1261
+ assert False
1262
+
1263
+ # 4. Prepare timesteps
1264
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1265
+ timesteps = self.scheduler.timesteps
1266
+
1267
+
1268
+ # round num frames to the nearest multiple of context size - overlap
1269
+ num_frames = (num_frames // (context_size - overlap)) * (context_size - overlap)
1270
+
1271
+ # 5. Prepare latent variables
1272
+ num_channels_latents = self.unet.config.in_channels
1273
+ if(latent_mode == "normal"):
1274
+ latents = self.prepare_latents(
1275
+ batch_size * num_videos_per_prompt,
1276
+ num_channels_latents,
1277
+ num_frames,
1278
+ height,
1279
+ width,
1280
+ prompt_embeds.dtype,
1281
+ device,
1282
+ generator,
1283
+ latents,
1284
+ )
1285
+ if(latent_mode == "same_start"):
1286
+ latents = self.prepare_latents_same_start(
1287
+ batch_size * num_videos_per_prompt,
1288
+ num_channels_latents,
1289
+ num_frames,
1290
+ height,
1291
+ width,
1292
+ prompt_embeds.dtype,
1293
+ device,
1294
+ generator,
1295
+ latents,
1296
+ context_size=context_size,
1297
+ overlap=overlap,
1298
+ strength=init_image_strength,
1299
+ )
1300
+ elif(latent_mode == "motion"):
1301
+ latents = self.prepare_motion_latents(
1302
+ batch_size * num_videos_per_prompt,
1303
+ num_channels_latents,
1304
+ num_frames,
1305
+ height,
1306
+ width,
1307
+ prompt_embeds.dtype,
1308
+ device,
1309
+ generator,
1310
+ latents,
1311
+ x_velocity=x_velocity,
1312
+ y_velocity=y_velocity,
1313
+ scale_velocity=scale_velocity,
1314
+ )
1315
+ elif(latent_mode == "correlated"):
1316
+ latents, init_latents = self.prepare_correlated_latents(
1317
+ init_image,
1318
+ init_image_strength,
1319
+ init_noise_correlation,
1320
+ batch_size,
1321
+ num_channels_latents,
1322
+ num_frames,
1323
+ height,
1324
+ width,
1325
+ prompt_embeds.dtype,
1326
+ device,
1327
+ generator,
1328
+ )
1329
+ elif(latent_mode == "consistent"):
1330
+ latents = self.prepare_latents_consistent(
1331
+ batch_size * num_videos_per_prompt,
1332
+ num_channels_latents,
1333
+ num_frames,
1334
+ height,
1335
+ width,
1336
+ prompt_embeds.dtype,
1337
+ device,
1338
+ generator,
1339
+ latents,
1340
+ smooth_weight,
1341
+ smooth_steps,
1342
+ )
1343
+ elif(latent_mode == "video"):
1344
+ # 4. Prepare timesteps
1345
+ # timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1346
+ # timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, init_image_strength, device)
1347
+ latent_timestep = timesteps[:1].repeat(batch_size * num_videos_per_prompt)
1348
+ self._num_timesteps = len(timesteps)
1349
+ num_channels_latents = self.unet.config.in_channels
1350
+ latents = self.prepare_video_latents(
1351
+ video=init_image,
1352
+ height=height,
1353
+ width=width,
1354
+ num_channels_latents=num_channels_latents,
1355
+ batch_size=batch_size * num_videos_per_prompt,
1356
+ timestep=latent_timestep,
1357
+ dtype=prompt_embeds.dtype,
1358
+ device=device,
1359
+ generator=generator,
1360
+ latents=latents,
1361
+ )
1362
+
1363
+
1364
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1365
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1366
+
1367
+
1368
+ # 7.1 Create tensor stating which controlnets to keep
1369
+ if self.controlnet != None:
1370
+ controlnet_keep = []
1371
+ for i in range(len(timesteps)):
1372
+ keeps = [
1373
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
1374
+ for s, e in zip(control_guidance_start, control_guidance_end)
1375
+ ]
1376
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
1377
+
1378
+ # divide the initial latents into context groups
1379
+
1380
+ def context_scheduler(context_size, overlap, offset, total_frames, total_timesteps):
1381
+ # Calculate the number of context groups based on frame count and context size
1382
+ number_of_context_groups = (total_frames // (context_size - overlap))
1383
+ # Initialize a list to store context indexes for all timesteps
1384
+ all_context_indexes = []
1385
+ # Iterate over each timestep
1386
+ for timestep in range(total_timesteps):
1387
+ # Initialize a list to store groups of context indexes for this timestep
1388
+ timestep_context_groups = []
1389
+ # Iterate over each context group
1390
+ for group_index in range(number_of_context_groups):
1391
+ # Initialize a list to store context indexes for this group
1392
+ context_group_indexes = []
1393
+ # Iterate over each index in the context group
1394
+ local_context_size = context_size
1395
+ if timestep <= 1:
1396
+ local_context_size = int(context_size * initial_context_scale)
1397
+ for index in range(local_context_size):
1398
+ # if its the first timestep, spread the indexes out evenly over the full frame range, offset by the group index
1399
+ frame_index = (group_index * (local_context_size - overlap)) + (offset * timestep) + index
1400
+ # If frame index exceeds total frames, wrap around
1401
+ if frame_index >= total_frames:
1402
+ frame_index %= total_frames
1403
+ # Add the frame index to the group's list
1404
+ context_group_indexes.append(frame_index)
1405
+ # Add the group's indexes to the timestep's list
1406
+ timestep_context_groups.append(context_group_indexes)
1407
+ # Add the timestep's context groups to the overall list
1408
+ all_context_indexes.append(timestep_context_groups)
1409
+ return all_context_indexes
1410
+
1411
+ context_indexes = context_scheduler(context_size, overlap, step, num_frames, len(timesteps))
1412
+
1413
+ # Denoising loop
1414
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1415
+ with self.progress_bar(total=len(timesteps)) as progress_bar:
1416
+ for i, t in enumerate(timesteps):
1417
+ noise_pred_uncond_sum = torch.zeros_like(latents).to(device).to(dtype=torch.float16)
1418
+ noise_pred_text_sum = torch.zeros_like(latents).to(device).to(dtype=torch.float16)
1419
+ latent_counter = torch.zeros(num_frames).to(device).to(dtype=torch.float16)
1420
+
1421
+ # foreach context group seperately denoise the current timestep
1422
+ for context_group in range(len(context_indexes[i])):
1423
+ # calculate to current indexes, considering overlapa
1424
+ current_context_indexes = context_indexes[i][context_group]
1425
+
1426
+ # select the relevent context from the latents
1427
+ current_context_latents = latents[:, :, current_context_indexes, :, :]
1428
+
1429
+ # expand the latents if we are doing classifier free guidance
1430
+ latent_model_input = torch.cat([current_context_latents] * 2) if do_classifier_free_guidance else current_context_latents
1431
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1432
+
1433
+ # get the current prompt index based on the current context group (for blending between multiple prompts)
1434
+ current_prompt_index = int((context_group / len(context_indexes[i])) * len(prompt_embeds_list))
1435
+
1436
+ # 7 Add image embeds for IP-Adapter
1437
+ added_cond_kwargs = {"image_embeds": image_embeds[min(current_prompt_index, len(image_embeds) - 1)]} if ip_adapter_image is not None else None
1438
+
1439
+ if self.controlnet != None and i < int(control_end*num_inference_steps):
1440
+
1441
+ current_context_conditioning_frames = conditioning_frames[current_context_indexes, :, :, :]
1442
+ current_context_conditioning_frames = torch.cat([current_context_conditioning_frames] * 2) if do_classifier_free_guidance else current_context_conditioning_frames
1443
+
1444
+
1445
+ if guess_mode and self.do_classifier_free_guidance:
1446
+ # Infer ControlNet only for the conditional batch.
1447
+ control_model_input = latents
1448
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1449
+ controlnet_prompt_embeds = prompt_embeds_list[current_prompt_index].chunk(2)[1]
1450
+ else:
1451
+ control_model_input = latent_model_input
1452
+ controlnet_prompt_embeds = prompt_embeds_list[current_prompt_index]
1453
+ controlnet_prompt_embeds = controlnet_prompt_embeds.repeat_interleave(len(current_context_indexes), dim=0)
1454
+
1455
+ if isinstance(controlnet_keep[i], list):
1456
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1457
+ else:
1458
+ controlnet_cond_scale = controlnet_conditioning_scale
1459
+ if isinstance(controlnet_cond_scale, list):
1460
+ controlnet_cond_scale = controlnet_cond_scale[0]
1461
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1462
+
1463
+
1464
+ control_model_input = torch.transpose(control_model_input, 1, 2)
1465
+ control_model_input = control_model_input.reshape(
1466
+ (-1, control_model_input.shape[2], control_model_input.shape[3], control_model_input.shape[4])
1467
+ )
1468
+
1469
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1470
+ control_model_input,
1471
+ t,
1472
+ encoder_hidden_states=controlnet_prompt_embeds,
1473
+ controlnet_cond=current_context_conditioning_frames,
1474
+ conditioning_scale=cond_scale,
1475
+ guess_mode=guess_mode,
1476
+ return_dict=False,
1477
+ )
1478
+
1479
+ # predict the noise residual with the added controlnet residuals
1480
+ noise_pred = self.unet(
1481
+ latent_model_input,
1482
+ t,
1483
+ encoder_hidden_states=prompt_embeds_list[current_prompt_index],
1484
+ cross_attention_kwargs=cross_attention_kwargs,
1485
+ added_cond_kwargs=added_cond_kwargs,
1486
+ down_block_additional_residuals=down_block_res_samples,
1487
+ mid_block_additional_residual=mid_block_res_sample,
1488
+ ).sample
1489
+
1490
+ else:
1491
+ noise_pred = self.unet(
1492
+ latent_model_input,
1493
+ t,
1494
+ encoder_hidden_states=prompt_embeds_list[current_prompt_index],
1495
+ cross_attention_kwargs=cross_attention_kwargs,
1496
+ added_cond_kwargs=added_cond_kwargs,
1497
+ ).sample
1498
+
1499
+ if do_classifier_free_guidance:
1500
+
1501
+ noise_pred_uncond, noise_pred_text = torch.chunk(noise_pred, 2, dim=0)
1502
+
1503
+ # Perform batch addition
1504
+ noise_pred_uncond_sum[..., current_context_indexes, :, :] += noise_pred_uncond
1505
+ noise_pred_text_sum[..., current_context_indexes, :, :] += noise_pred_text
1506
+ latent_counter[current_context_indexes] += 1
1507
+
1508
+ # set the step index to the current batch
1509
+ self.scheduler._step_index = i
1510
+
1511
+ # perform guidance
1512
+ if do_classifier_free_guidance:
1513
+ latent_counter = latent_counter.reshape(1, 1, num_frames, 1, 1)
1514
+ noise_pred_uncond = noise_pred_uncond_sum / latent_counter
1515
+ noise_pred_text = noise_pred_text_sum / latent_counter
1516
+
1517
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1518
+
1519
+ # compute the previous noisy sample x_t -> x_t-1
1520
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1521
+
1522
+ # call the callback, if provided
1523
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1524
+ progress_bar.update()
1525
+ if callback is not None and i % callback_steps == 0:
1526
+ callback(i, t, None)
1527
+
1528
+ if output_type == "latent":
1529
+ return AnimateDiffPipelineOutput(frames=latents)
1530
+
1531
+ # save frames
1532
+ if output_path is not None:
1533
+ output_batch_size = 2 # prevents out of memory errors with large videos
1534
+ num_digits = output_path.count('#') # count the number of '#' characters
1535
+ frame_format = output_path.replace('#' * num_digits, '{:0' + str(num_digits) + 'd}')
1536
+
1537
+ # if we had more then one prompt, we need to offset the video frames back by number of inference steps
1538
+ if len(prompt_embeds_list) > 1:
1539
+
1540
+ # wrap the first n number of frames to the end of the video to fix the offseting from the context scheduler
1541
+ offset_frames = num_inference_steps
1542
+ print("Offsetting video frames by ", offset_frames)
1543
+ latents = torch.cat((latents[:, :, offset_frames:, :, :], latents[:, :, :offset_frames, :, :]), dim=2)
1544
+
1545
+ for batch in range((num_frames + output_batch_size - 1) // output_batch_size):
1546
+ start_id = batch * output_batch_size
1547
+ end_id = min((batch + 1) * output_batch_size, num_frames)
1548
+ video_tensor = self.decode_latents(latents[:, :, start_id:end_id, :, :])
1549
+
1550
+ video = tensor2vid(video_tensor, self.image_processor, output_type=output_type)
1551
+ for f_id, frame in enumerate(video[0]):
1552
+ frame.save(frame_format.format(start_id + f_id))
1553
+ return output_path
1554
+
1555
+
1556
+ # Post-processing
1557
+ video_tensor = self.decode_latents(latents)
1558
+
1559
+ if output_type == "pt":
1560
+ video = video_tensor
1561
+ else:
1562
+ video = tensor2vid(video_tensor, self.image_processor, output_type=output_type)
1563
+
1564
+ # Offload all models
1565
+ self.maybe_free_model_hooks()
1566
+
1567
+ if not return_dict:
1568
+ return (video,)
1569
+
1570
+ return AnimateDiffPipelineOutput(frames=video)