From df1ed74e4d0b3dbb59c4e05c01a976e3d6198455 Mon Sep 17 00:00:00 2001 From: stevhliu Date: Tue, 18 Mar 2025 13:35:06 -0700 Subject: [PATCH 01/12] initial --- docs/source/en/api/pipelines/cogvideox.md | 249 ++++++++++++---------- 1 file changed, 141 insertions(+), 108 deletions(-) diff --git a/docs/source/en/api/pipelines/cogvideox.md b/docs/source/en/api/pipelines/cogvideox.md index 53ef93246fd1..10128782b32b 100644 --- a/docs/source/en/api/pipelines/cogvideox.md +++ b/docs/source/en/api/pipelines/cogvideox.md @@ -15,148 +15,181 @@ # CogVideoX -
- LoRA +
+
+ LoRA +
-[CogVideoX: Text-to-Video Diffusion Models with An Expert Transformer](https://huggingface.co/papers/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. +[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. -The abstract from the paper is: +You can find all the original CogVideoX checkpoints under the [CogVideoX collection](https://huggingface.co/collections/THUDM/cogvideo-66c08e62f1685a3ade464cce). -*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.* +> [!TIP] +> Click on the CogVideoX models in the right sidebar for more examples of how to use CogVideoX for other video generation tasks. - +The example below demonstrates how to generate a video with CogVideoX, optimized for memory or inference speed. -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. + + - - -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). - -There are three official CogVideoX checkpoints for text-to-video and video-to-video. - -| checkpoints | recommended inference dtype | -|:---:|:---:| -| [`THUDM/CogVideoX-2b`](https://huggingface.co/THUDM/CogVideoX-2b) | torch.float16 | -| [`THUDM/CogVideoX-5b`](https://huggingface.co/THUDM/CogVideoX-5b) | torch.bfloat16 | -| [`THUDM/CogVideoX1.5-5b`](https://huggingface.co/THUDM/CogVideoX1.5-5b) | torch.bfloat16 | - -There are two official CogVideoX checkpoints available for image-to-video. - -| checkpoints | recommended inference dtype | -|:---:|:---:| -| [`THUDM/CogVideoX-5b-I2V`](https://huggingface.co/THUDM/CogVideoX-5b-I2V) | torch.bfloat16 | -| [`THUDM/CogVideoX-1.5-5b-I2V`](https://huggingface.co/THUDM/CogVideoX-1.5-5b-I2V) | torch.bfloat16 | - -For the CogVideoX 1.5 series: -- Text-to-video (T2V) works best at a resolution of 1360x768 because it was trained with that specific resolution. -- 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. -- 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. - -There are two official CogVideoX checkpoints that support pose controllable generation (by the [Alibaba-PAI](https://huggingface.co/alibaba-pai) team). - -| checkpoints | recommended inference dtype | -|:---:|:---:| -| [`alibaba-pai/CogVideoX-Fun-V1.1-2b-Pose`](https://huggingface.co/alibaba-pai/CogVideoX-Fun-V1.1-2b-Pose) | torch.bfloat16 | -| [`alibaba-pai/CogVideoX-Fun-V1.1-5b-Pose`](https://huggingface.co/alibaba-pai/CogVideoX-Fun-V1.1-5b-Pose) | torch.bfloat16 | +```py +import torch +from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel +from diffusers.hooks import apply_group_offloading +from diffusers.utils import export_to_video -## Inference +# fp8 layerwise weight-casting +transformer = CogVideoXTransformer3DModel.from_pretrained( + "THUDM/CogVideoX-5b", + subfolder="transformer", + torch_dtype=torch.bfloat16 +) +transformer.enable_layerwise_casting( + storage_dtype=torch.float8_e4m3fn, + compute_dtype=torch.bfloat16 +) -Use [`torch.compile`](https://huggingface.co/docs/diffusers/main/en/tutorials/fast_diffusion#torchcompile) to reduce the inference latency. +pipeline = CogVideoXPipeline.from_pretrained( + "THUDM/CogVideoX-5b", + transformer=transformer, + torch_dtype=torch.bfloat16 +) +pipeline.to("cuda") + +# model-offloading +pipeline.enable_model_cpu_offload() + +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.") +video = pipeline( + prompt=prompt, + guidance_scale=6, + num_inference_steps=50 +).frames[0] +export_to_video(video, "output.mp4", fps=8) +``` -First, load the pipeline: +Reduce memory usage even more if necessary by quantizing a model to a lower precision data type. -```python +```py import torch -from diffusers import CogVideoXPipeline, CogVideoXImageToVideoPipeline -from diffusers.utils import export_to_video,load_image -pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b").to("cuda") # or "THUDM/CogVideoX-2b" -``` +from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel, TorchAoConfig +from diffusers.utils import export_to_video -If you are using the image-to-video pipeline, load it as follows: +# quantize weights to int8 with torchao +quantization_config = TorchAoConfig("int8wo") +transformer = CogVideoXTransformer3DModel.from_pretrained( + "THUDM/CogVideoX-5b", + subfolder="transformer", + quantization_config=quantization_config, + torch_dtype=torch.bfloat16, +) +# fp8 layerwise weight-casting +transformer.enable_layerwise_casting( + storage_dtype=torch.float8_e4m3fn, + compute_dtype=torch.bfloat16 +) -```python -pipe = CogVideoXImageToVideoPipeline.from_pretrained("THUDM/CogVideoX-5b-I2V").to("cuda") -``` +pipeline = CogVideoXPipeline.from_pretrained( + "THUDM/CogVideoX-5b", + transformer=transformer, + torch_dtype=torch.bfloat16, +) +pipeline.to("cuda") -Then change the memory layout of the pipelines `transformer` component to `torch.channels_last`: +# model-offloading +pipeline.enable_model_cpu_offload() -```python -pipe.transformer.to(memory_format=torch.channels_last) +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.") +video = pipeline(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0] +export_to_video(video, "output.mp4", fps=8) ``` -Compile the components and run inference: + + -```python -pipe.transformer = torch.compile(pipeline.transformer, mode="max-autotune", fullgraph=True) +Compilation is slow the first time but subsequent calls to the pipeline are faster. -# CogVideoX works well with long and well-described prompts -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." -video = pipe(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0] -``` +```py +import torch +from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel +from diffusers.hooks import apply_group_offloading +from diffusers.utils import export_to_video -The [T2V benchmark](https://gist.github.com/a-r-r-o-w/5183d75e452a368fd17448fcc810bd3f) results on an 80GB A100 machine are: +pipeline = CogVideoXPipeline.from_pretrained( + "THUDM/CogVideoX-2b", + torch_dtype=torch.float16 +).to("cuda") + +# torch.compile +pipeline.transformer.to(memory_format=torch.channels_last) +pipeline.transformer = torch.compile( + pipeline.transformer, mode="max-autotune", fullgraph=True +) -``` -Without torch.compile(): Average inference time: 96.89 seconds. -With torch.compile(): Average inference time: 76.27 seconds. +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.") +video = pipeline( + prompt=prompt, + guidance_scale=6, + num_inference_steps=50 +).frames[0] +export_to_video(video, "output.mp4", fps=8) ``` -### Memory optimization + + -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. - -- `pipe.enable_model_cpu_offload()`: - - Without enabling cpu offloading, memory usage is `33 GB` - - With enabling cpu offloading, memory usage is `19 GB` -- `pipe.enable_sequential_cpu_offload()`: - - Similar to `enable_model_cpu_offload` but can significantly reduce memory usage at the cost of slow inference - - When enabled, memory usage is under `4 GB` -- `pipe.vae.enable_tiling()`: - - With enabling cpu offloading and tiling, memory usage is `11 GB` -- `pipe.vae.enable_slicing()` - -## Quantization - -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. - -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. +CogVideoX supports LoRAs with [`~loaders.CogVideoXLoraLoaderMixin.load_lora_weights`]. ```py import torch -from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, CogVideoXTransformer3DModel, CogVideoXPipeline +from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel +from diffusers.hooks import apply_group_offloading from diffusers.utils import export_to_video -from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel - -quant_config = BitsAndBytesConfig(load_in_8bit=True) -text_encoder_8bit = T5EncoderModel.from_pretrained( - "THUDM/CogVideoX-2b", - subfolder="text_encoder", - quantization_config=quant_config, - torch_dtype=torch.float16, -) - -quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True) -transformer_8bit = CogVideoXTransformer3DModel.from_pretrained( - "THUDM/CogVideoX-2b", - subfolder="transformer", - quantization_config=quant_config, - torch_dtype=torch.float16, -) pipeline = CogVideoXPipeline.from_pretrained( - "THUDM/CogVideoX-2b", - text_encoder=text_encoder_8bit, - transformer=transformer_8bit, - torch_dtype=torch.float16, - device_map="balanced", + "THUDM/CogVideoX-5b", + torch_dtype=torch.bfloat16 ) - -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." -video = pipeline(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0] -export_to_video(video, "ship.mp4", fps=8) +pipeline.to("cuda") + +pipeline.load_lora_weights("finetrainers/CogVideoX-1.5-crush-smol-v0", adapter_name="crush-lora") +pipeline.set_adapters("crush-lora", 0.9) + +# model-offloading +pipeline.enable_model_cpu_offload() + +prompt = """ +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. +""" +negative_prompt = "inconsistent motion, blurry motion, worse quality, degenerate outputs, deformed outputs" + +video = pipeline( + prompt=prompt, + negative_prompt=negative_prompt, + num_frames=81, + height=480, + width=768, + num_inference_steps=50 +).frames[0] +export_to_video(video, "output.mp4", fps=16) ``` +## Notes + +- The text-to-video (T2V) checkpoints work best with a resolution of 1360x768 because that was the resolution it was pretrained on. +- 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. +- Both T2V and I2V checkpoints work best with 81 and 161 frames. It is recommended to export the generated video at 16fps. + ## CogVideoXPipeline [[autodoc]] CogVideoXPipeline From ef82096d5faeefb5c0127992d8ffb7a3a638ca56 Mon Sep 17 00:00:00 2001 From: stevhliu Date: Tue, 18 Mar 2025 16:02:42 -0700 Subject: [PATCH 02/12] update --- docs/source/en/_toctree.yml | 2 - docs/source/en/api/pipelines/cogvideox.md | 73 ++++++------ docs/source/en/using-diffusers/cogvideox.md | 120 -------------------- 3 files changed, 36 insertions(+), 159 deletions(-) delete mode 100644 docs/source/en/using-diffusers/cogvideox.md diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index 0d6d3aee5a6a..f13b7d54aec4 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -92,8 +92,6 @@ title: API Reference title: Hybrid Inference - sections: - - local: using-diffusers/cogvideox - title: CogVideoX - local: using-diffusers/consisid title: ConsisID - local: using-diffusers/sdxl diff --git a/docs/source/en/api/pipelines/cogvideox.md b/docs/source/en/api/pipelines/cogvideox.md index 10128782b32b..7dbfc586c4bb 100644 --- a/docs/source/en/api/pipelines/cogvideox.md +++ b/docs/source/en/api/pipelines/cogvideox.md @@ -13,14 +13,14 @@ # limitations under the License. --> -# CogVideoX -
LoRA
+# CogVideoX + [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. You can find all the original CogVideoX checkpoints under the [CogVideoX collection](https://huggingface.co/collections/THUDM/cogvideo-66c08e62f1685a3ade464cce). @@ -148,44 +148,43 @@ export_to_video(video, "output.mp4", fps=8) -CogVideoX supports LoRAs with [`~loaders.CogVideoXLoraLoaderMixin.load_lora_weights`]. - -```py -import torch -from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel -from diffusers.hooks import apply_group_offloading -from diffusers.utils import export_to_video - -pipeline = CogVideoXPipeline.from_pretrained( - "THUDM/CogVideoX-5b", - torch_dtype=torch.bfloat16 -) -pipeline.to("cuda") - -pipeline.load_lora_weights("finetrainers/CogVideoX-1.5-crush-smol-v0", adapter_name="crush-lora") -pipeline.set_adapters("crush-lora", 0.9) - -# model-offloading -pipeline.enable_model_cpu_offload() - -prompt = """ -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. -""" -negative_prompt = "inconsistent motion, blurry motion, worse quality, degenerate outputs, deformed outputs" +## Notes -video = pipeline( - prompt=prompt, - negative_prompt=negative_prompt, - num_frames=81, - height=480, - width=768, - num_inference_steps=50 -).frames[0] -export_to_video(video, "output.mp4", fps=16) -``` +- CogVideoX supports LoRAs with [`~loaders.CogVideoXLoraLoaderMixin.load_lora_weights`]. -## Notes + ```py + import torch + from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel + from diffusers.hooks import apply_group_offloading + from diffusers.utils import export_to_video + pipeline = CogVideoXPipeline.from_pretrained( + "THUDM/CogVideoX-5b", + torch_dtype=torch.bfloat16 + ) + pipeline.to("cuda") + + pipeline.load_lora_weights("finetrainers/CogVideoX-1.5-crush-smol-v0", adapter_name="crush-lora") + pipeline.set_adapters("crush-lora", 0.9) + + # model-offloading + pipeline.enable_model_cpu_offload() + + prompt = """ + 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. + """ + negative_prompt = "inconsistent motion, blurry motion, worse quality, degenerate outputs, deformed outputs" + + video = pipeline( + prompt=prompt, + negative_prompt=negative_prompt, + num_frames=81, + height=480, + width=768, + num_inference_steps=50 + ).frames[0] + export_to_video(video, "output.mp4", fps=16) + ``` - The text-to-video (T2V) checkpoints work best with a resolution of 1360x768 because that was the resolution it was pretrained on. - 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. - Both T2V and I2V checkpoints work best with 81 and 161 frames. It is recommended to export the generated video at 16fps. diff --git a/docs/source/en/using-diffusers/cogvideox.md b/docs/source/en/using-diffusers/cogvideox.md deleted file mode 100644 index 9c3091c074c5..000000000000 --- a/docs/source/en/using-diffusers/cogvideox.md +++ /dev/null @@ -1,120 +0,0 @@ - -# CogVideoX - -CogVideoX is a text-to-video generation model focused on creating more coherent videos aligned with a prompt. It achieves this using several methods. - -- a 3D variational autoencoder that compresses videos spatially and temporally, improving compression rate and video accuracy. - -- an expert transformer block to help align text and video, and a 3D full attention module for capturing and creating spatially and temporally accurate videos. - - - -## Load model checkpoints -Model weights may be stored in separate subfolders on the Hub or locally, in which case, you should use the [`~DiffusionPipeline.from_pretrained`] method. - - -```py -from diffusers import CogVideoXPipeline, CogVideoXImageToVideoPipeline -pipe = CogVideoXPipeline.from_pretrained( - "THUDM/CogVideoX-2b", - torch_dtype=torch.float16 -) - -pipe = CogVideoXImageToVideoPipeline.from_pretrained( - "THUDM/CogVideoX-5b-I2V", - torch_dtype=torch.bfloat16 -) - -``` - -## Text-to-Video -For text-to-video, pass a text prompt. By default, CogVideoX generates a 720x480 video for the best results. - -```py -import torch -from diffusers import CogVideoXPipeline -from diffusers.utils import export_to_video - -prompt = "An elderly gentleman, with a serene expression, sits at the water's edge, a steaming cup of tea by his side. He is engrossed in his artwork, brush in hand, as he renders an oil painting on a canvas that's propped up against a small, weathered table. The sea breeze whispers through his silver hair, gently billowing his loose-fitting white shirt, while the salty air adds an intangible element to his masterpiece in progress. The scene is one of tranquility and inspiration, with the artist's canvas capturing the vibrant hues of the setting sun reflecting off the tranquil sea." - -pipe = CogVideoXPipeline.from_pretrained( - "THUDM/CogVideoX-5b", - torch_dtype=torch.bfloat16 -) - -pipe.enable_model_cpu_offload() -pipe.vae.enable_tiling() - -video = pipe( - prompt=prompt, - num_videos_per_prompt=1, - num_inference_steps=50, - num_frames=49, - guidance_scale=6, - generator=torch.Generator(device="cuda").manual_seed(42), -).frames[0] - -export_to_video(video, "output.mp4", fps=8) - -``` - - -
- generated image of an astronaut in a jungle -
- - -## Image-to-Video - - -You'll use the [THUDM/CogVideoX-5b-I2V](https://huggingface.co/THUDM/CogVideoX-5b-I2V) checkpoint for this guide. - -```py -import torch -from diffusers import CogVideoXImageToVideoPipeline -from diffusers.utils import export_to_video, load_image - -prompt = "A vast, shimmering ocean flows gracefully under a twilight sky, its waves undulating in a mesmerizing dance of blues and greens. The surface glints with the last rays of the setting sun, casting golden highlights that ripple across the water. Seagulls soar above, their cries blending with the gentle roar of the waves. The horizon stretches infinitely, where the ocean meets the sky in a seamless blend of hues. Close-ups reveal the intricate patterns of the waves, capturing the fluidity and dynamic beauty of the sea in motion." -image = load_image(image="cogvideox_rocket.png") -pipe = CogVideoXImageToVideoPipeline.from_pretrained( - "THUDM/CogVideoX-5b-I2V", - torch_dtype=torch.bfloat16 -) - -pipe.vae.enable_tiling() -pipe.vae.enable_slicing() - -video = pipe( - prompt=prompt, - image=image, - num_videos_per_prompt=1, - num_inference_steps=50, - num_frames=49, - guidance_scale=6, - generator=torch.Generator(device="cuda").manual_seed(42), -).frames[0] - -export_to_video(video, "output.mp4", fps=8) -``` - -
-
- -
initial image
-
-
- -
generated video
-
-
- From 37a12e6f981fe8e0346da02faae7351b0c07e267 Mon Sep 17 00:00:00 2001 From: stevhliu Date: Wed, 19 Mar 2025 17:44:55 -0700 Subject: [PATCH 03/12] hunyuanvideo --- docs/source/en/api/pipelines/cogvideox.md | 5 +- docs/source/en/api/pipelines/hunyuan_video.md | 146 +++++++++++++----- 2 files changed, 110 insertions(+), 41 deletions(-) diff --git a/docs/source/en/api/pipelines/cogvideox.md b/docs/source/en/api/pipelines/cogvideox.md index 7dbfc586c4bb..2812ae175515 100644 --- a/docs/source/en/api/pipelines/cogvideox.md +++ b/docs/source/en/api/pipelines/cogvideox.md @@ -23,12 +23,12 @@ [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. -You can find all the original CogVideoX checkpoints under the [CogVideoX collection](https://huggingface.co/collections/THUDM/cogvideo-66c08e62f1685a3ade464cce). +You can find all the original CogVideoX checkpoints under the CogVideoX [collection](https://huggingface.co/collections/THUDM/cogvideo-66c08e62f1685a3ade464cce). > [!TIP] > Click on the CogVideoX models in the right sidebar for more examples of how to use CogVideoX for other video generation tasks. -The example below demonstrates how to generate a video with CogVideoX, optimized for memory or inference speed. +The example below demonstrates how to generate a video optimized for memory or inference speed. @@ -164,6 +164,7 @@ export_to_video(video, "output.mp4", fps=8) ) pipeline.to("cuda") + # load LoRA weights pipeline.load_lora_weights("finetrainers/CogVideoX-1.5-crush-smol-v0", adapter_name="crush-lora") pipeline.set_adapters("crush-lora", 0.9) diff --git a/docs/source/en/api/pipelines/hunyuan_video.md b/docs/source/en/api/pipelines/hunyuan_video.md index 5d068c8b6ef8..37b7de28dcb8 100644 --- a/docs/source/en/api/pipelines/hunyuan_video.md +++ b/docs/source/en/api/pipelines/hunyuan_video.md @@ -12,60 +12,66 @@ # See the License for the specific language governing permissions and # limitations under the License. --> -# HunyuanVideo - -
- LoRA +
+
+ LoRA +
-[HunyuanVideo](https://www.arxiv.org/abs/2412.03603) by Tencent. - -*Recent advancements in video generation have significantly impacted daily life for both individuals and industries. However, the leading video generation models remain closed-source, resulting in a notable performance gap between industry capabilities and those available to the public. In this report, we introduce HunyuanVideo, an innovative open-source video foundation model that demonstrates performance in video generation comparable to, or even surpassing, that of leading closed-source models. HunyuanVideo encompasses a comprehensive framework that integrates several key elements, including data curation, advanced architectural design, progressive model scaling and training, and an efficient infrastructure tailored for large-scale model training and inference. As a result, we successfully trained a video generative model with over 13 billion parameters, making it the largest among all open-source models. We conducted extensive experiments and implemented a series of targeted designs to ensure high visual quality, motion dynamics, text-video alignment, and advanced filming techniques. According to evaluations by professionals, HunyuanVideo outperforms previous state-of-the-art models, including Runway Gen-3, Luma 1.6, and three top-performing Chinese video generative models. By releasing the code for the foundation model and its applications, we aim to bridge the gap between closed-source and open-source communities. This initiative will empower individuals within the community to experiment with their ideas, fostering a more dynamic and vibrant video generation ecosystem. The code is publicly available at [this https URL](https://github.com/tencent/HunyuanVideo).* - - +# HunyuanVideo -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. +[HunyuanVideo](https://huggingface.co/papers/2412.03603) is a 13B diffusion transformer model designed to be competitive with closed-source video foundation models and enable wider community access. This model uses a "dual-stream to single-stream" architecture to separately process the video and text tokens first, before concatenating and feeding them to the transformer to fuse the multimodal information. A pretrained multimodal large language model (MLLM) is used as the encoder because it has better image-text alignment, better image detail description and reasoning, and it can be used as a zero-shot learner if system instructions are added to user prompts. Finally, HunyuanVideo uses a 3D causal variational autoencoder to more efficiently process video data at the original resolution and frame rate. - +You can find all the original HunyuanVideo checkpoints under the Tencent [organization](https://huggingface.co/tencent). -Recommendations for inference: -- Both text encoders should be in `torch.float16`. -- Transformer should be in `torch.bfloat16`. -- VAE should be in `torch.float16`. -- `num_frames` should be of the form `4 * k + 1`, for example `49` or `129`. -- For smaller resolution videos, try lower values of `shift` (between `2.0` to `5.0`) in the [Scheduler](https://huggingface.co/docs/diffusers/main/en/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler.shift). For larger resolution images, try higher values (between `7.0` and `12.0`). The default value is `7.0` for HunyuanVideo. -- For more information about supported resolutions and other details, please refer to the original repository [here](https://github.com/Tencent/HunyuanVideo/). +> [!TIP] +> The examples below use a checkpoint from [hunyuanvideo-community](https://huggingface.co/hunyuanvideo-community) because the weights are stored in a layout compatible with Diffusers. -## Available models +The example below demonstrates how to generate a video optimized for memory or inference speed. -The following models are available for the [`HunyuanVideoPipeline`](text-to-video) pipeline: + + -| Model name | Description | -|:---|:---| -| [`hunyuanvideo-community/HunyuanVideo`](https://huggingface.co/hunyuanvideo-community/HunyuanVideo) | Official HunyuanVideo (guidance-distilled). Performs best at multiple resolutions and frames. Performs best with `guidance_scale=6.0`, `true_cfg_scale=1.0` and without a negative prompt. | -| [`https://huggingface.co/Skywork/SkyReels-V1-Hunyuan-T2V`](https://huggingface.co/Skywork/SkyReels-V1-Hunyuan-T2V) | Skywork's custom finetune of HunyuanVideo (de-distilled). Performs best with `97x544x960` resolution, `guidance_scale=1.0`, `true_cfg_scale=6.0` and a negative prompt. | +```py +import torch +from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, HunyuanVideoTransformer3DModel, HunyuanVideoPipeline +from diffusers.utils import export_to_video -The following models are available for the image-to-video pipeline: +# quantization +quant_config = DiffusersBitsAndBytesConfig(load_in_4bit=True) +transformer = HunyuanVideoTransformer3DModel.from_pretrained( + "hunyuanvideo-community/HunyuanVideo", + subfolder="transformer", + quantization_config=quant_config, + torch_dtype=torch.bfloat16, +) -| Model name | Description | -|:---|:---| -| [`Skywork/SkyReels-V1-Hunyuan-I2V`](https://huggingface.co/Skywork/SkyReels-V1-Hunyuan-I2V) | Skywork's custom finetune of HunyuanVideo (de-distilled). Performs best with `97x544x960` resolution. Performs best at `97x544x960` resolution, `guidance_scale=1.0`, `true_cfg_scale=6.0` and a negative prompt. | -| [`hunyuanvideo-community/HunyuanVideo-I2V-33ch`](https://huggingface.co/hunyuanvideo-community/HunyuanVideo-I2V) | Tecent's official HunyuanVideo 33-channel I2V model. Performs best at resolutions of 480, 720, 960, 1280. A higher `shift` value when initializing the scheduler is recommended (good values are between 7 and 20). | -| [`hunyuanvideo-community/HunyuanVideo-I2V`](https://huggingface.co/hunyuanvideo-community/HunyuanVideo-I2V) | Tecent's official HunyuanVideo 16-channel I2V model. Performs best at resolutions of 480, 720, 960, 1280. A higher `shift` value when initializing the scheduler is recommended (good values are between 7 and 20) | +pipeline = HunyuanVideoPipeline.from_pretrained( + "hunyuanvideo-community/HunyuanVideo", + transformer=transformer, + torch_dtype=torch.float16, +) -## Quantization +# model-offloading +pipeline.enable_model_cpu_offload() +pipeline.vae.enable_tiling() -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. +prompt = "A fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys." +video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0] +export_to_video(video, "output.mp4", fps=15) +``` -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 [`HunyuanVideoPipeline`] for inference with bitsandbytes. + + ```py import torch from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, HunyuanVideoTransformer3DModel, HunyuanVideoPipeline from diffusers.utils import export_to_video -quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True) -transformer_8bit = HunyuanVideoTransformer3DModel.from_pretrained( +# quantization +quant_config = DiffusersBitsAndBytesConfig(load_in_4bit=True) +transformer = HunyuanVideoTransformer3DModel.from_pretrained( "hunyuanvideo-community/HunyuanVideo", subfolder="transformer", quantization_config=quant_config, @@ -74,16 +80,78 @@ transformer_8bit = HunyuanVideoTransformer3DModel.from_pretrained( pipeline = HunyuanVideoPipeline.from_pretrained( "hunyuanvideo-community/HunyuanVideo", - transformer=transformer_8bit, + transformer=transformer, torch_dtype=torch.float16, - device_map="balanced", ) -prompt = "A cat walks on the grass, realistic style." +# model-offloading +pipeline.enable_model_cpu_offload() +pipeline.vae.enable_tiling() + +# torch.compile +pipeline.transformer.to(memory_format=torch.channels_last) +pipeline.transformer = torch.compile( + pipeline.transformer, mode="max-autotune", fullgraph=True +) + +prompt = "A fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys." video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0] -export_to_video(video, "cat.mp4", fps=15) +export_to_video(video, "output.mp4", fps=15) ``` + + + +## Notes + +- HunyuanVideo supports LoRAs with [`~loaders.HunyuanVideoLoraLoaderMixin.load_lora_weights`]. + + ```py + import torch + from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, HunyuanVideoTransformer3DModel, HunyuanVideoPipeline + from diffusers.utils import export_to_video + + # quantize weights to int4 with bitsandbytes + quant_config = DiffusersBitsAndBytesConfig(load_in_4bit=True) + transformer = HunyuanVideoTransformer3DModel.from_pretrained( + "hunyuanvideo-community/HunyuanVideo", + subfolder="transformer", + quantization_config=quant_config, + torch_dtype=torch.bfloat16, + ) + + pipeline = HunyuanVideoPipeline.from_pretrained( + "hunyuanvideo-community/HunyuanVideo", + transformer=transformer, + torch_dtype=torch.float16, + ) + + # load LoRA weights + pipeline.load_lora_weights("https://huggingface.co/lucataco/hunyuan-steamboat-willie-10", adapter_name="steamboat-willie") + pipeline.set_adapters("steamboat-willie", 0.9) + + # model-offloading + pipeline.enable_model_cpu_offload() + pipeline.vae.enable_tiling() + + prompt = """ + In the style of SWR. A black and white animated scene featuring a fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys. + """ + video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0] + export_to_video(video, "output.mp4", fps=15) + ``` + +- Refer to the table below for recommended inference values. + + | parameter | recommended value | + |---|---| + | text encoder dtype | `torch.float16` | + | transformer dtype | `torch.bfloat16` | + | vae dtype | `torch.float16` | + | `num_frames` | 4 * k + 1 | + +- Try lower `shift` values (`2.0` to `5.0`) for lower resolution videos, and try higher `shift` values (`7.0` to `12.0`) for higher resolution images. + ## HunyuanVideoPipeline [[autodoc]] HunyuanVideoPipeline From 539c654b73c6346584d9843e6e17dd9629ee3c36 Mon Sep 17 00:00:00 2001 From: stevhliu Date: Mon, 24 Mar 2025 16:02:59 -0700 Subject: [PATCH 04/12] ltx --- docs/source/en/api/pipelines/cogvideox.md | 2 +- docs/source/en/api/pipelines/hunyuan_video.md | 4 +- docs/source/en/api/pipelines/ltx_video.md | 417 +++++------------- docs/source/en/api/pipelines/wan.md | 10 +- 4 files changed, 132 insertions(+), 301 deletions(-) diff --git a/docs/source/en/api/pipelines/cogvideox.md b/docs/source/en/api/pipelines/cogvideox.md index 2812ae175515..5fe5e50cbb92 100644 --- a/docs/source/en/api/pipelines/cogvideox.md +++ b/docs/source/en/api/pipelines/cogvideox.md @@ -23,7 +23,7 @@ [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. -You can find all the original CogVideoX checkpoints under the CogVideoX [collection](https://huggingface.co/collections/THUDM/cogvideo-66c08e62f1685a3ade464cce). +You can find all the original CogVideoX checkpoints under the [CogVideoX](https://huggingface.co/collections/THUDM/cogvideo-66c08e62f1685a3ade464cce) collection. > [!TIP] > Click on the CogVideoX models in the right sidebar for more examples of how to use CogVideoX for other video generation tasks. diff --git a/docs/source/en/api/pipelines/hunyuan_video.md b/docs/source/en/api/pipelines/hunyuan_video.md index 37b7de28dcb8..f12122729610 100644 --- a/docs/source/en/api/pipelines/hunyuan_video.md +++ b/docs/source/en/api/pipelines/hunyuan_video.md @@ -22,7 +22,7 @@ [HunyuanVideo](https://huggingface.co/papers/2412.03603) is a 13B diffusion transformer model designed to be competitive with closed-source video foundation models and enable wider community access. This model uses a "dual-stream to single-stream" architecture to separately process the video and text tokens first, before concatenating and feeding them to the transformer to fuse the multimodal information. A pretrained multimodal large language model (MLLM) is used as the encoder because it has better image-text alignment, better image detail description and reasoning, and it can be used as a zero-shot learner if system instructions are added to user prompts. Finally, HunyuanVideo uses a 3D causal variational autoencoder to more efficiently process video data at the original resolution and frame rate. -You can find all the original HunyuanVideo checkpoints under the Tencent [organization](https://huggingface.co/tencent). +You can find all the original HunyuanVideo checkpoints under the [Tencent](https://huggingface.co/tencent) organization. > [!TIP] > The examples below use a checkpoint from [hunyuanvideo-community](https://huggingface.co/hunyuanvideo-community) because the weights are stored in a layout compatible with Diffusers. @@ -64,6 +64,8 @@ export_to_video(video, "output.mp4", fps=15) +Compilation is slow the first time but subsequent calls to the pipeline are faster. + ```py import torch from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, HunyuanVideoTransformer3DModel, HunyuanVideoPipeline diff --git a/docs/source/en/api/pipelines/ltx_video.md b/docs/source/en/api/pipelines/ltx_video.md index 0ad558fef9d7..c7f8f97005eb 100644 --- a/docs/source/en/api/pipelines/ltx_video.md +++ b/docs/source/en/api/pipelines/ltx_video.md @@ -12,322 +12,141 @@ # See the License for the specific language governing permissions and # limitations under the License. --> -# LTX Video - -
- LoRA - MPS +
+
+ LoRA +
-[LTX Video](https://huggingface.co/Lightricks/LTX-Video) is the first DiT-based video generation model capable of generating high-quality videos in real-time. It produces 24 FPS videos at a 768x512 resolution faster than they can be watched. Trained on a large-scale dataset of diverse videos, the model generates high-resolution videos with realistic and varied content. We provide a model for both text-to-video as well as image + text-to-video usecases. - - - -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. - - - -Available models: - -| Model name | Recommended dtype | -|:-------------:|:-----------------:| -| [`LTX Video 2B 0.9.0`](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltx-video-2b-v0.9.safetensors) | `torch.bfloat16` | -| [`LTX Video 2B 0.9.1`](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltx-video-2b-v0.9.1.safetensors) | `torch.bfloat16` | -| [`LTX Video 2B 0.9.5`](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltx-video-2b-v0.9.5.safetensors) | `torch.bfloat16` | -| [`LTX Video 13B 0.9.7`](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-13b-0.9.7-dev.safetensors) | `torch.bfloat16` | -| [`LTX Video 13B 0.9.7 (distilled)`](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-13b-0.9.7-distilled.safetensors) | `torch.bfloat16` | -| [`LTX Video Spatial Upscaler 0.9.7`](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-spatial-upscaler-0.9.7.safetensors) | `torch.bfloat16` | - -Note: The recommended dtype is for the transformer component. The VAE and text encoders can be either `torch.float32`, `torch.bfloat16` or `torch.float16` but the recommended dtype is `torch.bfloat16` as used in the original repository. +# LTX-Video -## Recommended settings for generation +[LTX-Video](https://huggingface.co/Lightricks/LTX-Video) is a diffusion transformer designed for fast and real-time generation of high-resolution videos from text and images. The main feature of LTX-Video is the Video-VAE. The Video-VAE has a higher pixel to latent compression ratio (1:192) which enables more efficient video data processing and faster generation speed. To support and prevent the finer details from being lost during generation, the Video-VAE decoder performs the latent to pixel conversion *and* the last denoising step. -For the best results, it is recommended to follow the guidelines mentioned in the official LTX Video [repository](https://github.com/Lightricks/LTX-Video). +You can find all the original LTX-Video checkpoints under the [Lightricks](https://huggingface.co/Lightricks) organization. -- Some variants of LTX Video are guidance-distilled. For guidance-distilled models, `guidance_scale` must be set to `1.0`. For any other models, `guidance_scale` should be set higher (e.g., `5.0`) for good generation quality. -- For variants with a timestep-aware VAE (LTXV 0.9.1 and above), it is recommended to set `decode_timestep` to `0.05` and `image_cond_noise_scale` to `0.025`. -- For variants that support interpolation between multiple conditioning images and videos (LTXV 0.9.5 and above), it is recommended to use similar looking images/videos for the best results. High divergence between the conditionings may lead to abrupt transitions in the generated video. +> [!TIP] +> Click on the LTX-Video models in the right sidebar for more examples of how to use LTX-Video for other video generation tasks. - +The example below demonstrates how to generate a video optimized for memory or inference speed. - + + -The examples below show some recommended generation settings, but note that all features supported in the original [LTX Video repository](https://github.com/Lightricks/LTX-Video) are not supported in `diffusers` yet (for example, Spatio-temporal Guidance and CRF compression for image inputs). This will gradually be supported in the future. For the best possible generation quality, we recommend using the code from the original repository. - - - -## Using LTX Video 13B 0.9.7 - -LTX Video 0.9.7 comes with a spatial latent upscaler and a 13B parameter transformer. The inference involves generating a low resolution video first, which is very fast, followed by upscaling and refining the generated video. - - - -```python +```py import torch -from diffusers import LTXConditionPipeline, LTXLatentUpsamplePipeline -from diffusers.pipelines.ltx.pipeline_ltx_condition import LTXVideoCondition -from diffusers.utils import export_to_video, load_video - -pipe = LTXConditionPipeline.from_pretrained("Lightricks/LTX-Video-0.9.7-dev", torch_dtype=torch.bfloat16) -pipe_upsample = LTXLatentUpsamplePipeline.from_pretrained("Lightricks/ltxv-spatial-upscaler-0.9.7", vae=pipe.vae, torch_dtype=torch.bfloat16) -pipe.to("cuda") -pipe_upsample.to("cuda") -pipe.vae.enable_tiling() - -def round_to_nearest_resolution_acceptable_by_vae(height, width): - height = height - (height % pipe.vae_temporal_compression_ratio) - width = width - (width % pipe.vae_temporal_compression_ratio) - return height, width - -video = load_video( - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/cosmos/cosmos-video2world-input-vid.mp4" -)[:21] # Use only the first 21 frames as conditioning -condition1 = LTXVideoCondition(video=video, frame_index=0) - -prompt = "The video depicts a winding mountain road covered in snow, with a single vehicle traveling along it. The road is flanked by steep, rocky cliffs and sparse vegetation. The landscape is characterized by rugged terrain and a river visible in the distance. The scene captures the solitude and beauty of a winter drive through a mountainous region." -negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted" -expected_height, expected_width = 768, 1152 -downscale_factor = 2 / 3 -num_frames = 161 - -# Part 1. Generate video at smaller resolution -# Text-only conditioning is also supported without the need to pass `conditions` -downscaled_height, downscaled_width = int(expected_height * downscale_factor), int(expected_width * downscale_factor) -downscaled_height, downscaled_width = round_to_nearest_resolution_acceptable_by_vae(downscaled_height, downscaled_width) -latents = pipe( - conditions=[condition1], - prompt=prompt, - negative_prompt=negative_prompt, - width=downscaled_width, - height=downscaled_height, - num_frames=num_frames, - num_inference_steps=30, - decode_timestep=0.05, - decode_noise_scale=0.025, - image_cond_noise_scale=0.0, - guidance_scale=5.0, - guidance_rescale=0.7, - generator=torch.Generator().manual_seed(0), - output_type="latent", -).frames - -# Part 2. Upscale generated video using latent upsampler with fewer inference steps -# The available latent upsampler upscales the height/width by 2x -upscaled_height, upscaled_width = downscaled_height * 2, downscaled_width * 2 -upscaled_latents = pipe_upsample( - latents=latents, - output_type="latent" -).frames - -# Part 3. Denoise the upscaled video with few steps to improve texture (optional, but recommended) -video = pipe( - conditions=[condition1], - prompt=prompt, - negative_prompt=negative_prompt, - width=upscaled_width, - height=upscaled_height, - num_frames=num_frames, - denoise_strength=0.4, # Effectively, 4 inference steps out of 10 - num_inference_steps=10, - latents=upscaled_latents, - decode_timestep=0.05, - decode_noise_scale=0.025, - image_cond_noise_scale=0.0, - guidance_scale=5.0, - guidance_rescale=0.7, - generator=torch.Generator().manual_seed(0), - output_type="pil", -).frames[0] - -# Part 4. Downscale the video to the expected resolution -video = [frame.resize((expected_width, expected_height)) for frame in video] - -export_to_video(video, "output.mp4", fps=24) -``` - -## Using LTX Video 0.9.7 (distilled) +from diffusers import LTXPipeline, LTXVideoTransformer3DModel +from diffusers.hooks import apply_group_offloading +from diffusers.utils import export_to_video -The same example as above can be used with the exception of the `guidance_scale` parameter. The model is both guidance and timestep distilled in order to speedup generation. It requires `guidance_scale` to be set to `1.0`. Additionally, to benefit from the timestep distillation, `num_inference_steps` can be set between `4` and `10` for good generation quality. +# fp8 layerwise weight-casting +transformer = LTXVideoTransformer3DModel.from_pretrained( + "Lightricks/LTX-Video", + subfolder="transformer", + torch_dtype=torch.bfloat16 +) +transformer.enable_layerwise_casting( + storage_dtype=torch.float8_e4m3fn, + compute_dtype=torch.bfloat16 +) -Additionally, custom timesteps can also be used for conditioning the generation. The authors recommend using the following timesteps for best results: -- Base model inference to prepare for upscaling: `[1000, 993, 987, 981, 975, 909, 725, 0.03]` -- Upscaling: `[1000, 909, 725, 421, 0]` +pipeline = LTXPipeline.from_pretrained("Lightricks/LTX-Video", transformer=transformer, torch_dtype=torch.bfloat16) -
- Full example +# group-offloading +onload_device = torch.device("cuda") +offload_device = torch.device("cpu") +pipeline.transformer.enable_group_offload(onload_device=onload_device, offload_device=offload_device, offload_type="leaf_level", use_stream=True) +apply_group_offloading(pipeline.text_encoder, onload_device=onload_device, offload_type="block_level", num_blocks_per_group=2) +apply_group_offloading(pipeline.vae, onload_device=onload_device, offload_type="leaf_level") -```python -import torch -from diffusers import LTXConditionPipeline, LTXLatentUpsamplePipeline -from diffusers.pipelines.ltx.pipeline_ltx_condition import LTXVideoCondition -from diffusers.utils import export_to_video, load_video - -pipe = LTXConditionPipeline.from_pretrained("Lightricks/LTX-Video-0.9.7-distilled", torch_dtype=torch.bfloat16) -pipe_upsample = LTXLatentUpsamplePipeline.from_pretrained("Lightricks/ltxv-spatial-upscaler-0.9.7", vae=pipe.vae, torch_dtype=torch.bfloat16) -pipe.to("cuda") -pipe_upsample.to("cuda") -pipe.vae.enable_tiling() - -def round_to_nearest_resolution_acceptable_by_vae(height, width): - height = height - (height % pipe.vae_temporal_compression_ratio) - width = width - (width % pipe.vae_temporal_compression_ratio) - return height, width - -prompt = "artistic anatomical 3d render, utlra quality, human half full male body with transparent skin revealing structure instead of organs, muscular, intricate creative patterns, monochromatic with backlighting, lightning mesh, scientific concept art, blending biology with botany, surreal and ethereal quality, unreal engine 5, ray tracing, ultra realistic, 16K UHD, rich details. camera zooms out in a rotating fashion" +prompt = "A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be real-life footage" negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted" -expected_height, expected_width = 768, 1152 -downscale_factor = 2 / 3 -num_frames = 161 - -# Part 1. Generate video at smaller resolution -downscaled_height, downscaled_width = int(expected_height * downscale_factor), int(expected_width * downscale_factor) -downscaled_height, downscaled_width = round_to_nearest_resolution_acceptable_by_vae(downscaled_height, downscaled_width) -latents = pipe( - prompt=prompt, - negative_prompt=negative_prompt, - width=downscaled_width, - height=downscaled_height, - num_frames=num_frames, - timesteps=[1000, 993, 987, 981, 975, 909, 725, 0.03], - decode_timestep=0.05, - decode_noise_scale=0.025, - image_cond_noise_scale=0.0, - guidance_scale=1.0, - guidance_rescale=0.7, - generator=torch.Generator().manual_seed(0), - output_type="latent", -).frames - -# Part 2. Upscale generated video using latent upsampler with fewer inference steps -# The available latent upsampler upscales the height/width by 2x -upscaled_height, upscaled_width = downscaled_height * 2, downscaled_width * 2 -upscaled_latents = pipe_upsample( - latents=latents, - adain_factor=1.0, - output_type="latent" -).frames - -# Part 3. Denoise the upscaled video with few steps to improve texture (optional, but recommended) -video = pipe( + +video = pipeline( prompt=prompt, negative_prompt=negative_prompt, - width=upscaled_width, - height=upscaled_height, - num_frames=num_frames, - denoise_strength=0.999, # Effectively, 4 inference steps out of 5 - timesteps=[1000, 909, 725, 421, 0], - latents=upscaled_latents, - decode_timestep=0.05, + width=768, + height=512, + num_frames=161, + decode_timestep=0.03, decode_noise_scale=0.025, - image_cond_noise_scale=0.0, - guidance_scale=1.0, - guidance_rescale=0.7, - generator=torch.Generator().manual_seed(0), - output_type="pil", + num_inference_steps=50, ).frames[0] - -# Part 4. Downscale the video to the expected resolution -video = [frame.resize((expected_width, expected_height)) for frame in video] - export_to_video(video, "output.mp4", fps=24) ```
-## Loading Single Files - -Loading the original LTX Video checkpoints is also possible with [`~ModelMixin.from_single_file`]. We recommend using `from_single_file` for the Lightricks series of models, as they plan to release multiple models in the future in the single file format. - -```python -import torch -from diffusers import AutoencoderKLLTXVideo, LTXImageToVideoPipeline, LTXVideoTransformer3DModel - -# `single_file_url` could also be https://huggingface.co/Lightricks/LTX-Video/ltx-video-2b-v0.9.1.safetensors -single_file_url = "https://huggingface.co/Lightricks/LTX-Video/ltx-video-2b-v0.9.safetensors" -transformer = LTXVideoTransformer3DModel.from_single_file( - single_file_url, torch_dtype=torch.bfloat16 -) -vae = AutoencoderKLLTXVideo.from_single_file(single_file_url, torch_dtype=torch.bfloat16) -pipe = LTXImageToVideoPipeline.from_pretrained( - "Lightricks/LTX-Video", transformer=transformer, vae=vae, torch_dtype=torch.bfloat16 -) - -# ... inference code ... -``` - -Alternatively, the pipeline can be used to load the weights with [`~FromSingleFileMixin.from_single_file`]. - -```python -import torch -from diffusers import LTXImageToVideoPipeline -from transformers import T5EncoderModel, T5Tokenizer - -single_file_url = "https://huggingface.co/Lightricks/LTX-Video/ltx-video-2b-v0.9.safetensors" -text_encoder = T5EncoderModel.from_pretrained( - "Lightricks/LTX-Video", subfolder="text_encoder", torch_dtype=torch.bfloat16 -) -tokenizer = T5Tokenizer.from_pretrained( - "Lightricks/LTX-Video", subfolder="tokenizer", torch_dtype=torch.bfloat16 -) -pipe = LTXImageToVideoPipeline.from_single_file( - single_file_url, text_encoder=text_encoder, tokenizer=tokenizer, torch_dtype=torch.bfloat16 -) -``` - -Loading [LTX GGUF checkpoints](https://huggingface.co/city96/LTX-Video-gguf) are also supported: +Reduce memory usage even more if necessary by quantizing a model to a lower precision data type. ```py import torch from diffusers.utils import export_to_video -from diffusers import LTXPipeline, LTXVideoTransformer3DModel, GGUFQuantizationConfig +from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, LTXVideoTransformer3DModel, LTXPipeline +from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel -ckpt_path = ( - "https://huggingface.co/city96/LTX-Video-gguf/blob/main/ltx-video-2b-v0.9-Q3_K_S.gguf" +# quantize weights to int8 with bitsandbytes +quantization_config = BitsAndBytesConfig(load_in_8bit=True) +text_encoder = T5EncoderModel.from_pretrained( + "Lightricks/LTX-Video", + subfolder="text_encoder", + quantization_config=quantization_config, + torch_dtype=torch.bfloat16, ) -transformer = LTXVideoTransformer3DModel.from_single_file( - ckpt_path, - quantization_config=GGUFQuantizationConfig(compute_dtype=torch.bfloat16), + +quantization_config = DiffusersBitsAndBytesConfig(load_in_8bit=True) +transformer = LTXVideoTransformer3DModel.from_pretrained( + "Lightricks/LTX-Video", + subfolder="transformer", + quantization_config=quantization_config, torch_dtype=torch.bfloat16, ) -pipe = LTXPipeline.from_pretrained( + +pipeline = LTXPipeline.from_pretrained( "Lightricks/LTX-Video", + text_encoder=text_en, transformer=transformer, torch_dtype=torch.bfloat16, ) -pipe.enable_model_cpu_offload() prompt = "A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be real-life footage" negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted" - -video = pipe( +video = pipeline( prompt=prompt, negative_prompt=negative_prompt, - width=704, - height=480, + width=768, + height=512, num_frames=161, + decode_timestep=0.03, + decode_noise_scale=0.025, num_inference_steps=50, ).frames[0] -export_to_video(video, "output_gguf_ltx.mp4", fps=24) +export_to_video(video, "output.mp4", fps=24) ``` -Make sure to read the [documentation on GGUF](../../quantization/gguf) to learn more about our GGUF support. + + - +Compilation is slow the first time but subsequent calls to the pipeline are faster. -Loading and running inference with [LTX Video 0.9.1](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltx-video-2b-v0.9.1.safetensors) weights. - -```python +```py import torch from diffusers import LTXPipeline from diffusers.utils import export_to_video -pipe = LTXPipeline.from_pretrained("a-r-r-o-w/LTX-Video-0.9.1-diffusers", torch_dtype=torch.bfloat16) -pipe.to("cuda") +pipeline = LTXPipeline.from_pretrained( + "Lightricks/LTX-Video", torch_dtype=torch.bfloat16 +) + +# torch.compile +pipeline.transformer.to(memory_format=torch.channels_last) +pipeline.transformer = torch.compile( + pipeline.transformer, mode="max-autotune", fullgraph=True +) prompt = "A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be real-life footage" negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted" -video = pipe( +video = pipeline( prompt=prompt, negative_prompt=negative_prompt, width=768, @@ -340,48 +159,56 @@ video = pipe( export_to_video(video, "output.mp4", fps=24) ``` -Refer to [this section](https://huggingface.co/docs/diffusers/main/en/api/pipelines/cogvideox#memory-optimization) to learn more about optimizing memory consumption. + + -## Quantization +## Notes -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. +- LTX-Video supports LoRAs with [`~LTXVideoLoraLoaderMixin.load_lora_weights`]. -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 [`LTXPipeline`] for inference with bitsandbytes. + ```py + import torch + from diffusers import LTXConditionPipeline + from diffusers.utils import export_to_video -```py -import torch -from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, LTXVideoTransformer3DModel, LTXPipeline -from diffusers.utils import export_to_video -from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel + pipeline = LTXConditionPipeline.from_pretrained( + "Lightricks/LTX-Video-0.9.5", torch_dtype=torch.bfloat16 + ) -quant_config = BitsAndBytesConfig(load_in_8bit=True) -text_encoder_8bit = T5EncoderModel.from_pretrained( - "Lightricks/LTX-Video", - subfolder="text_encoder", - quantization_config=quant_config, - torch_dtype=torch.float16, -) + pipeline.load_lora_weights("Lightricks/LTX-Video-Cakeify-LoRA", adapter_name="cakeify") + pipeline.set_adapters("cakeify", 0.9) -quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True) -transformer_8bit = LTXVideoTransformer3DModel.from_pretrained( - "Lightricks/LTX-Video", - subfolder="transformer", - quantization_config=quant_config, - torch_dtype=torch.float16, -) + prompt = "CAKEIFY a person using a knife to cut a cake shaped like a pair of cowboy boots" -pipeline = LTXPipeline.from_pretrained( - "Lightricks/LTX-Video", - text_encoder=text_encoder_8bit, - transformer=transformer_8bit, - torch_dtype=torch.float16, - device_map="balanced", -) + video = pipeline( + prompt=prompt, + width=768, + height=512, + num_frames=161, + decode_timestep=0.03, + decode_noise_scale=0.025, + num_inference_steps=50, + ).frames[0] + export_to_video(video, "output.mp4", fps=24) + ``` +- LTX-Video supports loading from single files, such as [GGUF checkpoints](../../quantization/gguf), with [`FromOriginalModelMixin.from_single_file`] or [`FromSingleFileMixin.from_single_file`]. -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." -video = pipeline(prompt=prompt, num_frames=161, num_inference_steps=50).frames[0] -export_to_video(video, "ship.mp4", fps=24) -``` + ```py + import torch + from diffusers.utils import export_to_video + from diffusers import LTXPipeline, LTXVideoTransformer3DModel, GGUFQuantizationConfig + + transformer = LTXVideoTransformer3DModel.from_single_file( + "https://huggingface.co/city96/LTX-Video-gguf/blob/main/ltx-video-2b-v0.9-Q3_K_S.gguf" + quantization_config=GGUFQuantizationConfig(compute_dtype=torch.bfloat16), + torch_dtype=torch.bfloat16 + ) + pipeline = LTXPipeline.from_pretrained( + "Lightricks/LTX-Video", + transformer=transformer, + torch_dtype=bfloat16 + ) + ``` ## LTXPipeline diff --git a/docs/source/en/api/pipelines/wan.md b/docs/source/en/api/pipelines/wan.md index 09503125f5c5..3d81c5644f1a 100644 --- a/docs/source/en/api/pipelines/wan.md +++ b/docs/source/en/api/pipelines/wan.md @@ -12,12 +12,14 @@ # See the License for the specific language governing permissions and # limitations under the License. --> -# Wan - -
- LoRA +
+
+ LoRA +
+# Wan + [Wan 2.1](https://github.com/Wan-Video/Wan2.1) by the Alibaba Wan Team. From 3c6d331c8ad587155f4c207e1d158178e2ec6e98 Mon Sep 17 00:00:00 2001 From: stevhliu Date: Mon, 24 Mar 2025 16:44:57 -0700 Subject: [PATCH 05/12] fix --- docs/source/en/api/pipelines/hunyuan_video.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/source/en/api/pipelines/hunyuan_video.md b/docs/source/en/api/pipelines/hunyuan_video.md index f12122729610..7c5e300e0f25 100644 --- a/docs/source/en/api/pipelines/hunyuan_video.md +++ b/docs/source/en/api/pipelines/hunyuan_video.md @@ -61,7 +61,7 @@ video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0] export_to_video(video, "output.mp4", fps=15) ``` - + Compilation is slow the first time but subsequent calls to the pipeline are faster. From ba67eb225bc13f4cb6d71692ae88e05b70f89ebb Mon Sep 17 00:00:00 2001 From: stevhliu Date: Thu, 27 Mar 2025 11:10:56 -0700 Subject: [PATCH 06/12] wan --- docs/source/en/api/loaders/lora.md | 6 +- docs/source/en/api/pipelines/cogvideox.md | 80 +-- docs/source/en/api/pipelines/hunyuan_video.md | 19 +- docs/source/en/api/pipelines/ltx_video.md | 81 +-- docs/source/en/api/pipelines/wan.md | 546 +++++------------- 5 files changed, 206 insertions(+), 526 deletions(-) diff --git a/docs/source/en/api/loaders/lora.md b/docs/source/en/api/loaders/lora.md index 1c716f6d5e85..9271999d63a6 100644 --- a/docs/source/en/api/loaders/lora.md +++ b/docs/source/en/api/loaders/lora.md @@ -98,4 +98,8 @@ To learn more about how to load LoRA weights, see the [LoRA](../../using-diffuse ## LoraBaseMixin -[[autodoc]] loaders.lora_base.LoraBaseMixin \ No newline at end of file +[[autodoc]] loaders.lora_base.LoraBaseMixin + +## WanLoraLoaderMixin + +[[autodoc]] loaders.lora_pipeline.WanLoraLoaderMixin \ No newline at end of file diff --git a/docs/source/en/api/pipelines/cogvideox.md b/docs/source/en/api/pipelines/cogvideox.md index 5fe5e50cbb92..164d3e3b82b6 100644 --- a/docs/source/en/api/pipelines/cogvideox.md +++ b/docs/source/en/api/pipelines/cogvideox.md @@ -26,19 +26,32 @@ You can find all the original CogVideoX checkpoints under the [CogVideoX](https://huggingface.co/collections/THUDM/cogvideo-66c08e62f1685a3ade464cce) collection. > [!TIP] -> Click on the CogVideoX models in the right sidebar for more examples of how to use CogVideoX for other video generation tasks. +> Click on the CogVideoX models in the right sidebar for more examples of other video generation tasks. The example below demonstrates how to generate a video optimized for memory or inference speed. +Refer to the [Reduce memory usage](../../optimization/memory) guide for more details about the various memory saving techniques. + +The quantized CogVideoX 5B model below requires ~16GB of VRAM. + ```py import torch from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel from diffusers.hooks import apply_group_offloading from diffusers.utils import export_to_video +# quantize weights to int8 with torchao +quantization_config = TorchAoConfig("int8wo") +transformer = CogVideoXTransformer3DModel.from_pretrained( + "THUDM/CogVideoX-5b", + subfolder="transformer", + quantization_config=quantization_config, + torch_dtype=torch.bfloat16, +) + # fp8 layerwise weight-casting transformer = CogVideoXTransformer3DModel.from_pretrained( "THUDM/CogVideoX-5b", @@ -60,10 +73,13 @@ pipeline.to("cuda") # model-offloading pipeline.enable_model_cpu_offload() -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.") +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. +""" + video = pipeline( prompt=prompt, guidance_scale=6, @@ -72,45 +88,6 @@ video = pipeline( export_to_video(video, "output.mp4", fps=8) ``` -Reduce memory usage even more if necessary by quantizing a model to a lower precision data type. - -```py -import torch -from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel, TorchAoConfig -from diffusers.utils import export_to_video - -# quantize weights to int8 with torchao -quantization_config = TorchAoConfig("int8wo") -transformer = CogVideoXTransformer3DModel.from_pretrained( - "THUDM/CogVideoX-5b", - subfolder="transformer", - quantization_config=quantization_config, - torch_dtype=torch.bfloat16, -) -# fp8 layerwise weight-casting -transformer.enable_layerwise_casting( - storage_dtype=torch.float8_e4m3fn, - compute_dtype=torch.bfloat16 -) - -pipeline = CogVideoXPipeline.from_pretrained( - "THUDM/CogVideoX-5b", - transformer=transformer, - torch_dtype=torch.bfloat16, -) -pipeline.to("cuda") - -# model-offloading -pipeline.enable_model_cpu_offload() - -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.") -video = pipeline(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0] -export_to_video(video, "output.mp4", fps=8) -``` - @@ -119,7 +96,6 @@ Compilation is slow the first time but subsequent calls to the pipeline are fast ```py import torch from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel -from diffusers.hooks import apply_group_offloading from diffusers.utils import export_to_video pipeline = CogVideoXPipeline.from_pretrained( @@ -133,10 +109,13 @@ pipeline.transformer = torch.compile( pipeline.transformer, mode="max-autotune", fullgraph=True ) -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.") +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. +""" + video = pipeline( prompt=prompt, guidance_scale=6, @@ -186,8 +165,11 @@ export_to_video(video, "output.mp4", fps=8) ).frames[0] export_to_video(video, "output.mp4", fps=16) ``` + - The text-to-video (T2V) checkpoints work best with a resolution of 1360x768 because that was the resolution it was pretrained on. + - 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. + - Both T2V and I2V checkpoints work best with 81 and 161 frames. It is recommended to export the generated video at 16fps. ## CogVideoXPipeline diff --git a/docs/source/en/api/pipelines/hunyuan_video.md b/docs/source/en/api/pipelines/hunyuan_video.md index 7c5e300e0f25..24fd65972f7e 100644 --- a/docs/source/en/api/pipelines/hunyuan_video.md +++ b/docs/source/en/api/pipelines/hunyuan_video.md @@ -20,7 +20,7 @@ # HunyuanVideo -[HunyuanVideo](https://huggingface.co/papers/2412.03603) is a 13B diffusion transformer model designed to be competitive with closed-source video foundation models and enable wider community access. This model uses a "dual-stream to single-stream" architecture to separately process the video and text tokens first, before concatenating and feeding them to the transformer to fuse the multimodal information. A pretrained multimodal large language model (MLLM) is used as the encoder because it has better image-text alignment, better image detail description and reasoning, and it can be used as a zero-shot learner if system instructions are added to user prompts. Finally, HunyuanVideo uses a 3D causal variational autoencoder to more efficiently process video data at the original resolution and frame rate. +[HunyuanVideo](https://huggingface.co/papers/2412.03603) is a 13B parameter diffusion transformer model designed to be competitive with closed-source video foundation models and enable wider community access. This model uses a "dual-stream to single-stream" architecture to separately process the video and text tokens first, before concatenating and feeding them to the transformer to fuse the multimodal information. A pretrained multimodal large language model (MLLM) is used as the encoder because it has better image-text alignment, better image detail description and reasoning, and it can be used as a zero-shot learner if system instructions are added to user prompts. Finally, HunyuanVideo uses a 3D causal variational autoencoder to more efficiently process video data at the original resolution and frame rate. You can find all the original HunyuanVideo checkpoints under the [Tencent](https://huggingface.co/tencent) organization. @@ -32,12 +32,16 @@ The example below demonstrates how to generate a video optimized for memory or i +Refer to the [Reduce memory usage](../../optimization/memory) guide for more details about the various memory saving techniques. + +The quantized HunyuanVideo model below requires ~14GB of VRAM. + ```py import torch from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, HunyuanVideoTransformer3DModel, HunyuanVideoPipeline from diffusers.utils import export_to_video -# quantization +# quantize weights to int4 with bitsandbytes quant_config = DiffusersBitsAndBytesConfig(load_in_4bit=True) transformer = HunyuanVideoTransformer3DModel.from_pretrained( "hunyuanvideo-community/HunyuanVideo", @@ -52,7 +56,7 @@ pipeline = HunyuanVideoPipeline.from_pretrained( torch_dtype=torch.float16, ) -# model-offloading +# model-offloading and tiling pipeline.enable_model_cpu_offload() pipeline.vae.enable_tiling() @@ -71,7 +75,7 @@ import torch from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, HunyuanVideoTransformer3DModel, HunyuanVideoPipeline from diffusers.utils import export_to_video -# quantization +# quantize weights to int4 with bitsandbytes quant_config = DiffusersBitsAndBytesConfig(load_in_4bit=True) transformer = HunyuanVideoTransformer3DModel.from_pretrained( "hunyuanvideo-community/HunyuanVideo", @@ -86,7 +90,7 @@ pipeline = HunyuanVideoPipeline.from_pretrained( torch_dtype=torch.float16, ) -# model-offloading +# model-offloading and tiling pipeline.enable_model_cpu_offload() pipeline.vae.enable_tiling() @@ -132,10 +136,11 @@ export_to_video(video, "output.mp4", fps=15) pipeline.load_lora_weights("https://huggingface.co/lucataco/hunyuan-steamboat-willie-10", adapter_name="steamboat-willie") pipeline.set_adapters("steamboat-willie", 0.9) - # model-offloading + # model-offloading and tiling pipeline.enable_model_cpu_offload() pipeline.vae.enable_tiling() + # use "In the style of SWR" to trigger the LoRA prompt = """ In the style of SWR. A black and white animated scene featuring a fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys. """ @@ -150,7 +155,7 @@ export_to_video(video, "output.mp4", fps=15) | text encoder dtype | `torch.float16` | | transformer dtype | `torch.bfloat16` | | vae dtype | `torch.float16` | - | `num_frames` | 4 * k + 1 | + | `num_frames (k)` | 4 * `k` + 1 | - Try lower `shift` values (`2.0` to `5.0`) for lower resolution videos, and try higher `shift` values (`7.0` to `12.0`) for higher resolution images. diff --git a/docs/source/en/api/pipelines/ltx_video.md b/docs/source/en/api/pipelines/ltx_video.md index c7f8f97005eb..04aeebb70b9c 100644 --- a/docs/source/en/api/pipelines/ltx_video.md +++ b/docs/source/en/api/pipelines/ltx_video.md @@ -20,18 +20,22 @@ # LTX-Video -[LTX-Video](https://huggingface.co/Lightricks/LTX-Video) is a diffusion transformer designed for fast and real-time generation of high-resolution videos from text and images. The main feature of LTX-Video is the Video-VAE. The Video-VAE has a higher pixel to latent compression ratio (1:192) which enables more efficient video data processing and faster generation speed. To support and prevent the finer details from being lost during generation, the Video-VAE decoder performs the latent to pixel conversion *and* the last denoising step. +[LTX-Video](https://huggingface.co/Lightricks/LTX-Video) is a diffusion transformer designed for fast and real-time generation of high-resolution videos from text and images. The main feature of LTX-Video is the Video-VAE. The Video-VAE has a higher pixel to latent compression ratio (1:192) which enables more efficient video data processing and faster generation speed. To support and prevent finer details from being lost during generation, the Video-VAE decoder performs the latent to pixel conversion *and* the last denoising step. You can find all the original LTX-Video checkpoints under the [Lightricks](https://huggingface.co/Lightricks) organization. > [!TIP] -> Click on the LTX-Video models in the right sidebar for more examples of how to use LTX-Video for other video generation tasks. +> Click on the LTX-Video models in the right sidebar for more examples of other video generation tasks. The example below demonstrates how to generate a video optimized for memory or inference speed. +Refer to the [Reduce memory usage](../../optimization/memory) guide for more details about the various memory saving techniques. + +The LTX-Video model below requires ~10GB of VRAM. + ```py import torch from diffusers import LTXPipeline, LTXVideoTransformer3DModel @@ -58,7 +62,9 @@ pipeline.transformer.enable_group_offload(onload_device=onload_device, offload_d apply_group_offloading(pipeline.text_encoder, onload_device=onload_device, offload_type="block_level", num_blocks_per_group=2) apply_group_offloading(pipeline.vae, onload_device=onload_device, offload_type="leaf_level") -prompt = "A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be real-life footage" +prompt = """ +A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be real-life footage +""" negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted" video = pipeline( @@ -74,55 +80,6 @@ video = pipeline( export_to_video(video, "output.mp4", fps=24) ``` - - -Reduce memory usage even more if necessary by quantizing a model to a lower precision data type. - -```py -import torch -from diffusers.utils import export_to_video -from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, LTXVideoTransformer3DModel, LTXPipeline -from transformers import BitsAndBytesConfig as BitsAndBytesConfig, T5EncoderModel - -# quantize weights to int8 with bitsandbytes -quantization_config = BitsAndBytesConfig(load_in_8bit=True) -text_encoder = T5EncoderModel.from_pretrained( - "Lightricks/LTX-Video", - subfolder="text_encoder", - quantization_config=quantization_config, - torch_dtype=torch.bfloat16, -) - -quantization_config = DiffusersBitsAndBytesConfig(load_in_8bit=True) -transformer = LTXVideoTransformer3DModel.from_pretrained( - "Lightricks/LTX-Video", - subfolder="transformer", - quantization_config=quantization_config, - torch_dtype=torch.bfloat16, -) - -pipeline = LTXPipeline.from_pretrained( - "Lightricks/LTX-Video", - text_encoder=text_en, - transformer=transformer, - torch_dtype=torch.bfloat16, -) - -prompt = "A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be real-life footage" -negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted" -video = pipeline( - prompt=prompt, - negative_prompt=negative_prompt, - width=768, - height=512, - num_frames=161, - decode_timestep=0.03, - decode_noise_scale=0.025, - num_inference_steps=50, -).frames[0] -export_to_video(video, "output.mp4", fps=24) -``` - @@ -143,7 +100,9 @@ pipeline.transformer = torch.compile( pipeline.transformer, mode="max-autotune", fullgraph=True ) -prompt = "A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be real-life footage" +prompt = """ +A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be real-life footage +""" negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted" video = pipeline( @@ -164,24 +123,27 @@ export_to_video(video, "output.mp4", fps=24) ## Notes -- LTX-Video supports LoRAs with [`~LTXVideoLoraLoaderMixin.load_lora_weights`]. +- LTX-Video supports LoRAs with [`~loaders.LTXVideoLoraLoaderMixin.load_lora_weights`]. ```py import torch from diffusers import LTXConditionPipeline - from diffusers.utils import export_to_video + from diffusers.utils import export_to_video, load_image pipeline = LTXConditionPipeline.from_pretrained( "Lightricks/LTX-Video-0.9.5", torch_dtype=torch.bfloat16 ) pipeline.load_lora_weights("Lightricks/LTX-Video-Cakeify-LoRA", adapter_name="cakeify") - pipeline.set_adapters("cakeify", 0.9) + pipeline.set_adapters("cakeify") - prompt = "CAKEIFY a person using a knife to cut a cake shaped like a pair of cowboy boots" + # use "CAKEIFY" to trigger the LoRA + prompt = "CAKEIFY a person using a knife to cut a cake shaped like a cereal box" + image = load_image("https://i5.walmartimages.com/asr/c0463def-4995-47a7-9486-294fff8cf9fc.f9779f3fc4c621cf1fe86465af1d2ecd.jpeg") video = pipeline( prompt=prompt, + image=image, width=768, height=512, num_frames=161, @@ -191,7 +153,8 @@ export_to_video(video, "output.mp4", fps=24) ).frames[0] export_to_video(video, "output.mp4", fps=24) ``` -- LTX-Video supports loading from single files, such as [GGUF checkpoints](../../quantization/gguf), with [`FromOriginalModelMixin.from_single_file`] or [`FromSingleFileMixin.from_single_file`]. + +- LTX-Video supports loading from single files, such as [GGUF checkpoints](../../quantization/gguf), with [`loaders.FromOriginalModelMixin.from_single_file`] or [`loaders.FromSingleFileMixin.from_single_file`]. ```py import torch @@ -206,7 +169,7 @@ export_to_video(video, "output.mp4", fps=24) pipeline = LTXPipeline.from_pretrained( "Lightricks/LTX-Video", transformer=transformer, - torch_dtype=bfloat16 + torch_dtype=torch.bfloat16 ) ``` diff --git a/docs/source/en/api/pipelines/wan.md b/docs/source/en/api/pipelines/wan.md index 3d81c5644f1a..13ada8dc82e5 100644 --- a/docs/source/en/api/pipelines/wan.md +++ b/docs/source/en/api/pipelines/wan.md @@ -18,491 +18,217 @@
-# Wan +# Wan2.1 -[Wan 2.1](https://github.com/Wan-Video/Wan2.1) by the Alibaba Wan Team. +[Wan2.1](https://files.alicdn.com/tpsservice/5c9de1c74de03972b7aa657e5a54756b.pdf) is a series of large diffusion transformer available in two versions, a high-performance 14B parameter model and a more accessible 1.3B version. Trained on billions of images and videos, it supports tasks like text-to-video (T2V) and image-to-video (I2V) while enabling features such as camera control and stylistic diversity. The Wan-VAE features better image data compression and a feature cache mechanism that encodes and decodes a video in chunks. To maintain continuity, features from previous chunks are cached and reused for processing subsequent chunks. This improves inference efficiency by reducing memory usage. Wan2.1 also uses a multilingual text encoder and the diffusion transformer models space and time relationships and text conditions with each time step to capture more complex video dynamics. - +You can find all the original Wan2.1 checkpoints under the [Wan-AI](https://huggingface.co/Wan-AI) organization. -## Generating Videos with Wan 2.1 +> [!TIP] +> Click on the Wan2.1 models in the right sidebar for more examples of other video generation tasks. -We will first need to install some additional dependencies. +The example below demonstrates how to generate a video from text optimized for memory or inference speed. -```shell -pip install -u ftfy imageio-ffmpeg imageio -``` - -### Text to Video Generation - -The following example requires 11GB VRAM to run and uses the smaller `Wan-AI/Wan2.1-T2V-1.3B-Diffusers` model. You can switch it out -for the larger `Wan2.1-I2V-14B-720P-Diffusers` or `Wan-AI/Wan2.1-I2V-14B-480P-Diffusers` if you have at least 35GB VRAM available. - -```python -from diffusers import WanPipeline -from diffusers.utils import export_to_video - -# Available models: Wan-AI/Wan2.1-I2V-14B-720P-Diffusers or Wan-AI/Wan2.1-I2V-14B-480P-Diffusers -model_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers" - -pipe = WanPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16) -pipe.enable_model_cpu_offload() - -prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window." -negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" -num_frames = 33 - -frames = pipe(prompt=prompt, negative_prompt=negative_prompt, num_frames=num_frames).frames[0] -export_to_video(frames, "wan-t2v.mp4", fps=16) -``` - - -You can improve the quality of the generated video by running the decoding step in full precision. - - -```python -from diffusers import WanPipeline, AutoencoderKLWan -from diffusers.utils import export_to_video - -model_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers" - -vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32) -pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16) - -# replace this with pipe.to("cuda") if you have sufficient VRAM -pipe.enable_model_cpu_offload() - -prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window." -negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" -num_frames = 33 - -frames = pipe(prompt=prompt, num_frames=num_frames).frames[0] -export_to_video(frames, "wan-t2v.mp4", fps=16) -``` - -### Image to Video Generation - -The Image to Video pipeline requires loading the `AutoencoderKLWan` and the `CLIPVisionModel` components in full precision. The following example will need at least -35GB of VRAM to run. - -```python -import torch -import numpy as np -from diffusers import AutoencoderKLWan, WanImageToVideoPipeline -from diffusers.utils import export_to_video, load_image -from transformers import CLIPVisionModel - -# Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers -model_id = "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers" -image_encoder = CLIPVisionModel.from_pretrained( - model_id, subfolder="image_encoder", torch_dtype=torch.float32 -) -vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32) -pipe = WanImageToVideoPipeline.from_pretrained( - model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16 -) - -# replace this with pipe.to("cuda") if you have sufficient VRAM -pipe.enable_model_cpu_offload() - -image = load_image( - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg" -) - -max_area = 480 * 832 -aspect_ratio = image.height / image.width -mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1] -height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value -width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value -image = image.resize((width, height)) - -prompt = ( - "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in " - "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot." -) -negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" - -num_frames = 33 - -output = pipe( - image=image, - prompt=prompt, - negative_prompt=negative_prompt, - height=height, - width=width, - num_frames=num_frames, - guidance_scale=5.0, -).frames[0] -export_to_video(output, "wan-i2v.mp4", fps=16) -``` - -### First and Last Frame Interpolation - -```python -import numpy as np -import torch -import torchvision.transforms.functional as TF -from diffusers import AutoencoderKLWan, WanImageToVideoPipeline -from diffusers.utils import export_to_video, load_image -from transformers import CLIPVisionModel - - -model_id = "Wan-AI/Wan2.1-FLF2V-14B-720P-diffusers" -image_encoder = CLIPVisionModel.from_pretrained(model_id, subfolder="image_encoder", torch_dtype=torch.float32) -vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32) -pipe = WanImageToVideoPipeline.from_pretrained( - model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16 -) -pipe.to("cuda") - -first_frame = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png") -last_frame = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png") - -def aspect_ratio_resize(image, pipe, max_area=720 * 1280): - aspect_ratio = image.height / image.width - mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1] - height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value - width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value - image = image.resize((width, height)) - return image, height, width - -def center_crop_resize(image, height, width): - # Calculate resize ratio to match first frame dimensions - resize_ratio = max(width / image.width, height / image.height) - - # Resize the image - width = round(image.width * resize_ratio) - height = round(image.height * resize_ratio) - size = [width, height] - image = TF.center_crop(image, size) - - return image, height, width - -first_frame, height, width = aspect_ratio_resize(first_frame, pipe) -if last_frame.size != first_frame.size: - last_frame, _, _ = center_crop_resize(last_frame, height, width) - -prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective." - -output = pipe( - image=first_frame, last_image=last_frame, prompt=prompt, height=height, width=width, guidance_scale=5.5 -).frames[0] -export_to_video(output, "output.mp4", fps=16) -``` - -### Video to Video Generation - -```python -import torch -from diffusers.utils import load_video, export_to_video -from diffusers import AutoencoderKLWan, WanVideoToVideoPipeline, UniPCMultistepScheduler - -# Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers -model_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers" -vae = AutoencoderKLWan.from_pretrained( - model_id, subfolder="vae", torch_dtype=torch.float32 -) -pipe = WanVideoToVideoPipeline.from_pretrained( - model_id, vae=vae, torch_dtype=torch.bfloat16 -) -flow_shift = 3.0 # 5.0 for 720P, 3.0 for 480P -pipe.scheduler = UniPCMultistepScheduler.from_config( - pipe.scheduler.config, flow_shift=flow_shift -) -# change to pipe.to("cuda") if you have sufficient VRAM -pipe.enable_model_cpu_offload() - -prompt = "A robot standing on a mountain top. The sun is setting in the background" -negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" -video = load_video( - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4" -) -output = pipe( - video=video, - prompt=prompt, - negative_prompt=negative_prompt, - height=480, - width=512, - guidance_scale=7.0, - strength=0.7, -).frames[0] - -export_to_video(output, "wan-v2v.mp4", fps=16) -``` - -## Memory Optimizations for Wan 2.1 - -Base inference with the large 14B Wan 2.1 models can take up to 35GB of VRAM when generating videos at 720p resolution. We'll outline a few memory optimizations we can apply to reduce the VRAM required to run the model. - -We'll use `Wan-AI/Wan2.1-I2V-14B-720P-Diffusers` model in these examples to demonstrate the memory savings, but the techniques are applicable to all model checkpoints. - -### Group Offloading the Transformer and UMT5 Text Encoder + + -Find more information about group offloading [here](../optimization/memory.md) +Refer to the [Reduce memory usage](../../optimization/memory) guide for more details about the various memory saving techniques. -#### Block Level Group Offloading +The Wan2.1 text-to-video model below requires ~13GB of VRAM. -We can reduce our VRAM requirements by applying group offloading to the larger model components of the pipeline; the `WanTransformer3DModel` and `UMT5EncoderModel`. Group offloading will break up the individual modules of a model and offload/onload them onto your GPU as needed during inference. In this example, we'll apply `block_level` offloading, which will group the modules in a model into blocks of size `num_blocks_per_group` and offload/onload them to GPU. Moving to between CPU and GPU does add latency to the inference process. You can trade off between latency and memory savings by increasing or decreasing the `num_blocks_per_group`. +```py +# pip install ftfy -The following example will now only require 14GB of VRAM to run, but will take approximately 30 minutes to generate a video. - -```python import torch import numpy as np -from diffusers import AutoencoderKLWan, WanTransformer3DModel, WanImageToVideoPipeline +from diffusers import AutoencoderKLWan, WanTransformer3DModel, WanPipeline from diffusers.hooks.group_offloading import apply_group_offloading from diffusers.utils import export_to_video, load_image from transformers import UMT5EncoderModel, CLIPVisionModel -# Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers -model_id = "Wan-AI/Wan2.1-I2V-14B-720P-Diffusers" -image_encoder = CLIPVisionModel.from_pretrained( - model_id, subfolder="image_encoder", torch_dtype=torch.float32 -) - -text_encoder = UMT5EncoderModel.from_pretrained(model_id, subfolder="text_encoder", torch_dtype=torch.bfloat16) -vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32) -transformer = WanTransformer3DModel.from_pretrained(model_id, subfolder="transformer", torch_dtype=torch.bfloat16) +text_encoder = UMT5EncoderModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", torch_dtype=torch.bfloat16) +vae = AutoencoderKLWan.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", torch_dtype=torch.float32) +transformer = WanTransformer3DModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", torch_dtype=torch.bfloat16) +# group-offloading onload_device = torch.device("cuda") offload_device = torch.device("cpu") - apply_group_offloading(text_encoder, onload_device=onload_device, offload_device=offload_device, offload_type="block_level", num_blocks_per_group=4 ) - transformer.enable_group_offload( onload_device=onload_device, offload_device=offload_device, - offload_type="block_level", - num_blocks_per_group=4, + offload_type="leaf_level", + use_stream=True ) -pipe = WanImageToVideoPipeline.from_pretrained( + +pipeline = WanPipeline.from_pretrained( model_id, vae=vae, transformer=transformer, text_encoder=text_encoder, - image_encoder=image_encoder, torch_dtype=torch.bfloat16 ) -# Since we've offloaded the larger models already, we can move the rest of the model components to GPU -pipe.to("cuda") - -image = load_image( - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg" -) - -max_area = 720 * 832 -aspect_ratio = image.height / image.width -mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1] -height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value -width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value -image = image.resize((width, height)) - -prompt = ( - "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in " - "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot." -) -negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" - -num_frames = 33 - -output = pipe( - image=image, +pipeline.to("cuda") + +prompt = """ +The camera rushes from far to near in a low-angle shot, +revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in +for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground. +Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic +shadows and warm highlights. Medium composition, front view, low angle, with depth of field. +""" +negative_prompt = """ +Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, +low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, +misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards +""" + +output = pipeline( prompt=prompt, negative_prompt=negative_prompt, - height=height, - width=width, - num_frames=num_frames, + num_frames=81, guidance_scale=5.0, ).frames[0] - -export_to_video(output, "wan-i2v.mp4", fps=16) +export_to_video(output, "output.mp4", fps=16) ``` -#### Block Level Group Offloading with CUDA Streams + + -We can speed up group offloading inference, by enabling the use of [CUDA streams](https://pytorch.org/docs/stable/generated/torch.cuda.Stream.html). However, using CUDA streams requires moving the model parameters into pinned memory. This allocation is handled by Pytorch under the hood, and can result in a significant spike in CPU RAM usage. Please consider this option if your CPU RAM is atleast 2X the size of the model you are group offloading. +Compilation is slow the first time but subsequent calls to the pipeline are faster. -In the following example we will use CUDA streams when group offloading the `WanTransformer3DModel`. When testing on an A100, this example will require 14GB of VRAM, 52GB of CPU RAM, but will generate a video in approximately 9 minutes. +```py +# pip install ftfy -```python import torch import numpy as np -from diffusers import AutoencoderKLWan, WanTransformer3DModel, WanImageToVideoPipeline +from diffusers import AutoencoderKLWan, WanTransformer3DModel, WanPipeline from diffusers.hooks.group_offloading import apply_group_offloading from diffusers.utils import export_to_video, load_image from transformers import UMT5EncoderModel, CLIPVisionModel -# Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers -model_id = "Wan-AI/Wan2.1-I2V-14B-720P-Diffusers" -image_encoder = CLIPVisionModel.from_pretrained( - model_id, subfolder="image_encoder", torch_dtype=torch.float32 -) - -text_encoder = UMT5EncoderModel.from_pretrained(model_id, subfolder="text_encoder", torch_dtype=torch.bfloat16) -vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32) -transformer = WanTransformer3DModel.from_pretrained(model_id, subfolder="transformer", torch_dtype=torch.bfloat16) - -onload_device = torch.device("cuda") -offload_device = torch.device("cpu") - -apply_group_offloading(text_encoder, - onload_device=onload_device, - offload_device=offload_device, - offload_type="block_level", - num_blocks_per_group=4 -) +text_encoder = UMT5EncoderModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", torch_dtype=torch.bfloat16) +vae = AutoencoderKLWan.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", torch_dtype=torch.float32) +transformer = WanTransformer3DModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", torch_dtype=torch.bfloat16) -transformer.enable_group_offload( - onload_device=onload_device, - offload_device=offload_device, - offload_type="leaf_level", - use_stream=True -) -pipe = WanImageToVideoPipeline.from_pretrained( +pipeline = WanPipeline.from_pretrained( model_id, vae=vae, transformer=transformer, text_encoder=text_encoder, - image_encoder=image_encoder, torch_dtype=torch.bfloat16 ) -# Since we've offloaded the larger models already, we can move the rest of the model components to GPU -pipe.to("cuda") +pipeline.to("cuda") -image = load_image( - "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg" +# torch.compile +pipeline.transformer.to(memory_format=torch.channels_last) +pipeline.transformer = torch.compile( + pipeline.transformer, mode="max-autotune", fullgraph=True ) -max_area = 720 * 832 -aspect_ratio = image.height / image.width -mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1] -height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value -width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value -image = image.resize((width, height)) +prompt = """ +The camera rushes from far to near in a low-angle shot, +revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in +for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground. +Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic +shadows and warm highlights. Medium composition, front view, low angle, with depth of field. +""" +negative_prompt = """ +Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, +low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, +misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards +""" -prompt = ( - "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in " - "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot." -) -negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" - -num_frames = 33 - -output = pipe( - image=image, +output = pipeline( prompt=prompt, negative_prompt=negative_prompt, - height=height, - width=width, - num_frames=num_frames, + num_frames=81, guidance_scale=5.0, ).frames[0] - -export_to_video(output, "wan-i2v.mp4", fps=16) +export_to_video(output, "output.mp4", fps=16) ``` -### Applying Layerwise Casting to the Transformer - -Find more information about layerwise casting [here](../optimization/memory.md) - -In this example, we will model offloading with layerwise casting. Layerwise casting will downcast each layer's weights to `torch.float8_e4m3fn`, temporarily upcast to `torch.bfloat16` during the forward pass of the layer, then revert to `torch.float8_e4m3fn` afterward. This approach reduces memory requirements by approximately 50% while introducing a minor quality reduction in the generated video due to the precision trade-off. - -This example will require 20GB of VRAM. + + + +## Notes + +- Wan2.1 supports LoRAs with [`~loaders.WanLoraLoaderMixin.load_lora_weights`]. + + ```py + # pip install ftfy + + import torch + from diffusers import WanPipeline + from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler + from diffusers.utils import export_to_video + + vae = AutoencoderKLWan.from_pretrained( + "Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", torch_dtype=torch.float32 + ) + pipeline = WanPipeline.from_pretrained( + "Wan-AI/Wan2.1-T2V-14B-Diffusers", vae=vae, torch_dtype=torch.bfloat16 + ) + pipeline.scheduler = UniPCMultistepScheduler.from_config( + pipeline.scheduler.config, flow_shift=5.0 + ) + pipeline.to("cuda") + + pipeline.load_lora_weights("benjamin-paine/steamboat-willie-14b", adapter_name="steamboat-willie") + pipeline.set_adapters("steamboat-willie") + + pipeline.enable_model_cpu_offload() + + # use "steamboat willie style" to trigger the LoRA + prompt = """ + steamboat willie style, golden era animation, The camera rushes from far to near in a low-angle shot, + revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in + for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground. + Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic + shadows and warm highlights. Medium composition, front view, low angle, with depth of field. + """ + + output = pipeline( + prompt=prompt, + num_frames=81, + guidance_scale=5.0, + ).frames[0] + export_to_video(output, "output.mp4", fps=16) + ``` -```python -import torch -import numpy as np -from diffusers import AutoencoderKLWan, WanTransformer3DModel, WanImageToVideoPipeline -from diffusers.hooks.group_offloading import apply_group_offloading -from diffusers.utils import export_to_video, load_image -from transformers import UMT5EncoderModel, CLIPVisionModel +- [`WanTransformer3DModel`] and [`AutoencoderKLWan`] supports loading from single files with [`!loaders.FromSingleFileMixin.from_single_file`]. -model_id = "Wan-AI/Wan2.1-I2V-14B-720P-Diffusers" -image_encoder = CLIPVisionModel.from_pretrained( - model_id, subfolder="image_encoder", torch_dtype=torch.float32 -) -text_encoder = UMT5EncoderModel.from_pretrained(model_id, subfolder="text_encoder", torch_dtype=torch.bfloat16) -vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32) + ```py + # pip install ftfy -transformer = WanTransformer3DModel.from_pretrained(model_id, subfolder="transformer", torch_dtype=torch.bfloat16) -transformer.enable_layerwise_casting(storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16) + import torch + from diffusers import WanPipeline, WanTransformer3DModel, AutoencoderKLWan -pipe = WanImageToVideoPipeline.from_pretrained( - model_id, + vae = AutoencoderKLWan.from_single_file( + "https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/blob/main/split_files/vae/wan_2.1_vae.safetensors" + ) + transformer = WanTransformer3DModel.from_single_file( + "https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/blob/main/split_files/diffusion_models/wan2.1_t2v_1.3B_bf16.safetensors", + torch_dtype=torch.bfloat16 + ) + pipeline = WanPipeline.from_pretrained( + "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", vae=vae, transformer=transformer, - text_encoder=text_encoder, - image_encoder=image_encoder, torch_dtype=torch.bfloat16 -) -pipe.enable_model_cpu_offload() -image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg") - -max_area = 720 * 832 -aspect_ratio = image.height / image.width -mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1] -height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value -width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value -image = image.resize((width, height)) -prompt = ( - "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in " - "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot." -) -negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards" -num_frames = 33 + ) + ``` -output = pipe( - image=image, - prompt=prompt, - negative_prompt=negative_prompt, - height=height, - width=width, - num_frames=num_frames, - num_inference_steps=50, - guidance_scale=5.0, -).frames[0] -export_to_video(output, "wan-i2v.mp4", fps=16) -``` - -## Using a Custom Scheduler - -Wan can be used with many different schedulers, each with their own benefits regarding speed and generation quality. By default, Wan uses the `UniPCMultistepScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, flow_shift=3.0)` scheduler. You can use a different scheduler as follows: - -```python -from diffusers import FlowMatchEulerDiscreteScheduler, UniPCMultistepScheduler, WanPipeline - -scheduler_a = FlowMatchEulerDiscreteScheduler(shift=5.0) -scheduler_b = UniPCMultistepScheduler(prediction_type="flow_prediction", use_flow_sigmas=True, flow_shift=4.0) - -pipe = WanPipeline.from_pretrained("Wan-AI/Wan2.1-T2V-1.3B-Diffusers", scheduler=) +- Set the [`AutoencoderKLWan`] dtype to `torch.float32` for better decoding quality. -# or, -pipe.scheduler = -``` - -## Using Single File Loading with Wan 2.1 - -The `WanTransformer3DModel` and `AutoencoderKLWan` models support loading checkpoints in their original format via the `from_single_file` loading -method. - -```python -import torch -from diffusers import WanPipeline, WanTransformer3DModel - -ckpt_path = "https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/blob/main/split_files/diffusion_models/wan2.1_t2v_1.3B_bf16.safetensors" -transformer = WanTransformer3DModel.from_single_file(ckpt_path, torch_dtype=torch.bfloat16) - -pipe = WanPipeline.from_pretrained("Wan-AI/Wan2.1-T2V-1.3B-Diffusers", transformer=transformer) -``` +- The number of frames per second (fps) or `k` should be calculated by `4 * k + 1`. -## Recommendations for Inference -- Keep `AutencoderKLWan` in `torch.float32` for better decoding quality. -- `num_frames` should satisfy the following constraint: `(num_frames - 1) % 4 == 0` -- For smaller resolution videos, try lower values of `shift` (between `2.0` to `5.0`) in the [Scheduler](https://huggingface.co/docs/diffusers/main/en/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler.shift). For larger resolution videos, try higher values (between `7.0` and `12.0`). The default value is `3.0` for Wan. +- Try lower `shift` values (`2.0` to `5.0`) for lower resolution videos, and try higher `shift` values (`7.0` to `12.0`) for higher resolution images. ## WanPipeline @@ -518,4 +244,4 @@ pipe = WanPipeline.from_pretrained("Wan-AI/Wan2.1-T2V-1.3B-Diffusers", transform ## WanPipelineOutput -[[autodoc]] pipelines.wan.pipeline_output.WanPipelineOutput +[[autodoc]] pipelines.wan.pipeline_output.WanPipelineOutput \ No newline at end of file From aa600ae1125eb6017cf1e32914cc97c999567c05 Mon Sep 17 00:00:00 2001 From: stevhliu Date: Thu, 27 Mar 2025 15:18:27 -0700 Subject: [PATCH 07/12] gen guide --- docs/source/en/api/pipelines/ltx_video.md | 10 +- docs/source/en/api/pipelines/wan.md | 10 +- .../source/en/using-diffusers/text-img2vid.md | 755 ++++++++---------- 3 files changed, 331 insertions(+), 444 deletions(-) diff --git a/docs/source/en/api/pipelines/ltx_video.md b/docs/source/en/api/pipelines/ltx_video.md index 04aeebb70b9c..fff9f0aa0c29 100644 --- a/docs/source/en/api/pipelines/ltx_video.md +++ b/docs/source/en/api/pipelines/ltx_video.md @@ -138,20 +138,20 @@ export_to_video(video, "output.mp4", fps=24) pipeline.set_adapters("cakeify") # use "CAKEIFY" to trigger the LoRA - prompt = "CAKEIFY a person using a knife to cut a cake shaped like a cereal box" - image = load_image("https://i5.walmartimages.com/asr/c0463def-4995-47a7-9486-294fff8cf9fc.f9779f3fc4c621cf1fe86465af1d2ecd.jpeg") + prompt = "CAKEIFY a person using a knife to cut a cake shaped like a Pikachu plushie" + image = load_image("https://huggingface.co/Lightricks/LTX-Video-Cakeify-LoRA/resolve/main/assets/images/pikachu.png") video = pipeline( prompt=prompt, image=image, - width=768, - height=512, + width=576, + height=576, num_frames=161, decode_timestep=0.03, decode_noise_scale=0.025, num_inference_steps=50, ).frames[0] - export_to_video(video, "output.mp4", fps=24) + export_to_video(video, "output.mp4", fps=26) ``` - LTX-Video supports loading from single files, such as [GGUF checkpoints](../../quantization/gguf), with [`loaders.FromOriginalModelMixin.from_single_file`] or [`loaders.FromSingleFileMixin.from_single_file`]. diff --git a/docs/source/en/api/pipelines/wan.md b/docs/source/en/api/pipelines/wan.md index 13ada8dc82e5..72fe88b63489 100644 --- a/docs/source/en/api/pipelines/wan.md +++ b/docs/source/en/api/pipelines/wan.md @@ -169,19 +169,19 @@ export_to_video(output, "output.mp4", fps=16) from diffusers.utils import export_to_video vae = AutoencoderKLWan.from_pretrained( - "Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", torch_dtype=torch.float32 + "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", subfolder="vae", torch_dtype=torch.float32 ) pipeline = WanPipeline.from_pretrained( - "Wan-AI/Wan2.1-T2V-14B-Diffusers", vae=vae, torch_dtype=torch.bfloat16 + "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", vae=vae, torch_dtype=torch.bfloat16 ) pipeline.scheduler = UniPCMultistepScheduler.from_config( pipeline.scheduler.config, flow_shift=5.0 ) pipeline.to("cuda") - pipeline.load_lora_weights("benjamin-paine/steamboat-willie-14b", adapter_name="steamboat-willie") + pipeline.load_lora_weights("benjamin-paine/steamboat-willie-1.3b", adapter_name="steamboat-willie") pipeline.set_adapters("steamboat-willie") - + pipeline.enable_model_cpu_offload() # use "steamboat willie style" to trigger the LoRA @@ -201,7 +201,7 @@ export_to_video(output, "output.mp4", fps=16) export_to_video(output, "output.mp4", fps=16) ``` -- [`WanTransformer3DModel`] and [`AutoencoderKLWan`] supports loading from single files with [`!loaders.FromSingleFileMixin.from_single_file`]. +- [`WanTransformer3DModel`] and [`AutoencoderKLWan`] supports loading from single files with [`~loaders.FromSingleFileMixin.from_single_file`]. ```py # pip install ftfy diff --git a/docs/source/en/using-diffusers/text-img2vid.md b/docs/source/en/using-diffusers/text-img2vid.md index 0098d61cbab4..3254522d4579 100644 --- a/docs/source/en/using-diffusers/text-img2vid.md +++ b/docs/source/en/using-diffusers/text-img2vid.md @@ -1,4 +1,4 @@ -