diffusers 0.30.2__py3-none-any.whl → 0.30.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,827 @@
1
+ # Copyright 2024 The CogVideoX team, Tsinghua University & ZhipuAI and The HuggingFace Team.
2
+ # All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import inspect
17
+ import math
18
+ from typing import Callable, Dict, List, Optional, Tuple, Union
19
+
20
+ import PIL
21
+ import torch
22
+ from transformers import T5EncoderModel, T5Tokenizer
23
+
24
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
25
+ from ...image_processor import PipelineImageInput
26
+ from ...models import AutoencoderKLCogVideoX, CogVideoXTransformer3DModel
27
+ from ...models.embeddings import get_3d_rotary_pos_embed
28
+ from ...pipelines.pipeline_utils import DiffusionPipeline
29
+ from ...schedulers import CogVideoXDDIMScheduler, CogVideoXDPMScheduler
30
+ from ...utils import (
31
+ logging,
32
+ replace_example_docstring,
33
+ )
34
+ from ...utils.torch_utils import randn_tensor
35
+ from ...video_processor import VideoProcessor
36
+ from .pipeline_output import CogVideoXPipelineOutput
37
+
38
+
39
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
40
+
41
+
42
+ EXAMPLE_DOC_STRING = """
43
+ Examples:
44
+ ```py
45
+ >>> import torch
46
+ >>> from diffusers import CogVideoXImageToVideoPipeline
47
+ >>> from diffusers.utils import export_to_video, load_image
48
+
49
+ >>> pipe = CogVideoXImageToVideoPipeline.from_pretrained("THUDM/CogVideoX-5b-I2V", torch_dtype=torch.bfloat16)
50
+ >>> pipe.to("cuda")
51
+
52
+ >>> prompt = "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
53
+ >>> image = load_image(
54
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
55
+ ... )
56
+ >>> video = pipe(image, prompt, use_dynamic_cfg=True)
57
+ >>> export_to_video(video.frames[0], "output.mp4", fps=8)
58
+ ```
59
+ """
60
+
61
+
62
+ # Similar to diffusers.pipelines.hunyuandit.pipeline_hunyuandit.get_resize_crop_region_for_grid
63
+ def get_resize_crop_region_for_grid(src, tgt_width, tgt_height):
64
+ tw = tgt_width
65
+ th = tgt_height
66
+ h, w = src
67
+ r = h / w
68
+ if r > (th / tw):
69
+ resize_height = th
70
+ resize_width = int(round(th / h * w))
71
+ else:
72
+ resize_width = tw
73
+ resize_height = int(round(tw / w * h))
74
+
75
+ crop_top = int(round((th - resize_height) / 2.0))
76
+ crop_left = int(round((tw - resize_width) / 2.0))
77
+
78
+ return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
79
+
80
+
81
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
82
+ def retrieve_timesteps(
83
+ scheduler,
84
+ num_inference_steps: Optional[int] = None,
85
+ device: Optional[Union[str, torch.device]] = None,
86
+ timesteps: Optional[List[int]] = None,
87
+ sigmas: Optional[List[float]] = None,
88
+ **kwargs,
89
+ ):
90
+ """
91
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
92
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
93
+
94
+ Args:
95
+ scheduler (`SchedulerMixin`):
96
+ The scheduler to get timesteps from.
97
+ num_inference_steps (`int`):
98
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
99
+ must be `None`.
100
+ device (`str` or `torch.device`, *optional*):
101
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
102
+ timesteps (`List[int]`, *optional*):
103
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
104
+ `num_inference_steps` and `sigmas` must be `None`.
105
+ sigmas (`List[float]`, *optional*):
106
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
107
+ `num_inference_steps` and `timesteps` must be `None`.
108
+
109
+ Returns:
110
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
111
+ second element is the number of inference steps.
112
+ """
113
+ if timesteps is not None and sigmas is not None:
114
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
115
+ if timesteps is not None:
116
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
117
+ if not accepts_timesteps:
118
+ raise ValueError(
119
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
120
+ f" timestep schedules. Please check whether you are using the correct scheduler."
121
+ )
122
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
123
+ timesteps = scheduler.timesteps
124
+ num_inference_steps = len(timesteps)
125
+ elif sigmas is not None:
126
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
127
+ if not accept_sigmas:
128
+ raise ValueError(
129
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
130
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
131
+ )
132
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
133
+ timesteps = scheduler.timesteps
134
+ num_inference_steps = len(timesteps)
135
+ else:
136
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
137
+ timesteps = scheduler.timesteps
138
+ return timesteps, num_inference_steps
139
+
140
+
141
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
142
+ def retrieve_latents(
143
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
144
+ ):
145
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
146
+ return encoder_output.latent_dist.sample(generator)
147
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
148
+ return encoder_output.latent_dist.mode()
149
+ elif hasattr(encoder_output, "latents"):
150
+ return encoder_output.latents
151
+ else:
152
+ raise AttributeError("Could not access latents of provided encoder_output")
153
+
154
+
155
+ class CogVideoXImageToVideoPipeline(DiffusionPipeline):
156
+ r"""
157
+ Pipeline for image-to-video generation using CogVideoX.
158
+
159
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
160
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
161
+
162
+ Args:
163
+ vae ([`AutoencoderKL`]):
164
+ Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
165
+ text_encoder ([`T5EncoderModel`]):
166
+ Frozen text-encoder. CogVideoX uses
167
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel); specifically the
168
+ [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
169
+ tokenizer (`T5Tokenizer`):
170
+ Tokenizer of class
171
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
172
+ transformer ([`CogVideoXTransformer3DModel`]):
173
+ A text conditioned `CogVideoXTransformer3DModel` to denoise the encoded video latents.
174
+ scheduler ([`SchedulerMixin`]):
175
+ A scheduler to be used in combination with `transformer` to denoise the encoded video latents.
176
+ """
177
+
178
+ _optional_components = []
179
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
180
+
181
+ _callback_tensor_inputs = [
182
+ "latents",
183
+ "prompt_embeds",
184
+ "negative_prompt_embeds",
185
+ ]
186
+
187
+ def __init__(
188
+ self,
189
+ tokenizer: T5Tokenizer,
190
+ text_encoder: T5EncoderModel,
191
+ vae: AutoencoderKLCogVideoX,
192
+ transformer: CogVideoXTransformer3DModel,
193
+ scheduler: Union[CogVideoXDDIMScheduler, CogVideoXDPMScheduler],
194
+ ):
195
+ super().__init__()
196
+
197
+ self.register_modules(
198
+ tokenizer=tokenizer,
199
+ text_encoder=text_encoder,
200
+ vae=vae,
201
+ transformer=transformer,
202
+ scheduler=scheduler,
203
+ )
204
+ self.vae_scale_factor_spatial = (
205
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
206
+ )
207
+ self.vae_scale_factor_temporal = (
208
+ self.vae.config.temporal_compression_ratio if hasattr(self, "vae") and self.vae is not None else 4
209
+ )
210
+
211
+ self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
212
+
213
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline._get_t5_prompt_embeds
214
+ def _get_t5_prompt_embeds(
215
+ self,
216
+ prompt: Union[str, List[str]] = None,
217
+ num_videos_per_prompt: int = 1,
218
+ max_sequence_length: int = 226,
219
+ device: Optional[torch.device] = None,
220
+ dtype: Optional[torch.dtype] = None,
221
+ ):
222
+ device = device or self._execution_device
223
+ dtype = dtype or self.text_encoder.dtype
224
+
225
+ prompt = [prompt] if isinstance(prompt, str) else prompt
226
+ batch_size = len(prompt)
227
+
228
+ text_inputs = self.tokenizer(
229
+ prompt,
230
+ padding="max_length",
231
+ max_length=max_sequence_length,
232
+ truncation=True,
233
+ add_special_tokens=True,
234
+ return_tensors="pt",
235
+ )
236
+ text_input_ids = text_inputs.input_ids
237
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
238
+
239
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
240
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
241
+ logger.warning(
242
+ "The following part of your input was truncated because `max_sequence_length` is set to "
243
+ f" {max_sequence_length} tokens: {removed_text}"
244
+ )
245
+
246
+ prompt_embeds = self.text_encoder(text_input_ids.to(device))[0]
247
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
248
+
249
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
250
+ _, seq_len, _ = prompt_embeds.shape
251
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
252
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
253
+
254
+ return prompt_embeds
255
+
256
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.encode_prompt
257
+ def encode_prompt(
258
+ self,
259
+ prompt: Union[str, List[str]],
260
+ negative_prompt: Optional[Union[str, List[str]]] = None,
261
+ do_classifier_free_guidance: bool = True,
262
+ num_videos_per_prompt: int = 1,
263
+ prompt_embeds: Optional[torch.Tensor] = None,
264
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
265
+ max_sequence_length: int = 226,
266
+ device: Optional[torch.device] = None,
267
+ dtype: Optional[torch.dtype] = None,
268
+ ):
269
+ r"""
270
+ Encodes the prompt into text encoder hidden states.
271
+
272
+ Args:
273
+ prompt (`str` or `List[str]`, *optional*):
274
+ prompt to be encoded
275
+ negative_prompt (`str` or `List[str]`, *optional*):
276
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
277
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
278
+ less than `1`).
279
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
280
+ Whether to use classifier free guidance or not.
281
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
282
+ Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
283
+ prompt_embeds (`torch.Tensor`, *optional*):
284
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
285
+ provided, text embeddings will be generated from `prompt` input argument.
286
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
287
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
288
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
289
+ argument.
290
+ device: (`torch.device`, *optional*):
291
+ torch device
292
+ dtype: (`torch.dtype`, *optional*):
293
+ torch dtype
294
+ """
295
+ device = device or self._execution_device
296
+
297
+ prompt = [prompt] if isinstance(prompt, str) else prompt
298
+ if prompt is not None:
299
+ batch_size = len(prompt)
300
+ else:
301
+ batch_size = prompt_embeds.shape[0]
302
+
303
+ if prompt_embeds is None:
304
+ prompt_embeds = self._get_t5_prompt_embeds(
305
+ prompt=prompt,
306
+ num_videos_per_prompt=num_videos_per_prompt,
307
+ max_sequence_length=max_sequence_length,
308
+ device=device,
309
+ dtype=dtype,
310
+ )
311
+
312
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
313
+ negative_prompt = negative_prompt or ""
314
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
315
+
316
+ if prompt is not None and type(prompt) is not type(negative_prompt):
317
+ raise TypeError(
318
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
319
+ f" {type(prompt)}."
320
+ )
321
+ elif batch_size != len(negative_prompt):
322
+ raise ValueError(
323
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
324
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
325
+ " the batch size of `prompt`."
326
+ )
327
+
328
+ negative_prompt_embeds = self._get_t5_prompt_embeds(
329
+ prompt=negative_prompt,
330
+ num_videos_per_prompt=num_videos_per_prompt,
331
+ max_sequence_length=max_sequence_length,
332
+ device=device,
333
+ dtype=dtype,
334
+ )
335
+
336
+ return prompt_embeds, negative_prompt_embeds
337
+
338
+ def prepare_latents(
339
+ self,
340
+ image: torch.Tensor,
341
+ batch_size: int = 1,
342
+ num_channels_latents: int = 16,
343
+ num_frames: int = 13,
344
+ height: int = 60,
345
+ width: int = 90,
346
+ dtype: Optional[torch.dtype] = None,
347
+ device: Optional[torch.device] = None,
348
+ generator: Optional[torch.Generator] = None,
349
+ latents: Optional[torch.Tensor] = None,
350
+ ):
351
+ num_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
352
+ shape = (
353
+ batch_size,
354
+ num_frames,
355
+ num_channels_latents,
356
+ height // self.vae_scale_factor_spatial,
357
+ width // self.vae_scale_factor_spatial,
358
+ )
359
+
360
+ if isinstance(generator, list) and len(generator) != batch_size:
361
+ raise ValueError(
362
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
363
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
364
+ )
365
+
366
+ image = image.unsqueeze(2) # [B, C, F, H, W]
367
+
368
+ if isinstance(generator, list):
369
+ image_latents = [
370
+ retrieve_latents(self.vae.encode(image[i].unsqueeze(0)), generator[i]) for i in range(batch_size)
371
+ ]
372
+ else:
373
+ image_latents = [retrieve_latents(self.vae.encode(img.unsqueeze(0)), generator) for img in image]
374
+
375
+ image_latents = torch.cat(image_latents, dim=0).to(dtype).permute(0, 2, 1, 3, 4) # [B, F, C, H, W]
376
+ image_latents = self.vae.config.scaling_factor * image_latents
377
+
378
+ padding_shape = (
379
+ batch_size,
380
+ num_frames - 1,
381
+ num_channels_latents,
382
+ height // self.vae_scale_factor_spatial,
383
+ width // self.vae_scale_factor_spatial,
384
+ )
385
+ latent_padding = torch.zeros(padding_shape, device=device, dtype=dtype)
386
+ image_latents = torch.cat([image_latents, latent_padding], dim=1)
387
+
388
+ if latents is None:
389
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
390
+ else:
391
+ latents = latents.to(device)
392
+
393
+ # scale the initial noise by the standard deviation required by the scheduler
394
+ latents = latents * self.scheduler.init_noise_sigma
395
+ return latents, image_latents
396
+
397
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.decode_latents
398
+ def decode_latents(self, latents: torch.Tensor) -> torch.Tensor:
399
+ latents = latents.permute(0, 2, 1, 3, 4) # [batch_size, num_channels, num_frames, height, width]
400
+ latents = 1 / self.vae.config.scaling_factor * latents
401
+
402
+ frames = self.vae.decode(latents).sample
403
+ return frames
404
+
405
+ # Copied from diffusers.pipelines.animatediff.pipeline_animatediff_video2video.AnimateDiffVideoToVideoPipeline.get_timesteps
406
+ def get_timesteps(self, num_inference_steps, timesteps, strength, device):
407
+ # get the original timestep using init_timestep
408
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
409
+
410
+ t_start = max(num_inference_steps - init_timestep, 0)
411
+ timesteps = timesteps[t_start * self.scheduler.order :]
412
+
413
+ return timesteps, num_inference_steps - t_start
414
+
415
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
416
+ def prepare_extra_step_kwargs(self, generator, eta):
417
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
418
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
419
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
420
+ # and should be between [0, 1]
421
+
422
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
423
+ extra_step_kwargs = {}
424
+ if accepts_eta:
425
+ extra_step_kwargs["eta"] = eta
426
+
427
+ # check if the scheduler accepts generator
428
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
429
+ if accepts_generator:
430
+ extra_step_kwargs["generator"] = generator
431
+ return extra_step_kwargs
432
+
433
+ def check_inputs(
434
+ self,
435
+ image,
436
+ prompt,
437
+ height,
438
+ width,
439
+ negative_prompt,
440
+ callback_on_step_end_tensor_inputs,
441
+ video=None,
442
+ latents=None,
443
+ prompt_embeds=None,
444
+ negative_prompt_embeds=None,
445
+ ):
446
+ if (
447
+ not isinstance(image, torch.Tensor)
448
+ and not isinstance(image, PIL.Image.Image)
449
+ and not isinstance(image, list)
450
+ ):
451
+ raise ValueError(
452
+ "`image` has to be of type `torch.Tensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is"
453
+ f" {type(image)}"
454
+ )
455
+
456
+ if height % 8 != 0 or width % 8 != 0:
457
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
458
+
459
+ if callback_on_step_end_tensor_inputs is not None and not all(
460
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
461
+ ):
462
+ raise ValueError(
463
+ 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]}"
464
+ )
465
+ if prompt is not None and prompt_embeds is not None:
466
+ raise ValueError(
467
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
468
+ " only forward one of the two."
469
+ )
470
+ elif prompt is None and prompt_embeds is None:
471
+ raise ValueError(
472
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
473
+ )
474
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
475
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
476
+
477
+ if prompt is not None and negative_prompt_embeds is not None:
478
+ raise ValueError(
479
+ f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
480
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
481
+ )
482
+
483
+ if negative_prompt is not None and negative_prompt_embeds is not None:
484
+ raise ValueError(
485
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
486
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
487
+ )
488
+
489
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
490
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
491
+ raise ValueError(
492
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
493
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
494
+ f" {negative_prompt_embeds.shape}."
495
+ )
496
+
497
+ if video is not None and latents is not None:
498
+ raise ValueError("Only one of `video` or `latents` should be provided")
499
+
500
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.fuse_qkv_projections
501
+ def fuse_qkv_projections(self) -> None:
502
+ r"""Enables fused QKV projections."""
503
+ self.fusing_transformer = True
504
+ self.transformer.fuse_qkv_projections()
505
+
506
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline.unfuse_qkv_projections
507
+ def unfuse_qkv_projections(self) -> None:
508
+ r"""Disable QKV projection fusion if enabled."""
509
+ if not self.fusing_transformer:
510
+ logger.warning("The Transformer was not initially fused for QKV projections. Doing nothing.")
511
+ else:
512
+ self.transformer.unfuse_qkv_projections()
513
+ self.fusing_transformer = False
514
+
515
+ # Copied from diffusers.pipelines.cogvideo.pipeline_cogvideox.CogVideoXPipeline._prepare_rotary_positional_embeddings
516
+ def _prepare_rotary_positional_embeddings(
517
+ self,
518
+ height: int,
519
+ width: int,
520
+ num_frames: int,
521
+ device: torch.device,
522
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
523
+ grid_height = height // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
524
+ grid_width = width // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
525
+ base_size_width = 720 // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
526
+ base_size_height = 480 // (self.vae_scale_factor_spatial * self.transformer.config.patch_size)
527
+
528
+ grid_crops_coords = get_resize_crop_region_for_grid(
529
+ (grid_height, grid_width), base_size_width, base_size_height
530
+ )
531
+ freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
532
+ embed_dim=self.transformer.config.attention_head_dim,
533
+ crops_coords=grid_crops_coords,
534
+ grid_size=(grid_height, grid_width),
535
+ temporal_size=num_frames,
536
+ )
537
+
538
+ freqs_cos = freqs_cos.to(device=device)
539
+ freqs_sin = freqs_sin.to(device=device)
540
+ return freqs_cos, freqs_sin
541
+
542
+ @property
543
+ def guidance_scale(self):
544
+ return self._guidance_scale
545
+
546
+ @property
547
+ def num_timesteps(self):
548
+ return self._num_timesteps
549
+
550
+ @property
551
+ def interrupt(self):
552
+ return self._interrupt
553
+
554
+ @torch.no_grad()
555
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
556
+ def __call__(
557
+ self,
558
+ image: PipelineImageInput,
559
+ prompt: Optional[Union[str, List[str]]] = None,
560
+ negative_prompt: Optional[Union[str, List[str]]] = None,
561
+ height: int = 480,
562
+ width: int = 720,
563
+ num_frames: int = 49,
564
+ num_inference_steps: int = 50,
565
+ timesteps: Optional[List[int]] = None,
566
+ guidance_scale: float = 6,
567
+ use_dynamic_cfg: bool = False,
568
+ num_videos_per_prompt: int = 1,
569
+ eta: float = 0.0,
570
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
571
+ latents: Optional[torch.FloatTensor] = None,
572
+ prompt_embeds: Optional[torch.FloatTensor] = None,
573
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
574
+ output_type: str = "pil",
575
+ return_dict: bool = True,
576
+ callback_on_step_end: Optional[
577
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
578
+ ] = None,
579
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
580
+ max_sequence_length: int = 226,
581
+ ) -> Union[CogVideoXPipelineOutput, Tuple]:
582
+ """
583
+ Function invoked when calling the pipeline for generation.
584
+
585
+ Args:
586
+ image (`PipelineImageInput`):
587
+ The input video to condition the generation on. Must be an image, a list of images or a `torch.Tensor`.
588
+ prompt (`str` or `List[str]`, *optional*):
589
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
590
+ instead.
591
+ negative_prompt (`str` or `List[str]`, *optional*):
592
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
593
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
594
+ less than `1`).
595
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
596
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
597
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
598
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
599
+ num_frames (`int`, defaults to `48`):
600
+ Number of frames to generate. Must be divisible by self.vae_scale_factor_temporal. Generated video will
601
+ contain 1 extra frame because CogVideoX is conditioned with (num_seconds * fps + 1) frames where
602
+ num_seconds is 6 and fps is 4. However, since videos can be saved at any fps, the only condition that
603
+ needs to be satisfied is that of divisibility mentioned above.
604
+ num_inference_steps (`int`, *optional*, defaults to 50):
605
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
606
+ expense of slower inference.
607
+ timesteps (`List[int]`, *optional*):
608
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
609
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
610
+ passed will be used. Must be in descending order.
611
+ guidance_scale (`float`, *optional*, defaults to 7.0):
612
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
613
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
614
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
615
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
616
+ usually at the expense of lower image quality.
617
+ num_videos_per_prompt (`int`, *optional*, defaults to 1):
618
+ The number of videos to generate per prompt.
619
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
620
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
621
+ to make generation deterministic.
622
+ latents (`torch.FloatTensor`, *optional*):
623
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
624
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
625
+ tensor will ge generated by sampling using the supplied random `generator`.
626
+ prompt_embeds (`torch.FloatTensor`, *optional*):
627
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
628
+ provided, text embeddings will be generated from `prompt` input argument.
629
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
630
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
631
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
632
+ argument.
633
+ output_type (`str`, *optional*, defaults to `"pil"`):
634
+ The output format of the generate image. Choose between
635
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
636
+ return_dict (`bool`, *optional*, defaults to `True`):
637
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
638
+ of a plain tuple.
639
+ callback_on_step_end (`Callable`, *optional*):
640
+ A function that calls at the end of each denoising steps during the inference. The function is called
641
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
642
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
643
+ `callback_on_step_end_tensor_inputs`.
644
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
645
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
646
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
647
+ `._callback_tensor_inputs` attribute of your pipeline class.
648
+ max_sequence_length (`int`, defaults to `226`):
649
+ Maximum sequence length in encoded prompt. Must be consistent with
650
+ `self.transformer.config.max_text_seq_length` otherwise may lead to poor results.
651
+
652
+ Examples:
653
+
654
+ Returns:
655
+ [`~pipelines.cogvideo.pipeline_output.CogVideoXPipelineOutput`] or `tuple`:
656
+ [`~pipelines.cogvideo.pipeline_output.CogVideoXPipelineOutput`] if `return_dict` is True, otherwise a
657
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
658
+ """
659
+
660
+ if num_frames > 49:
661
+ raise ValueError(
662
+ "The number of frames must be less than 49 for now due to static positional embeddings. This will be updated in the future to remove this limitation."
663
+ )
664
+
665
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
666
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
667
+
668
+ height = height or self.transformer.config.sample_size * self.vae_scale_factor_spatial
669
+ width = width or self.transformer.config.sample_size * self.vae_scale_factor_spatial
670
+ num_videos_per_prompt = 1
671
+
672
+ # 1. Check inputs. Raise error if not correct
673
+ self.check_inputs(
674
+ image,
675
+ prompt,
676
+ height,
677
+ width,
678
+ negative_prompt,
679
+ callback_on_step_end_tensor_inputs,
680
+ prompt_embeds,
681
+ negative_prompt_embeds,
682
+ )
683
+ self._guidance_scale = guidance_scale
684
+ self._interrupt = False
685
+
686
+ # 2. Default call parameters
687
+ if prompt is not None and isinstance(prompt, str):
688
+ batch_size = 1
689
+ elif prompt is not None and isinstance(prompt, list):
690
+ batch_size = len(prompt)
691
+ else:
692
+ batch_size = prompt_embeds.shape[0]
693
+
694
+ device = self._execution_device
695
+
696
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
697
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
698
+ # corresponds to doing no classifier free guidance.
699
+ do_classifier_free_guidance = guidance_scale > 1.0
700
+
701
+ # 3. Encode input prompt
702
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
703
+ prompt=prompt,
704
+ negative_prompt=negative_prompt,
705
+ do_classifier_free_guidance=do_classifier_free_guidance,
706
+ num_videos_per_prompt=num_videos_per_prompt,
707
+ prompt_embeds=prompt_embeds,
708
+ negative_prompt_embeds=negative_prompt_embeds,
709
+ max_sequence_length=max_sequence_length,
710
+ device=device,
711
+ )
712
+ if do_classifier_free_guidance:
713
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
714
+
715
+ # 4. Prepare timesteps
716
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
717
+ self._num_timesteps = len(timesteps)
718
+
719
+ # 5. Prepare latents
720
+ image = self.video_processor.preprocess(image, height=height, width=width).to(
721
+ device, dtype=prompt_embeds.dtype
722
+ )
723
+
724
+ latent_channels = self.transformer.config.in_channels // 2
725
+ latents, image_latents = self.prepare_latents(
726
+ image,
727
+ batch_size * num_videos_per_prompt,
728
+ latent_channels,
729
+ num_frames,
730
+ height,
731
+ width,
732
+ prompt_embeds.dtype,
733
+ device,
734
+ generator,
735
+ latents,
736
+ )
737
+
738
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
739
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
740
+
741
+ # 7. Create rotary embeds if required
742
+ image_rotary_emb = (
743
+ self._prepare_rotary_positional_embeddings(height, width, latents.size(1), device)
744
+ if self.transformer.config.use_rotary_positional_embeddings
745
+ else None
746
+ )
747
+
748
+ # 8. Denoising loop
749
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
750
+
751
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
752
+ # for DPM-solver++
753
+ old_pred_original_sample = None
754
+ for i, t in enumerate(timesteps):
755
+ if self.interrupt:
756
+ continue
757
+
758
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
759
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
760
+
761
+ latent_image_input = torch.cat([image_latents] * 2) if do_classifier_free_guidance else image_latents
762
+ latent_model_input = torch.cat([latent_model_input, latent_image_input], dim=2)
763
+
764
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
765
+ timestep = t.expand(latent_model_input.shape[0])
766
+
767
+ # predict noise model_output
768
+ noise_pred = self.transformer(
769
+ hidden_states=latent_model_input,
770
+ encoder_hidden_states=prompt_embeds,
771
+ timestep=timestep,
772
+ image_rotary_emb=image_rotary_emb,
773
+ return_dict=False,
774
+ )[0]
775
+ noise_pred = noise_pred.float()
776
+
777
+ # perform guidance
778
+ if use_dynamic_cfg:
779
+ self._guidance_scale = 1 + guidance_scale * (
780
+ (1 - math.cos(math.pi * ((num_inference_steps - t.item()) / num_inference_steps) ** 5.0)) / 2
781
+ )
782
+ if do_classifier_free_guidance:
783
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
784
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
785
+
786
+ # compute the previous noisy sample x_t -> x_t-1
787
+ if not isinstance(self.scheduler, CogVideoXDPMScheduler):
788
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
789
+ else:
790
+ latents, old_pred_original_sample = self.scheduler.step(
791
+ noise_pred,
792
+ old_pred_original_sample,
793
+ t,
794
+ timesteps[i - 1] if i > 0 else None,
795
+ latents,
796
+ **extra_step_kwargs,
797
+ return_dict=False,
798
+ )
799
+ latents = latents.to(prompt_embeds.dtype)
800
+
801
+ # call the callback, if provided
802
+ if callback_on_step_end is not None:
803
+ callback_kwargs = {}
804
+ for k in callback_on_step_end_tensor_inputs:
805
+ callback_kwargs[k] = locals()[k]
806
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
807
+
808
+ latents = callback_outputs.pop("latents", latents)
809
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
810
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
811
+
812
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
813
+ progress_bar.update()
814
+
815
+ if not output_type == "latent":
816
+ video = self.decode_latents(latents)
817
+ video = self.video_processor.postprocess_video(video=video, output_type=output_type)
818
+ else:
819
+ video = latents
820
+
821
+ # Offload all models
822
+ self.maybe_free_model_hooks()
823
+
824
+ if not return_dict:
825
+ return (video,)
826
+
827
+ return CogVideoXPipelineOutput(frames=video)