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