smoothieAI commited on
Commit
9c621f0
·
1 Parent(s): 3b75e46

Create pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +797 -0
pipeline.py ADDED
@@ -0,0 +1,797 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from dataclasses import dataclass
17
+ from typing import Any, Callable, Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
22
+
23
+ # Updated to use absolute paths
24
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
25
+ from diffusers.loaders import IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
26
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel, UNetMotionModel
27
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
28
+ from diffusers.models.unet_motion_model import MotionAdapter
29
+ from diffusers.schedulers import (
30
+ DDIMScheduler,
31
+ DPMSolverMultistepScheduler,
32
+ EulerAncestralDiscreteScheduler,
33
+ EulerDiscreteScheduler,
34
+ LMSDiscreteScheduler,
35
+ PNDMScheduler,
36
+ )
37
+ from diffusers.utils import (
38
+ USE_PEFT_BACKEND,
39
+ BaseOutput,
40
+ logging,
41
+ scale_lora_layers,
42
+ unscale_lora_layers,
43
+ )
44
+ from diffusers.utils.torch_utils import 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, is_compiled_module
51
+
52
+
53
+
54
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
55
+
56
+ EXAMPLE_DOC_STRING = """
57
+ Examples:
58
+ ```py
59
+ >>> import torch
60
+ >>> from diffusers import MotionAdapter, AnimateDiffPipeline, DDIMScheduler
61
+ >>> from diffusers.utils import export_to_gif
62
+
63
+ >>> adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2")
64
+ >>> pipe = AnimateDiffPipeline.from_pretrained("frankjoshua/toonyou_beta6", motion_adapter=adapter)
65
+ >>> pipe.scheduler = DDIMScheduler(beta_schedule="linear", steps_offset=1, clip_sample=False)
66
+ >>> output = pipe(prompt="A corgi walking in the park")
67
+ >>> frames = output.frames[0]
68
+ >>> export_to_gif(frames, "animation.gif")
69
+ ```
70
+ """
71
+
72
+
73
+ def tensor2vid(video: torch.Tensor, processor, output_type="np"):
74
+ # Based on:
75
+ # https://github.com/modelscope/modelscope/blob/1509fdb973e5871f37148a4b5e5964cafd43e64d/modelscope/pipelines/multi_modal/text_to_video_synthesis_pipeline.py#L78
76
+
77
+ batch_size, channels, num_frames, height, width = video.shape
78
+ outputs = []
79
+ for batch_idx in range(batch_size):
80
+ batch_vid = video[batch_idx].permute(1, 0, 2, 3)
81
+ batch_output = processor.postprocess(batch_vid, output_type)
82
+
83
+ outputs.append(batch_output)
84
+
85
+ return outputs
86
+
87
+
88
+ @dataclass
89
+ class AnimateDiffPipelineOutput(BaseOutput):
90
+ frames: Union[torch.Tensor, np.ndarray]
91
+
92
+
93
+ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, IPAdapterMixin, LoraLoaderMixin):
94
+ r"""
95
+ Pipeline for text-to-video generation.
96
+
97
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
98
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
99
+
100
+ The pipeline also inherits the following loading methods:
101
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
102
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
103
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
104
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
105
+
106
+ Args:
107
+ vae ([`AutoencoderKL`]):
108
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
109
+ text_encoder ([`CLIPTextModel`]):
110
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
111
+ tokenizer (`CLIPTokenizer`):
112
+ A [`~transformers.CLIPTokenizer`] to tokenize text.
113
+ unet ([`UNet2DConditionModel`]):
114
+ A [`UNet2DConditionModel`] used to create a UNetMotionModel to denoise the encoded video latents.
115
+ motion_adapter ([`MotionAdapter`]):
116
+ A [`MotionAdapter`] to be used in combination with `unet` to denoise the encoded video latents.
117
+ scheduler ([`SchedulerMixin`]):
118
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
119
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
120
+ """
121
+
122
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
123
+ _optional_components = ["feature_extractor", "image_encoder"]
124
+
125
+ def __init__(
126
+ self,
127
+ vae: AutoencoderKL,
128
+ text_encoder: CLIPTextModel,
129
+ tokenizer: CLIPTokenizer,
130
+ unet: UNet2DConditionModel,
131
+ motion_adapter: MotionAdapter,
132
+ scheduler: Union[
133
+ DDIMScheduler,
134
+ PNDMScheduler,
135
+ LMSDiscreteScheduler,
136
+ EulerDiscreteScheduler,
137
+ EulerAncestralDiscreteScheduler,
138
+ DPMSolverMultistepScheduler,
139
+ ],
140
+ feature_extractor: CLIPImageProcessor = None,
141
+ image_encoder: CLIPVisionModelWithProjection = None,
142
+ ):
143
+ super().__init__()
144
+ unet = UNetMotionModel.from_unet2d(unet, motion_adapter)
145
+
146
+ self.register_modules(
147
+ vae=vae,
148
+ text_encoder=text_encoder,
149
+ tokenizer=tokenizer,
150
+ unet=unet,
151
+ motion_adapter=motion_adapter,
152
+ scheduler=scheduler,
153
+ feature_extractor=feature_extractor,
154
+ image_encoder=image_encoder,
155
+ )
156
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
157
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
158
+
159
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt with num_images_per_prompt -> num_videos_per_prompt
160
+ def encode_prompt(
161
+ self,
162
+ prompt,
163
+ device,
164
+ num_images_per_prompt,
165
+ do_classifier_free_guidance,
166
+ negative_prompt=None,
167
+ prompt_embeds: Optional[torch.FloatTensor] = None,
168
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
169
+ lora_scale: Optional[float] = None,
170
+ clip_skip: Optional[int] = None,
171
+ ):
172
+ r"""
173
+ Encodes the prompt into text encoder hidden states.
174
+
175
+ Args:
176
+ prompt (`str` or `List[str]`, *optional*):
177
+ prompt to be encoded
178
+ device: (`torch.device`):
179
+ torch device
180
+ num_images_per_prompt (`int`):
181
+ number of images that should be generated per prompt
182
+ do_classifier_free_guidance (`bool`):
183
+ whether to use classifier free guidance or not
184
+ negative_prompt (`str` or `List[str]`, *optional*):
185
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
186
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
187
+ less than `1`).
188
+ prompt_embeds (`torch.FloatTensor`, *optional*):
189
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
190
+ provided, text embeddings will be generated from `prompt` input argument.
191
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
192
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
193
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
194
+ argument.
195
+ lora_scale (`float`, *optional*):
196
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
197
+ clip_skip (`int`, *optional*):
198
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
199
+ the output of the pre-final layer will be used for computing the prompt embeddings.
200
+ """
201
+ # set lora scale so that monkey patched LoRA
202
+ # function of text encoder can correctly access it
203
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
204
+ self._lora_scale = lora_scale
205
+
206
+ # dynamically adjust the LoRA scale
207
+ if not USE_PEFT_BACKEND:
208
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
209
+ else:
210
+ scale_lora_layers(self.text_encoder, lora_scale)
211
+
212
+ if prompt is not None and isinstance(prompt, str):
213
+ batch_size = 1
214
+ elif prompt is not None and isinstance(prompt, list):
215
+ batch_size = len(prompt)
216
+ else:
217
+ batch_size = prompt_embeds.shape[0]
218
+
219
+ if prompt_embeds is None:
220
+ # textual inversion: procecss multi-vector tokens if necessary
221
+ if isinstance(self, TextualInversionLoaderMixin):
222
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
223
+
224
+ text_inputs = self.tokenizer(
225
+ prompt,
226
+ padding="max_length",
227
+ max_length=self.tokenizer.model_max_length,
228
+ truncation=True,
229
+ return_tensors="pt",
230
+ )
231
+ text_input_ids = text_inputs.input_ids
232
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
233
+
234
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
235
+ text_input_ids, untruncated_ids
236
+ ):
237
+ removed_text = self.tokenizer.batch_decode(
238
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
239
+ )
240
+ logger.warning(
241
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
242
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
243
+ )
244
+
245
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
246
+ attention_mask = text_inputs.attention_mask.to(device)
247
+ else:
248
+ attention_mask = None
249
+
250
+ if clip_skip is None:
251
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
252
+ prompt_embeds = prompt_embeds[0]
253
+ else:
254
+ prompt_embeds = self.text_encoder(
255
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
256
+ )
257
+ # Access the `hidden_states` first, that contains a tuple of
258
+ # all the hidden states from the encoder layers. Then index into
259
+ # the tuple to access the hidden states from the desired layer.
260
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
261
+ # We also need to apply the final LayerNorm here to not mess with the
262
+ # representations. The `last_hidden_states` that we typically use for
263
+ # obtaining the final prompt representations passes through the LayerNorm
264
+ # layer.
265
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
266
+
267
+ if self.text_encoder is not None:
268
+ prompt_embeds_dtype = self.text_encoder.dtype
269
+ elif self.unet is not None:
270
+ prompt_embeds_dtype = self.unet.dtype
271
+ else:
272
+ prompt_embeds_dtype = prompt_embeds.dtype
273
+
274
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
275
+
276
+ bs_embed, seq_len, _ = prompt_embeds.shape
277
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
278
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
279
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
280
+
281
+ # get unconditional embeddings for classifier free guidance
282
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
283
+ uncond_tokens: List[str]
284
+ if negative_prompt is None:
285
+ uncond_tokens = [""] * batch_size
286
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
287
+ raise TypeError(
288
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
289
+ f" {type(prompt)}."
290
+ )
291
+ elif isinstance(negative_prompt, str):
292
+ uncond_tokens = [negative_prompt]
293
+ elif batch_size != len(negative_prompt):
294
+ raise ValueError(
295
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
296
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
297
+ " the batch size of `prompt`."
298
+ )
299
+ else:
300
+ uncond_tokens = negative_prompt
301
+
302
+ # textual inversion: procecss multi-vector tokens if necessary
303
+ if isinstance(self, TextualInversionLoaderMixin):
304
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
305
+
306
+ max_length = prompt_embeds.shape[1]
307
+ uncond_input = self.tokenizer(
308
+ uncond_tokens,
309
+ padding="max_length",
310
+ max_length=max_length,
311
+ truncation=True,
312
+ return_tensors="pt",
313
+ )
314
+
315
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
316
+ attention_mask = uncond_input.attention_mask.to(device)
317
+ else:
318
+ attention_mask = None
319
+
320
+ negative_prompt_embeds = self.text_encoder(
321
+ uncond_input.input_ids.to(device),
322
+ attention_mask=attention_mask,
323
+ )
324
+ negative_prompt_embeds = negative_prompt_embeds[0]
325
+
326
+ if do_classifier_free_guidance:
327
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
328
+ seq_len = negative_prompt_embeds.shape[1]
329
+
330
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
331
+
332
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
333
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
334
+
335
+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
336
+ # Retrieve the original scale by scaling back the LoRA layers
337
+ unscale_lora_layers(self.text_encoder, lora_scale)
338
+
339
+ return prompt_embeds, negative_prompt_embeds
340
+
341
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
342
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
343
+ dtype = next(self.image_encoder.parameters()).dtype
344
+
345
+ if not isinstance(image, torch.Tensor):
346
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
347
+
348
+ image = image.to(device=device, dtype=dtype)
349
+ if output_hidden_states:
350
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
351
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
352
+ uncond_image_enc_hidden_states = self.image_encoder(
353
+ torch.zeros_like(image), output_hidden_states=True
354
+ ).hidden_states[-2]
355
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
356
+ num_images_per_prompt, dim=0
357
+ )
358
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
359
+ else:
360
+ image_embeds = self.image_encoder(image).image_embeds
361
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
362
+ uncond_image_embeds = torch.zeros_like(image_embeds)
363
+
364
+ return image_embeds, uncond_image_embeds
365
+
366
+ # Copied from diffusers.pipelines.text_to_video_synthesis/pipeline_text_to_video_synth.TextToVideoSDPipeline.decode_latents
367
+ def decode_latents(self, latents):
368
+ latents = 1 / self.vae.config.scaling_factor * latents
369
+
370
+ batch_size, channels, num_frames, height, width = latents.shape
371
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
372
+
373
+ image = self.vae.decode(latents).sample
374
+ video = (
375
+ image[None, :]
376
+ .reshape(
377
+ (
378
+ batch_size,
379
+ num_frames,
380
+ -1,
381
+ )
382
+ + image.shape[2:]
383
+ )
384
+ .permute(0, 2, 1, 3, 4)
385
+ )
386
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
387
+ video = video.float()
388
+ return video
389
+
390
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing
391
+ def enable_vae_slicing(self):
392
+ r"""
393
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
394
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
395
+ """
396
+ self.vae.enable_slicing()
397
+
398
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing
399
+ def disable_vae_slicing(self):
400
+ r"""
401
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
402
+ computing decoding in one step.
403
+ """
404
+ self.vae.disable_slicing()
405
+
406
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling
407
+ def enable_vae_tiling(self):
408
+ r"""
409
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
410
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
411
+ processing larger images.
412
+ """
413
+ self.vae.enable_tiling()
414
+
415
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling
416
+ def disable_vae_tiling(self):
417
+ r"""
418
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
419
+ computing decoding in one step.
420
+ """
421
+ self.vae.disable_tiling()
422
+
423
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_freeu
424
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
425
+ r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.
426
+
427
+ The suffixes after the scaling factors represent the stages where they are being applied.
428
+
429
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
430
+ that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
431
+
432
+ Args:
433
+ s1 (`float`):
434
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
435
+ mitigate "oversmoothing effect" in the enhanced denoising process.
436
+ s2 (`float`):
437
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
438
+ mitigate "oversmoothing effect" in the enhanced denoising process.
439
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
440
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
441
+ """
442
+ if not hasattr(self, "unet"):
443
+ raise ValueError("The pipeline must have `unet` for using FreeU.")
444
+ self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
445
+
446
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_freeu
447
+ def disable_freeu(self):
448
+ """Disables the FreeU mechanism if enabled."""
449
+ self.unet.disable_freeu()
450
+
451
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
452
+ def prepare_extra_step_kwargs(self, generator, eta):
453
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
454
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
455
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
456
+ # and should be between [0, 1]
457
+
458
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
459
+ extra_step_kwargs = {}
460
+ if accepts_eta:
461
+ extra_step_kwargs["eta"] = eta
462
+
463
+ # check if the scheduler accepts generator
464
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
465
+ if accepts_generator:
466
+ extra_step_kwargs["generator"] = generator
467
+ return extra_step_kwargs
468
+
469
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
470
+ def check_inputs(
471
+ self,
472
+ prompt,
473
+ height,
474
+ width,
475
+ callback_steps,
476
+ negative_prompt=None,
477
+ prompt_embeds=None,
478
+ negative_prompt_embeds=None,
479
+ callback_on_step_end_tensor_inputs=None,
480
+ ):
481
+ if height % 8 != 0 or width % 8 != 0:
482
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
483
+
484
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
485
+ raise ValueError(
486
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
487
+ f" {type(callback_steps)}."
488
+ )
489
+ if callback_on_step_end_tensor_inputs is not None and not all(
490
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
491
+ ):
492
+ raise ValueError(
493
+ 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]}"
494
+ )
495
+
496
+ if prompt is not None and prompt_embeds is not None:
497
+ raise ValueError(
498
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
499
+ " only forward one of the two."
500
+ )
501
+ elif prompt is None and prompt_embeds is None:
502
+ raise ValueError(
503
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
504
+ )
505
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
506
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
507
+
508
+ if negative_prompt is not None and negative_prompt_embeds is not None:
509
+ raise ValueError(
510
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
511
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
512
+ )
513
+
514
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
515
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
516
+ raise ValueError(
517
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
518
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
519
+ f" {negative_prompt_embeds.shape}."
520
+ )
521
+
522
+ # Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_synth.TextToVideoSDPipeline.prepare_latents
523
+ def prepare_latents(
524
+ self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None
525
+ ):
526
+ shape = (
527
+ batch_size,
528
+ num_channels_latents,
529
+ num_frames,
530
+ height // self.vae_scale_factor,
531
+ width // self.vae_scale_factor,
532
+ )
533
+ if isinstance(generator, list) and len(generator) != batch_size:
534
+ raise ValueError(
535
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
536
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
537
+ )
538
+
539
+ if latents is None:
540
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
541
+ else:
542
+ latents = latents.to(device)
543
+
544
+ # scale the initial noise by the standard deviation required by the scheduler
545
+ latents = latents * self.scheduler.init_noise_sigma
546
+ return latents
547
+
548
+ @torch.no_grad()
549
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
550
+ def __call__(
551
+ self,
552
+ prompt: Union[str, List[str]] = None,
553
+ num_frames: Optional[int] = 16,
554
+ context_size=16,
555
+ overlap=2,
556
+ step=1,
557
+ height: Optional[int] = None,
558
+ width: Optional[int] = None,
559
+ num_inference_steps: int = 50,
560
+ guidance_scale: float = 7.5,
561
+ negative_prompt: Optional[Union[str, List[str]]] = None,
562
+ num_videos_per_prompt: Optional[int] = 1,
563
+ eta: float = 0.0,
564
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
565
+ latents: Optional[torch.FloatTensor] = None,
566
+ prompt_embeds: Optional[torch.FloatTensor] = None,
567
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
568
+ ip_adapter_image: Optional[PipelineImageInput] = None,
569
+ output_type: Optional[str] = "pil",
570
+ return_dict: bool = True,
571
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
572
+ callback_steps: Optional[int] = 1,
573
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
574
+ clip_skip: Optional[int] = None,
575
+ ):
576
+ r"""
577
+ The call function to the pipeline for generation.
578
+
579
+ Args:
580
+ prompt (`str` or `List[str]`, *optional*):
581
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
582
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
583
+ The height in pixels of the generated video.
584
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
585
+ The width in pixels of the generated video.
586
+ num_frames (`int`, *optional*, defaults to 16):
587
+ The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
588
+ amounts to 2 seconds of video.
589
+ num_inference_steps (`int`, *optional*, defaults to 50):
590
+ The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
591
+ expense of slower inference.
592
+ guidance_scale (`float`, *optional*, defaults to 7.5):
593
+ A higher guidance scale value encourages the model to generate images closely linked to the text
594
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
595
+ negative_prompt (`str` or `List[str]`, *optional*):
596
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
597
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
598
+ eta (`float`, *optional*, defaults to 0.0):
599
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
600
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
601
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
602
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
603
+ generation deterministic.
604
+ latents (`torch.FloatTensor`, *optional*):
605
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for video
606
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
607
+ tensor is generated by sampling using the supplied random `generator`. Latents should be of shape
608
+ `(batch_size, num_channel, num_frames, height, width)`.
609
+ prompt_embeds (`torch.FloatTensor`, *optional*):
610
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
611
+ provided, text embeddings are generated from the `prompt` input argument.
612
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
613
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
614
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
615
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
616
+ output_type (`str`, *optional*, defaults to `"pil"`):
617
+ The output format of the generated video. Choose between `torch.FloatTensor`, `PIL.Image` or
618
+ `np.array`.
619
+ return_dict (`bool`, *optional*, defaults to `True`):
620
+ Whether or not to return a [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] instead
621
+ of a plain tuple.
622
+ callback (`Callable`, *optional*):
623
+ A function that calls every `callback_steps` steps during inference. The function is called with the
624
+ following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
625
+ callback_steps (`int`, *optional*, defaults to 1):
626
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
627
+ every step.
628
+ cross_attention_kwargs (`dict`, *optional*):
629
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
630
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
631
+ clip_skip (`int`, *optional*):
632
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
633
+ the output of the pre-final layer will be used for computing the prompt embeddings.
634
+ Examples:
635
+
636
+ Returns:
637
+ [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] or `tuple`:
638
+ If `return_dict` is `True`, [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] is
639
+ returned, otherwise a `tuple` is returned where the first element is a list with the generated frames.
640
+ """
641
+ # 0. Default height and width to unet
642
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
643
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
644
+
645
+ num_videos_per_prompt = 1
646
+
647
+ # 1. Check inputs. Raise error if not correct
648
+ self.check_inputs(
649
+ prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
650
+ )
651
+
652
+ # 2. Define call parameters
653
+ if prompt is not None and isinstance(prompt, str):
654
+ batch_size = 1
655
+ elif prompt is not None and isinstance(prompt, list):
656
+ batch_size = len(prompt)
657
+ else:
658
+ batch_size = prompt_embeds.shape[0]
659
+
660
+ device = self._execution_device
661
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
662
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
663
+ # corresponds to doing no classifier free guidance.
664
+ do_classifier_free_guidance = guidance_scale > 1.0
665
+
666
+ # 3. Encode input prompt
667
+ text_encoder_lora_scale = (
668
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
669
+ )
670
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
671
+ prompt,
672
+ device,
673
+ num_videos_per_prompt,
674
+ do_classifier_free_guidance,
675
+ negative_prompt,
676
+ prompt_embeds=prompt_embeds,
677
+ negative_prompt_embeds=negative_prompt_embeds,
678
+ lora_scale=text_encoder_lora_scale,
679
+ clip_skip=clip_skip,
680
+ )
681
+ # For classifier free guidance, we need to do two forward passes.
682
+ # Here we concatenate the unconditional and text embeddings into a single batch
683
+ # to avoid doing two forward passes
684
+ if do_classifier_free_guidance:
685
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
686
+
687
+ if ip_adapter_image is not None:
688
+ output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
689
+ image_embeds, negative_image_embeds = self.encode_image(
690
+ ip_adapter_image, device, num_videos_per_prompt, output_hidden_state
691
+ )
692
+ if do_classifier_free_guidance:
693
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
694
+
695
+ # 4. Prepare timesteps
696
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
697
+ timesteps = self.scheduler.timesteps
698
+
699
+ # round num frames to the nearest multiple of context size - overlap
700
+ num_frames = (num_frames // (context_size - overlap)) * (context_size - overlap)
701
+ print(f"Num frames: {num_frames}")
702
+
703
+ # 5. Prepare latent variables
704
+ num_channels_latents = self.unet.config.in_channels
705
+ latents = self.prepare_latents(
706
+ batch_size * num_videos_per_prompt,
707
+ num_channels_latents,
708
+ num_frames,
709
+ height,
710
+ width,
711
+ prompt_embeds.dtype,
712
+ device,
713
+ generator,
714
+ latents,
715
+ )
716
+
717
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
718
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
719
+ # 7 Add image embeds for IP-Adapter
720
+ added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
721
+
722
+ # divide the initial latents into context groups
723
+ num_context_groups = num_frames // (context_size-overlap)
724
+
725
+ # Denoising loop
726
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
727
+ with self.progress_bar(total=num_frames-(num_context_groups*overlap)) as progress_bar:
728
+ for i, t in enumerate(timesteps):
729
+
730
+ latent_sum = torch.zeros_like(latents).to(device).to(dtype=torch.float16)
731
+ latent_counter = torch.zeros(num_frames).to(device).to(dtype=torch.float16)
732
+
733
+ # foreach context group seperately denoise the current timestep
734
+ for context_group in range(num_context_groups):
735
+ # calculate to current indexes, considering overlap
736
+ if context_group == 0:current_context_start = 0
737
+ else:current_context_start = context_group * (context_size - overlap)
738
+
739
+ # select the relevent context from the latents
740
+ current_context_latents = latents[:, :, current_context_start : current_context_start + context_size, :, :]
741
+
742
+ # expand the latents if we are doing classifier free guidance
743
+ latent_model_input = torch.cat([current_context_latents] * 2) if do_classifier_free_guidance else current_context_latents
744
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
745
+
746
+ # predict the noise residual
747
+ noise_pred = self.unet(
748
+ latent_model_input,
749
+ t,
750
+ encoder_hidden_states=prompt_embeds,
751
+ cross_attention_kwargs=cross_attention_kwargs,
752
+ added_cond_kwargs=added_cond_kwargs,
753
+ ).sample
754
+
755
+ # perform guidance
756
+ if do_classifier_free_guidance:
757
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
758
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
759
+
760
+ # compute the previous noisy sample x_t -> x_t-1
761
+ current_context_latents = self.scheduler.step(noise_pred, t, current_context_latents, **extra_step_kwargs).prev_sample
762
+
763
+ # call the callback, if provided
764
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
765
+ progress_bar.update()
766
+ if callback is not None and i % callback_steps == 0:
767
+ callback(i, t, current_context_latents)
768
+
769
+ #add the context current_context_latents back to the latent sum starting from the current context start
770
+ latent_sum[:, :, current_context_start : current_context_start + context_size, :, :] += current_context_latents
771
+ # add one to the counter for each timestep in the context
772
+ latent_counter[current_context_start : current_context_start + context_size] += 1
773
+
774
+ latent_counter = latent_counter.reshape(1, 1, num_frames, 1, 1)
775
+ latents = latent_sum / latent_counter
776
+
777
+ # shuffle rotate latent images by step places, wrapping around the last 2 to the start
778
+ latents = torch.cat([latents[:, :, -step:, :, :], latents[:, :, :-step, :, :]], dim=2)
779
+
780
+ if output_type == "latent":
781
+ return AnimateDiffPipelineOutput(frames=latents)
782
+
783
+ # Post-processing
784
+ video_tensor = self.decode_latents(latents)
785
+
786
+ if output_type == "pt":
787
+ video = video_tensor
788
+ else:
789
+ video = tensor2vid(video_tensor, self.image_processor, output_type=output_type)
790
+
791
+ # Offload all models
792
+ self.maybe_free_model_hooks()
793
+
794
+ if not return_dict:
795
+ return (video,)
796
+
797
+ return AnimateDiffPipelineOutput(frames=video)