Skip to content

Commit b50748c

Browse files
committed
initial
1 parent 33d10af commit b50748c

File tree

1 file changed

+141
-108
lines changed

1 file changed

+141
-108
lines changed

Diff for: docs/source/en/api/pipelines/cogvideox.md

+141-108
Original file line numberDiff line numberDiff line change
@@ -15,148 +15,181 @@
1515

1616
# CogVideoX
1717

18-
<div class="flex flex-wrap space-x-1">
19-
<img alt="LoRA" src="https://img.shields.io/badge/LoRA-d8b4fe?style=flat"/>
18+
<div style="float: right;">
19+
<div class="flex flex-wrap space-x-1">
20+
<img alt="LoRA" src="https://img.shields.io/badge/LoRA-d8b4fe?style=flat"/>
21+
</div>
2022
</div>
2123

22-
[CogVideoX: Text-to-Video Diffusion Models with An Expert Transformer](https://arxiv.org/abs/2408.06072) from Tsinghua University & ZhipuAI, by Zhuoyi Yang, Jiayan Teng, Wendi Zheng, Ming Ding, Shiyu Huang, Jiazheng Xu, Yuanming Yang, Wenyi Hong, Xiaohan Zhang, Guanyu Feng, Da Yin, Xiaotao Gu, Yuxuan Zhang, Weihan Wang, Yean Cheng, Ting Liu, Bin Xu, Yuxiao Dong, Jie Tang.
24+
[CogVideoX](https://huggingface.co/papers/2408.06072) is a large diffusion transformer model - available in 2B and 5B parameters - designed to generate longer and more consistent videos from text. This model uses a 3D causal variational autoencoder to more efficiently process video data by reducing sequence length (and associated training compute) and preventing flickering in generated videos. An "expert" transformer with adaptive LayerNorm improves alignment between text and video, and 3D full attention helps accurately capture motion and time in generated videos.
2325

24-
The abstract from the paper is:
26+
You can find all the original CogVideoX checkpoints under the [CogVideoX collection](https://huggingface.co/collections/THUDM/cogvideo-66c08e62f1685a3ade464cce).
2527

26-
*We introduce CogVideoX, a large-scale diffusion transformer model designed for generating videos based on text prompts. To efficently model video data, we propose to levearge a 3D Variational Autoencoder (VAE) to compresses videos along both spatial and temporal dimensions. To improve the text-video alignment, we propose an expert transformer with the expert adaptive LayerNorm to facilitate the deep fusion between the two modalities. By employing a progressive training technique, CogVideoX is adept at producing coherent, long-duration videos characterized by significant motion. In addition, we develop an effectively text-video data processing pipeline that includes various data preprocessing strategies and a video captioning method. It significantly helps enhance the performance of CogVideoX, improving both generation quality and semantic alignment. Results show that CogVideoX demonstrates state-of-the-art performance across both multiple machine metrics and human evaluations. The model weight of CogVideoX-2B is publicly available at https://github.com/THUDM/CogVideo.*
28+
> [!TIP]
29+
> Click on the CogVideoX models in the right sidebar for more examples of how to use CogVideoX for other video generation tasks.
2730
28-
<Tip>
31+
The example below demonstrates how to generate a video with CogVideoX, optimized for memory or inference speed.
2932

30-
Make sure to check out the Schedulers [guide](../../using-diffusers/schedulers) to learn how to explore the tradeoff between scheduler speed and quality, and see the [reuse components across pipelines](../../using-diffusers/loading#reuse-a-pipeline) section to learn how to efficiently load the same components into multiple pipelines.
33+
<hfoptions id="usage">
34+
<hfoption id="memory">
3135

32-
</Tip>
33-
34-
This pipeline was contributed by [zRzRzRzRzRzRzR](https://github.com/zRzRzRzRzRzRzR). The original codebase can be found [here](https://huggingface.co/THUDM). The original weights can be found under [hf.co/THUDM](https://huggingface.co/THUDM).
35-
36-
There are three official CogVideoX checkpoints for text-to-video and video-to-video.
37-
38-
| checkpoints | recommended inference dtype |
39-
|:---:|:---:|
40-
| [`THUDM/CogVideoX-2b`](https://huggingface.co/THUDM/CogVideoX-2b) | torch.float16 |
41-
| [`THUDM/CogVideoX-5b`](https://huggingface.co/THUDM/CogVideoX-5b) | torch.bfloat16 |
42-
| [`THUDM/CogVideoX1.5-5b`](https://huggingface.co/THUDM/CogVideoX1.5-5b) | torch.bfloat16 |
43-
44-
There are two official CogVideoX checkpoints available for image-to-video.
45-
46-
| checkpoints | recommended inference dtype |
47-
|:---:|:---:|
48-
| [`THUDM/CogVideoX-5b-I2V`](https://huggingface.co/THUDM/CogVideoX-5b-I2V) | torch.bfloat16 |
49-
| [`THUDM/CogVideoX-1.5-5b-I2V`](https://huggingface.co/THUDM/CogVideoX-1.5-5b-I2V) | torch.bfloat16 |
50-
51-
For the CogVideoX 1.5 series:
52-
- Text-to-video (T2V) works best at a resolution of 1360x768 because it was trained with that specific resolution.
53-
- Image-to-video (I2V) works for multiple resolutions. The width can vary from 768 to 1360, but the height must be 768. The height/width must be divisible by 16.
54-
- Both T2V and I2V models support generation with 81 and 161 frames and work best at this value. Exporting videos at 16 FPS is recommended.
55-
56-
There are two official CogVideoX checkpoints that support pose controllable generation (by the [Alibaba-PAI](https://huggingface.co/alibaba-pai) team).
57-
58-
| checkpoints | recommended inference dtype |
59-
|:---:|:---:|
60-
| [`alibaba-pai/CogVideoX-Fun-V1.1-2b-Pose`](https://huggingface.co/alibaba-pai/CogVideoX-Fun-V1.1-2b-Pose) | torch.bfloat16 |
61-
| [`alibaba-pai/CogVideoX-Fun-V1.1-5b-Pose`](https://huggingface.co/alibaba-pai/CogVideoX-Fun-V1.1-5b-Pose) | torch.bfloat16 |
36+
```py
37+
import torch
38+
from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel
39+
from diffusers.hooks import apply_group_offloading
40+
from diffusers.utils import export_to_video
6241

63-
## Inference
42+
# fp8 layerwise weight-casting
43+
transformer = CogVideoXTransformer3DModel.from_pretrained(
44+
"THUDM/CogVideoX-5b",
45+
subfolder="transformer",
46+
torch_dtype=torch.bfloat16
47+
)
48+
transformer.enable_layerwise_casting(
49+
storage_dtype=torch.float8_e4m3fn,
50+
compute_dtype=torch.bfloat16
51+
)
6452

65-
Use [`torch.compile`](https://huggingface.co/docs/diffusers/main/en/tutorials/fast_diffusion#torchcompile) to reduce the inference latency.
53+
pipeline = CogVideoXPipeline.from_pretrained(
54+
"THUDM/CogVideoX-5b",
55+
transformer=transformer,
56+
torch_dtype=torch.bfloat16
57+
)
58+
pipeline.to("cuda")
59+
60+
# model-offloading
61+
pipeline.enable_model_cpu_offload()
62+
63+
prompt = ("A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. "
64+
"The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. "
65+
"Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, "
66+
"with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.")
67+
video = pipeline(
68+
prompt=prompt,
69+
guidance_scale=6,
70+
num_inference_steps=50
71+
).frames[0]
72+
export_to_video(video, "output.mp4", fps=8)
73+
```
6674

67-
First, load the pipeline:
75+
Reduce memory usage even more if necessary by quantizing a model to a lower precision data type.
6876

69-
```python
77+
```py
7078
import torch
71-
from diffusers import CogVideoXPipeline, CogVideoXImageToVideoPipeline
72-
from diffusers.utils import export_to_video,load_image
73-
pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b").to("cuda") # or "THUDM/CogVideoX-2b"
74-
```
79+
from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel, TorchAoConfig
80+
from diffusers.utils import export_to_video
7581

76-
If you are using the image-to-video pipeline, load it as follows:
82+
# quantize weights to int8 with torchao
83+
quantization_config = TorchAoConfig("int8wo")
84+
transformer = CogVideoXTransformer3DModel.from_pretrained(
85+
"THUDM/CogVideoX-5b",
86+
subfolder="transformer",
87+
quantization_config=quantization_config,
88+
torch_dtype=torch.bfloat16,
89+
)
90+
# fp8 layerwise weight-casting
91+
transformer.enable_layerwise_casting(
92+
storage_dtype=torch.float8_e4m3fn,
93+
compute_dtype=torch.bfloat16
94+
)
7795

78-
```python
79-
pipe = CogVideoXImageToVideoPipeline.from_pretrained("THUDM/CogVideoX-5b-I2V").to("cuda")
80-
```
96+
pipeline = CogVideoXPipeline.from_pretrained(
97+
"THUDM/CogVideoX-5b",
98+
transformer=transformer,
99+
torch_dtype=torch.bfloat16,
100+
)
101+
pipeline.to("cuda")
81102

82-
Then change the memory layout of the pipelines `transformer` component to `torch.channels_last`:
103+
# model-offloading
104+
pipeline.enable_model_cpu_offload()
83105

84-
```python
85-
pipe.transformer.to(memory_format=torch.channels_last)
106+
prompt = ("A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. "
107+
"The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. "
108+
"Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, "
109+
"with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.")
110+
video = pipeline(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
111+
export_to_video(video, "output.mp4", fps=8)
86112
```
87113

88-
Compile the components and run inference:
114+
</hfoption>
115+
<hfoption id="inference speed">
89116

90-
```python
91-
pipe.transformer = torch.compile(pipeline.transformer, mode="max-autotune", fullgraph=True)
117+
Compilation is slow the first time but subsequent calls to the pipeline are faster.
92118

93-
# CogVideoX works well with long and well-described prompts
94-
prompt = "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical atmosphere of this unique musical performance."
95-
video = pipe(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
96-
```
119+
```py
120+
import torch
121+
from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel
122+
from diffusers.hooks import apply_group_offloading
123+
from diffusers.utils import export_to_video
97124

98-
The [T2V benchmark](https://gist.github.com/a-r-r-o-w/5183d75e452a368fd17448fcc810bd3f) results on an 80GB A100 machine are:
125+
pipeline = CogVideoXPipeline.from_pretrained(
126+
"THUDM/CogVideoX-2b",
127+
torch_dtype=torch.float16
128+
).to("cuda")
129+
130+
# torch.compile
131+
pipeline.transformer.to(memory_format=torch.channels_last)
132+
pipeline.transformer = torch.compile(
133+
pipeline.transformer, mode="max-autotune", fullgraph=True
134+
)
99135

100-
```
101-
Without torch.compile(): Average inference time: 96.89 seconds.
102-
With torch.compile(): Average inference time: 76.27 seconds.
136+
prompt = ("A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. "
137+
"The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. "
138+
"Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, "
139+
"with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.")
140+
video = pipeline(
141+
prompt=prompt,
142+
guidance_scale=6,
143+
num_inference_steps=50
144+
).frames[0]
145+
export_to_video(video, "output.mp4", fps=8)
103146
```
104147

105-
### Memory optimization
148+
</hfoption>
149+
</hfoptions>
106150

107-
CogVideoX-2b requires about 19 GB of GPU memory to decode 49 frames (6 seconds of video at 8 FPS) with output resolution 720x480 (W x H), which makes it not possible to run on consumer GPUs or free-tier T4 Colab. The following memory optimizations could be used to reduce the memory footprint. For replication, you can refer to [this](https://gist.github.com/a-r-r-o-w/3959a03f15be5c9bd1fe545b09dfcc93) script.
108-
109-
- `pipe.enable_model_cpu_offload()`:
110-
- Without enabling cpu offloading, memory usage is `33 GB`
111-
- With enabling cpu offloading, memory usage is `19 GB`
112-
- `pipe.enable_sequential_cpu_offload()`:
113-
- Similar to `enable_model_cpu_offload` but can significantly reduce memory usage at the cost of slow inference
114-
- When enabled, memory usage is under `4 GB`
115-
- `pipe.vae.enable_tiling()`:
116-
- With enabling cpu offloading and tiling, memory usage is `11 GB`
117-
- `pipe.vae.enable_slicing()`
118-
119-
## Quantization
120-
121-
Quantization helps reduce the memory requirements of very large models by storing model weights in a lower precision data type. However, quantization may have varying impact on video quality depending on the video model.
122-
123-
Refer to the [Quantization](../../quantization/overview) overview to learn more about supported quantization backends and selecting a quantization backend that supports your use case. The example below demonstrates how to load a quantized [`CogVideoXPipeline`] for inference with bitsandbytes.
151+
CogVideoX supports LoRAs with [`~loaders.CogVideoXLoraLoaderMixin.load_lora_weights`].
124152

125153
```py
126154
import torch
127-
from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, CogVideoXTransformer3DModel, CogVideoXPipeline
155+
from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel
156+
from diffusers.hooks import apply_group_offloading
128157
from diffusers.utils import export_to_video
129-
from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel
130-
131-
quant_config = BitsAndBytesConfig(load_in_8bit=True)
132-
text_encoder_8bit = T5EncoderModel.from_pretrained(
133-
"THUDM/CogVideoX-2b",
134-
subfolder="text_encoder",
135-
quantization_config=quant_config,
136-
torch_dtype=torch.float16,
137-
)
138-
139-
quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True)
140-
transformer_8bit = CogVideoXTransformer3DModel.from_pretrained(
141-
"THUDM/CogVideoX-2b",
142-
subfolder="transformer",
143-
quantization_config=quant_config,
144-
torch_dtype=torch.float16,
145-
)
146158

147159
pipeline = CogVideoXPipeline.from_pretrained(
148-
"THUDM/CogVideoX-2b",
149-
text_encoder=text_encoder_8bit,
150-
transformer=transformer_8bit,
151-
torch_dtype=torch.float16,
152-
device_map="balanced",
160+
"THUDM/CogVideoX-5b",
161+
torch_dtype=torch.bfloat16
153162
)
154-
155-
prompt = "A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting."
156-
video = pipeline(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
157-
export_to_video(video, "ship.mp4", fps=8)
163+
pipeline.to("cuda")
164+
165+
pipeline.load_lora_weights("finetrainers/CogVideoX-1.5-crush-smol-v0", adapter_name="crush-lora")
166+
pipeline.set_adapters("crush-lora", 0.9)
167+
168+
# model-offloading
169+
pipeline.enable_model_cpu_offload()
170+
171+
prompt = """
172+
PIKA_CRUSH A large metal cylinder is seen pressing down on a pile of Oreo cookies, flattening them as if they were under a hydraulic press.
173+
"""
174+
negative_prompt = "inconsistent motion, blurry motion, worse quality, degenerate outputs, deformed outputs"
175+
176+
video = pipeline(
177+
prompt=prompt,
178+
negative_prompt=negative_prompt,
179+
num_frames=81,
180+
height=480,
181+
width=768,
182+
num_inference_steps=50
183+
).frames[0]
184+
export_to_video(video, "output.mp4", fps=16)
158185
```
159186

187+
## Notes
188+
189+
- The text-to-video (T2V) checkpoints work best with a resolution of 1360x768 because that was the resolution it was pretrained on.
190+
- The image-to-video (I2V) checkpoints work with multiple resolutions. The width can vary from 768 to 1360, but the height must be 758. Both height and width must be divisible by 16.
191+
- Both T2V and I2V checkpoints work best with 81 and 161 frames. It is recommended to export the generated video at 16fps.
192+
160193
## CogVideoXPipeline
161194

162195
[[autodoc]] CogVideoXPipeline

0 commit comments

Comments
 (0)