diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index d39b5a52d2fe..04c304d1cafd 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -87,8 +87,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/loaders/lora.md b/docs/source/en/api/loaders/lora.md index 58611a61c25d..6518ac28172d 100644 --- a/docs/source/en/api/loaders/lora.md +++ b/docs/source/en/api/loaders/lora.md @@ -79,4 +79,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 0de40f934548..164d3e3b82b6 100644 --- a/docs/source/en/api/pipelines/cogvideox.md +++ b/docs/source/en/api/pipelines/cogvideox.md @@ -13,150 +13,165 @@ # limitations under the License. --> -# CogVideoX - -
- LoRA +
+
+ LoRA +
-[CogVideoX: Text-to-Video Diffusion Models with An Expert Transformer](https://arxiv.org/abs/2408.06072) from Tsinghua University & ZhipuAI, by Zhuoyi Yang, Jiayan Teng, Wendi Zheng, Ming Ding, Shiyu Huang, Jiazheng Xu, Yuanming Yang, Wenyi Hong, Xiaohan Zhang, Guanyu Feng, Da Yin, Xiaotao Gu, Yuxuan Zhang, Weihan Wang, Yean Cheng, Ting Liu, Bin Xu, Yuxiao Dong, Jie Tang. - -The abstract from the paper is: - -*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.* - - - -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. +# CogVideoX -| 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 | +[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. -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. +You can find all the original CogVideoX checkpoints under the [CogVideoX](https://huggingface.co/collections/THUDM/cogvideo-66c08e62f1685a3ade464cce) collection. -There are two official CogVideoX checkpoints that support pose controllable generation (by the [Alibaba-PAI](https://huggingface.co/alibaba-pai) team). +> [!TIP] +> Click on the CogVideoX models in the right sidebar for more examples of other video generation tasks. -| 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 | +The example below demonstrates how to generate a video optimized for memory or inference speed. -## Inference + + -Use [`torch.compile`](https://huggingface.co/docs/diffusers/main/en/tutorials/fast_diffusion#torchcompile) to reduce the inference latency. +Refer to the [Reduce memory usage](../../optimization/memory) guide for more details about the various memory saving techniques. -First, load the pipeline: +The quantized CogVideoX 5B model below requires ~16GB of VRAM. -```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" -``` - -If you are using the image-to-video pipeline, load it as follows: +from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel +from diffusers.hooks import apply_group_offloading +from diffusers.utils import export_to_video -```python -pipe = CogVideoXImageToVideoPipeline.from_pretrained("THUDM/CogVideoX-5b-I2V").to("cuda") -``` +# 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, +) -Then change the memory layout of the pipelines `transformer` component to `torch.channels_last`: +# 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 +) -```python -pipe.transformer.to(memory_format=torch.channels_last) +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) ``` -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.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. +## Notes -- `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()` +- CogVideoX supports LoRAs with [`~loaders.CogVideoXLoraLoaderMixin.load_lora_weights`]. -## Quantization + ```py + import torch + from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel + from diffusers.hooks import apply_group_offloading + from diffusers.utils import export_to_video -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. + pipeline = CogVideoXPipeline.from_pretrained( + "THUDM/CogVideoX-5b", + torch_dtype=torch.bfloat16 + ) + pipeline.to("cuda") -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. + # 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) -```py -import torch -from diffusers import BitsAndBytesConfig as DiffusersBitsAndBytesConfig, CogVideoXTransformer3DModel, CogVideoXPipeline -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, -) + # model-offloading + pipeline.enable_model_cpu_offload() -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, -) + 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" -pipeline = CogVideoXPipeline.from_pretrained( - "THUDM/CogVideoX-2b", - text_encoder=text_encoder_8bit, - transformer=transformer_8bit, - torch_dtype=torch.float16, - device_map="balanced", -) + 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) + ``` -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) -``` +- 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 diff --git a/docs/source/en/api/pipelines/hunyuan_video.md b/docs/source/en/api/pipelines/hunyuan_video.md index 5d068c8b6ef8..24fd65972f7e 100644 --- a/docs/source/en/api/pipelines/hunyuan_video.md +++ b/docs/source/en/api/pipelines/hunyuan_video.md @@ -12,60 +12,72 @@ # 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. +# HunyuanVideo -*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](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. -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. +> [!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. - +The example below demonstrates how to generate a video optimized for memory or inference speed. -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/). + + -## Available models +Refer to the [Reduce memory usage](../../optimization/memory) guide for more details about the various memory saving techniques. -The following models are available for the [`HunyuanVideoPipeline`](text-to-video) pipeline: +The quantized HunyuanVideo model below requires ~14GB of VRAM. -| 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: +# 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, +) -| 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 and tiling +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. + + + +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 from diffusers.utils import export_to_video -quant_config = DiffusersBitsAndBytesConfig(load_in_8bit=True) -transformer_8bit = HunyuanVideoTransformer3DModel.from_pretrained( +# 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, @@ -74,16 +86,79 @@ 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 and tiling +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 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. + """ + 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 (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. + ## HunyuanVideoPipeline [[autodoc]] HunyuanVideoPipeline diff --git a/docs/source/en/api/pipelines/ltx_video.md b/docs/source/en/api/pipelines/ltx_video.md index 4bc22c0f9f6c..992f483ebfc4 100644 --- a/docs/source/en/api/pipelines/ltx_video.md +++ b/docs/source/en/api/pipelines/ltx_video.md @@ -12,123 +12,100 @@ # See the License for the specific language governing permissions and # limitations under the License. --> -# LTX Video - -
- LoRA +
+
+ 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 0.9.0`](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltx-video-2b-v0.9.safetensors) | `torch.bfloat16` | -| [`LTX Video 0.9.1`](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltx-video-2b-v0.9.1.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 -## Loading Single Files +[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. -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. +You can find all the original LTX-Video checkpoints under the [Lightricks](https://huggingface.co/Lightricks) organization. -```python -import torch -from diffusers import AutoencoderKLLTXVideo, LTXImageToVideoPipeline, LTXVideoTransformer3DModel +> [!TIP] +> Click on the LTX-Video models in the right sidebar for more examples of other video generation tasks. -# `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 -) +The example below demonstrates how to generate a video optimized for memory or inference speed. -# ... inference code ... -``` + + -Alternatively, the pipeline can be used to load the weights with [`~FromSingleFileMixin.from_single_file`]. +Refer to the [Reduce memory usage](../../optimization/memory) guide for more details about the various memory saving techniques. -```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: +The LTX-Video model below requires ~10GB of VRAM. ```py import torch +from diffusers import LTXPipeline, LTXVideoTransformer3DModel +from diffusers.hooks import apply_group_offloading from diffusers.utils import export_to_video -from diffusers import LTXPipeline, LTXVideoTransformer3DModel, GGUFQuantizationConfig -ckpt_path = ( - "https://huggingface.co/city96/LTX-Video-gguf/blob/main/ltx-video-2b-v0.9-Q3_K_S.gguf" +# fp8 layerwise weight-casting +transformer = LTXVideoTransformer3DModel.from_pretrained( + "Lightricks/LTX-Video", + subfolder="transformer", + torch_dtype=torch.bfloat16 ) -transformer = LTXVideoTransformer3DModel.from_single_file( - ckpt_path, - quantization_config=GGUFQuantizationConfig(compute_dtype=torch.bfloat16), - torch_dtype=torch.bfloat16, +transformer.enable_layerwise_casting( + storage_dtype=torch.float8_e4m3fn, + compute_dtype=torch.bfloat16 ) -pipe = LTXPipeline.from_pretrained( - "Lightricks/LTX-Video", - 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" +pipeline = LTXPipeline.from_pretrained("Lightricks/LTX-Video", transformer=transformer, torch_dtype=torch.bfloat16) + +# 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") + +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. - - + + -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. +Compilation is slow the first time but subsequent calls to the pipeline are faster. -```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 +) -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" +# 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, @@ -141,48 +118,60 @@ 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 [`~loaders.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, load_image -```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") -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, -) + # use "CAKEIFY" to trigger the LoRA + 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") -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, + image=image, + 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=26) + ``` -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) -``` +- 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 + 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=torch.bfloat16 + ) + ``` ## LTXPipeline diff --git a/docs/source/en/api/pipelines/wan.md b/docs/source/en/api/pipelines/wan.md index f73c1e0f35b4..72fe88b63489 100644 --- a/docs/source/en/api/pipelines/wan.md +++ b/docs/source/en/api/pipelines/wan.md @@ -12,401 +12,223 @@ # See the License for the specific language governing permissions and # limitations under the License. --> -# Wan - -
- LoRA +
+
+ LoRA +
-[Wan 2.1](https://github.com/Wan-Video/Wan2.1) by the Alibaba Wan Team. - - - -## Generating Videos with Wan 2.1 - -We will first need to install some addtional dependencies. - -```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. - +# Wan2.1 -```python -from diffusers import WanPipeline, AutoencoderKLWan -from diffusers.utils import export_to_video +[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. -model_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers" +You can find all the original Wan2.1 checkpoints under the [Wan-AI](https://huggingface.co/Wan-AI) organization. -vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32) -pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16) +> [!TIP] +> Click on the Wan2.1 models in the right sidebar for more examples of other video generation tasks. -# replace this with pipe.to("cuda") if you have sufficient VRAM -pipe.enable_model_cpu_offload() +The example below demonstrates how to generate a video from text optimized for memory or inference speed. -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) -``` +Refer to the [Reduce memory usage](../../optimization/memory) guide for more details about the various memory saving techniques. -### Image to Video Generation +The Wan2.1 text-to-video model below requires ~13GB of VRAM. -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. +```py +# pip install ftfy -```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) -``` - -## 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) - -#### Block Level Group Offloading - -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`. - -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 alrady, 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 alrady, 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 = ( - "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" +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 +""" -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) +## Notes -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. +- Wan2.1 supports LoRAs with [`~loaders.WanLoraLoaderMixin.load_lora_weights`]. -This example will require 20GB of VRAM. + ```py + # pip install ftfy -```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, CLIPVisionMode + import torch + from diffusers import WanPipeline + from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler + from diffusers.utils import export_to_video -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) + vae = AutoencoderKLWan.from_pretrained( + "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", subfolder="vae", torch_dtype=torch.float32 + ) + pipeline = WanPipeline.from_pretrained( + "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") -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) + pipeline.load_lora_weights("benjamin-paine/steamboat-willie-1.3b", adapter_name="steamboat-willie") + pipeline.set_adapters("steamboat-willie") -pipe = WanImageToVideoPipeline.from_pretrained( - model_id, - 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 + pipeline.enable_model_cpu_offload() -output = pipe( - image=image, + # 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, - negative_prompt=negative_prompt, - height=height, - width=width, - num_frames=num_frames, - num_inference_steps=50, + num_frames=81, 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 + ).frames[0] + export_to_video(output, "output.mp4", fps=16) + ``` -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=) - -# or, -pipe.scheduler = -``` +- [`WanTransformer3DModel`] and [`AutoencoderKLWan`] supports loading from single files with [`~loaders.FromSingleFileMixin.from_single_file`]. -## Using Single File Loading with Wan 2.1 + ```py + # pip install ftfy -The `WanTransformer3DModel` and `AutoencoderKLWan` models support loading checkpoints in their original format via the `from_single_file` loading -method. + import torch + from diffusers import WanPipeline, WanTransformer3DModel, AutoencoderKLWan -```python -import torch -from diffusers import WanPipeline, WanTransformer3DModel + 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, + torch_dtype=torch.bfloat16 + ) + ``` -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) +- Set the [`AutoencoderKLWan`] dtype to `torch.float32` for better decoding quality. -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 @@ -422,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 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
-
-
- diff --git a/docs/source/en/using-diffusers/text-img2vid.md b/docs/source/en/using-diffusers/text-img2vid.md index 92e740bb579d..3254522d4579 100644 --- a/docs/source/en/using-diffusers/text-img2vid.md +++ b/docs/source/en/using-diffusers/text-img2vid.md @@ -1,4 +1,4 @@ -