Skip to content

Official repository for LTX-Video

sync: Update tests, fp8 configs, and minor fixes

Yaki98a0ce6a69c9
diff --git a/.gitattributes b/.gitattributes
index 7ba3ccc..19861d7 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -2,3 +2,4 @@
*.jpeg filter=lfs diff=lfs merge=lfs -text
*.png filter=lfs diff=lfs merge=lfs -text
*.gif filter=lfs diff=lfs merge=lfs -text
+tests/utils/car.png filter=lfs diff=lfs merge=lfs -text
diff --git a/.github/workflows/pylint.yml b/.github/workflows/pylint.yml
index a07ba7b..dea7402 100644
--- a/.github/workflows/pylint.yml
+++ b/.github/workflows/pylint.yml
@@ -10,9 +10,9 @@ jobs:
python-version: ["3.10"]
steps:
- name: Checkout repository and submodules
- uses: actions/checkout@v3
+ uses: actions/checkout@v4
- name: Set up Python ${{ matrix.python-version }}
- uses: actions/setup-python@v3
+ uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
diff --git a/.gitignore b/.gitignore
index bccce0f..db788ba 100644
--- a/.gitignore
+++ b/.gitignore
@@ -163,4 +163,6 @@ cython_debug/
# From inference.py
outputs/
-video_output_*.mp4
\ No newline at end of file
+*.mp4
+*.png
+!tests/utils/car.png
\ No newline at end of file
diff --git a/README.md b/README.md
index 7182691..2268af7 100644
--- a/README.md
+++ b/README.md
@@ -17,9 +17,9 @@ This is the official repository for LTX-Video.
- [Introduction](#introduction)
- [What's new](#news)
-- [Models & Workflows](#models--workflows)
+- [Models](#models)
- [Quick Start Guide](#quick-start-guide)
- - [Use online](#online-inference)
+ - [Online demo](#online-inference)
- [Run locally](#run-locally)
- [Installation](#installation)
- [Inference](#inference)
@@ -27,8 +27,8 @@ This is the official repository for LTX-Video.
- [Diffusers Integration](#diffusers-integration)
- [Model User Guide](#model-user-guide)
- [Community Contribution](#community-contribution)
-- [Training](#⚡️-training)
-- [Join Us!](#🚀-join-us)
+- [Training](#training)
+- [Join Us!](#join-us-)
- [Acknowledgement](#acknowledgement)
# Introduction
@@ -38,23 +38,15 @@ It can generate 30 FPS videos at 1216×704 resolution, faster than it takes to w
The model is trained on a large-scale dataset of diverse videos and can generate high-resolution videos
with realistic and diverse content.
-The model supports text-to-image, image-to-video, keyframe-based animation, video extension (both forward and backward), video-to-video transformations, and any combination of these features.
+The model supports image-to-video, keyframe-based animation, video extension (both forward and backward), video-to-video transformations, and any combination of these features.
-### Image to video examples
+### Image-to-video examples
| | | |
|:---:|:---:|:---:|
| ![example1](./docs/_static/ltx-video_i2v_example_00001.gif) | ![example2](./docs/_static/ltx-video_i2v_example_00002.gif) | ![example3](./docs/_static/ltx-video_i2v_example_00003.gif) |
| ![example4](./docs/_static/ltx-video_i2v_example_00004.gif) | ![example5](./docs/_static/ltx-video_i2v_example_00005.gif) | ![example6](./docs/_static/ltx-video_i2v_example_00006.gif) |
| ![example7](./docs/_static/ltx-video_i2v_example_00007.gif) | ![example8](./docs/_static/ltx-video_i2v_example_00008.gif) | ![example9](./docs/_static/ltx-video_i2v_example_00009.gif) |
-
-### Text to video examples
-| | | |
-|:---:|:---:|:---:|
-| ![example1](./docs/_static/ltx-video_example_00001.gif)<br><details style="max-width: 300px; margin: auto;"><summary>A woman with long brown hair and light skin smiles at another woman...</summary>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.</details> | ![example10](./docs/_static/ltx-video_example_00010.gif)<br><details style="max-width: 300px; margin: auto;"><summary>A clear, turquoise river flows through a rocky canyon...</summary>A clear, turquoise river flows through a rocky canyon, cascading over a small waterfall and forming a pool of water at the bottom.The river is the main focus of the scene, with its clear water reflecting the surrounding trees and rocks. The canyon walls are steep and rocky, with some vegetation growing on them. The trees are mostly pine trees, with their green needles contrasting with the brown and gray rocks. The overall tone of the scene is one of peace and tranquility.</details> | ![example3](./docs/_static/ltx-video_example_00015.gif)<br><details style="max-width: 300px; margin: auto;"><summary>Two police officers in dark blue uniforms and matching hats...</summary>Two police officers in dark blue uniforms and matching hats enter a dimly lit room through a doorway on the left side of the frame. The first officer, with short brown hair and a mustache, steps inside first, followed by his partner, who has a shaved head and a goatee. Both officers have serious expressions and maintain a steady pace as they move deeper into the room. The camera remains stationary, capturing them from a slightly low angle as they enter. The room has exposed brick walls and a corrugated metal ceiling, with a barred window visible in the background. The lighting is low-key, casting shadows on the officers' faces and emphasizing the grim atmosphere. The scene appears to be from a film or television show.</details> |
-| ![example5](./docs/_static/ltx-video_example_00005.gif)<br><details style="max-width: 300px; margin: auto;"><summary>A woman with light skin, wearing a blue jacket and a black hat...</summary>A woman with light skin, wearing a blue jacket and a black hat with a veil, looks down and to her right, then back up as she speaks; she has brown hair styled in an updo, light brown eyebrows, and is wearing a white collared shirt under her jacket; the camera remains stationary on her face as she speaks; the background is out of focus, but shows trees and people in period clothing; the scene is captured in real-life footage.</details> | ![example6](./docs/_static/ltx-video_example_00006.gif)<br><details style="max-width: 300px; margin: auto;"><summary>A man in a dimly lit room talks on a vintage telephone...</summary>A man in a dimly lit room talks on a vintage telephone, hangs up, and looks down with a sad expression. He holds the black rotary phone to his right ear with his right hand, his left hand holding a rocks glass with amber liquid. He wears a brown suit jacket over a white shirt, and a gold ring on his left ring finger. His short hair is neatly combed, and he has light skin with visible wrinkles around his eyes. The camera remains stationary, focused on his face and upper body. The room is dark, lit only by a warm light source off-screen to the left, casting shadows on the wall behind him. The scene appears to be from a movie.</details> | ![example7](./docs/_static/ltx-video_example_00007.gif)<br><details style="max-width: 300px; margin: auto;"><summary>A prison guard unlocks and opens a cell door...</summary>A prison guard unlocks and opens a cell door to reveal a young man sitting at a table with a woman. The guard, wearing a dark blue uniform with a badge on his left chest, unlocks the cell door with a key held in his right hand and pulls it open; he has short brown hair, light skin, and a neutral expression. The young man, wearing a black and white striped shirt, sits at a table covered with a white tablecloth, facing the woman; he has short brown hair, light skin, and a neutral expression. The woman, wearing a dark blue shirt, sits opposite the young man, her face turned towards him; she has short blonde hair and light skin. The camera remains stationary, capturing the scene from a medium distance, positioned slightly to the right of the guard. The room is dimly lit, with a single light fixture illuminating the table and the two figures. The walls are made of large, grey concrete blocks, and a metal door is visible in the background. The scene is captured in real-life footage.</details> |
-| ![example2](./docs/_static/ltx-video_example_00014.gif)<br><details style="max-width: 300px; margin: auto;"><summary>A man walks towards a window, looks out, and then turns around...</summary>A man walks towards a window, looks out, and then turns around. He has short, dark hair, dark skin, and is wearing a brown coat over a red and gray scarf. He walks from left to right towards a window, his gaze fixed on something outside. The camera follows him from behind at a medium distance. The room is brightly lit, with white walls and a large window covered by a white curtain. As he approaches the window, he turns his head slightly to the left, then back to the right. He then turns his entire body to the right, facing the window. The camera remains stationary as he stands in front of the window. The scene is captured in real-life footage.</details> | ![example13](./docs/_static/ltx-video_example_00013.gif)<br><details style="max-width: 300px; margin: auto;"><summary>The camera pans across a cityscape of tall buildings...</summary>The camera pans across a cityscape of tall buildings with a circular building in the center. The camera moves from left to right, showing the tops of the buildings and the circular building in the center. The buildings are various shades of gray and white, and the circular building has a green roof. The camera angle is high, looking down at the city. The lighting is bright, with the sun shining from the upper left, casting shadows from the buildings. The scene is computer-generated imagery.</details> | ![example11](./docs/_static/ltx-video_example_00011.gif)<br><details style="max-width: 300px; margin: auto;"><summary>A man in a suit enters a room and speaks to two women...</summary>A man in a suit enters a room and speaks to two women sitting on a couch. The man, wearing a dark suit with a gold tie, enters the room from the left and walks towards the center of the frame. He has short gray hair, light skin, and a serious expression. He places his right hand on the back of a chair as he approaches the couch. Two women are seated on a light-colored couch in the background. The woman on the left wears a light blue sweater and has short blonde hair. The woman on the right wears a white sweater and has short blonde hair. The camera remains stationary, focusing on the man as he enters the room. The room is brightly lit, with warm tones reflecting off the walls and furniture. The scene appears to be from a film or television show.</details> |
-
# News
## May, 14th, 2025: New distilled model 13B v0.9.7:
@@ -65,11 +57,11 @@ The model supports text-to-image, image-to-video, keyframe-based animation, vide
* Also released a LoRA version of the distilled model, [ltxv-13b-0.9.7-distilled-lora128](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-13b-0.9.7-distilled-lora128.safetensors)
* Requires only 1GB of VRAM
* Can be used with the full 13B model for fast inference
-- Release a new quantized distilled model [ltxv-13b-0.9.7-distilled-fp8](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-13b-0.9.7-distilled-fp8.safetensors) for *real-time* generation (on H100) with even less VRAM (Supported in the [official ComfyUI workflow](https://github.com/Lightricks/ComfyUI-LTXVideo/))
+- Release a new quantized distilled model [ltxv-13b-0.9.7-distilled-fp8](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-13b-0.9.7-distilled-fp8.safetensors) for *real-time* generation (on H100) with even less VRAM
## May, 5th, 2025: New model 13B v0.9.7:
- Release a new 13B model [ltxv-13b-0.9.7-dev](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-13b-0.9.7-dev.safetensors)
-- Release a new quantized model [ltxv-13b-0.9.7-dev-fp8](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-13b-0.9.7-dev-fp8.safetensors) for faster inference with less VRAM (Supported in the [official ComfyUI workflow](https://github.com/Lightricks/ComfyUI-LTXVideo/))
+- Release a new quantized model [ltxv-13b-0.9.7-dev-fp8](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-13b-0.9.7-dev-fp8.safetensors) for faster inference with less VRam
- Release a new upscalers
* [ltxv-temporal-upscaler-0.9.7](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-temporal-upscaler-0.9.7.safetensors)
* [ltxv-spatial-upscaler-0.9.7](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-spatial-upscaler-0.9.7.safetensors)
@@ -132,8 +124,8 @@ The model supports text-to-image, image-to-video, keyframe-based animation, vide
| [ltxv-13b-0.9.7-mix](https://app.ltx.studio/motion-workspace?videoModel=ltxv-13b) | Mix ltxv-13b-dev and ltxv-13b-distilled in the same multi-scale rendering workflow for balanced speed-quality | N/A | [ltxv-13b-i2v-mixed-multiscale.json](https://github.com/Lightricks/ComfyUI-LTXVideo/blob/master/example_workflows/ltxv-13b-i2v-mixed-multiscale.json) |
[ltxv-13b-0.9.7-distilled](https://app.ltx.studio/motion-workspace?videoModel=ltxv) | Faster, less VRAM usage, slight quality reduction compared to 13b. Ideal for rapid iterations | [ltxv-13b-0.9.7-distilled.yaml](https://github.com/Lightricks/LTX-Video/blob/main/configs/ltxv-13b-0.9.7-dev.yaml) | [ltxv-13b-dist-i2v-base.json](https://github.com/Lightricks/ComfyUI-LTXVideo/blob/master/example_workflows/13b-distilled/ltxv-13b-dist-i2v-base.json) |
| [ltxv-13b-0.9.7-distilled-lora128](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-13b-0.9.7-distilled-lora128.safetensors) | LoRA to make ltxv-13b-dev behave like the distilled model | N/A | N/A |
-| ltxv-13b-0.9.7-fp8 | Quantized version of ltxv-13b | Coming soon | [ltxv-13b-i2v-base-fp8.json](https://github.com/Lightricks/ComfyUI-LTXVideo/blob/master/example_workflows/ltxv-13b-i2v-base-fp8.json) |
-| ltxv-13b-0.9.7-distilled-fp8 | Quantized version of ltxv-13b-distilled | Coming soon | [ltxv-13b-dist-i2v-base-fp8.json](https://github.com/Lightricks/ComfyUI-LTXVideo/blob/master/example_workflows/13b-distilled/ltxv-13b-dist-i2v-base-fp8.json) |
+| ltxv-13b-0.9.7-dev-fp8 | Quantized version of ltxv-13b | [ltxv-13b-0.9.7-dev-fp8.yaml](https://github.com/Lightricks/LTX-Video/blob/main/configs/ltxv-13b-0.9.7-dev-fp8.yaml) | [ltxv-13b-i2v-base-fp8.json](https://github.com/Lightricks/ComfyUI-LTXVideo/blob/master/example_workflows/ltxv-13b-i2v-base-fp8.json) |
+| ltxv-13b-0.9.7-distilled-fp8 | Quantized version of ltxv-13b-distilled | [ltxv-13b-0.9.7-distilled-fp8.yaml](https://github.com/Lightricks/LTX-Video/blob/main/configs/ltxv-13b-0.9.7-distilled-fp8.yaml) | [ltxv-13b-dist-i2v-base-fp8.json](https://github.com/Lightricks/ComfyUI-LTXVideo/blob/master/example_workflows/13b-distilled/ltxv-13b-dist-i2v-base-fp8.json) |
| ltxv-2b-0.9.6 | Good quality, lower VRAM requirement than ltxv-13b | [ltxv-2b-0.9.6-dev.yaml](https://github.com/Lightricks/LTX-Video/blob/main/configs/ltxv-2b-0.9.6-dev.yaml) | [ltxvideo-i2v.json](https://github.com/Lightricks/ComfyUI-LTXVideo/blob/master/example_workflows/low_level/ltxvideo-i2v.json) |
| ltxv-2b-0.9.6-distilled | 15× faster, real-time capable, fewer steps needed, no STG/CFG required | [ltxv-2b-0.9.6-distilled.yaml](https://github.com/Lightricks/LTX-Video/blob/main/configs/ltxv-2b-0.9.6-distilled.yaml) | [ltxvideo-i2v-distilled.json](https://github.com/Lightricks/ComfyUI-LTXVideo/blob/master/example_workflows/low_level/ltxvideo-i2v-distilled.json) |
@@ -144,15 +136,15 @@ The model supports text-to-image, image-to-video, keyframe-based animation, vide
The model is accessible right away via the following links:
- [LTX-Studio image-to-video (13B-mix)](https://app.ltx.studio/motion-workspace?videoModel=ltxv-13b)
- [LTX-Studio image-to-video (13B distilled)](https://app.ltx.studio/motion-workspace?videoModel=ltxv)
-- [Fal.ai text-to-video](https://fal.ai/models/fal-ai/ltx-video)
-- [Fal.ai image-to-video](https://fal.ai/models/fal-ai/ltx-video/image-to-video)
-- [Replicate text-to-video and image-to-video](https://replicate.com/lightricks/ltx-video)
+- [Fal.ai image-to-video (13B full)](https://fal.ai/models/fal-ai/ltx-video-13b-dev/image-to-video)
+- [Fal.ai image-to-video (13B distilled)](https://fal.ai/models/fal-ai/ltx-video-13b-distilled/image-to-video)
+- [Replicate image-to-video](https://replicate.com/lightricks/ltx-video)
## Run locally
### Installation
The codebase was tested with Python 3.10.5, CUDA version 12.2, and supports PyTorch >= 2.1.2.
-On macos, MPS was tested with PyTorch 2.3.0, and should support PyTorch == 2.3 or >= 2.6.
+On macOS, MPS was tested with PyTorch 2.3.0, and should support PyTorch == 2.3 or >= 2.6.
```bash
git clone https://github.com/Lightricks/LTX-Video.git
@@ -161,21 +153,19 @@ cd LTX-Video
# create env
python -m venv env
source env/bin/activate
-python -m pip install -e .\[inference-script\]
+python -m pip install -e \[inference\]
```
+#### FP8 Kernels (optional)
+
+[FP8 kernels](https://github.com/Lightricks/LTXVideo-Q8-Kernels) developed for LTX-Video provide performance boost on supported graphics cards (Ada architecture and later). To install FP8 kernels, follow the instructions in that repository.
+
### Inference
📝 **Note:** For best results, we recommend using our [ComfyUI](#comfyui-integration) workflow. We’re working on updating the inference.py script to match the high quality and output fidelity of ComfyUI.
To use our model, please follow the inference code in [inference.py](./inference.py):
-#### For text-to-video generation:
-
-```bash
-python inference.py --prompt "PROMPT" --height HEIGHT --width WIDTH --num_frames NUM_FRAMES --seed SEED --pipeline_config configs/ltxv-13b-0.9.7-distilled.yaml
-```
-
#### For image-to-video generation:
```bash
@@ -200,6 +190,23 @@ Simply provide a list of paths to the images or video segments you want to condi
python inference.py --prompt "PROMPT" --conditioning_media_paths IMAGE_OR_VIDEO_PATH_1 IMAGE_OR_VIDEO_PATH_2 --conditioning_start_frames TARGET_FRAME_1 TARGET_FRAME_2 --height HEIGHT --width WIDTH --num_frames NUM_FRAMES --seed SEED --pipeline_config configs/ltxv-13b-0.9.7-distilled.yaml
```
+### Using as a library
+
+```python
+from ltx_video.inference import infer, InferenceConfig
+
+infer(
+ InferenceConfig(
+ pipeline_config="configs/ltxv-13b-0.9.7-distilled.yaml",
+ prompt=PROMPT,
+ height=HEIGHT,
+ width=WIDTH,
+ num_frames=NUM_FRAMES,
+ output_path="output.mp4",
+ )
+)
+```
+
## ComfyUI Integration
To use our model with ComfyUI, please follow the instructions at [https://github.com/Lightricks/ComfyUI-LTXVideo/](https://github.com/Lightricks/ComfyUI-LTXVideo/).
@@ -224,7 +231,6 @@ When writing prompts, focus on detailed, chronological descriptions of actions a
* See [examples](#introduction) for more inspiration.
### Automatic Prompt Enhancement
-When using `inference.py`, shorts prompts (below `prompt_enhancement_words_threshold` words) are automatically enhanced by a language model. This is supported with text-to-video and image-to-video (first-frame conditioning).
When using `LTXVideoPipeline` directly, you can enable prompt enhancement by setting `enhance_prompt=True`.
diff --git a/__init__.py b/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/configs/ltxv-13b-0.9.7-dev-fp8.yaml b/configs/ltxv-13b-0.9.7-dev-fp8.yaml
new file mode 100644
index 0000000..66e9c69
--- /dev/null
+++ b/configs/ltxv-13b-0.9.7-dev-fp8.yaml
@@ -0,0 +1,34 @@
+pipeline_type: multi-scale
+checkpoint_path: "ltxv-13b-0.9.7-dev-fp8.safetensors"
+downscale_factor: 0.6666666
+spatial_upscaler_model_path: "ltxv-spatial-upscaler-0.9.7.safetensors"
+stg_mode: "attention_values" # options: "attention_values", "attention_skip", "residual", "transformer_block"
+decode_timestep: 0.05
+decode_noise_scale: 0.025
+text_encoder_model_name_or_path: "PixArt-alpha/PixArt-XL-2-1024-MS"
+precision: "float8_e4m3fn" # options: "float8_e4m3fn", "bfloat16", "mixed_precision"
+sampler: "from_checkpoint" # options: "uniform", "linear-quadratic", "from_checkpoint"
+prompt_enhancement_words_threshold: 120
+prompt_enhancer_image_caption_model_name_or_path: "MiaoshouAI/Florence-2-large-PromptGen-v2.0"
+prompt_enhancer_llm_model_name_or_path: "unsloth/Llama-3.2-3B-Instruct"
+stochastic_sampling: false
+
+first_pass:
+ guidance_scale: [1, 1, 6, 8, 6, 1, 1]
+ stg_scale: [0, 0, 4, 4, 4, 2, 1]
+ rescaling_scale: [1, 1, 0.5, 0.5, 1, 1, 1]
+ guidance_timesteps: [1.0, 0.996, 0.9933, 0.9850, 0.9767, 0.9008, 0.6180]
+ skip_block_list: [[], [11, 25, 35, 39], [22, 35, 39], [28], [28], [28], [28]]
+ num_inference_steps: 30
+ skip_final_inference_steps: 3
+ cfg_star_rescale: true
+
+second_pass:
+ guidance_scale: [1]
+ stg_scale: [1]
+ rescaling_scale: [1]
+ guidance_timesteps: [1.0]
+ skip_block_list: [27]
+ num_inference_steps: 30
+ skip_initial_inference_steps: 17
+ cfg_star_rescale: true
diff --git a/configs/ltxv-13b-0.9.7-distilled-fp8.yaml b/configs/ltxv-13b-0.9.7-distilled-fp8.yaml
new file mode 100644
index 0000000..151c6fc
--- /dev/null
+++ b/configs/ltxv-13b-0.9.7-distilled-fp8.yaml
@@ -0,0 +1,28 @@
+pipeline_type: multi-scale
+checkpoint_path: "ltxv-13b-0.9.7-distilled-fp8.safetensors"
+downscale_factor: 0.6666666
+spatial_upscaler_model_path: "ltxv-spatial-upscaler-0.9.7.safetensors"
+stg_mode: "attention_values" # options: "attention_values", "attention_skip", "residual", "transformer_block"
+decode_timestep: 0.05
+decode_noise_scale: 0.025
+text_encoder_model_name_or_path: "PixArt-alpha/PixArt-XL-2-1024-MS"
+precision: "float8_e4m3fn" # options: "float8_e4m3fn", "bfloat16", "mixed_precision"
+sampler: "from_checkpoint" # options: "uniform", "linear-quadratic", "from_checkpoint"
+prompt_enhancement_words_threshold: 120
+prompt_enhancer_image_caption_model_name_or_path: "MiaoshouAI/Florence-2-large-PromptGen-v2.0"
+prompt_enhancer_llm_model_name_or_path: "unsloth/Llama-3.2-3B-Instruct"
+stochastic_sampling: false
+
+first_pass:
+ timesteps: [1.0000, 0.9937, 0.9875, 0.9812, 0.9750, 0.9094, 0.7250]
+ guidance_scale: 1
+ stg_scale: 0
+ rescaling_scale: 1
+ skip_block_list: [42]
+
+second_pass:
+ timesteps: [0.9094, 0.7250, 0.4219]
+ guidance_scale: 1
+ stg_scale: 0
+ rescaling_scale: 1
+ skip_block_list: [42]
diff --git a/inference.py b/inference.py
index 0642afa..ff59133 100644
--- a/inference.py
+++ b/inference.py
@@ -1,773 +1,12 @@
-import argparse
-import os
-import random
-from datetime import datetime
-from pathlib import Path
-from diffusers.utils import logging
-from typing import Optional, List, Union
-import yaml
+from transformers import HfArgumentParser
-import imageio
-import json
-import numpy as np
-import torch
-import cv2
-from safetensors import safe_open
-from PIL import Image
-from transformers import (
- T5EncoderModel,
- T5Tokenizer,
- AutoModelForCausalLM,
- AutoProcessor,
- AutoTokenizer,
-)
-from huggingface_hub import hf_hub_download
-
-from ltx_video.models.autoencoders.causal_video_autoencoder import (
- CausalVideoAutoencoder,
-)
-from ltx_video.models.transformers.symmetric_patchifier import SymmetricPatchifier
-from ltx_video.models.transformers.transformer3d import Transformer3DModel
-from ltx_video.pipelines.pipeline_ltx_video import (
- ConditioningItem,
- LTXVideoPipeline,
- LTXMultiScalePipeline,
-)
-from ltx_video.schedulers.rf import RectifiedFlowScheduler
-from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
-from ltx_video.models.autoencoders.latent_upsampler import LatentUpsampler
-import ltx_video.pipelines.crf_compressor as crf_compressor
-
-MAX_HEIGHT = 720
-MAX_WIDTH = 1280
-MAX_NUM_FRAMES = 257
-
-logger = logging.get_logger("LTX-Video")
-
-
-def get_total_gpu_memory():
- if torch.cuda.is_available():
- total_memory = torch.cuda.get_device_properties(0).total_memory / (1024**3)
- return total_memory
- return 0
-
-
-def get_device():
- if torch.cuda.is_available():
- return "cuda"
- elif torch.backends.mps.is_available():
- return "mps"
- return "cpu"
-
-
-def load_image_to_tensor_with_resize_and_crop(
- image_input: Union[str, Image.Image],
- target_height: int = 512,
- target_width: int = 768,
- just_crop: bool = False,
-) -> torch.Tensor:
- """Load and process an image into a tensor.
-
- Args:
- image_input: Either a file path (str) or a PIL Image object
- target_height: Desired height of output tensor
- target_width: Desired width of output tensor
- just_crop: If True, only crop the image to the target size without resizing
- """
- if isinstance(image_input, str):
- image = Image.open(image_input).convert("RGB")
- elif isinstance(image_input, Image.Image):
- image = image_input
- else:
- raise ValueError("image_input must be either a file path or a PIL Image object")
-
- input_width, input_height = image.size
- aspect_ratio_target = target_width / target_height
- aspect_ratio_frame = input_width / input_height
- if aspect_ratio_frame > aspect_ratio_target:
- new_width = int(input_height * aspect_ratio_target)
- new_height = input_height
- x_start = (input_width - new_width) // 2
- y_start = 0
- else:
- new_width = input_width
- new_height = int(input_width / aspect_ratio_target)
- x_start = 0
- y_start = (input_height - new_height) // 2
-
- image = image.crop((x_start, y_start, x_start + new_width, y_start + new_height))
- if not just_crop:
- image = image.resize((target_width, target_height))
-
- image = np.array(image)
- image = cv2.GaussianBlur(image, (3, 3), 0)
- frame_tensor = torch.from_numpy(image).float()
- frame_tensor = crf_compressor.compress(frame_tensor / 255.0) * 255.0
- frame_tensor = frame_tensor.permute(2, 0, 1)
- frame_tensor = (frame_tensor / 127.5) - 1.0
- # Create 5D tensor: (batch_size=1, channels=3, num_frames=1, height, width)
- return frame_tensor.unsqueeze(0).unsqueeze(2)
-
-
-def calculate_padding(
- source_height: int, source_width: int, target_height: int, target_width: int
-) -> tuple[int, int, int, int]:
-
- # Calculate total padding needed
- pad_height = target_height - source_height
- pad_width = target_width - source_width
-
- # Calculate padding for each side
- pad_top = pad_height // 2
- pad_bottom = pad_height - pad_top # Handles odd padding
- pad_left = pad_width // 2
- pad_right = pad_width - pad_left # Handles odd padding
-
- # Return padded tensor
- # Padding format is (left, right, top, bottom)
- padding = (pad_left, pad_right, pad_top, pad_bottom)
- return padding
-
-
-def convert_prompt_to_filename(text: str, max_len: int = 20) -> str:
- # Remove non-letters and convert to lowercase
- clean_text = "".join(
- char.lower() for char in text if char.isalpha() or char.isspace()
- )
-
- # Split into words
- words = clean_text.split()
-
- # Build result string keeping track of length
- result = []
- current_length = 0
-
- for word in words:
- # Add word length plus 1 for underscore (except for first word)
- new_length = current_length + len(word)
-
- if new_length <= max_len:
- result.append(word)
- current_length += len(word)
- else:
- break
-
- return "-".join(result)
-
-
-# Generate output video name
-def get_unique_filename(
- base: str,
- ext: str,
- prompt: str,
- seed: int,
- resolution: tuple[int, int, int],
- dir: Path,
- endswith=None,
- index_range=1000,
-) -> Path:
- base_filename = f"{base}_{convert_prompt_to_filename(prompt, max_len=30)}_{seed}_{resolution[0]}x{resolution[1]}x{resolution[2]}"
- for i in range(index_range):
- filename = dir / f"{base_filename}_{i}{endswith if endswith else ''}{ext}"
- if not os.path.exists(filename):
- return filename
- raise FileExistsError(
- f"Could not find a unique filename after {index_range} attempts."
- )
-
-
-def seed_everething(seed: int):
- random.seed(seed)
- np.random.seed(seed)
- torch.manual_seed(seed)
- if torch.cuda.is_available():
- torch.cuda.manual_seed(seed)
- if torch.backends.mps.is_available():
- torch.mps.manual_seed(seed)
+from ltx_video.inference import infer, InferenceConfig
def main():
- parser = argparse.ArgumentParser(
- description="Load models from separate directories and run the pipeline."
- )
-
- # Directories
- parser.add_argument(
- "--output_path",
- type=str,
- default=None,
- help="Path to the folder to save output video, if None will save in outputs/ directory.",
- )
- parser.add_argument("--seed", type=int, default="171198")
-
- # Pipeline parameters
- parser.add_argument(
- "--num_images_per_prompt",
- type=int,
- default=1,
- help="Number of images per prompt",
- )
- parser.add_argument(
- "--image_cond_noise_scale",
- type=float,
- default=0.15,
- help="Amount of noise to add to the conditioned image",
- )
- parser.add_argument(
- "--height",
- type=int,
- default=704,
- help="Height of the output video frames. Optional if an input image provided.",
- )
- parser.add_argument(
- "--width",
- type=int,
- default=1216,
- help="Width of the output video frames. If None will infer from input image.",
- )
- parser.add_argument(
- "--num_frames",
- type=int,
- default=121,
- help="Number of frames to generate in the output video",
- )
- parser.add_argument(
- "--frame_rate", type=int, default=30, help="Frame rate for the output video"
- )
- parser.add_argument(
- "--device",
- default=None,
- help="Device to run inference on. If not specified, will automatically detect and use CUDA or MPS if available, else CPU.",
- )
- parser.add_argument(
- "--pipeline_config",
- type=str,
- default="configs/ltxv-13b-0.9.7-dev.yaml",
- help="The path to the config file for the pipeline, which contains the parameters for the pipeline",
- )
-
- # Prompts
- parser.add_argument(
- "--prompt",
- type=str,
- help="Text prompt to guide generation",
- )
- parser.add_argument(
- "--negative_prompt",
- type=str,
- default="worst quality, inconsistent motion, blurry, jittery, distorted",
- help="Negative prompt for undesired features",
- )
-
- parser.add_argument(
- "--offload_to_cpu",
- action="store_true",
- help="Offloading unnecessary computations to CPU.",
- )
-
- # video-to-video arguments:
- parser.add_argument(
- "--input_media_path",
- type=str,
- default=None,
- help="Path to the input video (or imaage) to be modified using the video-to-video pipeline",
- )
-
- # Conditioning arguments
- parser.add_argument(
- "--conditioning_media_paths",
- type=str,
- nargs="*",
- help="List of paths to conditioning media (images or videos). Each path will be used as a conditioning item.",
- )
- parser.add_argument(
- "--conditioning_strengths",
- type=float,
- nargs="*",
- help="List of conditioning strengths (between 0 and 1) for each conditioning item. Must match the number of conditioning items.",
- )
- parser.add_argument(
- "--conditioning_start_frames",
- type=int,
- nargs="*",
- help="List of frame indices where each conditioning item should be applied. Must match the number of conditioning items.",
- )
-
- args = parser.parse_args()
- logger.warning(f"Running generation with arguments: {args}")
- infer(**vars(args))
-
-
-def create_ltx_video_pipeline(
- ckpt_path: str,
- precision: str,
- text_encoder_model_name_or_path: str,
- sampler: Optional[str] = None,
- device: Optional[str] = None,
- enhance_prompt: bool = False,
- prompt_enhancer_image_caption_model_name_or_path: Optional[str] = None,
- prompt_enhancer_llm_model_name_or_path: Optional[str] = None,
-) -> LTXVideoPipeline:
- ckpt_path = Path(ckpt_path)
- assert os.path.exists(
- ckpt_path
- ), f"Ckpt path provided (--ckpt_path) {ckpt_path} does not exist"
-
- with safe_open(ckpt_path, framework="pt") as f:
- metadata = f.metadata()
- config_str = metadata.get("config")
- configs = json.loads(config_str)
- allowed_inference_steps = configs.get("allowed_inference_steps", None)
-
- vae = CausalVideoAutoencoder.from_pretrained(ckpt_path)
- transformer = Transformer3DModel.from_pretrained(ckpt_path)
-
- # Use constructor if sampler is specified, otherwise use from_pretrained
- if sampler == "from_checkpoint" or not sampler:
- scheduler = RectifiedFlowScheduler.from_pretrained(ckpt_path)
- else:
- scheduler = RectifiedFlowScheduler(
- sampler=("Uniform" if sampler.lower() == "uniform" else "LinearQuadratic")
- )
-
- text_encoder = T5EncoderModel.from_pretrained(
- text_encoder_model_name_or_path, subfolder="text_encoder"
- )
- patchifier = SymmetricPatchifier(patch_size=1)
- tokenizer = T5Tokenizer.from_pretrained(
- text_encoder_model_name_or_path, subfolder="tokenizer"
- )
-
- transformer = transformer.to(device)
- vae = vae.to(device)
- text_encoder = text_encoder.to(device)
-
- if enhance_prompt:
- prompt_enhancer_image_caption_model = AutoModelForCausalLM.from_pretrained(
- prompt_enhancer_image_caption_model_name_or_path, trust_remote_code=True
- )
- prompt_enhancer_image_caption_processor = AutoProcessor.from_pretrained(
- prompt_enhancer_image_caption_model_name_or_path, trust_remote_code=True
- )
- prompt_enhancer_llm_model = AutoModelForCausalLM.from_pretrained(
- prompt_enhancer_llm_model_name_or_path,
- torch_dtype="bfloat16",
- )
- prompt_enhancer_llm_tokenizer = AutoTokenizer.from_pretrained(
- prompt_enhancer_llm_model_name_or_path,
- )
- else:
- prompt_enhancer_image_caption_model = None
- prompt_enhancer_image_caption_processor = None
- prompt_enhancer_llm_model = None
- prompt_enhancer_llm_tokenizer = None
-
- vae = vae.to(torch.bfloat16)
- if precision == "bfloat16" and transformer.dtype != torch.bfloat16:
- transformer = transformer.to(torch.bfloat16)
- text_encoder = text_encoder.to(torch.bfloat16)
-
- # Use submodels for the pipeline
- submodel_dict = {
- "transformer": transformer,
- "patchifier": patchifier,
- "text_encoder": text_encoder,
- "tokenizer": tokenizer,
- "scheduler": scheduler,
- "vae": vae,
- "prompt_enhancer_image_caption_model": prompt_enhancer_image_caption_model,
- "prompt_enhancer_image_caption_processor": prompt_enhancer_image_caption_processor,
- "prompt_enhancer_llm_model": prompt_enhancer_llm_model,
- "prompt_enhancer_llm_tokenizer": prompt_enhancer_llm_tokenizer,
- "allowed_inference_steps": allowed_inference_steps,
- }
-
- pipeline = LTXVideoPipeline(**submodel_dict)
- pipeline = pipeline.to(device)
- return pipeline
-
-
-def create_latent_upsampler(latent_upsampler_model_path: str, device: str):
- latent_upsampler = LatentUpsampler.from_pretrained(latent_upsampler_model_path)
- latent_upsampler.to(device)
- latent_upsampler.eval()
- return latent_upsampler
-
-
-def infer(
- output_path: Optional[str],
- seed: int,
- pipeline_config: str,
- image_cond_noise_scale: float,
- height: Optional[int],
- width: Optional[int],
- num_frames: int,
- frame_rate: int,
- prompt: str,
- negative_prompt: str,
- offload_to_cpu: bool,
- input_media_path: Optional[str] = None,
- conditioning_media_paths: Optional[List[str]] = None,
- conditioning_strengths: Optional[List[float]] = None,
- conditioning_start_frames: Optional[List[int]] = None,
- device: Optional[str] = None,
- **kwargs,
-):
- # check if pipeline_config is a file
- if not os.path.isfile(pipeline_config):
- raise ValueError(f"Pipeline config file {pipeline_config} does not exist")
- with open(pipeline_config, "r") as f:
- pipeline_config = yaml.safe_load(f)
-
- models_dir = "MODEL_DIR"
-
- ltxv_model_name_or_path = pipeline_config["checkpoint_path"]
- if not os.path.isfile(ltxv_model_name_or_path):
- ltxv_model_path = hf_hub_download(
- repo_id="Lightricks/LTX-Video",
- filename=ltxv_model_name_or_path,
- local_dir=models_dir,
- repo_type="model",
- )
- else:
- ltxv_model_path = ltxv_model_name_or_path
-
- spatial_upscaler_model_name_or_path = pipeline_config.get(
- "spatial_upscaler_model_path"
- )
- if spatial_upscaler_model_name_or_path and not os.path.isfile(
- spatial_upscaler_model_name_or_path
- ):
- spatial_upscaler_model_path = hf_hub_download(
- repo_id="Lightricks/LTX-Video",
- filename=spatial_upscaler_model_name_or_path,
- local_dir=models_dir,
- repo_type="model",
- )
- else:
- spatial_upscaler_model_path = spatial_upscaler_model_name_or_path
-
- if kwargs.get("input_image_path", None):
- logger.warning(
- "Please use conditioning_media_paths instead of input_image_path."
- )
- assert not conditioning_media_paths and not conditioning_start_frames
- conditioning_media_paths = [kwargs["input_image_path"]]
- conditioning_start_frames = [0]
-
- # Validate conditioning arguments
- if conditioning_media_paths:
- # Use default strengths of 1.0
- if not conditioning_strengths:
- conditioning_strengths = [1.0] * len(conditioning_media_paths)
- if not conditioning_start_frames:
- raise ValueError(
- "If `conditioning_media_paths` is provided, "
- "`conditioning_start_frames` must also be provided"
- )
- if len(conditioning_media_paths) != len(conditioning_strengths) or len(
- conditioning_media_paths
- ) != len(conditioning_start_frames):
- raise ValueError(
- "`conditioning_media_paths`, `conditioning_strengths`, "
- "and `conditioning_start_frames` must have the same length"
- )
- if any(s < 0 or s > 1 for s in conditioning_strengths):
- raise ValueError("All conditioning strengths must be between 0 and 1")
- if any(f < 0 or f >= num_frames for f in conditioning_start_frames):
- raise ValueError(
- f"All conditioning start frames must be between 0 and {num_frames-1}"
- )
-
- seed_everething(seed)
- if offload_to_cpu and not torch.cuda.is_available():
- logger.warning(
- "offload_to_cpu is set to True, but offloading will not occur since the model is already running on CPU."
- )
- offload_to_cpu = False
- else:
- offload_to_cpu = offload_to_cpu and get_total_gpu_memory() < 30
-
- output_dir = (
- Path(output_path)
- if output_path
- else Path(f"outputs/{datetime.today().strftime('%Y-%m-%d')}")
- )
- output_dir.mkdir(parents=True, exist_ok=True)
-
- # Adjust dimensions to be divisible by 32 and num_frames to be (N * 8 + 1)
- height_padded = ((height - 1) // 32 + 1) * 32
- width_padded = ((width - 1) // 32 + 1) * 32
- num_frames_padded = ((num_frames - 2) // 8 + 1) * 8 + 1
-
- padding = calculate_padding(height, width, height_padded, width_padded)
-
- logger.warning(
- f"Padded dimensions: {height_padded}x{width_padded}x{num_frames_padded}"
- )
-
- prompt_enhancement_words_threshold = pipeline_config[
- "prompt_enhancement_words_threshold"
- ]
-
- prompt_word_count = len(prompt.split())
- enhance_prompt = (
- prompt_enhancement_words_threshold > 0
- and prompt_word_count < prompt_enhancement_words_threshold
- )
-
- if prompt_enhancement_words_threshold > 0 and not enhance_prompt:
- logger.info(
- f"Prompt has {prompt_word_count} words, which exceeds the threshold of {prompt_enhancement_words_threshold}. Prompt enhancement disabled."
- )
-
- precision = pipeline_config["precision"]
- text_encoder_model_name_or_path = pipeline_config["text_encoder_model_name_or_path"]
- sampler = pipeline_config["sampler"]
- prompt_enhancer_image_caption_model_name_or_path = pipeline_config[
- "prompt_enhancer_image_caption_model_name_or_path"
- ]
- prompt_enhancer_llm_model_name_or_path = pipeline_config[
- "prompt_enhancer_llm_model_name_or_path"
- ]
-
- pipeline = create_ltx_video_pipeline(
- ckpt_path=ltxv_model_path,
- precision=precision,
- text_encoder_model_name_or_path=text_encoder_model_name_or_path,
- sampler=sampler,
- device=kwargs.get("device", get_device()),
- enhance_prompt=enhance_prompt,
- prompt_enhancer_image_caption_model_name_or_path=prompt_enhancer_image_caption_model_name_or_path,
- prompt_enhancer_llm_model_name_or_path=prompt_enhancer_llm_model_name_or_path,
- )
-
- if pipeline_config.get("pipeline_type", None) == "multi-scale":
- if not spatial_upscaler_model_path:
- raise ValueError(
- "spatial upscaler model path is missing from pipeline config file and is required for multi-scale rendering"
- )
- latent_upsampler = create_latent_upsampler(
- spatial_upscaler_model_path, pipeline.device
- )
- pipeline = LTXMultiScalePipeline(pipeline, latent_upsampler=latent_upsampler)
-
- media_item = None
- if input_media_path:
- media_item = load_media_file(
- media_path=input_media_path,
- height=height,
- width=width,
- max_frames=num_frames_padded,
- padding=padding,
- )
-
- conditioning_items = (
- prepare_conditioning(
- conditioning_media_paths=conditioning_media_paths,
- conditioning_strengths=conditioning_strengths,
- conditioning_start_frames=conditioning_start_frames,
- height=height,
- width=width,
- num_frames=num_frames,
- padding=padding,
- pipeline=pipeline,
- )
- if conditioning_media_paths
- else None
- )
-
- stg_mode = pipeline_config.get("stg_mode", "attention_values")
- del pipeline_config["stg_mode"]
- if stg_mode.lower() == "stg_av" or stg_mode.lower() == "attention_values":
- skip_layer_strategy = SkipLayerStrategy.AttentionValues
- elif stg_mode.lower() == "stg_as" or stg_mode.lower() == "attention_skip":
- skip_layer_strategy = SkipLayerStrategy.AttentionSkip
- elif stg_mode.lower() == "stg_r" or stg_mode.lower() == "residual":
- skip_layer_strategy = SkipLayerStrategy.Residual
- elif stg_mode.lower() == "stg_t" or stg_mode.lower() == "transformer_block":
- skip_layer_strategy = SkipLayerStrategy.TransformerBlock
- else:
- raise ValueError(f"Invalid spatiotemporal guidance mode: {stg_mode}")
-
- # Prepare input for the pipeline
- sample = {
- "prompt": prompt,
- "prompt_attention_mask": None,
- "negative_prompt": negative_prompt,
- "negative_prompt_attention_mask": None,
- }
-
- device = device or get_device()
- generator = torch.Generator(device=device).manual_seed(seed)
-
- images = pipeline(
- **pipeline_config,
- skip_layer_strategy=skip_layer_strategy,
- generator=generator,
- output_type="pt",
- callback_on_step_end=None,
- height=height_padded,
- width=width_padded,
- num_frames=num_frames_padded,
- frame_rate=frame_rate,
- **sample,
- media_items=media_item,
- conditioning_items=conditioning_items,
- is_video=True,
- vae_per_channel_normalize=True,
- image_cond_noise_scale=image_cond_noise_scale,
- mixed_precision=(precision == "mixed_precision"),
- offload_to_cpu=offload_to_cpu,
- device=device,
- enhance_prompt=enhance_prompt,
- ).images
-
- # Crop the padded images to the desired resolution and number of frames
- (pad_left, pad_right, pad_top, pad_bottom) = padding
- pad_bottom = -pad_bottom
- pad_right = -pad_right
- if pad_bottom == 0:
- pad_bottom = images.shape[3]
- if pad_right == 0:
- pad_right = images.shape[4]
- images = images[:, :, :num_frames, pad_top:pad_bottom, pad_left:pad_right]
-
- for i in range(images.shape[0]):
- # Gathering from B, C, F, H, W to C, F, H, W and then permuting to F, H, W, C
- video_np = images[i].permute(1, 2, 3, 0).cpu().float().numpy()
- # Unnormalizing images to [0, 255] range
- video_np = (video_np * 255).astype(np.uint8)
- fps = frame_rate
- height, width = video_np.shape[1:3]
- # In case a single image is generated
- if video_np.shape[0] == 1:
- output_filename = get_unique_filename(
- f"image_output_{i}",
- ".png",
- prompt=prompt,
- seed=seed,
- resolution=(height, width, num_frames),
- dir=output_dir,
- )
- imageio.imwrite(output_filename, video_np[0])
- else:
- output_filename = get_unique_filename(
- f"video_output_{i}",
- ".mp4",
- prompt=prompt,
- seed=seed,
- resolution=(height, width, num_frames),
- dir=output_dir,
- )
-
- # Write video
- with imageio.get_writer(output_filename, fps=fps) as video:
- for frame in video_np:
- video.append_data(frame)
-
- logger.warning(f"Output saved to {output_filename}")
-
-
-def prepare_conditioning(
- conditioning_media_paths: List[str],
- conditioning_strengths: List[float],
- conditioning_start_frames: List[int],
- height: int,
- width: int,
- num_frames: int,
- padding: tuple[int, int, int, int],
- pipeline: LTXVideoPipeline,
-) -> Optional[List[ConditioningItem]]:
- """Prepare conditioning items based on input media paths and their parameters.
-
- Args:
- conditioning_media_paths: List of paths to conditioning media (images or videos)
- conditioning_strengths: List of conditioning strengths for each media item
- conditioning_start_frames: List of frame indices where each item should be applied
- height: Height of the output frames
- width: Width of the output frames
- num_frames: Number of frames in the output video
- padding: Padding to apply to the frames
- pipeline: LTXVideoPipeline object used for condition video trimming
-
- Returns:
- A list of ConditioningItem objects.
- """
- conditioning_items = []
- for path, strength, start_frame in zip(
- conditioning_media_paths, conditioning_strengths, conditioning_start_frames
- ):
- num_input_frames = orig_num_input_frames = get_media_num_frames(path)
- if hasattr(pipeline, "trim_conditioning_sequence") and callable(
- getattr(pipeline, "trim_conditioning_sequence")
- ):
- num_input_frames = pipeline.trim_conditioning_sequence(
- start_frame, orig_num_input_frames, num_frames
- )
- if num_input_frames < orig_num_input_frames:
- logger.warning(
- f"Trimming conditioning video {path} from {orig_num_input_frames} to {num_input_frames} frames."
- )
-
- media_tensor = load_media_file(
- media_path=path,
- height=height,
- width=width,
- max_frames=num_input_frames,
- padding=padding,
- just_crop=True,
- )
- conditioning_items.append(ConditioningItem(media_tensor, start_frame, strength))
- return conditioning_items
-
-
-def get_media_num_frames(media_path: str) -> int:
- is_video = any(
- media_path.lower().endswith(ext) for ext in [".mp4", ".avi", ".mov", ".mkv"]
- )
- num_frames = 1
- if is_video:
- reader = imageio.get_reader(media_path)
- num_frames = reader.count_frames()
- reader.close()
- return num_frames
-
-
-def load_media_file(
- media_path: str,
- height: int,
- width: int,
- max_frames: int,
- padding: tuple[int, int, int, int],
- just_crop: bool = False,
-) -> torch.Tensor:
- is_video = any(
- media_path.lower().endswith(ext) for ext in [".mp4", ".avi", ".mov", ".mkv"]
- )
- if is_video:
- reader = imageio.get_reader(media_path)
- num_input_frames = min(reader.count_frames(), max_frames)
-
- # Read and preprocess the relevant frames from the video file.
- frames = []
- for i in range(num_input_frames):
- frame = Image.fromarray(reader.get_data(i))
- frame_tensor = load_image_to_tensor_with_resize_and_crop(
- frame, height, width, just_crop=just_crop
- )
- frame_tensor = torch.nn.functional.pad(frame_tensor, padding)
- frames.append(frame_tensor)
- reader.close()
-
- # Stack frames along the temporal dimension
- media_tensor = torch.cat(frames, dim=2)
- else: # Input image
- media_tensor = load_image_to_tensor_with_resize_and_crop(
- media_path, height, width, just_crop=just_crop
- )
- media_tensor = torch.nn.functional.pad(media_tensor, padding)
- return media_tensor
+ parser = HfArgumentParser(InferenceConfig)
+ config = parser.parse_args_into_dataclasses()[0]
+ infer(config=config)
if __name__ == "__main__":
diff --git a/ltx_video/inference.py b/ltx_video/inference.py
new file mode 100644
index 0000000..1eddc8e
--- /dev/null
+++ b/ltx_video/inference.py
@@ -0,0 +1,715 @@
+import os
+import random
+from datetime import datetime
+from pathlib import Path
+from diffusers.utils import logging
+from typing import Optional, List, Union
+import yaml
+
+import imageio
+import json
+import numpy as np
+import torch
+from safetensors import safe_open
+from PIL import Image
+import torchvision.transforms.functional as TVF
+from transformers import (
+ T5EncoderModel,
+ T5Tokenizer,
+ AutoModelForCausalLM,
+ AutoProcessor,
+ AutoTokenizer,
+)
+from huggingface_hub import hf_hub_download
+from dataclasses import dataclass, field
+
+from ltx_video.models.autoencoders.causal_video_autoencoder import (
+ CausalVideoAutoencoder,
+)
+from ltx_video.models.transformers.symmetric_patchifier import SymmetricPatchifier
+from ltx_video.models.transformers.transformer3d import Transformer3DModel
+from ltx_video.pipelines.pipeline_ltx_video import (
+ ConditioningItem,
+ LTXVideoPipeline,
+ LTXMultiScalePipeline,
+)
+from ltx_video.schedulers.rf import RectifiedFlowScheduler
+from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
+from ltx_video.models.autoencoders.latent_upsampler import LatentUpsampler
+import ltx_video.pipelines.crf_compressor as crf_compressor
+
+logger = logging.get_logger("LTX-Video")
+
+
+def get_total_gpu_memory():
+ if torch.cuda.is_available():
+ total_memory = torch.cuda.get_device_properties(0).total_memory / (1024**3)
+ return total_memory
+ return 0
+
+
+def get_device():
+ if torch.cuda.is_available():
+ return "cuda"
+ elif torch.backends.mps.is_available():
+ return "mps"
+ return "cpu"
+
+
+def load_image_to_tensor_with_resize_and_crop(
+ image_input: Union[str, Image.Image],
+ target_height: int = 512,
+ target_width: int = 768,
+ just_crop: bool = False,
+) -> torch.Tensor:
+ """Load and process an image into a tensor.
+
+ Args:
+ image_input: Either a file path (str) or a PIL Image object
+ target_height: Desired height of output tensor
+ target_width: Desired width of output tensor
+ just_crop: If True, only crop the image to the target size without resizing
+ """
+ if isinstance(image_input, str):
+ image = Image.open(image_input).convert("RGB")
+ elif isinstance(image_input, Image.Image):
+ image = image_input
+ else:
+ raise ValueError("image_input must be either a file path or a PIL Image object")
+
+ input_width, input_height = image.size
+ aspect_ratio_target = target_width / target_height
+ aspect_ratio_frame = input_width / input_height
+ if aspect_ratio_frame > aspect_ratio_target:
+ new_width = int(input_height * aspect_ratio_target)
+ new_height = input_height
+ x_start = (input_width - new_width) // 2
+ y_start = 0
+ else:
+ new_width = input_width
+ new_height = int(input_width / aspect_ratio_target)
+ x_start = 0
+ y_start = (input_height - new_height) // 2
+
+ image = image.crop((x_start, y_start, x_start + new_width, y_start + new_height))
+ if not just_crop:
+ image = image.resize((target_width, target_height))
+
+ frame_tensor = TVF.to_tensor(image) # PIL -> tensor (C, H, W), [0,1]
+ frame_tensor = TVF.gaussian_blur(frame_tensor, kernel_size=3, sigma=1.0)
+ frame_tensor_hwc = frame_tensor.permute(1, 2, 0) # (C, H, W) -> (H, W, C)
+ frame_tensor_hwc = crf_compressor.compress(frame_tensor_hwc)
+ frame_tensor = frame_tensor_hwc.permute(2, 0, 1) * 255.0 # (H, W, C) -> (C, H, W)
+ frame_tensor = (frame_tensor / 127.5) - 1.0
+ # Create 5D tensor: (batch_size=1, channels=3, num_frames=1, height, width)
+ return frame_tensor.unsqueeze(0).unsqueeze(2)
+
+
+def calculate_padding(
+ source_height: int, source_width: int, target_height: int, target_width: int
+) -> tuple[int, int, int, int]:
+
+ # Calculate total padding needed
+ pad_height = target_height - source_height
+ pad_width = target_width - source_width
+
+ # Calculate padding for each side
+ pad_top = pad_height // 2
+ pad_bottom = pad_height - pad_top # Handles odd padding
+ pad_left = pad_width // 2
+ pad_right = pad_width - pad_left # Handles odd padding
+
+ # Return padded tensor
+ # Padding format is (left, right, top, bottom)
+ padding = (pad_left, pad_right, pad_top, pad_bottom)
+ return padding
+
+
+def convert_prompt_to_filename(text: str, max_len: int = 20) -> str:
+ # Remove non-letters and convert to lowercase
+ clean_text = "".join(
+ char.lower() for char in text if char.isalpha() or char.isspace()
+ )
+
+ # Split into words
+ words = clean_text.split()
+
+ # Build result string keeping track of length
+ result = []
+ current_length = 0
+
+ for word in words:
+ # Add word length plus 1 for underscore (except for first word)
+ new_length = current_length + len(word)
+
+ if new_length <= max_len:
+ result.append(word)
+ current_length += len(word)
+ else:
+ break
+
+ return "-".join(result)
+
+
+# Generate output video name
+def get_unique_filename(
+ base: str,
+ ext: str,
+ prompt: str,
+ seed: int,
+ resolution: tuple[int, int, int],
+ dir: Path,
+ endswith=None,
+ index_range=1000,
+) -> Path:
+ base_filename = f"{base}_{convert_prompt_to_filename(prompt, max_len=30)}_{seed}_{resolution[0]}x{resolution[1]}x{resolution[2]}"
+ for i in range(index_range):
+ filename = dir / f"{base_filename}_{i}{endswith if endswith else ''}{ext}"
+ if not os.path.exists(filename):
+ return filename
+ raise FileExistsError(
+ f"Could not find a unique filename after {index_range} attempts."
+ )
+
+
+def seed_everething(seed: int):
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ if torch.cuda.is_available():
+ torch.cuda.manual_seed(seed)
+ if torch.backends.mps.is_available():
+ torch.mps.manual_seed(seed)
+
+
+def create_ltx_video_pipeline(
+ ckpt_path: str,
+ precision: str,
+ text_encoder_model_name_or_path: str,
+ sampler: Optional[str] = None,
+ device: Optional[str] = None,
+ enhance_prompt: bool = False,
+ prompt_enhancer_image_caption_model_name_or_path: Optional[str] = None,
+ prompt_enhancer_llm_model_name_or_path: Optional[str] = None,
+) -> LTXVideoPipeline:
+ ckpt_path = Path(ckpt_path)
+ assert os.path.exists(
+ ckpt_path
+ ), f"Ckpt path provided (--ckpt_path) {ckpt_path} does not exist"
+
+ with safe_open(ckpt_path, framework="pt") as f:
+ metadata = f.metadata()
+ config_str = metadata.get("config")
+ configs = json.loads(config_str)
+ allowed_inference_steps = configs.get("allowed_inference_steps", None)
+
+ vae = CausalVideoAutoencoder.from_pretrained(ckpt_path)
+ transformer = Transformer3DModel.from_pretrained(ckpt_path)
+
+ # Use constructor if sampler is specified, otherwise use from_pretrained
+ if sampler == "from_checkpoint" or not sampler:
+ scheduler = RectifiedFlowScheduler.from_pretrained(ckpt_path)
+ else:
+ scheduler = RectifiedFlowScheduler(
+ sampler=("Uniform" if sampler.lower() == "uniform" else "LinearQuadratic")
+ )
+
+ text_encoder = T5EncoderModel.from_pretrained(
+ text_encoder_model_name_or_path, subfolder="text_encoder"
+ )
+ patchifier = SymmetricPatchifier(patch_size=1)
+ tokenizer = T5Tokenizer.from_pretrained(
+ text_encoder_model_name_or_path, subfolder="tokenizer"
+ )
+
+ transformer = transformer.to(device)
+ vae = vae.to(device)
+ text_encoder = text_encoder.to(device)
+
+ if enhance_prompt:
+ prompt_enhancer_image_caption_model = AutoModelForCausalLM.from_pretrained(
+ prompt_enhancer_image_caption_model_name_or_path, trust_remote_code=True
+ )
+ prompt_enhancer_image_caption_processor = AutoProcessor.from_pretrained(
+ prompt_enhancer_image_caption_model_name_or_path, trust_remote_code=True
+ )
+ prompt_enhancer_llm_model = AutoModelForCausalLM.from_pretrained(
+ prompt_enhancer_llm_model_name_or_path,
+ torch_dtype="bfloat16",
+ )
+ prompt_enhancer_llm_tokenizer = AutoTokenizer.from_pretrained(
+ prompt_enhancer_llm_model_name_or_path,
+ )
+ else:
+ prompt_enhancer_image_caption_model = None
+ prompt_enhancer_image_caption_processor = None
+ prompt_enhancer_llm_model = None
+ prompt_enhancer_llm_tokenizer = None
+
+ vae = vae.to(torch.bfloat16)
+ if precision == "bfloat16" and transformer.dtype != torch.bfloat16:
+ transformer = transformer.to(torch.bfloat16)
+ text_encoder = text_encoder.to(torch.bfloat16)
+
+ # Use submodels for the pipeline
+ submodel_dict = {
+ "transformer": transformer,
+ "patchifier": patchifier,
+ "text_encoder": text_encoder,
+ "tokenizer": tokenizer,
+ "scheduler": scheduler,
+ "vae": vae,
+ "prompt_enhancer_image_caption_model": prompt_enhancer_image_caption_model,
+ "prompt_enhancer_image_caption_processor": prompt_enhancer_image_caption_processor,
+ "prompt_enhancer_llm_model": prompt_enhancer_llm_model,
+ "prompt_enhancer_llm_tokenizer": prompt_enhancer_llm_tokenizer,
+ "allowed_inference_steps": allowed_inference_steps,
+ }
+
+ pipeline = LTXVideoPipeline(**submodel_dict)
+ pipeline = pipeline.to(device)
+ return pipeline
+
+
+def create_latent_upsampler(latent_upsampler_model_path: str, device: str):
+ latent_upsampler = LatentUpsampler.from_pretrained(latent_upsampler_model_path)
+ latent_upsampler.to(device)
+ latent_upsampler.eval()
+ return latent_upsampler
+
+
+def load_pipeline_config(pipeline_config: str):
+ current_file = Path(__file__)
+
+ path = None
+ if os.path.isfile(current_file.parent / pipeline_config):
+ path = current_file.parent / pipeline_config
+ elif os.path.isfile(pipeline_config):
+ path = pipeline_config
+ else:
+ raise ValueError(f"Pipeline config file {pipeline_config} does not exist")
+
+ with open(path, "r") as f:
+ return yaml.safe_load(f)
+
+
+@dataclass
+class InferenceConfig:
+ prompt: str = field(metadata={"help": "Prompt for the generation"})
+
+ output_path: str = field(
+ default_factory=lambda: Path(
+ f"outputs/{datetime.today().strftime('%Y-%m-%d')}"
+ ),
+ metadata={"help": "Path to the folder to save the output video"},
+ )
+
+ # Pipeline settings
+ pipeline_config: str = field(
+ default="configs/ltxv-13b-0.9.7-dev.yaml",
+ metadata={"help": "Path to the pipeline config file"},
+ )
+ seed: int = field(
+ default=171198, metadata={"help": "Random seed for the inference"}
+ )
+ height: int = field(
+ default=704, metadata={"help": "Height of the output video frames"}
+ )
+ width: int = field(
+ default=1216, metadata={"help": "Width of the output video frames"}
+ )
+ num_frames: int = field(
+ default=121,
+ metadata={"help": "Number of frames to generate in the output video"},
+ )
+ frame_rate: int = field(
+ default=30, metadata={"help": "Frame rate for the output video"}
+ )
+ offload_to_cpu: bool = field(
+ default=False, metadata={"help": "Offloading unnecessary computations to CPU."}
+ )
+ negative_prompt: str = field(
+ default="worst quality, inconsistent motion, blurry, jittery, distorted",
+ metadata={"help": "Negative prompt for undesired features"},
+ )
+
+ # Video-to-video arguments
+ input_media_path: Optional[str] = field(
+ default=None,
+ metadata={
+ "help": "Path to the input video (or image) to be modified using the video-to-video pipeline"
+ },
+ )
+
+ # Conditioning
+ image_cond_noise_scale: float = field(
+ default=0.15,
+ metadata={"help": "Amount of noise to add to the conditioned image"},
+ )
+ conditioning_media_paths: Optional[List[str]] = field(
+ default=None,
+ metadata={
+ "help": "List of paths to conditioning media (images or videos). Each path will be used as a conditioning item."
+ },
+ )
+ conditioning_strengths: Optional[List[float]] = field(
+ default=None,
+ metadata={
+ "help": "List of conditioning strengths (between 0 and 1) for each conditioning item. Must match the number of conditioning items."
+ },
+ )
+ conditioning_start_frames: Optional[List[int]] = field(
+ default=None,
+ metadata={
+ "help": "List of frame indices where each conditioning item should be applied. Must match the number of conditioning items."
+ },
+ )
+
+
+def infer(config: InferenceConfig):
+ pipeline_config = load_pipeline_config(config.pipeline_config)
+
+ ltxv_model_name_or_path = pipeline_config["checkpoint_path"]
+ if not os.path.isfile(ltxv_model_name_or_path):
+ ltxv_model_path = hf_hub_download(
+ repo_id="Lightricks/LTX-Video",
+ filename=ltxv_model_name_or_path,
+ repo_type="model",
+ )
+ else:
+ ltxv_model_path = ltxv_model_name_or_path
+
+ spatial_upscaler_model_name_or_path = pipeline_config.get(
+ "spatial_upscaler_model_path"
+ )
+ if spatial_upscaler_model_name_or_path and not os.path.isfile(
+ spatial_upscaler_model_name_or_path
+ ):
+ spatial_upscaler_model_path = hf_hub_download(
+ repo_id="Lightricks/LTX-Video",
+ filename=spatial_upscaler_model_name_or_path,
+ repo_type="model",
+ )
+ else:
+ spatial_upscaler_model_path = spatial_upscaler_model_name_or_path
+
+ conditioning_media_paths = config.conditioning_media_paths
+ conditioning_strengths = config.conditioning_strengths
+ conditioning_start_frames = config.conditioning_start_frames
+
+ # Validate conditioning arguments
+ if conditioning_media_paths:
+ # Use default strengths of 1.0
+ if not conditioning_strengths:
+ conditioning_strengths = [1.0] * len(conditioning_media_paths)
+ if not conditioning_start_frames:
+ raise ValueError(
+ "If `conditioning_media_paths` is provided, "
+ "`conditioning_start_frames` must also be provided"
+ )
+ if len(conditioning_media_paths) != len(conditioning_strengths) or len(
+ conditioning_media_paths
+ ) != len(conditioning_start_frames):
+ raise ValueError(
+ "`conditioning_media_paths`, `conditioning_strengths`, "
+ "and `conditioning_start_frames` must have the same length"
+ )
+ if any(s < 0 or s > 1 for s in conditioning_strengths):
+ raise ValueError("All conditioning strengths must be between 0 and 1")
+ if any(f < 0 or f >= config.num_frames for f in conditioning_start_frames):
+ raise ValueError(
+ f"All conditioning start frames must be between 0 and {config.num_frames-1}"
+ )
+
+ seed_everething(config.seed)
+ if config.offload_to_cpu and not torch.cuda.is_available():
+ logger.warning(
+ "offload_to_cpu is set to True, but offloading will not occur since the model is already running on CPU."
+ )
+ offload_to_cpu = False
+ else:
+ offload_to_cpu = config.offload_to_cpu and get_total_gpu_memory() < 30
+
+ output_dir = (
+ Path(config.output_path)
+ if config.output_path
+ else Path(f"outputs/{datetime.today().strftime('%Y-%m-%d')}")
+ )
+ output_dir.mkdir(parents=True, exist_ok=True)
+
+ # Adjust dimensions to be divisible by 32 and num_frames to be (N * 8 + 1)
+ height_padded = ((config.height - 1) // 32 + 1) * 32
+ width_padded = ((config.width - 1) // 32 + 1) * 32
+ num_frames_padded = ((config.num_frames - 2) // 8 + 1) * 8 + 1
+
+ padding = calculate_padding(
+ config.height, config.width, height_padded, width_padded
+ )
+
+ logger.warning(
+ f"Padded dimensions: {height_padded}x{width_padded}x{num_frames_padded}"
+ )
+
+ device = get_device()
+
+ prompt_enhancement_words_threshold = pipeline_config[
+ "prompt_enhancement_words_threshold"
+ ]
+
+ prompt_word_count = len(config.prompt.split())
+ enhance_prompt = (
+ prompt_enhancement_words_threshold > 0
+ and prompt_word_count < prompt_enhancement_words_threshold
+ )
+
+ if prompt_enhancement_words_threshold > 0 and not enhance_prompt:
+ logger.info(
+ f"Prompt has {prompt_word_count} words, which exceeds the threshold of {prompt_enhancement_words_threshold}. Prompt enhancement disabled."
+ )
+
+ precision = pipeline_config["precision"]
+ text_encoder_model_name_or_path = pipeline_config["text_encoder_model_name_or_path"]
+ sampler = pipeline_config.get("sampler", None)
+ prompt_enhancer_image_caption_model_name_or_path = pipeline_config[
+ "prompt_enhancer_image_caption_model_name_or_path"
+ ]
+ prompt_enhancer_llm_model_name_or_path = pipeline_config[
+ "prompt_enhancer_llm_model_name_or_path"
+ ]
+
+ pipeline = create_ltx_video_pipeline(
+ ckpt_path=ltxv_model_path,
+ precision=precision,
+ text_encoder_model_name_or_path=text_encoder_model_name_or_path,
+ sampler=sampler,
+ device=device,
+ enhance_prompt=enhance_prompt,
+ prompt_enhancer_image_caption_model_name_or_path=prompt_enhancer_image_caption_model_name_or_path,
+ prompt_enhancer_llm_model_name_or_path=prompt_enhancer_llm_model_name_or_path,
+ )
+
+ if pipeline_config.get("pipeline_type", None) == "multi-scale":
+ if not spatial_upscaler_model_path:
+ raise ValueError(
+ "spatial upscaler model path is missing from pipeline config file and is required for multi-scale rendering"
+ )
+ latent_upsampler = create_latent_upsampler(
+ spatial_upscaler_model_path, pipeline.device
+ )
+ pipeline = LTXMultiScalePipeline(pipeline, latent_upsampler=latent_upsampler)
+
+ media_item = None
+ if config.input_media_path:
+ media_item = load_media_file(
+ media_path=config.input_media_path,
+ height=config.height,
+ width=config.width,
+ max_frames=num_frames_padded,
+ padding=padding,
+ )
+
+ conditioning_items = (
+ prepare_conditioning(
+ conditioning_media_paths=conditioning_media_paths,
+ conditioning_strengths=conditioning_strengths,
+ conditioning_start_frames=conditioning_start_frames,
+ height=config.height,
+ width=config.width,
+ num_frames=config.num_frames,
+ padding=padding,
+ pipeline=pipeline,
+ )
+ if conditioning_media_paths
+ else None
+ )
+
+ stg_mode = pipeline_config.get("stg_mode", "attention_values")
+ del pipeline_config["stg_mode"]
+ if stg_mode.lower() == "stg_av" or stg_mode.lower() == "attention_values":
+ skip_layer_strategy = SkipLayerStrategy.AttentionValues
+ elif stg_mode.lower() == "stg_as" or stg_mode.lower() == "attention_skip":
+ skip_layer_strategy = SkipLayerStrategy.AttentionSkip
+ elif stg_mode.lower() == "stg_r" or stg_mode.lower() == "residual":
+ skip_layer_strategy = SkipLayerStrategy.Residual
+ elif stg_mode.lower() == "stg_t" or stg_mode.lower() == "transformer_block":
+ skip_layer_strategy = SkipLayerStrategy.TransformerBlock
+ else:
+ raise ValueError(f"Invalid spatiotemporal guidance mode: {stg_mode}")
+
+ # Prepare input for the pipeline
+ sample = {
+ "prompt": config.prompt,
+ "prompt_attention_mask": None,
+ "negative_prompt": config.negative_prompt,
+ "negative_prompt_attention_mask": None,
+ }
+
+ generator = torch.Generator(device=device).manual_seed(config.seed)
+
+ images = pipeline(
+ **pipeline_config,
+ skip_layer_strategy=skip_layer_strategy,
+ generator=generator,
+ output_type="pt",
+ callback_on_step_end=None,
+ height=height_padded,
+ width=width_padded,
+ num_frames=num_frames_padded,
+ frame_rate=config.frame_rate,
+ **sample,
+ media_items=media_item,
+ conditioning_items=conditioning_items,
+ is_video=True,
+ vae_per_channel_normalize=True,
+ image_cond_noise_scale=config.image_cond_noise_scale,
+ mixed_precision=(precision == "mixed_precision"),
+ offload_to_cpu=offload_to_cpu,
+ device=device,
+ enhance_prompt=enhance_prompt,
+ ).images
+
+ # Crop the padded images to the desired resolution and number of frames
+ (pad_left, pad_right, pad_top, pad_bottom) = padding
+ pad_bottom = -pad_bottom
+ pad_right = -pad_right
+ if pad_bottom == 0:
+ pad_bottom = images.shape[3]
+ if pad_right == 0:
+ pad_right = images.shape[4]
+ images = images[:, :, : config.num_frames, pad_top:pad_bottom, pad_left:pad_right]
+
+ for i in range(images.shape[0]):
+ # Gathering from B, C, F, H, W to C, F, H, W and then permuting to F, H, W, C
+ video_np = images[i].permute(1, 2, 3, 0).cpu().float().numpy()
+ # Unnormalizing images to [0, 255] range
+ video_np = (video_np * 255).astype(np.uint8)
+ fps = config.frame_rate
+ height, width = video_np.shape[1:3]
+ # In case a single image is generated
+ if video_np.shape[0] == 1:
+ output_filename = get_unique_filename(
+ f"image_output_{i}",
+ ".png",
+ prompt=config.prompt,
+ seed=config.seed,
+ resolution=(height, width, config.num_frames),
+ dir=output_dir,
+ )
+ imageio.imwrite(output_filename, video_np[0])
+ else:
+ output_filename = get_unique_filename(
+ f"video_output_{i}",
+ ".mp4",
+ prompt=config.prompt,
+ seed=config.seed,
+ resolution=(height, width, config.num_frames),
+ dir=output_dir,
+ )
+
+ # Write video
+ with imageio.get_writer(output_filename, fps=fps) as video:
+ for frame in video_np:
+ video.append_data(frame)
+
+ logger.warning(f"Output saved to {output_filename}")
+
+
+def prepare_conditioning(
+ conditioning_media_paths: List[str],
+ conditioning_strengths: List[float],
+ conditioning_start_frames: List[int],
+ height: int,
+ width: int,
+ num_frames: int,
+ padding: tuple[int, int, int, int],
+ pipeline: LTXVideoPipeline,
+) -> Optional[List[ConditioningItem]]:
+ """Prepare conditioning items based on input media paths and their parameters.
+
+ Args:
+ conditioning_media_paths: List of paths to conditioning media (images or videos)
+ conditioning_strengths: List of conditioning strengths for each media item
+ conditioning_start_frames: List of frame indices where each item should be applied
+ height: Height of the output frames
+ width: Width of the output frames
+ num_frames: Number of frames in the output video
+ padding: Padding to apply to the frames
+ pipeline: LTXVideoPipeline object used for condition video trimming
+
+ Returns:
+ A list of ConditioningItem objects.
+ """
+ conditioning_items = []
+ for path, strength, start_frame in zip(
+ conditioning_media_paths, conditioning_strengths, conditioning_start_frames
+ ):
+ num_input_frames = orig_num_input_frames = get_media_num_frames(path)
+ if hasattr(pipeline, "trim_conditioning_sequence") and callable(
+ getattr(pipeline, "trim_conditioning_sequence")
+ ):
+ num_input_frames = pipeline.trim_conditioning_sequence(
+ start_frame, orig_num_input_frames, num_frames
+ )
+ if num_input_frames < orig_num_input_frames:
+ logger.warning(
+ f"Trimming conditioning video {path} from {orig_num_input_frames} to {num_input_frames} frames."
+ )
+
+ media_tensor = load_media_file(
+ media_path=path,
+ height=height,
+ width=width,
+ max_frames=num_input_frames,
+ padding=padding,
+ just_crop=True,
+ )
+ conditioning_items.append(ConditioningItem(media_tensor, start_frame, strength))
+ return conditioning_items
+
+
+def get_media_num_frames(media_path: str) -> int:
+ is_video = any(
+ media_path.lower().endswith(ext) for ext in [".mp4", ".avi", ".mov", ".mkv"]
+ )
+ num_frames = 1
+ if is_video:
+ reader = imageio.get_reader(media_path)
+ num_frames = reader.count_frames()
+ reader.close()
+ return num_frames
+
+
+def load_media_file(
+ media_path: str,
+ height: int,
+ width: int,
+ max_frames: int,
+ padding: tuple[int, int, int, int],
+ just_crop: bool = False,
+) -> torch.Tensor:
+ is_video = any(
+ media_path.lower().endswith(ext) for ext in [".mp4", ".avi", ".mov", ".mkv"]
+ )
+ if is_video:
+ reader = imageio.get_reader(media_path)
+ num_input_frames = min(reader.count_frames(), max_frames)
+
+ # Read and preprocess the relevant frames from the video file.
+ frames = []
+ for i in range(num_input_frames):
+ frame = Image.fromarray(reader.get_data(i))
+ frame_tensor = load_image_to_tensor_with_resize_and_crop(
+ frame, height, width, just_crop=just_crop
+ )
+ frame_tensor = torch.nn.functional.pad(frame_tensor, padding)
+ frames.append(frame_tensor)
+ reader.close()
+
+ # Stack frames along the temporal dimension
+ media_tensor = torch.cat(frames, dim=2)
+ else: # Input image
+ media_tensor = load_image_to_tensor_with_resize_and_crop(
+ media_path, height, width, just_crop=just_crop
+ )
+ media_tensor = torch.nn.functional.pad(media_tensor, padding)
+ return media_tensor
diff --git a/ltx_video/models/autoencoders/causal_video_autoencoder.py b/ltx_video/models/autoencoders/causal_video_autoencoder.py
index 3a347bc..736c96a 100644
--- a/ltx_video/models/autoencoders/causal_video_autoencoder.py
+++ b/ltx_video/models/autoencoders/causal_video_autoencoder.py
@@ -235,7 +235,7 @@ class CausalVideoAutoencoder(AutoencoderKLWrapper):
"compress_time",
"compress_all",
"compress_all_res",
- "compress_space_res",
+ "compress_time_res",
]
]
)
@@ -608,7 +608,7 @@ class Decoder(nn.Module):
block_params = block_params if isinstance(block_params, dict) else {}
if block_name == "res_x_y":
output_channel = output_channel * block_params.get("multiplier", 2)
- if block_name == "compress_all":
+ if block_name.startswith("compress"):
output_channel = output_channel * block_params.get("multiplier", 1)
self.conv_in = make_conv_nd(
@@ -1303,20 +1303,15 @@ def create_video_autoencoder_demo_config(
encoder_blocks = [
("res_x", {"num_layers": 2}),
("compress_space_res", {"multiplier": 2}),
- ("res_x", {"num_layers": 2}),
("compress_time_res", {"multiplier": 2}),
- ("res_x", {"num_layers": 1}),
("compress_all_res", {"multiplier": 2}),
- ("res_x", {"num_layers": 1}),
("compress_all_res", {"multiplier": 2}),
("res_x", {"num_layers": 1}),
]
decoder_blocks = [
("res_x", {"num_layers": 2, "inject_noise": False}),
("compress_all", {"residual": True, "multiplier": 2}),
- ("res_x", {"num_layers": 2, "inject_noise": False}),
("compress_all", {"residual": True, "multiplier": 2}),
- ("res_x", {"num_layers": 2, "inject_noise": False}),
("compress_all", {"residual": True, "multiplier": 2}),
("res_x", {"num_layers": 2, "inject_noise": False}),
]
diff --git a/ltx_video/models/transformers/attention.py b/ltx_video/models/transformers/attention.py
index 6ea0ed1..bee0839 100644
--- a/ltx_video/models/transformers/attention.py
+++ b/ltx_video/models/transformers/attention.py
@@ -205,7 +205,6 @@ class BasicTransformerBlock(nn.Module):
timestep: Optional[torch.LongTensor] = None,
cross_attention_kwargs: Dict[str, Any] = None,
class_labels: Optional[torch.LongTensor] = None,
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
skip_layer_mask: Optional[torch.Tensor] = None,
skip_layer_strategy: Optional[SkipLayerStrategy] = None,
) -> torch.FloatTensor:
diff --git a/ltx_video/models/transformers/transformer3d.py b/ltx_video/models/transformers/transformer3d.py
index 15b388d..3dc08d8 100644
--- a/ltx_video/models/transformers/transformer3d.py
+++ b/ltx_video/models/transformers/transformer3d.py
@@ -268,7 +268,7 @@ class Transformer3DModel(ModelMixin, ConfigMixin):
for key, value in state_dict.items()
if key.startswith("model.diffusion_model.")
}
- super().load_state_dict(state_dict, **kwargs)
+ super().load_state_dict(state_dict, *args, **kwargs)
@classmethod
def from_pretrained(
diff --git a/ltx_video/pipelines/pipeline_ltx_video.py b/ltx_video/pipelines/pipeline_ltx_video.py
index 16ee39e..243f4a3 100644
--- a/ltx_video/pipelines/pipeline_ltx_video.py
+++ b/ltx_video/pipelines/pipeline_ltx_video.py
@@ -45,11 +45,6 @@ from ltx_video.models.autoencoders.vae_encode import (
)
-try:
- import torch_xla.distributed.spmd as xs
-except ImportError:
- xs = None
-
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
@@ -978,10 +973,6 @@ class LTXVideoPipeline(DiffusionPipeline):
guidance_scale[guidance_mapping[i]] for i in range(len(timesteps))
]
- # For simplicity, we are using a constant num_conds for all timesteps, so we need to zero
- # out cases where the guidance scale should not be applied.
- guidance_scale = [x if x > 1.0 else 0.0 for x in guidance_scale]
-
if not isinstance(stg_scale, List):
stg_scale = [stg_scale] * len(timesteps)
else:
@@ -994,16 +985,6 @@ class LTXVideoPipeline(DiffusionPipeline):
rescaling_scale[guidance_mapping[i]] for i in range(len(timesteps))
]
- do_classifier_free_guidance = any(x > 1.0 for x in guidance_scale)
- do_spatio_temporal_guidance = any(x > 0.0 for x in stg_scale)
- do_rescaling = any(x != 1.0 for x in rescaling_scale)
-
- num_conds = 1
- if do_classifier_free_guidance:
- num_conds += 1
- if do_spatio_temporal_guidance:
- num_conds += 1
-
# Normalize skip_block_list to always be None or a list of lists matching timesteps
if skip_block_list is not None:
# Convert single list to list of lists if needed
@@ -1015,17 +996,6 @@ class LTXVideoPipeline(DiffusionPipeline):
new_skip_block_list.append(skip_block_list[guidance_mapping[i]])
skip_block_list = new_skip_block_list
- # Prepare skip layer masks
- skip_layer_masks: Optional[List[torch.Tensor]] = None
- if do_spatio_temporal_guidance:
- if skip_block_list is not None:
- skip_layer_masks = [
- self.transformer.create_skip_layer_mask(
- batch_size, num_conds, num_conds - 1, skip_blocks
- )
- for skip_blocks in skip_block_list
- ]
-
if enhance_prompt:
self.prompt_enhancer_image_caption_model = (
self.prompt_enhancer_image_caption_model.to(self._execution_device)
@@ -1055,7 +1025,7 @@ class LTXVideoPipeline(DiffusionPipeline):
negative_prompt_attention_mask,
) = self.encode_prompt(
prompt,
- do_classifier_free_guidance,
+ True,
negative_prompt=negative_prompt,
num_images_per_prompt=num_images_per_prompt,
device=device,
@@ -1073,23 +1043,28 @@ class LTXVideoPipeline(DiffusionPipeline):
prompt_embeds_batch = prompt_embeds
prompt_attention_mask_batch = prompt_attention_mask
- if do_classifier_free_guidance:
- prompt_embeds_batch = torch.cat(
- [negative_prompt_embeds, prompt_embeds], dim=0
- )
- prompt_attention_mask_batch = torch.cat(
- [negative_prompt_attention_mask, prompt_attention_mask], dim=0
- )
- if do_spatio_temporal_guidance:
- prompt_embeds_batch = torch.cat([prompt_embeds_batch, prompt_embeds], dim=0)
- prompt_attention_mask_batch = torch.cat(
- [
- prompt_attention_mask_batch,
- prompt_attention_mask,
- ],
- dim=0,
- )
+ negative_prompt_embeds = (
+ torch.zeros_like(prompt_embeds)
+ if negative_prompt_embeds is None
+ else negative_prompt_embeds
+ )
+ negative_prompt_attention_mask = (
+ torch.zeros_like(prompt_attention_mask)
+ if negative_prompt_attention_mask is None
+ else negative_prompt_attention_mask
+ )
+ prompt_embeds_batch = torch.cat(
+ [negative_prompt_embeds, prompt_embeds, prompt_embeds], dim=0
+ )
+ prompt_attention_mask_batch = torch.cat(
+ [
+ negative_prompt_attention_mask,
+ prompt_attention_mask,
+ prompt_attention_mask,
+ ],
+ dim=0,
+ )
# 4. Prepare the initial latents using the provided media and conditioning items
# Prepare the initial latents tensor, shape = (b, c, f, h, w)
@@ -1098,7 +1073,7 @@ class LTXVideoPipeline(DiffusionPipeline):
media_items=media_items,
timestep=timesteps[0],
latent_shape=latent_shape,
- dtype=prompt_embeds_batch.dtype,
+ dtype=prompt_embeds.dtype,
device=device,
generator=generator,
vae_per_channel_normalize=vae_per_channel_normalize,
@@ -1118,14 +1093,6 @@ class LTXVideoPipeline(DiffusionPipeline):
)
init_latents = latents.clone() # Used for image_cond_noise_update
- pixel_coords = torch.cat([pixel_coords] * num_conds)
- orig_conditioning_mask = conditioning_mask
- if conditioning_mask is not None and is_video:
- assert num_images_per_prompt == 1
- conditioning_mask = torch.cat([conditioning_mask] * num_conds)
- fractional_coords = pixel_coords.to(torch.float32)
- fractional_coords[:, 0] = fractional_coords[:, 0] * (1.0 / frame_rate)
-
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
@@ -1134,8 +1101,50 @@ class LTXVideoPipeline(DiffusionPipeline):
len(timesteps) - num_inference_steps * self.scheduler.order, 0
)
+ orig_conditioning_mask = conditioning_mask
+
+ # Befor compiling this code please be aware:
+ # This code might generate different input shapes if some timesteps have no STG or CFG.
+ # This means that the codes might need to be compiled mutliple times.
+ # To avoid that, use the same STG and CFG values for all timesteps.
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
for i, t in enumerate(timesteps):
+ do_classifier_free_guidance = guidance_scale[i] > 1.0
+ do_spatio_temporal_guidance = stg_scale[i] > 0
+ do_rescaling = rescaling_scale[i] != 1.0
+
+ num_conds = 1
+ if do_classifier_free_guidance:
+ num_conds += 1
+ if do_spatio_temporal_guidance:
+ num_conds += 1
+
+ if do_classifier_free_guidance and do_spatio_temporal_guidance:
+ indices = slice(batch_size * 0, batch_size * 3)
+ elif do_classifier_free_guidance:
+ indices = slice(batch_size * 0, batch_size * 2)
+ elif do_spatio_temporal_guidance:
+ indices = slice(batch_size * 1, batch_size * 3)
+ else:
+ indices = slice(batch_size * 1, batch_size * 2)
+
+ # Prepare skip layer masks
+ skip_layer_mask: Optional[torch.Tensor] = None
+ if do_spatio_temporal_guidance:
+ if skip_block_list is not None:
+ skip_layer_mask = self.transformer.create_skip_layer_mask(
+ batch_size, num_conds, num_conds - 1, skip_block_list[i]
+ )
+
+ batch_pixel_coords = torch.cat([pixel_coords] * num_conds)
+ conditioning_mask = orig_conditioning_mask
+ if conditioning_mask is not None and is_video:
+ assert num_images_per_prompt == 1
+ conditioning_mask = torch.cat([conditioning_mask] * num_conds)
+ fractional_coords = batch_pixel_coords.to(torch.float32)
+ fractional_coords[:, 0] = fractional_coords[:, 0] * (1.0 / frame_rate)
+
if conditioning_mask is not None and image_cond_noise_scale > 0.0:
latents = self.add_noise_to_image_conditioning_latents(
t,
@@ -1194,16 +1203,12 @@ class LTXVideoPipeline(DiffusionPipeline):
noise_pred = self.transformer(
latent_model_input.to(self.transformer.dtype),
indices_grid=fractional_coords,
- encoder_hidden_states=prompt_embeds_batch.to(
+ encoder_hidden_states=prompt_embeds_batch[indices].to(
self.transformer.dtype
),
- encoder_attention_mask=prompt_attention_mask_batch,
+ encoder_attention_mask=prompt_attention_mask_batch[indices],
timestep=current_timestep,
- skip_layer_mask=(
- skip_layer_masks[i]
- if skip_layer_masks is not None
- else None
- ),
+ skip_layer_mask=skip_layer_mask,
skip_layer_strategy=skip_layer_strategy,
return_dict=False,
)[0]
diff --git a/ltx_video/schedulers/rf.py b/ltx_video/schedulers/rf.py
index 0e36e61..c7d2ab3 100644
--- a/ltx_video/schedulers/rf.py
+++ b/ltx_video/schedulers/rf.py
@@ -314,7 +314,7 @@ class RectifiedFlowScheduler(SchedulerMixin, ConfigMixin, TimestepShifter):
"""
Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
process from the learned model outputs (most often the predicted noise).
- z_{t_1} = z_t - \Delta_t * v
+ z_{t_1} = z_t - Delta_t * v
The method finds the next timestep that is lower than the input timestep(s) and denoises the latents
to that level. The input timestep(s) are not required to be one of the predefined timesteps.
diff --git a/pyproject.toml b/pyproject.toml
index bcf8544..cb7ef9c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -7,7 +7,7 @@ name = "ltx-video"
version = "0.1.2"
description = "A package for LTX-Video model"
authors = [
- { name = "Sapir Weissbuch", email = "[email protected]" }
+ { name = "LTX-Video Team", email = "[email protected]" }
]
requires-python = ">=3.10"
readme = "README.md"
@@ -18,7 +18,7 @@ classifiers = [
dependencies = [
"torch>=2.1.0",
"diffusers>=0.28.2",
- "transformers>=4.47.2",
+ "transformers>=4.47.2,<4.52.0",
"sentencepiece>=0.1.96",
"huggingface-hub~=0.30",
"einops",
@@ -26,17 +26,17 @@ dependencies = [
]
[project.optional-dependencies]
-# Instead of thinking of them as optional, think of them as specific modes
-inference-script = [
- "accelerate",
- "matplotlib",
+inference = [
"imageio[ffmpeg]",
"av",
- "opencv-python"
+ "torchvision"
]
test = [
"pytest",
]
[tool.setuptools.packages.find]
-include = ["ltx_video*"]
\ No newline at end of file
+include = ["ltx_video*"]
+
+[tool.setuptools.package-data]
+ltx_video = ["configs/*.yaml"]
diff --git a/tests/conftest.py b/tests/conftest.py
index 48a95ce..28b1b94 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,92 +1,97 @@
+import json
import pytest
-import shutil
-import os
+import safetensors.torch
+import torch
+from ltx_video.models.autoencoders.causal_video_autoencoder import (
+ CausalVideoAutoencoder,
+ create_video_autoencoder_demo_config,
+ PER_CHANNEL_STATISTICS_PREFIX,
+)
+from ltx_video.models.transformers.transformer3d import Transformer3DModel
[email protected](scope="session")
-def test_paths(request, pytestconfig):
- try:
- output_path = "output"
- ckpt_path = request.param # This will get the current parameterized item
- text_encoder_model_name_or_path = pytestconfig.getoption(
- "text_encoder_model_name_or_path"
- )
- input_image_path = pytestconfig.getoption("input_image_path")
- input_video_path = pytestconfig.getoption("input_video_path")
- prompt_enhancer_image_caption_model_name_or_path = pytestconfig.getoption(
- "prompt_enhancer_image_caption_model_name_or_path"
- )
- prompt_enhancer_llm_model_name_or_path = pytestconfig.getoption(
- "prompt_enhancer_llm_model_name_or_path"
- )
- prompt_enhancement_words_threshold = pytestconfig.getoption(
- "prompt_enhancement_words_threshold"
- )
- config = {
- "ckpt_path": ckpt_path,
- "input_image_path": input_image_path,
- "input_video_path": input_video_path,
- "output_path": output_path,
- "text_encoder_model_name_or_path": text_encoder_model_name_or_path,
- "prompt_enhancer_image_caption_model_name_or_path": prompt_enhancer_image_caption_model_name_or_path,
- "prompt_enhancer_llm_model_name_or_path": prompt_enhancer_llm_model_name_or_path,
- "prompt_enhancement_words_threshold": prompt_enhancement_words_threshold,
- }
+def pytest_make_parametrize_id(config, val, argname):
+ if isinstance(val, str):
+ return f"{argname}-{val}"
+ return f"{argname}-{repr(val)}"
- yield config
- finally:
- if os.path.exists(output_path):
- shutil.rmtree(output_path)
+def num_latent_channels():
+ return 16
-def pytest_generate_tests(metafunc):
- if "test_paths" in metafunc.fixturenames:
- ckpt_paths = metafunc.config.getoption("ckpt_path")
- metafunc.parametrize("test_paths", ckpt_paths, indirect=True)
+def video_autoencoder(num_latent_channels):
+ config = create_video_autoencoder_demo_config(latent_channels=num_latent_channels)
+ model = CausalVideoAutoencoder.from_config(config)
+ model.eval().to(torch.bfloat16)
+ return model
-def pytest_addoption(parser):
- parser.addoption(
- "--ckpt_path",
- action="append",
- default=[],
- help="Path to checkpoint files (can specify multiple)",
- )
- parser.addoption(
- "--text_encoder_model_name_or_path",
- action="store",
- default="PixArt-alpha/PixArt-XL-2-1024-MS",
- help="Path to the checkpoint file",
- )
- parser.addoption(
- "--input_image_path",
- action="store",
- default="tests/utils/woman.jpeg",
- help="Path to input image file.",
- )
- parser.addoption(
- "--input_video_path",
- action="store",
- default="tests/utils/woman.mp4",
- help="Path to input video file.",
- )
- parser.addoption(
- "--prompt_enhancer_image_caption_model_name_or_path",
- action="store",
- default="MiaoshouAI/Florence-2-large-PromptGen-v2.0",
- help="Path to prompt_enhancer_image_caption_model.",
+def transformer_config(num_latent_channels):
+ transformer_config = {
+ "activation_fn": "gelu-approximate",
+ "attention_bias": True,
+ "attention_head_dim": 12,
+ "attention_type": "default",
+ "caption_channels": 4096,
+ "cross_attention_dim": 192,
+ "double_self_attention": False,
+ "dropout": 0.0,
+ "in_channels": num_latent_channels,
+ "norm_elementwise_affine": False,
+ "norm_eps": 1e-06,
+ "norm_num_groups": 32,
+ "num_attention_heads": 16,
+ "num_embeds_ada_norm": 1000,
+ "num_layers": 2,
+ "num_vector_embeds": None,
+ "only_cross_attention": False,
+ "out_channels": num_latent_channels,
+ "upcast_attention": False,
+ "use_linear_projection": False,
+ "qk_norm": "rms_norm",
+ "standardization_norm": "rms_norm",
+ "positional_embedding_type": "rope",
+ "positional_embedding_theta": 10000.0,
+ "positional_embedding_max_pos": [120, 1, 1],
+ "timestep_scale_multiplier": 1000,
+ }
+ return transformer_config
+
+
+def synthetic_ckpt_path(
+ tmp_path, video_autoencoder, num_latent_channels, transformer_config
+):
+ # Create transformer
+ transformer = Transformer3DModel.from_config(transformer_config)
+ transformer.to(torch.bfloat16)
+
+ # Prepare configs and state dicts
+ configs = {"transformer": transformer_config, "vae": vars(video_autoencoder.config)}
+ transformer_sd = transformer.state_dict()
+ transformer_sd = {
+ "model.diffusion_model." + key: value for key, value in transformer_sd.items()
+ }
+
+ # Prepare VAE state dict with per-channel statistics
+ vae_sd = video_autoencoder.state_dict()
+ vae_sd[f"{PER_CHANNEL_STATISTICS_PREFIX}std-of-means"] = torch.rand(
+ num_latent_channels,
)
- parser.addoption(
- "--prompt_enhancer_llm_model_name_or_path",
- action="store",
- default="unsloth/Llama-3.2-3B-Instruct",
- help="Path to LLM model for prompt enhancement.",
+ vae_sd[f"{PER_CHANNEL_STATISTICS_PREFIX}mean-of-means"] = torch.rand(
+ num_latent_channels,
)
- parser.addoption(
- "--prompt_enhancement_words_threshold",
- type=int,
- default=50,
- help="Enable prompt enhancement only if input prompt has fewer words than this threshold. Set to 0 to disable enhancement completely.",
+ vae_sd = {"vae." + key: value for key, value in vae_sd.items()}
+
+ out_file_path = f"{tmp_path}/test_ckpt.safetensors"
+ safetensors.torch.save_file(
+ {**transformer_sd, **vae_sd},
+ out_file_path,
+ metadata={"config": json.dumps(configs)},
)
+ return out_file_path
diff --git a/tests/test_configs.py b/tests/test_configs.py
new file mode 100644
index 0000000..ae327b1
--- /dev/null
+++ b/tests/test_configs.py
@@ -0,0 +1,30 @@
+import pytest
+from pathlib import Path
+
+from ltx_video.inference import infer, InferenceConfig
+
+CONFIGS_DIR = Path(__file__).parents[1] / "configs"
+
+
+def prompt():
+ return "A video of a cat playing with a ball."
+
+
+# mark as slow to avoid running these tests by default
+ "pipeline_config",
+ [pytest.param(config, id=config.stem) for config in CONFIGS_DIR.glob("*.yaml")],
+)
+def test_run_config(tmp_path, prompt, pipeline_config):
+ if "fp8" in pipeline_config.stem:
+ pytest.skip("Skipping fp8 configs as they require specific hardware support.")
+
+ inference_config = InferenceConfig(prompt=prompt)
+ inference_config.pipeline_config = CONFIGS_DIR / pipeline_config
+ inference_config.output_path = tmp_path / f"{pipeline_config.stem}"
+ inference_config.height = 256
+ inference_config.width = 320
+ inference_config.num_frames = 33
+ infer(config=inference_config)
diff --git a/tests/test_inference.py b/tests/test_inference.py
index 0a7cf91..9d07359 100644
--- a/tests/test_inference.py
+++ b/tests/test_inference.py
@@ -1,14 +1,61 @@
+from dataclasses import asdict
import pytest
import torch
import yaml
-from inference import infer, create_ltx_video_pipeline
+
+from ltx_video.inference import (
+ create_ltx_video_pipeline,
+ get_device,
+ infer,
+ InferenceConfig,
+)
from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
-def pytest_make_parametrize_id(config, val, argname):
- if isinstance(val, str):
- return f"{argname}-{val}"
- return f"{argname}-{repr(val)}"
+def input_image_path():
+ return "tests/utils/woman.jpeg"
+
+
+def input_video_path():
+ return "tests/utils/woman.mp4"
+
+
+def base_inference_config(tmp_path, pipeline_config):
+ temp_config_path = tmp_path / "config.yaml"
+ with open(temp_config_path, "w") as f:
+ yaml.dump(pipeline_config, f)
+
+ return InferenceConfig(
+ seed=42,
+ height=256,
+ width=320,
+ num_frames=49,
+ frame_rate=25,
+ prompt="A young woman with wavy, shoulder-length light brown hair stands outdoors on a foggy day. She wears a cozy pink turtleneck sweater, with a serene expression and piercing blue eyes. A wooden fence and a misty, grassy field fade into the background, evoking a calm and introspective mood.",
+ negative_prompt="worst quality, inconsistent motion, blurry, jittery, distorted",
+ output_path=tmp_path,
+ pipeline_config=temp_config_path,
+ )
+
+
+def base_pipeline_config(synthetic_ckpt_path):
+ return {
+ "num_inference_steps": 1,
+ "stg_mode": "attention_values",
+ "skip_block_list": [1],
+ "precision": "bfloat16",
+ "decode_timestep": 0.05,
+ "decode_noise_scale": 0.025,
+ "checkpoint_path": synthetic_ckpt_path,
+ "text_encoder_model_name_or_path": "PixArt-alpha/PixArt-XL-2-1024-MS",
+ "prompt_enhancer_image_caption_model_name_or_path": "MiaoshouAI/Florence-2-large-PromptGen-v2.0",
+ "prompt_enhancer_llm_model_name_or_path": "unsloth/Llama-3.2-3B-Instruct",
+ "prompt_enhancement_words_threshold": 120,
+ "sampler": "LinearQuadratic",
+ }
@pytest.mark.parametrize(
@@ -16,310 +63,162 @@ def pytest_make_parametrize_id(config, val, argname):
["unconditional", "first-frame", "first-sequence", "sequence-and-frame"],
ids=lambda x: f"conditioning_test_mode={x}",
)
-def test_infer_runs_on_real_path(tmp_path, test_paths, conditioning_test_mode):
- conditioning_params = {}
+def test_condition_modes(
+ tmp_path,
+ conditioning_test_mode,
+ input_image_path,
+ input_video_path,
+ base_pipeline_config,
+):
+ inference_config = base_inference_config(tmp_path, base_pipeline_config)
+
if conditioning_test_mode == "unconditional":
pass
elif conditioning_test_mode == "first-frame":
- conditioning_params["conditioning_media_paths"] = [
- test_paths["input_image_path"]
- ]
- conditioning_params["conditioning_start_frames"] = [0]
+ inference_config.conditioning_media_paths = [input_image_path]
+ inference_config.conditioning_start_frames = [0]
elif conditioning_test_mode == "first-sequence":
- conditioning_params["conditioning_media_paths"] = [
- test_paths["input_video_path"]
- ]
- conditioning_params["conditioning_start_frames"] = [0]
+ inference_config.conditioning_media_paths = [input_video_path]
+ inference_config.conditioning_start_frames = [0]
elif conditioning_test_mode == "sequence-and-frame":
- conditioning_params["conditioning_media_paths"] = [
- test_paths["input_video_path"],
- test_paths["input_image_path"],
- ]
- conditioning_params["conditioning_start_frames"] = [16, 67]
+ inference_config.conditioning_media_paths = [input_video_path, input_image_path]
+ inference_config.conditioning_start_frames = [16, 43]
else:
raise ValueError(f"Unknown conditioning mode: {conditioning_test_mode}")
- test_paths = {
- k: v
- for k, v in test_paths.items()
- if k not in ["input_image_path", "input_video_path"]
- }
- params = {
- "seed": 42,
- "num_inference_steps": 1,
- "height": 512,
- "width": 768,
- "num_frames": 121,
- "frame_rate": 25,
- "prompt": "A young woman with wavy, shoulder-length light brown hair stands outdoors on a foggy day. She wears a cozy pink turtleneck sweater, with a serene expression and piercing blue eyes. A wooden fence and a misty, grassy field fade into the background, evoking a calm and introspective mood.",
- "negative_prompt": "worst quality, inconsistent motion, blurry, jittery, distorted",
- "offload_to_cpu": False,
- "output_path": tmp_path,
- "image_cond_noise_scale": 0.15,
- }
+ # Test that the infer function runs without errors
+ infer(inference_config)
- config = {
- "pipeline_type": "base",
- "num_images_per_prompt": 1,
- "guidance_scale": 2.5,
- "stg_scale": 1,
- "stg_rescale": 0.7,
- "stg_mode": "attention_values",
- "stg_skip_layers": "1,2,3",
- "precision": "bfloat16",
- "decode_timestep": 0.05,
- "decode_noise_scale": 0.025,
- "checkpoint_path": test_paths["ckpt_path"],
- "text_encoder_model_name_or_path": test_paths[
- "text_encoder_model_name_or_path"
- ],
- "prompt_enhancer_image_caption_model_name_or_path": test_paths[
- "prompt_enhancer_image_caption_model_name_or_path"
- ],
- "prompt_enhancer_llm_model_name_or_path": test_paths[
- "prompt_enhancer_llm_model_name_or_path"
- ],
- "prompt_enhancement_words_threshold": 120,
- "stochastic_sampling": False,
- "sampler": "from_checkpoint",
- }
- temp_config_path = tmp_path / "config.yaml"
- with open(temp_config_path, "w") as f:
- yaml.dump(config, f)
-
- infer(**{**conditioning_params, **params, "pipeline_config": temp_config_path})
-
-
-def test_vid2vid(tmp_path, test_paths):
- params = {
- "seed": 42,
- "image_cond_noise_scale": 0.15,
- "height": 512,
- "width": 768,
- "num_frames": 25,
- "frame_rate": 25,
- "prompt": "A young woman with wavy, shoulder-length light brown hair stands outdoors on a foggy day. She wears a cozy pink turtleneck sweater, with a serene expression and piercing blue eyes. A wooden fence and a misty, grassy field fade into the background, evoking a calm and introspective mood.",
- "negative_prompt": "worst quality, inconsistent motion, blurry, jittery, distorted",
- "offload_to_cpu": False,
- "input_media_path": test_paths["input_video_path"],
- }
+def test_vid2vid(tmp_path, input_video_path, base_pipeline_config):
+ pipeline_config = base_pipeline_config
+ pipeline_config["num_inference_steps"] = 3
+ pipeline_config["skip_initial_inference_steps"] = 1
- config = {
- "num_inference_steps": 3,
- "skip_initial_inference_steps": 1,
- "guidance_scale": 2.5,
- "stg_scale": 1,
- "stg_rescale": 0.7,
- "stg_mode": "attention_values",
- "stg_skip_layers": "1,2,3",
- "precision": "bfloat16",
- "decode_timestep": 0.05,
- "decode_noise_scale": 0.025,
- "sampler": "from_checkpoint",
- "checkpoint_path": test_paths["ckpt_path"],
- "text_encoder_model_name_or_path": test_paths[
- "text_encoder_model_name_or_path"
- ],
- "prompt_enhancer_image_caption_model_name_or_path": test_paths[
- "prompt_enhancer_image_caption_model_name_or_path"
- ],
- "prompt_enhancer_llm_model_name_or_path": test_paths[
- "prompt_enhancer_llm_model_name_or_path"
- ],
- "prompt_enhancement_words_threshold": 120,
- }
- test_paths = {
- k: v
- for k, v in test_paths.items()
- if k not in ["input_image_path", "input_video_path"]
- }
- temp_config_path = tmp_path / "config.yaml"
- with open(temp_config_path, "w") as f:
- yaml.dump(config, f)
-
- infer(**{**test_paths, **params, "pipeline_config": temp_config_path})
+ inference_config = base_inference_config(tmp_path, pipeline_config)
+ inference_config.num_frames = 25
+ inference_config.input_media_path = input_video_path
+ # Test that the infer function runs without errors
+ infer(inference_config)
-def get_device():
- if torch.cuda.is_available():
- return "cuda"
- elif torch.backends.mps.is_available():
- return "mps"
- return "cpu"
+def test_pipeline_on_batch(tmp_path, base_pipeline_config):
+ pipeline_config = base_pipeline_config
+ inference_config = base_inference_config(tmp_path, pipeline_config)
+ inference_config.num_frames = 1 # For faster test, we use a single frame
-def test_pipeline_on_batch(tmp_path, test_paths):
device = get_device()
pipeline = create_ltx_video_pipeline(
- ckpt_path=test_paths["ckpt_path"],
+ ckpt_path=pipeline_config["checkpoint_path"],
device=device,
- precision="bfloat16",
- text_encoder_model_name_or_path=test_paths["text_encoder_model_name_or_path"],
+ precision=pipeline_config["precision"],
+ text_encoder_model_name_or_path=pipeline_config[
+ "text_encoder_model_name_or_path"
+ ],
enhance_prompt=False,
- prompt_enhancer_image_caption_model_name_or_path=test_paths[
+ prompt_enhancer_image_caption_model_name_or_path=pipeline_config[
"prompt_enhancer_image_caption_model_name_or_path"
],
- prompt_enhancer_llm_model_name_or_path=test_paths[
+ prompt_enhancer_llm_model_name_or_path=pipeline_config[
"prompt_enhancer_llm_model_name_or_path"
],
+ sampler="LinearQuadratic",
)
- params = {
- "seed": 42,
- "image_cond_noise_scale": 0.15,
- "height": 512,
- "width": 768,
- "num_frames": 1,
- "frame_rate": 25,
- "offload_to_cpu": False,
- "output_type": "pt",
- "is_video": False,
- "vae_per_channel_normalize": True,
- "mixed_precision": False,
- }
-
- config = {
- "num_inference_steps": 2,
- "guidance_scale": 2.5,
- "stg_scale": 1,
- "rescaling_scale": 0.7,
- "skip_block_list": [1, 2],
- "decode_timestep": 0.05,
- "decode_noise_scale": 0.025,
- }
-
- temp_config_path = tmp_path / "config.yaml"
- with open(temp_config_path, "w") as f:
- yaml.dump(config, f)
-
first_prompt = "A vintage yellow car drives along a wet mountain road, its rear wheels kicking up a light spray as it moves. The camera follows close behind, capturing the curvature of the road as it winds through rocky cliffs and lush green hills. The sunlight pierces through scattered clouds, reflecting off the car's rain-speckled surface, creating a dynamic, cinematic moment. The scene conveys a sense of freedom and exploration as the car disappears into the distance."
second_prompt = "A woman with blonde hair styled up, wearing a black dress with sequins and pearl earrings, looks down with a sad expression on her face. The camera remains stationary, focused on the woman's face. The lighting is dim, casting soft shadows on her face. The scene appears to be from a movie or TV show."
- sample = {
- "negative_prompt": "worst quality, inconsistent motion, blurry, jittery, distorted",
- "prompt_attention_mask": None,
- "negative_prompt_attention_mask": None,
- "media_items": None,
- }
-
def get_images(prompts):
generators = [
- torch.Generator(device=device).manual_seed(params["seed"]) for _ in range(2)
+ torch.Generator(device=device).manual_seed(inference_config.seed)
+ for _ in range(2)
]
- torch.manual_seed(params["seed"])
+ torch.manual_seed(inference_config.seed)
- images = pipeline(
- prompt=prompts,
+ params = asdict(inference_config)
+ params["prompt"] = prompts
+
+ pipeline_result = pipeline(
generator=generators,
- **sample,
+ output_type="pt",
+ vae_per_channel_normalize=True,
**params,
- pipeline_config=temp_config_path,
- ).images
- return images
+ )
+ return pipeline_result.images
+ # Run the pipeline on two different batches of prompts
batch_diff_images = get_images([first_prompt, second_prompt])
batch_same_images = get_images([second_prompt, second_prompt])
- # Take the second image from both runs
+ # Take the second image from both runs, which should be equal
image2_not_same = batch_diff_images[1, :, 0, :, :]
image2_same = batch_same_images[1, :, 0, :, :]
- # Compute mean absolute difference, should be 0
- mad = torch.mean(torch.abs(image2_not_same - image2_same)).item()
- print(f"Mean absolute difference: {mad}")
-
assert torch.allclose(image2_not_same, image2_same)
-def test_prompt_enhancement(tmp_path, test_paths, monkeypatch):
- # Create pipeline with prompt enhancement enabled
+def test_prompt_enhancement(tmp_path, base_pipeline_config):
+ pipeline_config = base_pipeline_config
+ inference_config = base_inference_config(tmp_path, pipeline_config)
+ inference_config.num_frames = 1 # For faster test, we use a single frame
+
device = get_device()
pipeline = create_ltx_video_pipeline(
- ckpt_path=test_paths["ckpt_path"],
+ ckpt_path=pipeline_config["checkpoint_path"],
device=device,
- precision="bfloat16",
- text_encoder_model_name_or_path=test_paths["text_encoder_model_name_or_path"],
+ precision=pipeline_config["precision"],
+ text_encoder_model_name_or_path=pipeline_config[
+ "text_encoder_model_name_or_path"
+ ],
enhance_prompt=True,
- prompt_enhancer_image_caption_model_name_or_path=test_paths[
+ prompt_enhancer_image_caption_model_name_or_path=pipeline_config[
"prompt_enhancer_image_caption_model_name_or_path"
],
- prompt_enhancer_llm_model_name_or_path=test_paths[
+ prompt_enhancer_llm_model_name_or_path=pipeline_config[
"prompt_enhancer_llm_model_name_or_path"
],
+ sampler="LinearQuadratic",
)
-
- original_prompt = "A cat sitting on a windowsill"
-
# Mock the pipeline's _encode_prompt method to verify the prompt being used
original_encode_prompt = pipeline.encode_prompt
- prompts_used = []
-
def mock_encode_prompt(prompt, *args, **kwargs):
prompts_used.append(prompt[0] if isinstance(prompt, list) else prompt)
return original_encode_prompt(prompt, *args, **kwargs)
pipeline.encode_prompt = mock_encode_prompt
- # Set up minimal parameters for a quick test
- params = {
- "seed": 42,
- "image_cond_noise_scale": 0.15,
- "height": 512,
- "width": 768,
- "skip_layer_strategy": SkipLayerStrategy.AttentionValues,
- "num_frames": 1,
- "frame_rate": 25,
- "offload_to_cpu": False,
- "output_type": "pt",
- "is_video": False,
- "vae_per_channel_normalize": True,
- "mixed_precision": False,
- }
-
- config = {
- "pipeline_type": "base",
- "num_inference_steps": 1,
- "guidance_scale": 2.5,
- "stg_scale": 1,
- "rescaling_scale": 0.7,
- "skip_block_list": [1, 2],
- "decode_timestep": 0.05,
- "decode_noise_scale": 0.025,
- }
+ original_prompt = "A cat sitting on a windowsill"
+ inference_config.prompt = original_prompt
- temp_config_path = tmp_path / "config.yaml"
- with open(temp_config_path, "w") as f:
- yaml.dump(config, f)
+ def run_pipeline(enhance_prompt):
+ params = asdict(inference_config)
+ pipeline(
+ enhance_prompt=enhance_prompt,
+ **params,
+ skip_layer_strategy=SkipLayerStrategy.AttentionValues,
+ vae_per_channel_normalize=True,
+ output_type="pt",
+ )
+ assert (
+ len(prompts_used) > 0
+ ), f"No prompts were used in the pipeline run with enhance_prompt={enhance_prompt}"
+
+ if enhance_prompt:
+ # Verify that the enhanced prompt was used
+ assert (
+ prompts_used[0] != original_prompt
+ ), f"Expected enhanced prompt to be different from original prompt, but got: {original_prompt}"
+ else:
+ # Verify that the original prompt was used
+ assert (
+ prompts_used[0] == original_prompt
+ ), f"Expected original prompt to be used, but got: {prompts_used[0]}"
# Run pipeline with prompt enhancement enabled
- _ = pipeline(
- prompt=original_prompt,
- negative_prompt="worst quality",
- enhance_prompt=True,
- **params,
- pipeline_config=temp_config_path,
- )
-
- # Verify that the enhanced prompt was used
- assert len(prompts_used) > 0
- assert (
- prompts_used[0] != original_prompt
- ), f"Expected enhanced prompt to be different from original prompt, but got: {original_prompt}"
-
+ prompts_used = []
+ run_pipeline(enhance_prompt=True)
# Run pipeline with prompt enhancement disabled
- prompts_used.clear()
- _ = pipeline(
- prompt=original_prompt,
- negative_prompt="worst quality",
- enhance_prompt=False,
- **params,
- pipeline_config=temp_config_path,
- )
-
- # Verify that the original prompt was used
- assert len(prompts_used) > 0
- assert (
- prompts_used[0] == original_prompt
- ), f"Expected original prompt to be used, but got: {prompts_used[0]}"
+ prompts_used = []
+ run_pipeline(enhance_prompt=False)
diff --git a/tests/test_vae.py b/tests/test_vae.py
index 0e72dec..24b5b91 100644
--- a/tests/test_vae.py
+++ b/tests/test_vae.py
@@ -1,32 +1,85 @@
+import pytest
import torch
-
from ltx_video.models.autoencoders.causal_video_autoencoder import (
CausalVideoAutoencoder,
- create_video_autoencoder_demo_config,
)
-def test_vae():
- # create vae and run a forward and backward pass
- config = create_video_autoencoder_demo_config(latent_channels=16)
- video_autoencoder = CausalVideoAutoencoder.from_config(config)
- video_autoencoder.eval()
- input_videos = torch.randn(2, 3, 17, 64, 64)
+def test_encode_decode_shape(video_autoencoder, num_latent_channels):
+ spatial_factor = video_autoencoder.spatial_downscale_factor
+ temporal_factor = video_autoencoder.temporal_downscale_factor
+ input_videos = torch.randn(2, 3, 17, 64, 64, dtype=torch.bfloat16)
+
+ # Encode
latent = video_autoencoder.encode(input_videos).latent_dist.mode()
- assert latent.shape == (2, 16, 3, 2, 2)
+ expected_shape = (
+ input_videos.shape[0],
+ num_latent_channels,
+ (input_videos.shape[2] + 7) // temporal_factor,
+ input_videos.shape[3] // spatial_factor,
+ input_videos.shape[4] // spatial_factor,
+ )
+ assert latent.shape == expected_shape
+
+ # Decode
timestep = torch.ones(input_videos.shape[0]) * 0.1
reconstructed_videos = video_autoencoder.decode(
latent, target_shape=input_videos.shape, timestep=timestep
).sample
assert input_videos.shape == reconstructed_videos.shape
- loss = torch.nn.functional.mse_loss(input_videos, reconstructed_videos)
- loss.backward()
+
+def test_temporal_causality(video_autoencoder):
# validate temporal causality in encoder
+ input_videos = torch.randn(2, 3, 17, 64, 64, dtype=torch.bfloat16)
+ latent = video_autoencoder.encode(input_videos).latent_dist.mode()
+
+ # Check that encoding a single frame matches the corresponding slice in the full latent
input_image = input_videos[:, :, :1, :, :]
image_latent = video_autoencoder.encode(input_image).latent_dist.mode()
assert torch.allclose(image_latent, latent[:, :, :1, :, :], atol=1e-6)
+ # Check that encoding a sequence of frames matches the corresponding slice in the full latent
input_sequence = input_videos[:, :, :9, :, :]
sequence_latent = video_autoencoder.encode(input_sequence).latent_dist.mode()
assert torch.allclose(sequence_latent, latent[:, :, :2, :, :], atol=1e-6)
+
+
+ "layer_name,expected_temporal_factor,expected_spatial_factor",
+ [
+ ("compress_space_res", 1, 2),
+ ("compress_space", 1, 2),
+ ("compress_time_res", 2, 1),
+ ("compress_time", 2, 1),
+ ("compress_all_res", 2, 2),
+ ("compress_all", 2, 2),
+ ],
+)
+def test_downscale_factors(
+ num_latent_channels, layer_name, expected_temporal_factor, expected_spatial_factor
+):
+ patch_size = 4
+ encoder_blocks = [
+ (layer_name, {"multiplier": 2}),
+ ]
+ decoder_blocks = [
+ ("compress_all", {"residual": True, "multiplier": 2}),
+ ]
+ config = {
+ "_class_name": "CausalVideoAutoencoder",
+ "dims": 3,
+ "encoder_blocks": encoder_blocks,
+ "decoder_blocks": decoder_blocks,
+ "latent_channels": num_latent_channels,
+ "norm_layer": "pixel_norm",
+ "patch_size": patch_size,
+ "latent_log_var": "uniform",
+ "use_quant_conv": False,
+ "causal_decoder": False,
+ "timestep_conditioning": True,
+ "spatial_padding_mode": "replicate",
+ }
+ model = CausalVideoAutoencoder.from_config(config)
+ assert model.temporal_downscale_factor == expected_temporal_factor
+ assert model.spatial_downscale_factor == expected_spatial_factor * patch_size