smoothieAI commited on
Commit
af7ccfa
·
1 Parent(s): f2e534c

Upload pipeline_animatediff_controlnet.py

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