Datasets:

ArXiv:
diffusers-benchmarking-bot commited on
Commit
d913a15
·
verified ·
1 Parent(s): 97ae914

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. main/README.md +37 -0
  2. main/cogvideox_ddim_inversion.py +645 -0
main/README.md CHANGED
@@ -83,6 +83,7 @@ PIXART-α Controlnet pipeline | Implementation of the controlnet model for pixar
83
  | [🪆Matryoshka Diffusion Models](https://huggingface.co/papers/2310.15111) | A diffusion process that denoises inputs at multiple resolutions jointly and uses a NestedUNet architecture where features and parameters for small scale inputs are nested within those of the large scales. See [original codebase](https://github.com/apple/ml-mdm). | [🪆Matryoshka Diffusion Models](#matryoshka-diffusion-models) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/pcuenq/mdm) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/gist/tolgacangoz/1f54875fc7aeaabcf284ebde64820966/matryoshka_hf.ipynb) | [M. Tolga Cangöz](https://github.com/tolgacangoz) |
84
  | Stable Diffusion XL Attentive Eraser Pipeline |[[AAAI2025 Oral] Attentive Eraser](https://github.com/Anonym0u3/AttentiveEraser) is a novel tuning-free method that enhances object removal capabilities in pre-trained diffusion models.|[Stable Diffusion XL Attentive Eraser Pipeline](#stable-diffusion-xl-attentive-eraser-pipeline)|-|[Wenhao Sun](https://github.com/Anonym0u3) and [Benlei Cui](https://github.com/Benny079)|
85
  | Perturbed-Attention Guidance |StableDiffusionPAGPipeline is a modification of StableDiffusionPipeline to support Perturbed-Attention Guidance (PAG).|[Perturbed-Attention Guidance](#perturbed-attention-guidance)|[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/perturbed_attention_guidance.ipynb)|[Hyoungwon Cho](https://github.com/HyoungwonCho)|
 
86
 
87
  To load a custom pipeline you just need to pass the `custom_pipeline` argument to `DiffusionPipeline`, as one of the files in `diffusers/examples/community`. Feel free to send a PR with your own pipelines, we will merge them quickly.
88
 
@@ -5222,3 +5223,39 @@ with torch.no_grad():
5222
 
5223
  In the folder examples/pixart there is also a script that can be used to train new models.
5224
  Please check the script `train_controlnet_hf_diffusers.sh` on how to start the training.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  | [🪆Matryoshka Diffusion Models](https://huggingface.co/papers/2310.15111) | A diffusion process that denoises inputs at multiple resolutions jointly and uses a NestedUNet architecture where features and parameters for small scale inputs are nested within those of the large scales. See [original codebase](https://github.com/apple/ml-mdm). | [🪆Matryoshka Diffusion Models](#matryoshka-diffusion-models) | [![Hugging Face Space](https://img.shields.io/badge/🤗%20Hugging%20Face-Space-yellow)](https://huggingface.co/spaces/pcuenq/mdm) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/gist/tolgacangoz/1f54875fc7aeaabcf284ebde64820966/matryoshka_hf.ipynb) | [M. Tolga Cangöz](https://github.com/tolgacangoz) |
84
  | Stable Diffusion XL Attentive Eraser Pipeline |[[AAAI2025 Oral] Attentive Eraser](https://github.com/Anonym0u3/AttentiveEraser) is a novel tuning-free method that enhances object removal capabilities in pre-trained diffusion models.|[Stable Diffusion XL Attentive Eraser Pipeline](#stable-diffusion-xl-attentive-eraser-pipeline)|-|[Wenhao Sun](https://github.com/Anonym0u3) and [Benlei Cui](https://github.com/Benny079)|
85
  | Perturbed-Attention Guidance |StableDiffusionPAGPipeline is a modification of StableDiffusionPipeline to support Perturbed-Attention Guidance (PAG).|[Perturbed-Attention Guidance](#perturbed-attention-guidance)|[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/perturbed_attention_guidance.ipynb)|[Hyoungwon Cho](https://github.com/HyoungwonCho)|
86
+ | CogVideoX DDIM Inversion Pipeline | Implementation of DDIM inversion and guided attention-based editing denoising process on CogVideoX. | [CogVideoX DDIM Inversion Pipeline](#cogvideox-ddim-inversion-pipeline) | - | [LittleNyima](https://github.com/LittleNyima) |
87
 
88
  To load a custom pipeline you just need to pass the `custom_pipeline` argument to `DiffusionPipeline`, as one of the files in `diffusers/examples/community`. Feel free to send a PR with your own pipelines, we will merge them quickly.
89
 
 
5223
 
5224
  In the folder examples/pixart there is also a script that can be used to train new models.
5225
  Please check the script `train_controlnet_hf_diffusers.sh` on how to start the training.
5226
+
5227
+ # CogVideoX DDIM Inversion Pipeline
5228
+
5229
+ This implementation performs DDIM inversion on the video based on CogVideoX and uses guided attention to reconstruct or edit the inversion latents.
5230
+
5231
+ ## Example Usage
5232
+
5233
+ ```python
5234
+ import torch
5235
+
5236
+ from examples.community.cogvideox_ddim_inversion import CogVideoXPipelineForDDIMInversion
5237
+
5238
+
5239
+ # Load pretrained pipeline
5240
+ pipeline = CogVideoXPipelineForDDIMInversion.from_pretrained(
5241
+ "THUDM/CogVideoX1.5-5B",
5242
+ torch_dtype=torch.bfloat16,
5243
+ ).to("cuda")
5244
+
5245
+ # Run DDIM inversion, and the videos will be generated in the output_path
5246
+ output = pipeline_for_inversion(
5247
+ prompt="prompt that describes the edited video",
5248
+ video_path="path/to/input.mp4",
5249
+ guidance_scale=6.0,
5250
+ num_inference_steps=50,
5251
+ skip_frames_start=0,
5252
+ skip_frames_end=0,
5253
+ frame_sample_step=None,
5254
+ max_num_frames=81,
5255
+ width=720,
5256
+ height=480,
5257
+ seed=42,
5258
+ )
5259
+ pipeline.export_latents_to_video(output.inverse_latents[-1], "path/to/inverse_video.mp4", fps=8)
5260
+ pipeline.export_latents_to_video(output.recon_latents[-1], "path/to/recon_video.mp4", fps=8)
5261
+ ```
main/cogvideox_ddim_inversion.py ADDED
@@ -0,0 +1,645 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This script performs DDIM inversion for video frames using a pre-trained model and generates
3
+ a video reconstruction based on a provided prompt. It utilizes the CogVideoX pipeline to
4
+ process video frames, apply the DDIM inverse scheduler, and produce an output video.
5
+
6
+ **Please notice that this script is based on the CogVideoX 5B model, and would not generate
7
+ a good result for 2B variants.**
8
+
9
+ Usage:
10
+ python cogvideox_ddim_inversion.py
11
+ --model-path /path/to/model
12
+ --prompt "a prompt"
13
+ --video-path /path/to/video.mp4
14
+ --output-path /path/to/output
15
+
16
+ For more details about the cli arguments, please run `python cogvideox_ddim_inversion.py --help`.
17
+
18
+ Author:
19
+ LittleNyima <littlenyima[at]163[dot]com>
20
+ """
21
+
22
+ import argparse
23
+ import math
24
+ import os
25
+ from typing import Any, Dict, List, Optional, Tuple, TypedDict, Union, cast
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ import torchvision.transforms as T
30
+ from transformers import T5EncoderModel, T5Tokenizer
31
+
32
+ from diffusers.models.attention_processor import Attention, CogVideoXAttnProcessor2_0
33
+ from diffusers.models.autoencoders import AutoencoderKLCogVideoX
34
+ from diffusers.models.embeddings import apply_rotary_emb
35
+ from diffusers.models.transformers.cogvideox_transformer_3d import CogVideoXBlock, CogVideoXTransformer3DModel
36
+ from diffusers.pipelines.cogvideo.pipeline_cogvideox import CogVideoXPipeline, retrieve_timesteps
37
+ from diffusers.schedulers import CogVideoXDDIMScheduler, DDIMInverseScheduler
38
+ from diffusers.utils import export_to_video
39
+
40
+
41
+ # Must import after torch because this can sometimes lead to a nasty segmentation fault, or stack smashing error.
42
+ # Very few bug reports but it happens. Look in decord Github issues for more relevant information.
43
+ import decord # isort: skip
44
+
45
+
46
+ class DDIMInversionArguments(TypedDict):
47
+ model_path: str
48
+ prompt: str
49
+ video_path: str
50
+ output_path: str
51
+ guidance_scale: float
52
+ num_inference_steps: int
53
+ skip_frames_start: int
54
+ skip_frames_end: int
55
+ frame_sample_step: Optional[int]
56
+ max_num_frames: int
57
+ width: int
58
+ height: int
59
+ fps: int
60
+ dtype: torch.dtype
61
+ seed: int
62
+ device: torch.device
63
+
64
+
65
+ def get_args() -> DDIMInversionArguments:
66
+ parser = argparse.ArgumentParser()
67
+
68
+ parser.add_argument("--model_path", type=str, required=True, help="Path of the pretrained model")
69
+ parser.add_argument("--prompt", type=str, required=True, help="Prompt for the direct sample procedure")
70
+ parser.add_argument("--video_path", type=str, required=True, help="Path of the video for inversion")
71
+ parser.add_argument("--output_path", type=str, default="output", help="Path of the output videos")
72
+ parser.add_argument("--guidance_scale", type=float, default=6.0, help="Classifier-free guidance scale")
73
+ parser.add_argument("--num_inference_steps", type=int, default=50, help="Number of inference steps")
74
+ parser.add_argument("--skip_frames_start", type=int, default=0, help="Number of skipped frames from the start")
75
+ parser.add_argument("--skip_frames_end", type=int, default=0, help="Number of skipped frames from the end")
76
+ parser.add_argument("--frame_sample_step", type=int, default=None, help="Temporal stride of the sampled frames")
77
+ parser.add_argument("--max_num_frames", type=int, default=81, help="Max number of sampled frames")
78
+ parser.add_argument("--width", type=int, default=720, help="Resized width of the video frames")
79
+ parser.add_argument("--height", type=int, default=480, help="Resized height of the video frames")
80
+ parser.add_argument("--fps", type=int, default=8, help="Frame rate of the output videos")
81
+ parser.add_argument("--dtype", type=str, default="bf16", choices=["bf16", "fp16"], help="Dtype of the model")
82
+ parser.add_argument("--seed", type=int, default=42, help="Seed for the random number generator")
83
+ parser.add_argument("--device", type=str, default="cuda", choices=["cuda", "cpu"], help="Device for inference")
84
+
85
+ args = parser.parse_args()
86
+ args.dtype = torch.bfloat16 if args.dtype == "bf16" else torch.float16
87
+ args.device = torch.device(args.device)
88
+
89
+ return DDIMInversionArguments(**vars(args))
90
+
91
+
92
+ class CogVideoXAttnProcessor2_0ForDDIMInversion(CogVideoXAttnProcessor2_0):
93
+ def __init__(self):
94
+ super().__init__()
95
+
96
+ def calculate_attention(
97
+ self,
98
+ query: torch.Tensor,
99
+ key: torch.Tensor,
100
+ value: torch.Tensor,
101
+ attn: Attention,
102
+ batch_size: int,
103
+ image_seq_length: int,
104
+ text_seq_length: int,
105
+ attention_mask: Optional[torch.Tensor],
106
+ image_rotary_emb: Optional[torch.Tensor],
107
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
108
+ r"""
109
+ Core attention computation with inversion-guided RoPE integration.
110
+
111
+ Args:
112
+ query (`torch.Tensor`): `[batch_size, seq_len, dim]` query tensor
113
+ key (`torch.Tensor`): `[batch_size, seq_len, dim]` key tensor
114
+ value (`torch.Tensor`): `[batch_size, seq_len, dim]` value tensor
115
+ attn (`Attention`): Parent attention module with projection layers
116
+ batch_size (`int`): Effective batch size (after chunk splitting)
117
+ image_seq_length (`int`): Length of image feature sequence
118
+ text_seq_length (`int`): Length of text feature sequence
119
+ attention_mask (`Optional[torch.Tensor]`): Attention mask tensor
120
+ image_rotary_emb (`Optional[torch.Tensor]`): Rotary embeddings for image positions
121
+
122
+ Returns:
123
+ `Tuple[torch.Tensor, torch.Tensor]`:
124
+ (1) hidden_states: [batch_size, image_seq_length, dim] processed image features
125
+ (2) encoder_hidden_states: [batch_size, text_seq_length, dim] processed text features
126
+ """
127
+ inner_dim = key.shape[-1]
128
+ head_dim = inner_dim // attn.heads
129
+
130
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
131
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
132
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
133
+
134
+ if attn.norm_q is not None:
135
+ query = attn.norm_q(query)
136
+ if attn.norm_k is not None:
137
+ key = attn.norm_k(key)
138
+
139
+ # Apply RoPE if needed
140
+ if image_rotary_emb is not None:
141
+ query[:, :, text_seq_length:] = apply_rotary_emb(query[:, :, text_seq_length:], image_rotary_emb)
142
+ if not attn.is_cross_attention:
143
+ if key.size(2) == query.size(2): # Attention for reference hidden states
144
+ key[:, :, text_seq_length:] = apply_rotary_emb(key[:, :, text_seq_length:], image_rotary_emb)
145
+ else: # RoPE should be applied to each group of image tokens
146
+ key[:, :, text_seq_length : text_seq_length + image_seq_length] = apply_rotary_emb(
147
+ key[:, :, text_seq_length : text_seq_length + image_seq_length], image_rotary_emb
148
+ )
149
+ key[:, :, text_seq_length * 2 + image_seq_length :] = apply_rotary_emb(
150
+ key[:, :, text_seq_length * 2 + image_seq_length :], image_rotary_emb
151
+ )
152
+
153
+ hidden_states = F.scaled_dot_product_attention(
154
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
155
+ )
156
+
157
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
158
+
159
+ # linear proj
160
+ hidden_states = attn.to_out[0](hidden_states)
161
+ # dropout
162
+ hidden_states = attn.to_out[1](hidden_states)
163
+
164
+ encoder_hidden_states, hidden_states = hidden_states.split(
165
+ [text_seq_length, hidden_states.size(1) - text_seq_length], dim=1
166
+ )
167
+ return hidden_states, encoder_hidden_states
168
+
169
+ def __call__(
170
+ self,
171
+ attn: Attention,
172
+ hidden_states: torch.Tensor,
173
+ encoder_hidden_states: torch.Tensor,
174
+ attention_mask: Optional[torch.Tensor] = None,
175
+ image_rotary_emb: Optional[torch.Tensor] = None,
176
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
177
+ r"""
178
+ Process the dual-path attention for the inversion-guided denoising procedure.
179
+
180
+ Args:
181
+ attn (`Attention`): Parent attention module
182
+ hidden_states (`torch.Tensor`): `[batch_size, image_seq_len, dim]` Image tokens
183
+ encoder_hidden_states (`torch.Tensor`): `[batch_size, text_seq_len, dim]` Text tokens
184
+ attention_mask (`Optional[torch.Tensor]`): Optional attention mask
185
+ image_rotary_emb (`Optional[torch.Tensor]`): Rotary embeddings for image tokens
186
+
187
+ Returns:
188
+ `Tuple[torch.Tensor, torch.Tensor]`:
189
+ (1) Final hidden states: `[batch_size, image_seq_length, dim]` Resulting image tokens
190
+ (2) Final encoder states: `[batch_size, text_seq_length, dim]` Resulting text tokens
191
+ """
192
+ image_seq_length = hidden_states.size(1)
193
+ text_seq_length = encoder_hidden_states.size(1)
194
+
195
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
196
+
197
+ batch_size, sequence_length, _ = (
198
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
199
+ )
200
+
201
+ if attention_mask is not None:
202
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
203
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
204
+
205
+ query = attn.to_q(hidden_states)
206
+ key = attn.to_k(hidden_states)
207
+ value = attn.to_v(hidden_states)
208
+
209
+ query, query_reference = query.chunk(2)
210
+ key, key_reference = key.chunk(2)
211
+ value, value_reference = value.chunk(2)
212
+ batch_size = batch_size // 2
213
+
214
+ hidden_states, encoder_hidden_states = self.calculate_attention(
215
+ query=query,
216
+ key=torch.cat((key, key_reference), dim=1),
217
+ value=torch.cat((value, value_reference), dim=1),
218
+ attn=attn,
219
+ batch_size=batch_size,
220
+ image_seq_length=image_seq_length,
221
+ text_seq_length=text_seq_length,
222
+ attention_mask=attention_mask,
223
+ image_rotary_emb=image_rotary_emb,
224
+ )
225
+ hidden_states_reference, encoder_hidden_states_reference = self.calculate_attention(
226
+ query=query_reference,
227
+ key=key_reference,
228
+ value=value_reference,
229
+ attn=attn,
230
+ batch_size=batch_size,
231
+ image_seq_length=image_seq_length,
232
+ text_seq_length=text_seq_length,
233
+ attention_mask=attention_mask,
234
+ image_rotary_emb=image_rotary_emb,
235
+ )
236
+
237
+ return (
238
+ torch.cat((hidden_states, hidden_states_reference)),
239
+ torch.cat((encoder_hidden_states, encoder_hidden_states_reference)),
240
+ )
241
+
242
+
243
+ class OverrideAttnProcessors:
244
+ r"""
245
+ Context manager for temporarily overriding attention processors in CogVideo transformer blocks.
246
+
247
+ Designed for DDIM inversion process, replaces original attention processors with
248
+ `CogVideoXAttnProcessor2_0ForDDIMInversion` and restores them upon exit. Uses Python context manager
249
+ pattern to safely manage processor replacement.
250
+
251
+ Typical usage:
252
+ ```python
253
+ with OverrideAttnProcessors(transformer):
254
+ # Perform DDIM inversion operations
255
+ ```
256
+
257
+ Args:
258
+ transformer (`CogVideoXTransformer3DModel`):
259
+ The transformer model containing attention blocks to be modified. Should have
260
+ `transformer_blocks` attribute containing `CogVideoXBlock` instances.
261
+ """
262
+
263
+ def __init__(self, transformer: CogVideoXTransformer3DModel):
264
+ self.transformer = transformer
265
+ self.original_processors = {}
266
+
267
+ def __enter__(self):
268
+ for block in self.transformer.transformer_blocks:
269
+ block = cast(CogVideoXBlock, block)
270
+ self.original_processors[id(block)] = block.attn1.get_processor()
271
+ block.attn1.set_processor(CogVideoXAttnProcessor2_0ForDDIMInversion())
272
+
273
+ def __exit__(self, _0, _1, _2):
274
+ for block in self.transformer.transformer_blocks:
275
+ block = cast(CogVideoXBlock, block)
276
+ block.attn1.set_processor(self.original_processors[id(block)])
277
+
278
+
279
+ def get_video_frames(
280
+ video_path: str,
281
+ width: int,
282
+ height: int,
283
+ skip_frames_start: int,
284
+ skip_frames_end: int,
285
+ max_num_frames: int,
286
+ frame_sample_step: Optional[int],
287
+ ) -> torch.FloatTensor:
288
+ """
289
+ Extract and preprocess video frames from a video file for VAE processing.
290
+
291
+ Args:
292
+ video_path (`str`): Path to input video file
293
+ width (`int`): Target frame width for decoding
294
+ height (`int`): Target frame height for decoding
295
+ skip_frames_start (`int`): Number of frames to skip at video start
296
+ skip_frames_end (`int`): Number of frames to skip at video end
297
+ max_num_frames (`int`): Maximum allowed number of output frames
298
+ frame_sample_step (`Optional[int]`):
299
+ Frame sampling step size. If None, automatically calculated as:
300
+ (total_frames - skipped_frames) // max_num_frames
301
+
302
+ Returns:
303
+ `torch.FloatTensor`: Preprocessed frames in `[F, C, H, W]` format where:
304
+ - `F`: Number of frames (adjusted to 4k + 1 for VAE compatibility)
305
+ - `C`: Channels (3 for RGB)
306
+ - `H`: Frame height
307
+ - `W`: Frame width
308
+ """
309
+ with decord.bridge.use_torch():
310
+ video_reader = decord.VideoReader(uri=video_path, width=width, height=height)
311
+ video_num_frames = len(video_reader)
312
+ start_frame = min(skip_frames_start, video_num_frames)
313
+ end_frame = max(0, video_num_frames - skip_frames_end)
314
+
315
+ if end_frame <= start_frame:
316
+ indices = [start_frame]
317
+ elif end_frame - start_frame <= max_num_frames:
318
+ indices = list(range(start_frame, end_frame))
319
+ else:
320
+ step = frame_sample_step or (end_frame - start_frame) // max_num_frames
321
+ indices = list(range(start_frame, end_frame, step))
322
+
323
+ frames = video_reader.get_batch(indices=indices)
324
+ frames = frames[:max_num_frames].float() # ensure that we don't go over the limit
325
+
326
+ # Choose first (4k + 1) frames as this is how many is required by the VAE
327
+ selected_num_frames = frames.size(0)
328
+ remainder = (3 + selected_num_frames) % 4
329
+ if remainder != 0:
330
+ frames = frames[:-remainder]
331
+ assert frames.size(0) % 4 == 1
332
+
333
+ # Normalize the frames
334
+ transform = T.Lambda(lambda x: x / 255.0 * 2.0 - 1.0)
335
+ frames = torch.stack(tuple(map(transform, frames)), dim=0)
336
+
337
+ return frames.permute(0, 3, 1, 2).contiguous() # [F, C, H, W]
338
+
339
+
340
+ class CogVideoXDDIMInversionOutput:
341
+ inverse_latents: torch.FloatTensor
342
+ recon_latents: torch.FloatTensor
343
+
344
+ def __init__(self, inverse_latents: torch.FloatTensor, recon_latents: torch.FloatTensor):
345
+ self.inverse_latents = inverse_latents
346
+ self.recon_latents = recon_latents
347
+
348
+
349
+ class CogVideoXPipelineForDDIMInversion(CogVideoXPipeline):
350
+ def __init__(
351
+ self,
352
+ tokenizer: T5Tokenizer,
353
+ text_encoder: T5EncoderModel,
354
+ vae: AutoencoderKLCogVideoX,
355
+ transformer: CogVideoXTransformer3DModel,
356
+ scheduler: CogVideoXDDIMScheduler,
357
+ ):
358
+ super().__init__(
359
+ tokenizer=tokenizer,
360
+ text_encoder=text_encoder,
361
+ vae=vae,
362
+ transformer=transformer,
363
+ scheduler=scheduler,
364
+ )
365
+ self.inverse_scheduler = DDIMInverseScheduler(**scheduler.config)
366
+
367
+ def encode_video_frames(self, video_frames: torch.FloatTensor) -> torch.FloatTensor:
368
+ """
369
+ Encode video frames into latent space using Variational Autoencoder.
370
+
371
+ Args:
372
+ video_frames (`torch.FloatTensor`):
373
+ Input frames tensor in `[F, C, H, W]` format from `get_video_frames()`
374
+
375
+ Returns:
376
+ `torch.FloatTensor`: Encoded latents in `[1, F, D, H_latent, W_latent]` format where:
377
+ - `F`: Number of frames (same as input)
378
+ - `D`: Latent channel dimension
379
+ - `H_latent`: Latent space height (H // 2^vae.downscale_factor)
380
+ - `W_latent`: Latent space width (W // 2^vae.downscale_factor)
381
+ """
382
+ vae: AutoencoderKLCogVideoX = self.vae
383
+ video_frames = video_frames.to(device=vae.device, dtype=vae.dtype)
384
+ video_frames = video_frames.unsqueeze(0).permute(0, 2, 1, 3, 4) # [B, C, F, H, W]
385
+ latent_dist = vae.encode(x=video_frames).latent_dist.sample().transpose(1, 2)
386
+ return latent_dist * vae.config.scaling_factor
387
+
388
+ @torch.no_grad()
389
+ def export_latents_to_video(self, latents: torch.FloatTensor, video_path: str, fps: int):
390
+ r"""
391
+ Decode latent vectors into video and export as video file.
392
+
393
+ Args:
394
+ latents (`torch.FloatTensor`): Encoded latents in `[B, F, D, H_latent, W_latent]` format from
395
+ `encode_video_frames()`
396
+ video_path (`str`): Output path for video file
397
+ fps (`int`): Target frames per second for output video
398
+ """
399
+ video = self.decode_latents(latents)
400
+ frames = self.video_processor.postprocess_video(video=video, output_type="pil")
401
+ os.makedirs(os.path.dirname(video_path), exist_ok=True)
402
+ export_to_video(video_frames=frames[0], output_video_path=video_path, fps=fps)
403
+
404
+ # Modified from CogVideoXPipeline.__call__
405
+ @torch.no_grad()
406
+ def sample(
407
+ self,
408
+ latents: torch.FloatTensor,
409
+ scheduler: Union[DDIMInverseScheduler, CogVideoXDDIMScheduler],
410
+ prompt: Optional[Union[str, List[str]]] = None,
411
+ negative_prompt: Optional[Union[str, List[str]]] = None,
412
+ num_inference_steps: int = 50,
413
+ guidance_scale: float = 6,
414
+ use_dynamic_cfg: bool = False,
415
+ eta: float = 0.0,
416
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
417
+ attention_kwargs: Optional[Dict[str, Any]] = None,
418
+ reference_latents: torch.FloatTensor = None,
419
+ ) -> torch.FloatTensor:
420
+ r"""
421
+ Execute the core sampling loop for video generation/inversion using CogVideoX.
422
+
423
+ Implements the full denoising trajectory recording for both DDIM inversion and
424
+ generation processes. Supports dynamic classifier-free guidance and reference
425
+ latent conditioning.
426
+
427
+ Args:
428
+ latents (`torch.FloatTensor`):
429
+ Initial noise tensor of shape `[B, F, C, H, W]`.
430
+ scheduler (`Union[DDIMInverseScheduler, CogVideoXDDIMScheduler]`):
431
+ Scheduling strategy for diffusion process. Use:
432
+ (1) `DDIMInverseScheduler` for inversion
433
+ (2) `CogVideoXDDIMScheduler` for generation
434
+ prompt (`Optional[Union[str, List[str]]]`):
435
+ Text prompt(s) for conditional generation. Defaults to unconditional.
436
+ negative_prompt (`Optional[Union[str, List[str]]]`):
437
+ Negative prompt(s) for guidance. Requires `guidance_scale > 1`.
438
+ num_inference_steps (`int`):
439
+ Number of denoising steps. Affects quality/compute trade-off.
440
+ guidance_scale (`float`):
441
+ Classifier-free guidance weight. 1.0 = no guidance.
442
+ use_dynamic_cfg (`bool`):
443
+ Enable time-varying guidance scale (cosine schedule)
444
+ eta (`float`):
445
+ DDIM variance parameter (0 = deterministic process)
446
+ generator (`Optional[Union[torch.Generator, List[torch.Generator]]]`):
447
+ Random number generator(s) for reproducibility
448
+ attention_kwargs (`Optional[Dict[str, Any]]`):
449
+ Custom parameters for attention modules
450
+ reference_latents (`torch.FloatTensor`):
451
+ Reference latent trajectory for conditional sampling. Shape should match
452
+ `[T, B, F, C, H, W]` where `T` is number of timesteps
453
+
454
+ Returns:
455
+ `torch.FloatTensor`:
456
+ Full denoising trajectory tensor of shape `[T, B, F, C, H, W]`.
457
+ """
458
+ self._guidance_scale = guidance_scale
459
+ self._attention_kwargs = attention_kwargs
460
+ self._interrupt = False
461
+
462
+ device = self._execution_device
463
+
464
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
465
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
466
+ # corresponds to doing no classifier free guidance.
467
+ do_classifier_free_guidance = guidance_scale > 1.0
468
+
469
+ # 3. Encode input prompt
470
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
471
+ prompt,
472
+ negative_prompt,
473
+ do_classifier_free_guidance,
474
+ device=device,
475
+ )
476
+ if do_classifier_free_guidance:
477
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
478
+ if reference_latents is not None:
479
+ prompt_embeds = torch.cat([prompt_embeds] * 2, dim=0)
480
+
481
+ # 4. Prepare timesteps
482
+ timesteps, num_inference_steps = retrieve_timesteps(scheduler, num_inference_steps, device)
483
+ self._num_timesteps = len(timesteps)
484
+
485
+ # 5. Prepare latents.
486
+ latents = latents.to(device=device) * scheduler.init_noise_sigma
487
+
488
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
489
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
490
+ if isinstance(scheduler, DDIMInverseScheduler): # Inverse scheduler does not accept extra kwargs
491
+ extra_step_kwargs = {}
492
+
493
+ # 7. Create rotary embeds if required
494
+ image_rotary_emb = (
495
+ self._prepare_rotary_positional_embeddings(
496
+ height=latents.size(3) * self.vae_scale_factor_spatial,
497
+ width=latents.size(4) * self.vae_scale_factor_spatial,
498
+ num_frames=latents.size(1),
499
+ device=device,
500
+ )
501
+ if self.transformer.config.use_rotary_positional_embeddings
502
+ else None
503
+ )
504
+
505
+ # 8. Denoising loop
506
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * scheduler.order, 0)
507
+
508
+ trajectory = torch.zeros_like(latents).unsqueeze(0).repeat(len(timesteps), 1, 1, 1, 1, 1)
509
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
510
+ for i, t in enumerate(timesteps):
511
+ if self.interrupt:
512
+ continue
513
+
514
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
515
+ if reference_latents is not None:
516
+ reference = reference_latents[i]
517
+ reference = torch.cat([reference] * 2) if do_classifier_free_guidance else reference
518
+ latent_model_input = torch.cat([latent_model_input, reference], dim=0)
519
+ latent_model_input = scheduler.scale_model_input(latent_model_input, t)
520
+
521
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
522
+ timestep = t.expand(latent_model_input.shape[0])
523
+
524
+ # predict noise model_output
525
+ noise_pred = self.transformer(
526
+ hidden_states=latent_model_input,
527
+ encoder_hidden_states=prompt_embeds,
528
+ timestep=timestep,
529
+ image_rotary_emb=image_rotary_emb,
530
+ attention_kwargs=attention_kwargs,
531
+ return_dict=False,
532
+ )[0]
533
+ noise_pred = noise_pred.float()
534
+
535
+ if reference_latents is not None: # Recover the original batch size
536
+ noise_pred, _ = noise_pred.chunk(2)
537
+
538
+ # perform guidance
539
+ if use_dynamic_cfg:
540
+ self._guidance_scale = 1 + guidance_scale * (
541
+ (1 - math.cos(math.pi * ((num_inference_steps - t.item()) / num_inference_steps) ** 5.0)) / 2
542
+ )
543
+ if do_classifier_free_guidance:
544
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
545
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
546
+
547
+ # compute the noisy sample x_t-1 -> x_t
548
+ latents = scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
549
+ latents = latents.to(prompt_embeds.dtype)
550
+ trajectory[i] = latents
551
+
552
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0):
553
+ progress_bar.update()
554
+
555
+ # Offload all models
556
+ self.maybe_free_model_hooks()
557
+
558
+ return trajectory
559
+
560
+ @torch.no_grad()
561
+ def __call__(
562
+ self,
563
+ prompt: str,
564
+ video_path: str,
565
+ guidance_scale: float,
566
+ num_inference_steps: int,
567
+ skip_frames_start: int,
568
+ skip_frames_end: int,
569
+ frame_sample_step: Optional[int],
570
+ max_num_frames: int,
571
+ width: int,
572
+ height: int,
573
+ seed: int,
574
+ ):
575
+ """
576
+ Performs DDIM inversion on a video to reconstruct it with a new prompt.
577
+
578
+ Args:
579
+ prompt (`str`): The text prompt to guide the reconstruction.
580
+ video_path (`str`): Path to the input video file.
581
+ guidance_scale (`float`): Scale for classifier-free guidance.
582
+ num_inference_steps (`int`): Number of denoising steps.
583
+ skip_frames_start (`int`): Number of frames to skip from the beginning of the video.
584
+ skip_frames_end (`int`): Number of frames to skip from the end of the video.
585
+ frame_sample_step (`Optional[int]`): Step size for sampling frames. If None, all frames are used.
586
+ max_num_frames (`int`): Maximum number of frames to process.
587
+ width (`int`): Width of the output video frames.
588
+ height (`int`): Height of the output video frames.
589
+ seed (`int`): Random seed for reproducibility.
590
+
591
+ Returns:
592
+ `CogVideoXDDIMInversionOutput`: Contains the inverse latents and reconstructed latents.
593
+ """
594
+ if not self.transformer.config.use_rotary_positional_embeddings:
595
+ raise NotImplementedError("This script supports CogVideoX 5B model only.")
596
+ video_frames = get_video_frames(
597
+ video_path=video_path,
598
+ width=width,
599
+ height=height,
600
+ skip_frames_start=skip_frames_start,
601
+ skip_frames_end=skip_frames_end,
602
+ max_num_frames=max_num_frames,
603
+ frame_sample_step=frame_sample_step,
604
+ ).to(device=self.device)
605
+ video_latents = self.encode_video_frames(video_frames=video_frames)
606
+ inverse_latents = self.sample(
607
+ latents=video_latents,
608
+ scheduler=self.inverse_scheduler,
609
+ prompt="",
610
+ num_inference_steps=num_inference_steps,
611
+ guidance_scale=guidance_scale,
612
+ generator=torch.Generator(device=self.device).manual_seed(seed),
613
+ )
614
+ with OverrideAttnProcessors(transformer=self.transformer):
615
+ recon_latents = self.sample(
616
+ latents=torch.randn_like(video_latents),
617
+ scheduler=self.scheduler,
618
+ prompt=prompt,
619
+ num_inference_steps=num_inference_steps,
620
+ guidance_scale=guidance_scale,
621
+ generator=torch.Generator(device=self.device).manual_seed(seed),
622
+ reference_latents=reversed(inverse_latents),
623
+ )
624
+ return CogVideoXDDIMInversionOutput(
625
+ inverse_latents=inverse_latents,
626
+ recon_latents=recon_latents,
627
+ )
628
+
629
+
630
+ if __name__ == "__main__":
631
+ arguments = get_args()
632
+ pipeline = CogVideoXPipelineForDDIMInversion.from_pretrained(
633
+ arguments.pop("model_path"),
634
+ torch_dtype=arguments.pop("dtype"),
635
+ ).to(device=arguments.pop("device"))
636
+
637
+ output_path = arguments.pop("output_path")
638
+ fps = arguments.pop("fps")
639
+ inverse_video_path = os.path.join(output_path, f"{arguments.get('video_path')}_inversion.mp4")
640
+ recon_video_path = os.path.join(output_path, f"{arguments.get('video_path')}_reconstruction.mp4")
641
+
642
+ # Run DDIM inversion
643
+ output = pipeline(**arguments)
644
+ pipeline.export_latents_to_video(output.inverse_latents[-1], inverse_video_path, fps)
645
+ pipeline.export_latents_to_video(output.recon_latents[-1], recon_video_path, fps)