AlanB commited on
Commit
1758d32
1 Parent(s): eaf3c7d

Had to fix No module named 'diffusers.models.unet_motion_model'

Browse files

They forgot .unets, I should submit the error. Used in https://DiffusionDeluxe.com

Files changed (1) hide show
  1. pipeline.py +990 -0
pipeline.py ADDED
@@ -0,0 +1,990 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 types import FunctionType
18
+ from typing import Any, Callable, Dict, List, Optional, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
23
+
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.models.unets.unet_motion_model import MotionAdapter
30
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
31
+ from diffusers.schedulers import (
32
+ DDIMScheduler,
33
+ DPMSolverMultistepScheduler,
34
+ EulerAncestralDiscreteScheduler,
35
+ EulerDiscreteScheduler,
36
+ LMSDiscreteScheduler,
37
+ PNDMScheduler,
38
+ )
39
+ from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, logging, scale_lora_layers, unscale_lora_layers
40
+ from diffusers.utils.torch_utils import randn_tensor
41
+
42
+
43
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
44
+
45
+ EXAMPLE_DOC_STRING = """
46
+ Examples:
47
+ ```py
48
+ >>> import torch
49
+ >>> from diffusers import MotionAdapter, DiffusionPipeline, DDIMScheduler
50
+ >>> from diffusers.utils import export_to_gif, load_image
51
+
52
+ >>> adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2")
53
+ >>> pipe = DiffusionPipeline.from_pretrained("SG161222/Realistic_Vision_V5.1_noVAE", motion_adapter=adapter, custom_pipeline="pipeline_animatediff_img2video").to("cuda")
54
+ >>> pipe.scheduler = DDIMScheduler(beta_schedule="linear", steps_offset=1, clip_sample=False, timespace_spacing="linspace")
55
+
56
+ >>> image = load_image("snail.png")
57
+ >>> output = pipe(image=image, prompt="A snail moving on the ground", strength=0.8, latent_interpolation_method="slerp")
58
+ >>> frames = output.frames[0]
59
+ >>> export_to_gif(frames, "animation.gif")
60
+ ```
61
+ """
62
+
63
+
64
+ def lerp(
65
+ v0: torch.Tensor,
66
+ v1: torch.Tensor,
67
+ t: Union[float, torch.Tensor],
68
+ ) -> torch.Tensor:
69
+ r"""
70
+ Linear Interpolation between two tensors.
71
+
72
+ Args:
73
+ v0 (`torch.Tensor`): First tensor.
74
+ v1 (`torch.Tensor`): Second tensor.
75
+ t: (`float` or `torch.Tensor`): Interpolation factor.
76
+ """
77
+ t_is_float = False
78
+ input_device = v0.device
79
+ v0 = v0.cpu().numpy()
80
+ v1 = v1.cpu().numpy()
81
+
82
+ if isinstance(t, torch.Tensor):
83
+ t = t.cpu().numpy()
84
+ else:
85
+ t_is_float = True
86
+ t = np.array([t], dtype=v0.dtype)
87
+
88
+ t = t[..., None]
89
+ v0 = v0[None, ...]
90
+ v1 = v1[None, ...]
91
+ v2 = (1 - t) * v0 + t * v1
92
+
93
+ if t_is_float and v0.ndim > 1:
94
+ assert v2.shape[0] == 1
95
+ v2 = np.squeeze(v2, axis=0)
96
+
97
+ v2 = torch.from_numpy(v2).to(input_device)
98
+ return v2
99
+
100
+
101
+ def slerp(
102
+ v0: torch.Tensor,
103
+ v1: torch.Tensor,
104
+ t: Union[float, torch.Tensor],
105
+ DOT_THRESHOLD: float = 0.9995,
106
+ ) -> torch.Tensor:
107
+ r"""
108
+ Spherical Linear Interpolation between two tensors.
109
+
110
+ Args:
111
+ v0 (`torch.Tensor`): First tensor.
112
+ v1 (`torch.Tensor`): Second tensor.
113
+ t: (`float` or `torch.Tensor`): Interpolation factor.
114
+ DOT_THRESHOLD (`float`):
115
+ Dot product threshold exceeding which linear interpolation will be used
116
+ because input tensors are close to parallel.
117
+ """
118
+ t_is_float = False
119
+ input_device = v0.device
120
+ v0 = v0.cpu().numpy()
121
+ v1 = v1.cpu().numpy()
122
+
123
+ if isinstance(t, torch.Tensor):
124
+ t = t.cpu().numpy()
125
+ else:
126
+ t_is_float = True
127
+ t = np.array([t], dtype=v0.dtype)
128
+
129
+ dot = np.sum(v0 * v1 / (np.linalg.norm(v0) * np.linalg.norm(v1)))
130
+
131
+ if np.abs(dot) > DOT_THRESHOLD:
132
+ # v0 and v1 are close to parallel, so use linear interpolation instead
133
+ v2 = lerp(v0, v1, t)
134
+ else:
135
+ theta_0 = np.arccos(dot)
136
+ sin_theta_0 = np.sin(theta_0)
137
+ theta_t = theta_0 * t
138
+ sin_theta_t = np.sin(theta_t)
139
+ s0 = np.sin(theta_0 - theta_t) / sin_theta_0
140
+ s1 = sin_theta_t / sin_theta_0
141
+ s0 = s0[..., None]
142
+ s1 = s1[..., None]
143
+ v0 = v0[None, ...]
144
+ v1 = v1[None, ...]
145
+ v2 = s0 * v0 + s1 * v1
146
+
147
+ if t_is_float and v0.ndim > 1:
148
+ assert v2.shape[0] == 1
149
+ v2 = np.squeeze(v2, axis=0)
150
+
151
+ v2 = torch.from_numpy(v2).to(input_device)
152
+ return v2
153
+
154
+
155
+ def tensor2vid(video: torch.Tensor, processor, output_type="np"):
156
+ # Based on:
157
+ # https://github.com/modelscope/modelscope/blob/1509fdb973e5871f37148a4b5e5964cafd43e64d/modelscope/pipelines/multi_modal/text_to_video_synthesis_pipeline.py#L78
158
+
159
+ batch_size, channels, num_frames, height, width = video.shape
160
+ outputs = []
161
+ for batch_idx in range(batch_size):
162
+ batch_vid = video[batch_idx].permute(1, 0, 2, 3)
163
+ batch_output = processor.postprocess(batch_vid, output_type)
164
+
165
+ outputs.append(batch_output)
166
+
167
+ return outputs
168
+
169
+
170
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
171
+ def retrieve_latents(
172
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
173
+ ):
174
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
175
+ return encoder_output.latent_dist.sample(generator)
176
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
177
+ return encoder_output.latent_dist.mode()
178
+ elif hasattr(encoder_output, "latents"):
179
+ return encoder_output.latents
180
+ else:
181
+ raise AttributeError("Could not access latents of provided encoder_output")
182
+
183
+
184
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
185
+ def retrieve_timesteps(
186
+ scheduler,
187
+ num_inference_steps: Optional[int] = None,
188
+ device: Optional[Union[str, torch.device]] = None,
189
+ timesteps: Optional[List[int]] = None,
190
+ **kwargs,
191
+ ):
192
+ """
193
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
194
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
195
+
196
+ Args:
197
+ scheduler (`SchedulerMixin`):
198
+ The scheduler to get timesteps from.
199
+ num_inference_steps (`int`):
200
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
201
+ `timesteps` must be `None`.
202
+ device (`str` or `torch.device`, *optional*):
203
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
204
+ timesteps (`List[int]`, *optional*):
205
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
206
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
207
+ must be `None`.
208
+
209
+ Returns:
210
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
211
+ second element is the number of inference steps.
212
+ """
213
+ if timesteps is not None:
214
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
215
+ if not accepts_timesteps:
216
+ raise ValueError(
217
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
218
+ f" timestep schedules. Please check whether you are using the correct scheduler."
219
+ )
220
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
221
+ timesteps = scheduler.timesteps
222
+ num_inference_steps = len(timesteps)
223
+ else:
224
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
225
+ timesteps = scheduler.timesteps
226
+ return timesteps, num_inference_steps
227
+
228
+
229
+ @dataclass
230
+ class AnimateDiffImgToVideoPipelineOutput(BaseOutput):
231
+ frames: Union[torch.Tensor, np.ndarray]
232
+
233
+
234
+ class AnimateDiffImgToVideoPipeline(DiffusionPipeline, TextualInversionLoaderMixin, IPAdapterMixin, LoraLoaderMixin):
235
+ r"""
236
+ Pipeline for text-to-video generation.
237
+
238
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
239
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
240
+
241
+ The pipeline also inherits the following loading methods:
242
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
243
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
244
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
245
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
246
+
247
+ Args:
248
+ vae ([`AutoencoderKL`]):
249
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
250
+ text_encoder ([`CLIPTextModel`]):
251
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
252
+ tokenizer (`CLIPTokenizer`):
253
+ A [`~transformers.CLIPTokenizer`] to tokenize text.
254
+ unet ([`UNet2DConditionModel`]):
255
+ A [`UNet2DConditionModel`] used to create a UNetMotionModel to denoise the encoded video latents.
256
+ motion_adapter ([`MotionAdapter`]):
257
+ A [`MotionAdapter`] to be used in combination with `unet` to denoise the encoded video latents.
258
+ scheduler ([`SchedulerMixin`]):
259
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
260
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
261
+ """
262
+
263
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
264
+ _optional_components = ["feature_extractor", "image_encoder"]
265
+
266
+ def __init__(
267
+ self,
268
+ vae: AutoencoderKL,
269
+ text_encoder: CLIPTextModel,
270
+ tokenizer: CLIPTokenizer,
271
+ unet: UNet2DConditionModel,
272
+ motion_adapter: MotionAdapter,
273
+ scheduler: Union[
274
+ DDIMScheduler,
275
+ PNDMScheduler,
276
+ LMSDiscreteScheduler,
277
+ EulerDiscreteScheduler,
278
+ EulerAncestralDiscreteScheduler,
279
+ DPMSolverMultistepScheduler,
280
+ ],
281
+ feature_extractor: CLIPImageProcessor = None,
282
+ image_encoder: CLIPVisionModelWithProjection = None,
283
+ ):
284
+ super().__init__()
285
+ unet = UNetMotionModel.from_unet2d(unet, motion_adapter)
286
+
287
+ self.register_modules(
288
+ vae=vae,
289
+ text_encoder=text_encoder,
290
+ tokenizer=tokenizer,
291
+ unet=unet,
292
+ motion_adapter=motion_adapter,
293
+ scheduler=scheduler,
294
+ feature_extractor=feature_extractor,
295
+ image_encoder=image_encoder,
296
+ )
297
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
298
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
299
+
300
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt with num_images_per_prompt -> num_videos_per_prompt
301
+ def encode_prompt(
302
+ self,
303
+ prompt,
304
+ device,
305
+ num_images_per_prompt,
306
+ do_classifier_free_guidance,
307
+ negative_prompt=None,
308
+ prompt_embeds: Optional[torch.FloatTensor] = None,
309
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
310
+ lora_scale: Optional[float] = None,
311
+ clip_skip: Optional[int] = None,
312
+ ):
313
+ r"""
314
+ Encodes the prompt into text encoder hidden states.
315
+
316
+ Args:
317
+ prompt (`str` or `List[str]`, *optional*):
318
+ prompt to be encoded
319
+ device: (`torch.device`):
320
+ torch device
321
+ num_images_per_prompt (`int`):
322
+ number of images that should be generated per prompt
323
+ do_classifier_free_guidance (`bool`):
324
+ whether to use classifier free guidance or not
325
+ negative_prompt (`str` or `List[str]`, *optional*):
326
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
327
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
328
+ less than `1`).
329
+ prompt_embeds (`torch.FloatTensor`, *optional*):
330
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
331
+ provided, text embeddings will be generated from `prompt` input argument.
332
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
333
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
334
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
335
+ argument.
336
+ lora_scale (`float`, *optional*):
337
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
338
+ clip_skip (`int`, *optional*):
339
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
340
+ the output of the pre-final layer will be used for computing the prompt embeddings.
341
+ """
342
+ # set lora scale so that monkey patched LoRA
343
+ # function of text encoder can correctly access it
344
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
345
+ self._lora_scale = lora_scale
346
+
347
+ # dynamically adjust the LoRA scale
348
+ if not USE_PEFT_BACKEND:
349
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
350
+ else:
351
+ scale_lora_layers(self.text_encoder, lora_scale)
352
+
353
+ if prompt is not None and isinstance(prompt, str):
354
+ batch_size = 1
355
+ elif prompt is not None and isinstance(prompt, list):
356
+ batch_size = len(prompt)
357
+ else:
358
+ batch_size = prompt_embeds.shape[0]
359
+
360
+ if prompt_embeds is None:
361
+ # textual inversion: procecss multi-vector tokens if necessary
362
+ if isinstance(self, TextualInversionLoaderMixin):
363
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
364
+
365
+ text_inputs = self.tokenizer(
366
+ prompt,
367
+ padding="max_length",
368
+ max_length=self.tokenizer.model_max_length,
369
+ truncation=True,
370
+ return_tensors="pt",
371
+ )
372
+ text_input_ids = text_inputs.input_ids
373
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
374
+
375
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
376
+ text_input_ids, untruncated_ids
377
+ ):
378
+ removed_text = self.tokenizer.batch_decode(
379
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
380
+ )
381
+ logger.warning(
382
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
383
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
384
+ )
385
+
386
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
387
+ attention_mask = text_inputs.attention_mask.to(device)
388
+ else:
389
+ attention_mask = None
390
+
391
+ if clip_skip is None:
392
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
393
+ prompt_embeds = prompt_embeds[0]
394
+ else:
395
+ prompt_embeds = self.text_encoder(
396
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
397
+ )
398
+ # Access the `hidden_states` first, that contains a tuple of
399
+ # all the hidden states from the encoder layers. Then index into
400
+ # the tuple to access the hidden states from the desired layer.
401
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
402
+ # We also need to apply the final LayerNorm here to not mess with the
403
+ # representations. The `last_hidden_states` that we typically use for
404
+ # obtaining the final prompt representations passes through the LayerNorm
405
+ # layer.
406
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
407
+
408
+ if self.text_encoder is not None:
409
+ prompt_embeds_dtype = self.text_encoder.dtype
410
+ elif self.unet is not None:
411
+ prompt_embeds_dtype = self.unet.dtype
412
+ else:
413
+ prompt_embeds_dtype = prompt_embeds.dtype
414
+
415
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
416
+
417
+ bs_embed, seq_len, _ = prompt_embeds.shape
418
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
419
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
420
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
421
+
422
+ # get unconditional embeddings for classifier free guidance
423
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
424
+ uncond_tokens: List[str]
425
+ if negative_prompt is None:
426
+ uncond_tokens = [""] * batch_size
427
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
428
+ raise TypeError(
429
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
430
+ f" {type(prompt)}."
431
+ )
432
+ elif isinstance(negative_prompt, str):
433
+ uncond_tokens = [negative_prompt]
434
+ elif batch_size != len(negative_prompt):
435
+ raise ValueError(
436
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
437
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
438
+ " the batch size of `prompt`."
439
+ )
440
+ else:
441
+ uncond_tokens = negative_prompt
442
+
443
+ # textual inversion: procecss multi-vector tokens if necessary
444
+ if isinstance(self, TextualInversionLoaderMixin):
445
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
446
+
447
+ max_length = prompt_embeds.shape[1]
448
+ uncond_input = self.tokenizer(
449
+ uncond_tokens,
450
+ padding="max_length",
451
+ max_length=max_length,
452
+ truncation=True,
453
+ return_tensors="pt",
454
+ )
455
+
456
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
457
+ attention_mask = uncond_input.attention_mask.to(device)
458
+ else:
459
+ attention_mask = None
460
+
461
+ negative_prompt_embeds = self.text_encoder(
462
+ uncond_input.input_ids.to(device),
463
+ attention_mask=attention_mask,
464
+ )
465
+ negative_prompt_embeds = negative_prompt_embeds[0]
466
+
467
+ if do_classifier_free_guidance:
468
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
469
+ seq_len = negative_prompt_embeds.shape[1]
470
+
471
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
472
+
473
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
474
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
475
+
476
+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
477
+ # Retrieve the original scale by scaling back the LoRA layers
478
+ unscale_lora_layers(self.text_encoder, lora_scale)
479
+
480
+ return prompt_embeds, negative_prompt_embeds
481
+
482
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
483
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
484
+ dtype = next(self.image_encoder.parameters()).dtype
485
+
486
+ if not isinstance(image, torch.Tensor):
487
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
488
+
489
+ image = image.to(device=device, dtype=dtype)
490
+ if output_hidden_states:
491
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
492
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
493
+ uncond_image_enc_hidden_states = self.image_encoder(
494
+ torch.zeros_like(image), output_hidden_states=True
495
+ ).hidden_states[-2]
496
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
497
+ num_images_per_prompt, dim=0
498
+ )
499
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
500
+ else:
501
+ image_embeds = self.image_encoder(image).image_embeds
502
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
503
+ uncond_image_embeds = torch.zeros_like(image_embeds)
504
+
505
+ return image_embeds, uncond_image_embeds
506
+
507
+ # Copied from diffusers.pipelines.text_to_video_synthesis/pipeline_text_to_video_synth.TextToVideoSDPipeline.decode_latents
508
+ def decode_latents(self, latents):
509
+ latents = 1 / self.vae.config.scaling_factor * latents
510
+
511
+ batch_size, channels, num_frames, height, width = latents.shape
512
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
513
+
514
+ image = self.vae.decode(latents).sample
515
+ video = (
516
+ image[None, :]
517
+ .reshape(
518
+ (
519
+ batch_size,
520
+ num_frames,
521
+ -1,
522
+ )
523
+ + image.shape[2:]
524
+ )
525
+ .permute(0, 2, 1, 3, 4)
526
+ )
527
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
528
+ video = video.float()
529
+ return video
530
+
531
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
532
+ def enable_vae_slicing(self):
533
+ r"""
534
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
535
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
536
+ """
537
+ self.vae.enable_slicing()
538
+
539
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
540
+ def disable_vae_slicing(self):
541
+ r"""
542
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
543
+ computing decoding in one step.
544
+ """
545
+ self.vae.disable_slicing()
546
+
547
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
548
+ def enable_vae_tiling(self):
549
+ r"""
550
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
551
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
552
+ processing larger images.
553
+ """
554
+ self.vae.enable_tiling()
555
+
556
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
557
+ def disable_vae_tiling(self):
558
+ r"""
559
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
560
+ computing decoding in one step.
561
+ """
562
+ self.vae.disable_tiling()
563
+
564
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_freeu
565
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
566
+ r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.
567
+
568
+ The suffixes after the scaling factors represent the stages where they are being applied.
569
+
570
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
571
+ that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
572
+
573
+ Args:
574
+ s1 (`float`):
575
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
576
+ mitigate "oversmoothing effect" in the enhanced denoising process.
577
+ s2 (`float`):
578
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
579
+ mitigate "oversmoothing effect" in the enhanced denoising process.
580
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
581
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
582
+ """
583
+ if not hasattr(self, "unet"):
584
+ raise ValueError("The pipeline must have `unet` for using FreeU.")
585
+ self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
586
+
587
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_freeu
588
+ def disable_freeu(self):
589
+ """Disables the FreeU mechanism if enabled."""
590
+ self.unet.disable_freeu()
591
+
592
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
593
+ def prepare_extra_step_kwargs(self, generator, eta):
594
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
595
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
596
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
597
+ # and should be between [0, 1]
598
+
599
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
600
+ extra_step_kwargs = {}
601
+ if accepts_eta:
602
+ extra_step_kwargs["eta"] = eta
603
+
604
+ # check if the scheduler accepts generator
605
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
606
+ if accepts_generator:
607
+ extra_step_kwargs["generator"] = generator
608
+ return extra_step_kwargs
609
+
610
+ def check_inputs(
611
+ self,
612
+ prompt,
613
+ height,
614
+ width,
615
+ callback_steps,
616
+ negative_prompt=None,
617
+ prompt_embeds=None,
618
+ negative_prompt_embeds=None,
619
+ callback_on_step_end_tensor_inputs=None,
620
+ latent_interpolation_method=None,
621
+ ):
622
+ if height % 8 != 0 or width % 8 != 0:
623
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
624
+
625
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
626
+ raise ValueError(
627
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
628
+ f" {type(callback_steps)}."
629
+ )
630
+ if callback_on_step_end_tensor_inputs is not None and not all(
631
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
632
+ ):
633
+ raise ValueError(
634
+ 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]}"
635
+ )
636
+
637
+ if prompt is not None and prompt_embeds is not None:
638
+ raise ValueError(
639
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
640
+ " only forward one of the two."
641
+ )
642
+ elif prompt is None and prompt_embeds is None:
643
+ raise ValueError(
644
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
645
+ )
646
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
647
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
648
+
649
+ if negative_prompt is not None and negative_prompt_embeds is not None:
650
+ raise ValueError(
651
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
652
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
653
+ )
654
+
655
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
656
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
657
+ raise ValueError(
658
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
659
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
660
+ f" {negative_prompt_embeds.shape}."
661
+ )
662
+
663
+ if latent_interpolation_method is not None:
664
+ if latent_interpolation_method not in ["lerp", "slerp"] and not isinstance(
665
+ latent_interpolation_method, FunctionType
666
+ ):
667
+ raise ValueError(
668
+ "`latent_interpolation_method` must be one of `lerp`, `slerp` or a Callable[[torch.Tensor, torch.Tensor, int], torch.Tensor]"
669
+ )
670
+
671
+ def prepare_latents(
672
+ self,
673
+ image,
674
+ strength,
675
+ batch_size,
676
+ num_channels_latents,
677
+ num_frames,
678
+ height,
679
+ width,
680
+ dtype,
681
+ device,
682
+ generator,
683
+ latents=None,
684
+ latent_interpolation_method="slerp",
685
+ ):
686
+ shape = (
687
+ batch_size,
688
+ num_channels_latents,
689
+ num_frames,
690
+ height // self.vae_scale_factor,
691
+ width // self.vae_scale_factor,
692
+ )
693
+
694
+ if latents is None:
695
+ image = image.to(device=device, dtype=dtype)
696
+
697
+ if image.shape[1] == 4:
698
+ latents = image
699
+ else:
700
+ # make sure the VAE is in float32 mode, as it overflows in float16
701
+ if self.vae.config.force_upcast:
702
+ image = image.float()
703
+ self.vae.to(dtype=torch.float32)
704
+
705
+ if isinstance(generator, list):
706
+ if len(generator) != batch_size:
707
+ raise ValueError(
708
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
709
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
710
+ )
711
+
712
+ init_latents = [
713
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
714
+ for i in range(batch_size)
715
+ ]
716
+ init_latents = torch.cat(init_latents, dim=0)
717
+ else:
718
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
719
+
720
+ if self.vae.config.force_upcast:
721
+ self.vae.to(dtype)
722
+
723
+ init_latents = init_latents.to(dtype)
724
+ init_latents = self.vae.config.scaling_factor * init_latents
725
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
726
+ latents = latents * self.scheduler.init_noise_sigma
727
+
728
+ if latent_interpolation_method == "lerp":
729
+
730
+ def latent_cls(v0, v1, index):
731
+ return lerp(v0, v1, index / num_frames * (1 - strength))
732
+ elif latent_interpolation_method == "slerp":
733
+
734
+ def latent_cls(v0, v1, index):
735
+ return slerp(v0, v1, index / num_frames * (1 - strength))
736
+ else:
737
+ latent_cls = latent_interpolation_method
738
+
739
+ for i in range(num_frames):
740
+ latents[:, :, i, :, :] = latent_cls(latents[:, :, i, :, :], init_latents, i)
741
+ else:
742
+ if shape != latents.shape:
743
+ # [B, C, F, H, W]
744
+ raise ValueError(f"`latents` expected to have {shape=}, but found {latents.shape=}")
745
+ latents = latents.to(device, dtype=dtype)
746
+
747
+ return latents
748
+
749
+ @torch.no_grad()
750
+ def __call__(
751
+ self,
752
+ image: PipelineImageInput,
753
+ prompt: Optional[Union[str, List[str]]] = None,
754
+ height: Optional[int] = None,
755
+ width: Optional[int] = None,
756
+ num_frames: int = 16,
757
+ num_inference_steps: int = 50,
758
+ timesteps: Optional[List[int]] = None,
759
+ guidance_scale: float = 7.5,
760
+ strength: float = 0.8,
761
+ negative_prompt: Optional[Union[str, List[str]]] = None,
762
+ num_videos_per_prompt: Optional[int] = 1,
763
+ eta: float = 0.0,
764
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
765
+ latents: Optional[torch.FloatTensor] = None,
766
+ prompt_embeds: Optional[torch.FloatTensor] = None,
767
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
768
+ ip_adapter_image: Optional[PipelineImageInput] = None,
769
+ output_type: Optional[str] = "pil",
770
+ return_dict: bool = True,
771
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
772
+ callback_steps: Optional[int] = 1,
773
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
774
+ clip_skip: Optional[int] = None,
775
+ latent_interpolation_method: Union[str, Callable[[torch.Tensor, torch.Tensor, int], torch.Tensor]] = "slerp",
776
+ ):
777
+ r"""
778
+ The call function to the pipeline for generation.
779
+
780
+ Args:
781
+ image (`PipelineImageInput`):
782
+ The input image to condition the generation on.
783
+ prompt (`str` or `List[str]`, *optional*):
784
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
785
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
786
+ The height in pixels of the generated video.
787
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
788
+ The width in pixels of the generated video.
789
+ num_frames (`int`, *optional*, defaults to 16):
790
+ The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
791
+ amounts to 2 seconds of video.
792
+ num_inference_steps (`int`, *optional*, defaults to 50):
793
+ The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
794
+ expense of slower inference.
795
+ strength (`float`, *optional*, defaults to 0.8):
796
+ Higher strength leads to more differences between original image and generated video.
797
+ guidance_scale (`float`, *optional*, defaults to 7.5):
798
+ A higher guidance scale value encourages the model to generate images closely linked to the text
799
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
800
+ negative_prompt (`str` or `List[str]`, *optional*):
801
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
802
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
803
+ eta (`float`, *optional*, defaults to 0.0):
804
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
805
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
806
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
807
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
808
+ generation deterministic.
809
+ latents (`torch.FloatTensor`, *optional*):
810
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for video
811
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
812
+ tensor is generated by sampling using the supplied random `generator`. Latents should be of shape
813
+ `(batch_size, num_channel, num_frames, height, width)`.
814
+ prompt_embeds (`torch.FloatTensor`, *optional*):
815
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
816
+ provided, text embeddings are generated from the `prompt` input argument.
817
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
818
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
819
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
820
+ ip_adapter_image: (`PipelineImageInput`, *optional*):
821
+ Optional image input to work with IP Adapters.
822
+ output_type (`str`, *optional*, defaults to `"pil"`):
823
+ The output format of the generated video. Choose between `torch.FloatTensor`, `PIL.Image` or
824
+ `np.array`.
825
+ return_dict (`bool`, *optional*, defaults to `True`):
826
+ Whether or not to return a [`AnimateDiffImgToVideoPipelineOutput`] instead
827
+ of a plain tuple.
828
+ callback (`Callable`, *optional*):
829
+ A function that calls every `callback_steps` steps during inference. The function is called with the
830
+ following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
831
+ callback_steps (`int`, *optional*, defaults to 1):
832
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
833
+ every step.
834
+ cross_attention_kwargs (`dict`, *optional*):
835
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
836
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
837
+ clip_skip (`int`, *optional*):
838
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
839
+ the output of the pre-final layer will be used for computing the prompt embeddings.
840
+ latent_interpolation_method (`str` or `Callable[[torch.Tensor, torch.Tensor, int], torch.Tensor]]`, *optional*):
841
+ Must be one of "lerp", "slerp" or a callable that takes in a random noisy latent, image latent and a frame index
842
+ as input and returns an initial latent for sampling.
843
+ Examples:
844
+
845
+ Returns:
846
+ [`AnimateDiffImgToVideoPipelineOutput`] or `tuple`:
847
+ If `return_dict` is `True`, [`AnimateDiffImgToVideoPipelineOutput`] is
848
+ returned, otherwise a `tuple` is returned where the first element is a list with the generated frames.
849
+ """
850
+ # 0. Default height and width to unet
851
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
852
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
853
+
854
+ num_videos_per_prompt = 1
855
+
856
+ # 1. Check inputs. Raise error if not correct
857
+ self.check_inputs(
858
+ prompt=prompt,
859
+ height=height,
860
+ width=width,
861
+ callback_steps=callback_steps,
862
+ negative_prompt=negative_prompt,
863
+ prompt_embeds=prompt_embeds,
864
+ negative_prompt_embeds=negative_prompt_embeds,
865
+ latent_interpolation_method=latent_interpolation_method,
866
+ )
867
+
868
+ # 2. Define call parameters
869
+ if prompt is not None and isinstance(prompt, str):
870
+ batch_size = 1
871
+ elif prompt is not None and isinstance(prompt, list):
872
+ batch_size = len(prompt)
873
+ else:
874
+ batch_size = prompt_embeds.shape[0]
875
+
876
+ device = self._execution_device
877
+
878
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
879
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
880
+ # corresponds to doing no classifier free guidance.
881
+ do_classifier_free_guidance = guidance_scale > 1.0
882
+
883
+ # 3. Encode input prompt
884
+ text_encoder_lora_scale = (
885
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
886
+ )
887
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
888
+ prompt,
889
+ device,
890
+ num_videos_per_prompt,
891
+ do_classifier_free_guidance,
892
+ negative_prompt,
893
+ prompt_embeds=prompt_embeds,
894
+ negative_prompt_embeds=negative_prompt_embeds,
895
+ lora_scale=text_encoder_lora_scale,
896
+ clip_skip=clip_skip,
897
+ )
898
+
899
+ # For classifier free guidance, we need to do two forward passes.
900
+ # Here we concatenate the unconditional and text embeddings into a single batch
901
+ # to avoid doing two forward passes
902
+ if do_classifier_free_guidance:
903
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
904
+
905
+ if ip_adapter_image is not None:
906
+ output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
907
+ image_embeds, negative_image_embeds = self.encode_image(
908
+ ip_adapter_image, device, num_videos_per_prompt, output_hidden_state
909
+ )
910
+ if do_classifier_free_guidance:
911
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
912
+
913
+ # 4. Preprocess image
914
+ image = self.image_processor.preprocess(image, height=height, width=width)
915
+
916
+ # 5. Prepare timesteps
917
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
918
+
919
+ # 6. Prepare latent variables
920
+ num_channels_latents = self.unet.config.in_channels
921
+ latents = self.prepare_latents(
922
+ image=image,
923
+ strength=strength,
924
+ batch_size=batch_size * num_videos_per_prompt,
925
+ num_channels_latents=num_channels_latents,
926
+ num_frames=num_frames,
927
+ height=height,
928
+ width=width,
929
+ dtype=prompt_embeds.dtype,
930
+ device=device,
931
+ generator=generator,
932
+ latents=latents,
933
+ latent_interpolation_method=latent_interpolation_method,
934
+ )
935
+
936
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
937
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
938
+
939
+ # 8. Add image embeds for IP-Adapter
940
+ added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
941
+
942
+ # 9. Denoising loop
943
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
944
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
945
+ for i, t in enumerate(timesteps):
946
+ # expand the latents if we are doing classifier free guidance
947
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
948
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
949
+
950
+ # predict the noise residual
951
+ noise_pred = self.unet(
952
+ latent_model_input,
953
+ t,
954
+ encoder_hidden_states=prompt_embeds,
955
+ cross_attention_kwargs=cross_attention_kwargs,
956
+ added_cond_kwargs=added_cond_kwargs,
957
+ ).sample
958
+
959
+ # perform guidance
960
+ if do_classifier_free_guidance:
961
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
962
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
963
+
964
+ # compute the previous noisy sample x_t -> x_t-1
965
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
966
+
967
+ # call the callback, if provided
968
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
969
+ progress_bar.update()
970
+ if callback is not None and i % callback_steps == 0:
971
+ callback(i, t, latents)
972
+
973
+ if output_type == "latent":
974
+ return AnimateDiffImgToVideoPipelineOutput(frames=latents)
975
+
976
+ # 10. Post-processing
977
+ video_tensor = self.decode_latents(latents)
978
+
979
+ if output_type == "pt":
980
+ video = video_tensor
981
+ else:
982
+ video = tensor2vid(video_tensor, self.image_processor, output_type=output_type)
983
+
984
+ # 11. Offload all models
985
+ self.maybe_free_model_hooks()
986
+
987
+ if not return_dict:
988
+ return (video,)
989
+
990
+ return AnimateDiffImgToVideoPipelineOutput(frames=video)