Official repository for LTX-Video
Python diffusion-modelsditimage-to-videoimage-to-video-generationtext-to-videotext-to-video-generation
Inference: Support multiscale pipeline and new models
Yoav HaCohen69213dba5fb4
diff --git a/README.md b/README.mdindex 93567a3..af89988 100644--- a/README.md+++ b/README.md@@ -7,7 +7,8 @@ This is the official repository for LTX-Video.[Website](https://www.lightricks.com/ltxv) |[Model](https://huggingface.co/Lightricks/LTX-Video) |[Demo](https://app.ltx.studio/ltx-video) |-[Paper](https://arxiv.org/abs/2501.00103)+[Paper](https://arxiv.org/abs/2501.00103) |+[Discord](https://discord.gg/Mn8BRgUKKy)</div>@@ -46,13 +47,22 @@ The model supports text-to-image, image-to-video, keyframe-based animation, vide# News+## 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 CompfyUI workflow](https://github.com/Lightricks/ComfyUI-LTXVideo/))+- 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)+- Breakthrough prompt adherence and physical understanding.+- New Pipeline for multi-scale video rendering for fast and high quality results++## April, 15th, 2025: New checkpoints v0.9.6:- Release a new checkpoint [ltxv-2b-0.9.6-dev-04-25](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-2b-0.9.6-dev-04-25.safetensors) with improved quality- Release a new distilled model [ltxv-2b-0.9.6-distilled-04-25](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-2b-0.9.6-distilled-04-25.safetensors)* 15x faster inference than non-distilled model.* Does not require classifier-free guidance and spatio-temporal guidance.* Supports sampling with 8 (recommended), 4, 2 or 1 diffusion steps.- * New license for commercial use ([Open Weights](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltxv-2b-0.9.6-dev-04-25.license.txt))- Improved prompt adherence, motion quality and fine details.- New default resolution and FPS: 1216 × 704 pixels at 30 FPS* Still real time on H100 with the distilled model.@@ -60,7 +70,7 @@ The model supports text-to-image, image-to-video, keyframe-based animation, vide- Support stochastic inference (can improve visual quality when using the distilled model)## March, 5th, 2025: New checkpoint v0.9.5-- New license for commercial use ([OpenRail-M](https://huggingface.co/Lightricks/LTX-Video/blob/main/ltx-video-2b-v0.9.5.license.txt))+- New license for commercial use ([OpenRail-M](https://huggingface.co/Lightricks/LTX-Video/ltx-video-2b-v0.9.5.license.txt))- Release a new checkpoint v0.9.5 with improved quality- Support keyframes and video extension- Support higher resolutions@@ -93,6 +103,17 @@ The model supports text-to-image, image-to-video, keyframe-based animation, vide- Initial release of LTX-Video- Support text-to-video and image-to-video generation++# Models++| Model | Version | Notes | inference.py config | ComfyUI workflow (Recommended) |+|--------------------|---------|--------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|------------------|+| ltxv-13b | 0.9.7 | Highest quality, requires more VRAM | [ltxv-13b-0.9.7-dev.yaml](https://github.com/Lightricks/LTX-Video/blob/main/configs/ltxv-13b-0.9.7-dev.yaml) | [ltxv-13b-i2v-base.json](https://github.com/Lightricks/ComfyUI-LTXVideo/example_workflows/ltxv-13b-i2v-base.json) |+| ltxv-13b-fp8 | 0.9.7 | Quantized model | Coming soon | Coming soon |+| 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/example_workflows/low_level/ltxvideo-i2v.json) |+| ltxv-2b-distilled | 0.9.6 | 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/example_workflows/low_level/ltxvideo-i2v-distilled.json) |++# Quick Start Guide## Online inference@@ -118,34 +139,22 @@ source env/bin/activatepython -m pip install -e .\[inference-script\]```-Then, download the model from [Hugging Face](https://huggingface.co/Lightricks/LTX-Video)--```python-from huggingface_hub import hf_hub_download--model_dir = 'MODEL_DIR' # The local directory to save downloaded checkpoint--# Distilled model:-hf_hub_download(repo_id="Lightricks/LTX-Video", filename="ltxv-2b-0.9.6-distilled-04-25.safetensors", local_dir=model_dir, local_dir_use_symlinks=False, repo_type='model')--# Full model:-hf_hub_download(repo_id="Lightricks/LTX-Video", filename="ltxv-2b-0.9.6-dev-04-25.safetensors", local_dir=model_dir, local_dir_use_symlinks=False, repo_type='model')-```-### 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 --ckpt_path 'PATH' --prompt "PROMPT" --height HEIGHT --width WIDTH --num_frames NUM_FRAMES --seed SEED+python inference.py --prompt "PROMPT" --height HEIGHT --width WIDTH --num_frames NUM_FRAMES --seed SEED --pipeline_config configs/ltxv-13b-0.9.7-dev.yaml```#### For image-to-video generation:```bash-python inference.py --ckpt_path 'PATH' --prompt "PROMPT" --conditioning_media_paths IMAGE_PATH --conditioning_start_frames 0 --height HEIGHT --width WIDTH --num_frames NUM_FRAMES --seed SEED+python inference.py --prompt "PROMPT" --conditioning_media_paths IMAGE_PATH --conditioning_start_frames 0 --height HEIGHT --width WIDTH --num_frames NUM_FRAMES --seed SEED --pipeline_config configs/ltxv-13b-0.9.7-dev.yaml```#### Extending a video:@@ -154,7 +163,7 @@ python inference.py --ckpt_path 'PATH' --prompt "PROMPT" --conditioning_media_pa```bash-python inference.py --ckpt_path 'PATH' --prompt "PROMPT" --conditioning_media_paths VIDEO_PATH --conditioning_start_frames START_FRAME --height HEIGHT --width WIDTH --num_frames NUM_FRAMES --seed SEED+python inference.py --prompt "PROMPT" --conditioning_media_paths VIDEO_PATH --conditioning_start_frames START_FRAME --height HEIGHT --width WIDTH --num_frames NUM_FRAMES --seed SEED --pipeline_config configs/ltxv-13b-0.9.7-dev.yaml```#### For video generation with multiple conditions:@@ -163,7 +172,7 @@ You can now generate a video conditioned on a set of images and/or short video sSimply provide a list of paths to the images or video segments you want to condition on, along with their target frame numbers in the generated video. You can also specify the conditioning strength for each item (default: 1.0).```bash-python inference.py --ckpt_path 'PATH' --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+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-dev.yaml```## ComfyUI Integrationdiff --git a/configs/ltxv-13b-0.9.7-dev.yaml b/configs/ltxv-13b-0.9.7-dev.yamlnew file mode 100644index 0000000..0a4724e--- /dev/null+++ b/configs/ltxv-13b-0.9.7-dev.yaml@@ -0,0 +1,33 @@++pipeline_type: multi-scale+checkpoint_path: "ltxv-13b-0.9.7-dev.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: "bfloat16"+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: [3]+ stg_scale: [1]+ rescaling_scale: [0.7]+ guidance_timesteps: [1.0]+ skip_block_list: [19] # [[1], [1,2], [1,2,3], [27], [28], [28]]+ num_inference_steps: 30++second_pass:+ guidance_scale: [3]+ stg_scale: [1]+ rescaling_scale: [0.7]+ guidance_timesteps: [1.0]+ skip_block_list: [19] # [[1], [1,2], [1,2,3], [27], [28], [28]]+ num_inference_steps: 10+ strength: 0.85diff --git a/configs/ltxv-2b-0.9.6-dev.yaml b/configs/ltxv-2b-0.9.6-dev.yamlnew file mode 100644index 0000000..487f997--- /dev/null+++ b/configs/ltxv-2b-0.9.6-dev.yaml@@ -0,0 +1,17 @@+pipeline_type: base+checkpoint_path: "ltxv-2b-0.9.6-dev-04-25.safetensors"+guidance_scale: 3+stg_scale: 1+rescaling_scale: 0.7+skip_block_list: [19]+num_inference_steps: 40+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: "bfloat16"+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\ No newline at end of filediff --git a/configs/ltxv-2b-0.9.6-distilled.yaml b/configs/ltxv-2b-0.9.6-distilled.yamlnew file mode 100644index 0000000..39fae26--- /dev/null+++ b/configs/ltxv-2b-0.9.6-distilled.yaml@@ -0,0 +1,17 @@+pipeline_type: base+checkpoint_path: "ltxv-2b-0.9.6-distilled-04-25.safetensors"+guidance_scale: 3+stg_scale: 1+rescaling_scale: 0.7+skip_block_list: [19]+num_inference_steps: 8+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: "bfloat16"+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: true\ No newline at end of filediff --git a/inference.py b/inference.pyindex 34e94ba..322809e 100644--- a/inference.py+++ b/inference.py@@ -5,6 +5,7 @@ from datetime import datetimefrom pathlib import Pathfrom diffusers.utils import loggingfrom typing import Optional, List, Union+import yamlimport imageioimport json@@ -19,15 +20,21 @@ from transformers import (AutoProcessor,AutoTokenizer,)+from huggingface_hub import hf_hub_downloadfrom ltx_video.models.autoencoders.causal_video_autoencoder import (CausalVideoAutoencoder,)from ltx_video.models.transformers.symmetric_patchifier import SymmetricPatchifierfrom ltx_video.models.transformers.transformer3d import Transformer3DModel-from ltx_video.pipelines.pipeline_ltx_video import ConditioningItem, LTXVideoPipeline+from ltx_video.pipelines.pipeline_ltx_video import (+ ConditioningItem,+ LTXVideoPipeline,+ LTXMultiScalePipeline,+)from ltx_video.schedulers.rf import RectifiedFlowSchedulerfrom ltx_video.utils.skip_layer_strategy import SkipLayerStrategy+from ltx_video.models.autoencoders.latent_upsampler import LatentUpsamplerMAX_HEIGHT = 720MAX_WIDTH = 1280@@ -55,6 +62,7 @@ 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.@@ -62,6 +70,7 @@ def load_image_to_tensor_with_resize_and_crop(image_input: Either a file path (str) or a PIL Image objecttarget_height: Desired height of output tensortarget_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")@@ -85,7 +94,8 @@ def load_image_to_tensor_with_resize_and_crop(y_start = (input_height - new_height) // 2image = image.crop((x_start, y_start, x_start + new_width, y_start + new_height))- image = image.resize((target_width, target_height))+ if not just_crop:+ image = image.resize((target_width, target_height))frame_tensor = torch.tensor(np.array(image)).permute(2, 0, 1).float()frame_tensor = (frame_tensor / 127.5) - 1.0# Create 5D tensor: (batch_size=1, channels=3, num_frames=1, height, width)@@ -175,12 +185,6 @@ def main():)# Directories- parser.add_argument(- "--ckpt_path",- type=str,- required=True,- help="Path to a safetensors file that contains all model parts.",- )parser.add_argument("--output_path",type=str,@@ -190,46 +194,12 @@ def main():parser.add_argument("--seed", type=int, default="171198")# Pipeline parameters- parser.add_argument(- "--num_inference_steps", type=int, default=40, help="Number of inference steps"- )parser.add_argument("--num_images_per_prompt",type=int,default=1,help="Number of images per prompt",)- parser.add_argument(- "--guidance_scale",- type=float,- default=3,- help="Guidance scale.",- )- parser.add_argument(- "--stg_scale",- type=float,- default=1,- help="Spatiotemporal guidance scale. 0 to disable STG.",- )- parser.add_argument(- "--stg_rescale",- type=float,- default=0.7,- help="Spatiotemporal guidance rescaling scale. 1 to disable rescale.",- )- parser.add_argument(- "--stg_mode",- type=str,- default="attention_values",- help="Spatiotemporal guidance mode. "- "It can be one of 'attention_values' (default), 'attension_skip', 'residual', or 'transformer_block'.",- )- parser.add_argument(- "--stg_skip_layers",- type=str,- default="19",- help="Layers to block for spatiotemporal guidance. Comma separated list of integers.",- )parser.add_argument("--image_cond_noise_scale",type=float,@@ -263,24 +233,10 @@ def main():help="Device to run inference on. If not specified, will automatically detect and use CUDA or MPS if available, else CPU.",)parser.add_argument(- "--precision",- choices=["bfloat16", "mixed_precision"],- default="bfloat16",- help="Sets the precision for the transformer and tokenizer. Default is bfloat16. If 'mixed_precision' is enabled, it moves to mixed-precision.",- )-- # VAE noise augmentation- parser.add_argument(- "--decode_timestep",- type=float,- default=0.05,- help="Timestep for decoding noise",- )- parser.add_argument(- "--decode_noise_scale",- type=float,- default=0.025,- help="Noise level for decoding noise",+ "--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@@ -302,11 +258,19 @@ def main():help="Offloading unnecessary computations to CPU.",)+ # video-to-video arguments:parser.add_argument(- "--text_encoder_model_name_or_path",+ "--input_media_path",type=str,- default="PixArt-alpha/PixArt-XL-2-1024-MS",- help="Local path or model identifier for both the tokenizer and text encoder. Defaults to pretrained model on Hugging Face.",+ default=None,+ help="Path to the input video (or imaage) to be modified using the video-to-video pipeline",+ )++ parser.add_argument(+ "--strength",+ type=float,+ default=1.0,+ help="Editing strength (noising level) for video-to-video pipeline.",)# Conditioning arguments@@ -328,38 +292,6 @@ def main():nargs="*",help="List of frame indices where each conditioning item should be applied. Must match the number of conditioning items.",)- parser.add_argument(- "--sampler",- type=str,- choices=["uniform", "linear-quadratic"],- default=None,- help="Sampler to use for noise scheduling. Can be either 'uniform' or 'linear-quadratic'. If not specified, uses the sampler from the checkpoint.",- )-- # Prompt enhancement- parser.add_argument(- "--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.",- )- parser.add_argument(- "--prompt_enhancer_image_caption_model_name_or_path",- type=str,- default="MiaoshouAI/Florence-2-large-PromptGen-v2.0",- help="Path to the image caption model",- )- parser.add_argument(- "--prompt_enhancer_llm_model_name_or_path",- type=str,- default="unsloth/Llama-3.2-3B-Instruct",- help="Path to the LLM model, default is Llama-3.2-3B-Instruct, but you can use other models like Llama-3.1-8B-Instruct, or other models supported by Hugging Face",- )- parser.add_argument(- "--stochastic_sampling",- action="store_true",- help="Runs inference with stochastic sampling.",- )args = parser.parse_args()logger.warning(f"Running generation with arguments: {args}")@@ -391,12 +323,12 @@ def create_ltx_video_pipeline(transformer = Transformer3DModel.from_pretrained(ckpt_path)# Use constructor if sampler is specified, otherwise use from_pretrained- if sampler:+ if sampler == "from_checkpoint" or not sampler:+ scheduler = RectifiedFlowScheduler.from_pretrained(ckpt_path)+ else:scheduler = RectifiedFlowScheduler(sampler=("Uniform" if sampler.lower() == "uniform" else "LinearQuadratic"))- else:- scheduler = RectifiedFlowScheduler.from_pretrained(ckpt_path)text_encoder = T5EncoderModel.from_pretrained(text_encoder_model_name_or_path, subfolder="text_encoder"@@ -455,40 +387,67 @@ def create_ltx_video_pipeline(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(- ckpt_path: str,output_path: Optional[str],seed: int,- num_inference_steps: int,- num_images_per_prompt: int,- guidance_scale: float,- stg_scale: float,- stg_rescale: float,- stg_mode: str,- stg_skip_layers: str,+ pipeline_config: str,image_cond_noise_scale: float,height: Optional[int],width: Optional[int],num_frames: int,frame_rate: int,- precision: str,- decode_timestep: float,- decode_noise_scale: float,prompt: str,negative_prompt: str,offload_to_cpu: bool,- text_encoder_model_name_or_path: str,+ input_media_path: Optional[str] = None,+ strength: Optional[float] = 1.0,conditioning_media_paths: Optional[List[str]] = None,conditioning_strengths: Optional[List[float]] = None,conditioning_start_frames: Optional[List[int]] = None,- sampler: Optional[str] = None,device: Optional[str] = None,- prompt_enhancement_words_threshold: int = 50,- prompt_enhancer_image_caption_model_name_or_path: str = "MiaoshouAI/Florence-2-large-PromptGen-v2.0",- prompt_enhancer_llm_model_name_or_path: str = "unsloth/Llama-3.2-3B-Instruct",- stochastic_sampling: bool = False,**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."@@ -548,6 +507,10 @@ def infer(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@@ -559,8 +522,18 @@ def infer(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=ckpt_path,+ ckpt_path=ltxv_model_path,precision=precision,text_encoder_model_name_or_path=text_encoder_model_name_or_path,sampler=sampler,@@ -570,6 +543,26 @@ def infer(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,@@ -585,8 +578,8 @@ def infer(else None)- # Set spatiotemporal guidance- skip_block_list = [int(x.strip()) for x in stg_skip_layers.split(",")]+ 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.AttentionValueselif stg_mode.lower() == "stg_as" or stg_mode.lower() == "attention_skip":@@ -610,14 +603,8 @@ def infer(generator = torch.Generator(device=device).manual_seed(seed)images = pipeline(- num_inference_steps=num_inference_steps,- num_images_per_prompt=num_images_per_prompt,- guidance_scale=guidance_scale,+ **pipeline_config,skip_layer_strategy=skip_layer_strategy,- skip_block_list=skip_block_list,- stg_scale=stg_scale,- do_rescaling=stg_rescale != 1,- rescaling_scale=stg_rescale,generator=generator,output_type="pt",callback_on_step_end=None,@@ -626,17 +613,16 @@ def infer(num_frames=num_frames_padded,frame_rate=frame_rate,**sample,+ media_items=media_item,+ strength=strength,conditioning_items=conditioning_items,is_video=True,vae_per_channel_normalize=True,image_cond_noise_scale=image_cond_noise_scale,- decode_timestep=decode_timestep,- decode_noise_scale=decode_noise_scale,mixed_precision=(precision == "mixed_precision"),offload_to_cpu=offload_to_cpu,device=device,enhance_prompt=enhance_prompt,- stochastic_sampling=stochastic_sampling,).images# Crop the padded images to the desired resolution and number of frames@@ -682,7 +668,7 @@ def infer(for frame in video_np:video.append_data(frame)- logger.warning(f"Output saved to {output_dir}")+ logger.warning(f"Output saved to {output_filename}")def prepare_conditioning(@@ -714,48 +700,76 @@ def prepare_conditioning(for path, strength, start_frame in zip(conditioning_media_paths, conditioning_strengths, conditioning_start_frames):- # Check if the path points to an image or video- is_video = any(- path.lower().endswith(ext) for ext in [".mp4", ".avi", ".mov", ".mkv"]- )-- if is_video:- reader = imageio.get_reader(path)- orig_num_input_frames = reader.count_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."- )-- # 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- )- frame_tensor = torch.nn.functional.pad(frame_tensor, padding)- frames.append(frame_tensor)- reader.close()-- # Stack frames along the temporal dimension- video_tensor = torch.cat(frames, dim=2)- conditioning_items.append(- ConditioningItem(video_tensor, start_frame, strength)+ 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.")- else: # Input image++ 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(- path, height, width+ frame, height, width, just_crop=just_crop)frame_tensor = torch.nn.functional.pad(frame_tensor, padding)- conditioning_items.append(- ConditioningItem(frame_tensor, start_frame, strength)- )-- return conditioning_items+ 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_tensorif __name__ == "__main__":diff --git a/ltx_video/models/autoencoders/causal_video_autoencoder.py b/ltx_video/models/autoencoders/causal_video_autoencoder.pyindex 60893cb..3a347bc 100644--- a/ltx_video/models/autoencoders/causal_video_autoencoder.py+++ b/ltx_video/models/autoencoders/causal_video_autoencoder.py@@ -17,6 +17,7 @@ from safetensors import safe_openfrom ltx_video.models.autoencoders.conv_nd_factory import make_conv_nd, make_linear_ndfrom ltx_video.models.autoencoders.pixel_norm import PixelNorm+from ltx_video.models.autoencoders.pixel_shuffle import PixelShuffleNDfrom ltx_video.models.autoencoders.vae import AutoencoderKLWrapperfrom ltx_video.models.transformers.attention import Attentionfrom ltx_video.utils.diffusers_config_mapping import (@@ -1041,31 +1042,20 @@ class DepthToSpaceUpsample(nn.Module):causal=True,spatial_padding_mode=spatial_padding_mode,)+ self.pixel_shuffle = PixelShuffleND(dims=dims, upscale_factors=stride)self.residual = residualself.out_channels_reduction_factor = out_channels_reduction_factordef forward(self, x, causal: bool = True):if self.residual:# Reshape and duplicate the input to match the output shape- x_in = rearrange(- x,- "b (c p1 p2 p3) d h w -> b c (d p1) (h p2) (w p3)",- p1=self.stride[0],- p2=self.stride[1],- p3=self.stride[2],- )+ x_in = self.pixel_shuffle(x)num_repeat = np.prod(self.stride) // self.out_channels_reduction_factorx_in = x_in.repeat(1, num_repeat, 1, 1, 1)if self.stride[0] == 2:x_in = x_in[:, :, 1:, :, :]x = self.conv(x, causal=causal)- x = rearrange(- x,- "b (c p1 p2 p3) d h w -> b c (d p1) (h p2) (w p3)",- p1=self.stride[0],- p2=self.stride[1],- p3=self.stride[2],- )+ x = self.pixel_shuffle(x)if self.stride[0] == 2:x = x[:, :, 1:, :, :]if self.residual:diff --git a/ltx_video/models/autoencoders/latent_upsampler.py b/ltx_video/models/autoencoders/latent_upsampler.pynew file mode 100644index 0000000..4a76bc2--- /dev/null+++ b/ltx_video/models/autoencoders/latent_upsampler.py@@ -0,0 +1,203 @@+from typing import Optional, Union+from pathlib import Path+import os+import json++import torch+import torch.nn as nn+from einops import rearrange+from diffusers import ConfigMixin, ModelMixin+from safetensors.torch import safe_open++from ltx_video.models.autoencoders.pixel_shuffle import PixelShuffleND+++class ResBlock(nn.Module):+ def __init__(+ self, channels: int, mid_channels: Optional[int] = None, dims: int = 3+ ):+ super().__init__()+ if mid_channels is None:+ mid_channels = channels++ Conv = nn.Conv2d if dims == 2 else nn.Conv3d++ self.conv1 = Conv(channels, mid_channels, kernel_size=3, padding=1)+ self.norm1 = nn.GroupNorm(32, mid_channels)+ self.conv2 = Conv(mid_channels, channels, kernel_size=3, padding=1)+ self.norm2 = nn.GroupNorm(32, channels)+ self.activation = nn.SiLU()++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ residual = x+ x = self.conv1(x)+ x = self.norm1(x)+ x = self.activation(x)+ x = self.conv2(x)+ x = self.norm2(x)+ x = self.activation(x + residual)+ return x+++class LatentUpsampler(ModelMixin, ConfigMixin):+ """+ Model to spatially upsample VAE latents.++ Args:+ in_channels (`int`): Number of channels in the input latent+ mid_channels (`int`): Number of channels in the middle layers+ num_blocks_per_stage (`int`): Number of ResBlocks to use in each stage (pre/post upsampling)+ dims (`int`): Number of dimensions for convolutions (2 or 3)+ spatial_upsample (`bool`): Whether to spatially upsample the latent+ temporal_upsample (`bool`): Whether to temporally upsample the latent+ """++ def __init__(+ self,+ in_channels: int = 128,+ mid_channels: int = 512,+ num_blocks_per_stage: int = 4,+ dims: int = 3,+ spatial_upsample: bool = True,+ temporal_upsample: bool = False,+ ):+ super().__init__()++ self.in_channels = in_channels+ self.mid_channels = mid_channels+ self.num_blocks_per_stage = num_blocks_per_stage+ self.dims = dims+ self.spatial_upsample = spatial_upsample+ self.temporal_upsample = temporal_upsample++ Conv = nn.Conv2d if dims == 2 else nn.Conv3d++ self.initial_conv = Conv(in_channels, mid_channels, kernel_size=3, padding=1)+ self.initial_norm = nn.GroupNorm(32, mid_channels)+ self.initial_activation = nn.SiLU()++ self.res_blocks = nn.ModuleList(+ [ResBlock(mid_channels, dims=dims) for _ in range(num_blocks_per_stage)]+ )++ if spatial_upsample and temporal_upsample:+ self.upsampler = nn.Sequential(+ nn.Conv3d(mid_channels, 8 * mid_channels, kernel_size=3, padding=1),+ PixelShuffleND(3),+ )+ elif spatial_upsample:+ self.upsampler = nn.Sequential(+ nn.Conv2d(mid_channels, 4 * mid_channels, kernel_size=3, padding=1),+ PixelShuffleND(2),+ )+ elif temporal_upsample:+ self.upsampler = nn.Sequential(+ nn.Conv3d(mid_channels, 2 * mid_channels, kernel_size=3, padding=1),+ PixelShuffleND(1),+ )+ else:+ raise ValueError(+ "Either spatial_upsample or temporal_upsample must be True"+ )++ self.post_upsample_res_blocks = nn.ModuleList(+ [ResBlock(mid_channels, dims=dims) for _ in range(num_blocks_per_stage)]+ )++ self.final_conv = Conv(mid_channels, in_channels, kernel_size=3, padding=1)++ def forward(self, latent: torch.Tensor) -> torch.Tensor:+ b, c, f, h, w = latent.shape++ if self.dims == 2:+ x = rearrange(latent, "b c f h w -> (b f) c h w")+ x = self.initial_conv(x)+ x = self.initial_norm(x)+ x = self.initial_activation(x)++ for block in self.res_blocks:+ x = block(x)++ x = self.upsampler(x)++ for block in self.post_upsample_res_blocks:+ x = block(x)++ x = self.final_conv(x)+ x = rearrange(x, "(b f) c h w -> b c f h w", b=b, f=f)+ else:+ x = self.initial_conv(latent)+ x = self.initial_norm(x)+ x = self.initial_activation(x)++ for block in self.res_blocks:+ x = block(x)++ if self.temporal_upsample:+ x = self.upsampler(x)+ x = x[:, :, 1:, :, :]+ else:+ x = rearrange(x, "b c f h w -> (b f) c h w")+ x = self.upsampler(x)+ x = rearrange(x, "(b f) c h w -> b c f h w", b=b, f=f)++ for block in self.post_upsample_res_blocks:+ x = block(x)++ x = self.final_conv(x)++ return x++ @classmethod+ def from_config(cls, config):+ return cls(+ in_channels=config.get("in_channels", 4),+ mid_channels=config.get("mid_channels", 128),+ num_blocks_per_stage=config.get("num_blocks_per_stage", 4),+ dims=config.get("dims", 2),+ spatial_upsample=config.get("spatial_upsample", True),+ temporal_upsample=config.get("temporal_upsample", False),+ )++ def config(self):+ return {+ "_class_name": "LatentUpsampler",+ "in_channels": self.in_channels,+ "mid_channels": self.mid_channels,+ "num_blocks_per_stage": self.num_blocks_per_stage,+ "dims": self.dims,+ "spatial_upsample": self.spatial_upsample,+ "temporal_upsample": self.temporal_upsample,+ }++ @classmethod+ def from_pretrained(+ cls,+ pretrained_model_path: Optional[Union[str, os.PathLike]],+ *args,+ **kwargs,+ ):+ pretrained_model_path = Path(pretrained_model_path)+ if pretrained_model_path.is_file() and str(pretrained_model_path).endswith(+ ".safetensors"+ ):+ state_dict = {}+ with safe_open(pretrained_model_path, framework="pt", device="cpu") as f:+ metadata = f.metadata()+ for k in f.keys():+ state_dict[k] = f.get_tensor(k)+ config = json.loads(metadata["config"])+ with torch.device("meta"):+ latent_upsampler = LatentUpsampler.from_config(config)+ latent_upsampler.load_state_dict(state_dict, assign=True)+ return latent_upsampler+++if __name__ == "__main__":+ latent_upsampler = LatentUpsampler(num_blocks_per_stage=4, dims=3)+ print(latent_upsampler)+ total_params = sum(p.numel() for p in latent_upsampler.parameters())+ print(f"Total number of parameters: {total_params:,}")+ latent = torch.randn(1, 128, 9, 16, 16)+ upsampled_latent = latent_upsampler(latent)+ print(f"Upsampled latent shape: {upsampled_latent.shape}")diff --git a/ltx_video/models/autoencoders/pixel_shuffle.py b/ltx_video/models/autoencoders/pixel_shuffle.pynew file mode 100644index 0000000..4e79ae2--- /dev/null+++ b/ltx_video/models/autoencoders/pixel_shuffle.py@@ -0,0 +1,33 @@+import torch.nn as nn+from einops import rearrange+++class PixelShuffleND(nn.Module):+ def __init__(self, dims, upscale_factors=(2, 2, 2)):+ super().__init__()+ assert dims in [1, 2, 3], "dims must be 1, 2, or 3"+ self.dims = dims+ self.upscale_factors = upscale_factors++ def forward(self, x):+ if self.dims == 3:+ return rearrange(+ x,+ "b (c p1 p2 p3) d h w -> b c (d p1) (h p2) (w p3)",+ p1=self.upscale_factors[0],+ p2=self.upscale_factors[1],+ p3=self.upscale_factors[2],+ )+ elif self.dims == 2:+ return rearrange(+ x,+ "b (c p1 p2) h w -> b c (h p1) (w p2)",+ p1=self.upscale_factors[0],+ p2=self.upscale_factors[1],+ )+ elif self.dims == 1:+ return rearrange(+ x,+ "b (c p1) f h w -> b c (f p1) h w",+ p1=self.upscale_factors[0],+ )diff --git a/ltx_video/pipelines/pipeline_ltx_video.py b/ltx_video/pipelines/pipeline_ltx_video.pyindex f2f9cc2..85161fd 100644--- a/ltx_video/pipelines/pipeline_ltx_video.py+++ b/ltx_video/pipelines/pipeline_ltx_video.py@@ -1,10 +1,11 @@# Adapted from: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py+import copyimport inspectimport mathimport refrom contextlib import nullcontextfrom dataclasses import dataclass-from typing import Callable, Dict, List, Optional, Tuple, Union+from typing import Any, Callable, Dict, List, Optional, Tuple, Unionimport torchimport torch.nn.functional as F@@ -37,6 +38,12 @@ from ltx_video.models.transformers.transformer3d import Transformer3DModelfrom ltx_video.schedulers.rf import TimestepShifterfrom ltx_video.utils.skip_layer_strategy import SkipLayerStrategyfrom ltx_video.utils.prompt_enhance_utils import generate_cinematic_prompt+from ltx_video.models.autoencoders.latent_upsampler import LatentUpsampler+from ltx_video.models.autoencoders.vae_encode import (+ un_normalize_latents,+ normalize_latents,+)+logger = logging.get_logger(__name__) # pylint: disable=invalid-name@@ -120,6 +127,7 @@ def retrieve_timesteps(num_inference_steps: Optional[int] = None,device: Optional[Union[str, torch.device]] = None,timesteps: Optional[List[int]] = None,+ max_timestep: Optional[float] = 1.0,**kwargs,):"""@@ -135,9 +143,12 @@ def retrieve_timesteps(device (`str` or `torch.device`, *optional*):The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.timesteps (`List[int]`, *optional*):- Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default- timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`- must be `None`.+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`+ must be `None`.+ max_timestep ('float', *optional*, defaults to 1.0):+ The initial noising level for image-to-image/video-to-video. The list if timestamps will be+ truncated to start with a timestamp greater or equal to this.Returns:`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the@@ -158,6 +169,16 @@ def retrieve_timesteps(else:scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)timesteps = scheduler.timesteps++ if max_timestep < 1.0:+ if max_timestep < timesteps.min():+ raise ValueError(+ f"max_timestep {max_timestep} is smaller than the minimum timestep {timesteps.min()}"+ )+ timesteps = timesteps[timesteps <= max_timestep]+ num_inference_steps = len(timesteps)+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)+return timesteps, num_inference_steps@@ -165,15 +186,20 @@ def retrieve_timesteps(class ConditioningItem:"""Defines a single frame-conditioning item - a single frame or a sequence of frames.+Attributes:- media_item (torch.Tensor), shape=(b, 3, f, h, w): The media item to condition on.+ media_item (torch.Tensor): shape=(b, 3, f, h, w). The media item to condition on.media_frame_number (int): The start-frame number of the media item in the generated video.conditioning_strength (float): The strength of the conditioning (1.0 = full conditioning).+ media_x (Optional[int]): Optional left x coordinate of the media item in the generated frame.+ media_y (Optional[int]): Optional top y coordinate of the media item in the generated frame."""media_item: torch.Tensormedia_frame_number: intconditioning_strength: float+ media_x: Optional[int] = None+ media_y: Optional[int] = Noneclass LTXVideoPipeline(DiffusionPipeline):@@ -588,26 +614,82 @@ class LTXVideoPipeline(DiffusionPipeline):# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latentsdef prepare_latents(self,- latent_shape,- dtype,- device,- generator,+ latents: torch.Tensor | None,+ media_items: torch.Tensor | None,+ timestep: float,+ latent_shape: torch.Size | Tuple[Any, ...],+ dtype: torch.dtype,+ device: torch.device,+ generator: torch.Generator | List[torch.Generator],+ vae_per_channel_normalize: bool = True,):+ """+ Prepare the initial latent tensor to be denoised.+ The latents are either pure noise or a noised version of the encoded media items.+ Args:+ latents (`torch.FloatTensor` or `None`):+ The latents to use (provided by the user) or `None` to create new latents.+ media_items (`torch.FloatTensor` or `None`):+ An image or video to be updated using img2img or vid2vid. The media item is encoded and noised.+ timestep (`float`):+ The timestep to noise the encoded media_items to.+ latent_shape (`torch.Size`):+ The target latent shape.+ dtype (`torch.dtype`):+ The target dtype.+ device (`torch.device`):+ The target device.+ generator (`torch.Generator` or `List[torch.Generator]`):+ Generator(s) to be used for the noising process.+ vae_per_channel_normalize ('bool'):+ When encoding the media_items, whether to normalize the latents per-channel.+ Returns:+ `torch.FloatTensor`: The latents to be used for the denoising process. This is a tensor of shape+ (batch_size, num_channels, height, width).+ """if isinstance(generator, list) and len(generator) != latent_shape[0]:raise ValueError(f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"f" size of {latent_shape[0]}. Make sure the batch size matches the length of the generators.")+ # Initialize the latents with the given latents or encoded media item, if provided+ assert (+ latents is None or media_items is None+ ), "Cannot provide both latents and media_items. Please provide only one of the two."++ assert (+ latents is None and media_items is None or timestep < 1.0+ ), "Input media_item or latents are provided, but they will be replaced with noise."++ if media_items is not None:+ latents = vae_encode(+ media_items.to(dtype=self.vae.dtype, device=self.vae.device),+ self.vae,+ vae_per_channel_normalize=vae_per_channel_normalize,+ )+ if latents is not None:+ assert (+ latents.shape == latent_shape+ ), f"Latents have to be of shape {latent_shape} but are {latents.shape}."+ latents = latents.to(device=device, dtype=dtype)+# For backward compatibility, generate in the "patchified" shape and rearrangeb, c, f, h, w = latent_shape- latents = randn_tensor(+ noise = randn_tensor((b, f * h * w, c), generator=generator, device=device, dtype=dtype)- latents = rearrange(latents, "b (f h w) c -> b c f h w", f=f, h=h, w=w)+ noise = rearrange(noise, "b (f h w) c -> b c f h w", f=f, h=h, w=w)# scale the initial noise by the standard deviation required by the scheduler- latents = latents * self.scheduler.init_noise_sigma+ noise = noise * self.scheduler.init_noise_sigma++ if latents is None:+ latents = noise+ else:+ # Noise the latents to the required (first) timestep+ latents = timestep * noise + (1 - timestep) * latents+return latents@staticmethod@@ -633,14 +715,9 @@ class LTXVideoPipeline(DiffusionPipeline):resized_height = int(orig_height * ratio)# Resize- samples = rearrange(samples, "b c n h w -> (b n) c h w")- samples = F.interpolate(- samples,- size=(resized_height, resized_width),- mode="bilinear",- align_corners=False,+ samples = LTXVideoPipeline.resize_tensor(+ samples, resized_height, resized_width)- samples = rearrange(samples, "(b n) c h w -> b c n h w", n=n_frames)# Center Cropstart_x = (resized_width - new_width) // 2@@ -651,6 +728,20 @@ class LTXVideoPipeline(DiffusionPipeline):return samples+ @staticmethod+ def resize_tensor(media_items, height, width):+ n_frames = media_items.shape[2]+ if media_items.shape[-2:] != (height, width):+ media_items = rearrange(media_items, "b c n h w -> (b n) c h w")+ media_items = F.interpolate(+ media_items,+ size=(height, width),+ mode="bilinear",+ align_corners=False,+ )+ media_items = rearrange(media_items, "(b n) c h w -> b c n h w", n=n_frames)+ return media_items+@torch.no_grad()def __call__(self,@@ -662,12 +753,12 @@ class LTXVideoPipeline(DiffusionPipeline):negative_prompt: str = "",num_inference_steps: int = 20,timesteps: List[int] = None,- guidance_scale: float = 4.5,+ guidance_scale: Union[float, List[float]] = 4.5,skip_layer_strategy: Optional[SkipLayerStrategy] = None,- skip_block_list: Optional[List[int]] = None,- stg_scale: float = 1.0,- do_rescaling: bool = True,- rescaling_scale: float = 0.7,+ skip_block_list: Optional[Union[List[List[int]], List[int]]] = None,+ stg_scale: Union[float, List[float]] = 1.0,+ rescaling_scale: Union[float, List[float]] = 0.7,+ guidance_timesteps: Optional[List[int]] = None,num_images_per_prompt: Optional[int] = 1,eta: float = 0.0,generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,@@ -687,6 +778,8 @@ class LTXVideoPipeline(DiffusionPipeline):enhance_prompt: bool = False,text_encoder_max_tokens: int = 256,stochastic_sampling: bool = False,+ media_items: Optional[torch.Tensor] = None,+ strength: Optional[float] = 1.0,**kwargs,) -> Union[ImagePipelineOutput, Tuple]:"""@@ -702,7 +795,7 @@ class LTXVideoPipeline(DiffusionPipeline):less than `1`).num_inference_steps (`int`, *optional*, defaults to 100):The number of denoising steps. More denoising steps usually lead to a higher quality image at the- expense of slower inference.+ expense of slower inference. If `timesteps` is provided, this parameter is ignored.timesteps (`List[int]`, *optional*):Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`timesteps are used. Must be in descending order.@@ -741,7 +834,7 @@ class LTXVideoPipeline(DiffusionPipeline):The output format of the generate image. Choose between[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.return_dict (`bool`, *optional*, defaults to `True`):- Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.+ Whether to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.callback_on_step_end (`Callable`, *optional*):A function that calls at the end of each denoising steps during the inference. The function is calledwith the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,@@ -757,7 +850,12 @@ class LTXVideoPipeline(DiffusionPipeline):The maximum number of tokens to use for the text encoder.stochastic_sampling (`bool`, *optional*, defaults to `False`):If set to `True`, the sampling is stochastic. If set to `False`, the sampling is deterministic.-+ media_items ('torch.Tensor', *optional*):+ The input media item used for image-to-image / video-to-video.+ When provided, they will be noised according to 'strength' and then fully denoised.+ strength ('floaty', *optional* defaults to 1.0):+ The editing level in image-to-image / video-to-video. The provided input will be noised+ to this level.Examples:Returns:@@ -781,13 +879,6 @@ class LTXVideoPipeline(DiffusionPipeline):negative_prompt_attention_mask,)- if kwargs.get("media_items", None) is not None:- # Backwards compatibility mode for first-frame conditioning- assert (- conditioning_items is None- ), "Cannot pass both `conditioning_items` and `media_items`."- conditioning_items = [ConditioningItem(kwargs["media_items"], 0, 1.0)]-# 2. Default height and width to transformerif prompt is not None and isinstance(prompt, str):batch_size = 1@@ -798,11 +889,88 @@ class LTXVideoPipeline(DiffusionPipeline):device = self._execution_device+ self.video_scale_factor = self.video_scale_factor if is_video else 1+ vae_per_channel_normalize = kwargs.get("vae_per_channel_normalize", True)+ image_cond_noise_scale = kwargs.get("image_cond_noise_scale", 0.0)++ latent_height = height // self.vae_scale_factor+ latent_width = width // self.vae_scale_factor+ latent_num_frames = num_frames // self.video_scale_factor+ if isinstance(self.vae, CausalVideoAutoencoder) and is_video:+ latent_num_frames += 1+ latent_shape = (+ batch_size * num_images_per_prompt,+ self.transformer.config.in_channels,+ latent_num_frames,+ latent_height,+ latent_width,+ )++ # Prepare the list of denoising time-steps++ retrieve_timesteps_kwargs = {}+ if isinstance(self.scheduler, TimestepShifter):+ retrieve_timesteps_kwargs["samples_shape"] = latent_shape++ assert strength == 1.0 or latents is not None or media_items is not None, (+ "strength < 1 is used for image-to-image/video-to-video - "+ "media_item or latents should be provided."+ )++ timesteps, num_inference_steps = retrieve_timesteps(+ self.scheduler,+ num_inference_steps,+ device,+ timesteps,+ max_timestep=strength,+ **retrieve_timesteps_kwargs,+ )+ if self.allowed_inference_steps is not None:+ for timestep in [round(x, 4) for x in timesteps.tolist()]:+ assert (+ timestep in self.allowed_inference_steps+ ), f"Invalid inference timestep {timestep}. Allowed timesteps are {self.allowed_inference_steps}."++ if guidance_timesteps:+ guidance_mapping = []+ for timestep in timesteps:+ indices = [+ i for i, val in enumerate(guidance_timesteps) if val <= timestep+ ]+ # assert len(indices) > 0, f"No guidance timestep found for {timestep}"+ guidance_mapping.append(+ indices[0] if len(indices) > 0 else (len(guidance_timesteps) - 1)+ )+# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`# corresponds to doing no classifier free guidance.- do_classifier_free_guidance = guidance_scale > 1.0- do_spatio_temporal_guidance = stg_scale > 0.0+ if not isinstance(guidance_scale, List):+ guidance_scale = [guidance_scale] * len(timesteps)+ else:+ guidance_scale = [+ 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:+ stg_scale = [stg_scale[guidance_mapping[i]] for i in range(len(timesteps))]++ if not isinstance(rescaling_scale, List):+ rescaling_scale = [rescaling_scale] * len(timesteps)+ else:+ rescaling_scale = [+ 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 = 1if do_classifier_free_guidance:@@ -810,11 +978,27 @@ class LTXVideoPipeline(DiffusionPipeline):if do_spatio_temporal_guidance:num_conds += 1- skip_layer_mask = None+ # 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+ if not isinstance(skip_block_list[0], list):+ skip_block_list = [skip_block_list] * len(timesteps)+ else:+ new_skip_block_list = []+ for i, timestep in enumerate(timesteps):+ 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]] = Noneif do_spatio_temporal_guidance:- skip_layer_mask = self.transformer.create_skip_layer_mask(- batch_size, num_conds, 2, skip_block_list- )+ 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 = (@@ -880,31 +1064,18 @@ class LTXVideoPipeline(DiffusionPipeline):dim=0,)- # 3b. Encode and prepare conditioning data- self.video_scale_factor = self.video_scale_factor if is_video else 1- vae_per_channel_normalize = kwargs.get("vae_per_channel_normalize", False)- image_cond_noise_scale = kwargs.get("image_cond_noise_scale", 0.0)+ # 4. Prepare the initial latents using the provided media and conditioning items- # 4. Prepare latents.- latent_height = height // self.vae_scale_factor- latent_width = width // self.vae_scale_factor- latent_num_frames = num_frames // self.video_scale_factor- if isinstance(self.vae, CausalVideoAutoencoder) and is_video:- latent_num_frames += 1- latent_shape = (- batch_size * num_images_per_prompt,- self.transformer.config.in_channels,- latent_num_frames,- latent_height,- latent_width,- )-- # Prepare the initial random latents tensor, shape = (b, c, f, h, w)+ # Prepare the initial latents tensor, shape = (b, c, f, h, w)latents = self.prepare_latents(+ latents=latents,+ media_items=media_items,+ timestep=timesteps[0],latent_shape=latent_shape,dtype=prompt_embeds_batch.dtype,device=device,generator=generator,+ vae_per_channel_normalize=vae_per_channel_normalize,)# Update the latents with the conditioning items and patchify them into (b, n, c)@@ -929,23 +1100,6 @@ class LTXVideoPipeline(DiffusionPipeline):fractional_coords = pixel_coords.to(torch.float32)fractional_coords[:, 0] = fractional_coords[:, 0] * (1.0 / frame_rate)- # 5. Prepare timesteps- retrieve_timesteps_kwargs = {}- if isinstance(self.scheduler, TimestepShifter):- retrieve_timesteps_kwargs["samples"] = latents- timesteps, num_inference_steps = retrieve_timesteps(- self.scheduler,- num_inference_steps,- device,- timesteps,- **retrieve_timesteps_kwargs,- )- if self.allowed_inference_steps is not None:- for timestep in [round(x, 4) for x in timesteps.tolist()]:- assert (- timestep in self.allowed_inference_steps- ), f"Invalid inference timestep {timestep}. Allowed timesteps are {self.allowed_inference_steps}."-# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipelineextra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)@@ -1005,11 +1159,6 @@ class LTXVideoPipeline(DiffusionPipeline):# Choose the appropriate context manager based on `mixed_precision`if mixed_precision:- if "xla" in device.type:- raise NotImplementedError(- "Mixed precision is not supported yet on XLA devices."- )-context_manager = torch.autocast(device.type, dtype=torch.bfloat16)else:context_manager = nullcontext() # Dummy context manager@@ -1024,7 +1173,11 @@ class LTXVideoPipeline(DiffusionPipeline):),encoder_attention_mask=prompt_attention_mask_batch,timestep=current_timestep,- skip_layer_mask=skip_layer_mask,+ skip_layer_mask=(+ skip_layer_masks[i]+ if skip_layer_masks is not None+ else None+ ),skip_layer_strategy=skip_layer_strategy,return_dict=False,)[0]@@ -1036,16 +1189,16 @@ class LTXVideoPipeline(DiffusionPipeline):)[-2:]if do_classifier_free_guidance:noise_pred_uncond, noise_pred_text = noise_pred.chunk(num_conds)[:2]- noise_pred = noise_pred_uncond + guidance_scale * (+ noise_pred = noise_pred_uncond + guidance_scale[i] * (noise_pred_text - noise_pred_uncond)elif do_spatio_temporal_guidance:noise_pred = noise_pred_textif do_spatio_temporal_guidance:- noise_pred = noise_pred + stg_scale * (+ noise_pred = noise_pred + stg_scale[i] * (noise_pred_text - noise_pred_text_perturb)- if do_rescaling:+ if do_rescaling and stg_scale[i] > 0.0:noise_pred_text_std = noise_pred_text.view(batch_size, -1).std(dim=1, keepdim=True)@@ -1054,7 +1207,7 @@ class LTXVideoPipeline(DiffusionPipeline):)factor = noise_pred_text_std / noise_pred_std- factor = rescaling_scale * factor + (1 - rescaling_scale)+ factor = rescaling_scale[i] * factor + (1 - rescaling_scale[i])noise_pred = noise_pred * factor.view(batch_size, 1, 1)@@ -1127,6 +1280,7 @@ class LTXVideoPipeline(DiffusionPipeline):vae_per_channel_normalize=kwargs["vae_per_channel_normalize"],timestep=decode_timestep,)+image = self.image_processor.postprocess(image, output_type=output_type)else:@@ -1219,9 +1373,9 @@ class LTXVideoPipeline(DiffusionPipeline):if conditioning_items:batch_size, _, num_latent_frames = init_latents.shape[:3]- # Initialize the conditioning mask- conditioning_latent_frames_mask = torch.zeros(- (batch_size, num_latent_frames),++ init_conditioning_mask = torch.zeros(+ init_latents[:, 0, :, :, :].shape,dtype=torch.float32,device=init_latents.device,)@@ -1233,12 +1387,17 @@ class LTXVideoPipeline(DiffusionPipeline):# Process each conditioning itemfor conditioning_item in conditioning_items:+ conditioning_item = self._resize_conditioning_item(+ conditioning_item, height, width+ )media_item = conditioning_item.media_itemmedia_frame_number = conditioning_item.media_frame_numberstrength = conditioning_item.conditioning_strengthassert media_item.ndim == 5 # (b, c, f, h, w)b, c, n_frames, h, w = media_item.shape- assert height == h and width == w+ assert (+ height == h and width == w+ ) or media_frame_number == 0, f"Dimensions do not match: {height}x{width} != {h}x{w} - allowed only when media_frame_number == 0"assert n_frames % 8 == 1assert (media_frame_number >= 0@@ -1246,7 +1405,7 @@ class LTXVideoPipeline(DiffusionPipeline):)# Encode the provided conditioning media item- latents = vae_encode(+ media_item_latents = vae_encode(media_item.to(dtype=self.vae.dtype, device=self.vae.device),self.vae,vae_per_channel_normalize=vae_per_channel_normalize,@@ -1254,40 +1413,60 @@ class LTXVideoPipeline(DiffusionPipeline):# Handle the different conditioning casesif media_frame_number == 0:+ # Get the target spatial position of the latent conditioning item+ media_item_latents, l_x, l_y = self._get_latent_spatial_position(+ media_item_latents,+ conditioning_item,+ height,+ width,+ strip_latent_border=True,+ )+ b, c_l, f_l, h_l, w_l = media_item_latents.shape+# First frame or sequence - just update the initial noise latents and the mask- f_l = latents.shape[2]- init_latents[:, :, :f_l] = torch.lerp(- init_latents[:, :, :f_l], latents, strength+ init_latents[:, :, :f_l, l_y : l_y + h_l, l_x : l_x + w_l] = (+ torch.lerp(+ init_latents[:, :, :f_l, l_y : l_y + h_l, l_x : l_x + w_l],+ media_item_latents,+ strength,+ ))- conditioning_latent_frames_mask[:, :f_l] = strength+ init_conditioning_mask[+ :, :f_l, l_y : l_y + h_l, l_x : l_x + w_l+ ] = strengthelse:# Non-first frame or sequenceif n_frames > 1:# Handle non-first sequence.# Encoded latents are either fully consumed, or the prefix is handled separately below.- init_latents, conditioning_latent_frames_mask, latents = (- self._handle_non_first_conditioning_sequence(- init_latents,- conditioning_latent_frames_mask,- latents,- media_frame_number,- strength,- )+ (+ init_latents,+ init_conditioning_mask,+ media_item_latents,+ ) = self._handle_non_first_conditioning_sequence(+ init_latents,+ init_conditioning_mask,+ media_item_latents,+ media_frame_number,+ strength,)- if latents is not None: # Single frame or sequence-prefix latents+ # Single frame or sequence-prefix latents+ if media_item_latents is not None:noise = randn_tensor(- latents.shape,+ media_item_latents.shape,generator=generator,- device=latents.device,- dtype=latents.dtype,+ device=media_item_latents.device,+ dtype=media_item_latents.dtype,)- latents = torch.lerp(noise, latents, strength)+ media_item_latents = torch.lerp(+ noise, media_item_latents, strength+ )# Patchify the extra conditioning latents and calculate their pixel coordinates- latents, latent_coords = self.patchifier.patchify(- latents=latents+ media_item_latents, latent_coords = self.patchifier.patchify(+ latents=media_item_latents)pixel_coords = latent_to_pixel_coords(latent_coords,@@ -1297,16 +1476,16 @@ class LTXVideoPipeline(DiffusionPipeline):# Update the frame numbers to match the target frame numberpixel_coords[:, 0] += media_frame_number- extra_conditioning_num_latents += latents.shape[1]+ extra_conditioning_num_latents += media_item_latents.shape[1]conditioning_mask = torch.full(- latents.shape[:2],+ media_item_latents.shape[:2],strength,dtype=torch.float32,- device=conditioning_latent_frames_mask.device,+ device=init_latents.device,)- extra_conditioning_latents.append(latents)+ extra_conditioning_latents.append(media_item_latents)extra_conditioning_pixel_coords.append(pixel_coords)extra_conditioning_mask.append(conditioning_mask)@@ -1323,10 +1502,10 @@ class LTXVideoPipeline(DiffusionPipeline):if not conditioning_items:return init_latents, init_pixel_coords, None, 0- # Create a per-token mask based on the updated conditioning_latent_frames_mask- init_conditioning_mask = conditioning_latent_frames_mask.gather(- 1, init_latent_coords[:, 0]+ init_conditioning_mask, _ = self.patchifier.patchify(+ latents=init_conditioning_mask.unsqueeze(1))+ init_conditioning_mask = init_conditioning_mask.squeeze(-1)if extra_conditioning_latents:# Stack the extra conditioning latents, pixel coordinates and mask@@ -1338,6 +1517,17 @@ class LTXVideoPipeline(DiffusionPipeline):[*extra_conditioning_mask, init_conditioning_mask], dim=1)+ if self.transformer.use_tpu_flash_attention:+ # When flash attention is used, keep the original number of tokens by removing+ # tokens from the end.+ init_latents = init_latents[:, :-extra_conditioning_num_latents]+ init_pixel_coords = init_pixel_coords[+ :, :, :-extra_conditioning_num_latents+ ]+ init_conditioning_mask = init_conditioning_mask[+ :, :-extra_conditioning_num_latents+ ]+return (init_latents,init_pixel_coords,@@ -1345,10 +1535,73 @@ class LTXVideoPipeline(DiffusionPipeline):extra_conditioning_num_latents,)+ @staticmethod+ def _resize_conditioning_item(+ conditioning_item: ConditioningItem,+ height: int,+ width: int,+ ):+ if conditioning_item.media_x or conditioning_item.media_y:+ raise ValueError(+ "Provide media_item in the target size for spatial conditioning."+ )+ new_conditioning_item = copy.copy(conditioning_item)+ new_conditioning_item.media_item = LTXVideoPipeline.resize_tensor(+ conditioning_item.media_item, height, width+ )+ return new_conditioning_item++ def _get_latent_spatial_position(+ self,+ latents: torch.Tensor,+ conditioning_item: ConditioningItem,+ height: int,+ width: int,+ strip_latent_border,+ ):+ """+ Get the spatial position of the conditioning item in the latent space.+ If requested, strip the conditioning latent borders that do not align with target borders.+ (border latents look different then other latents and might confuse the model)+ """+ scale = self.vae_scale_factor+ h, w = conditioning_item.media_item.shape[-2:]+ assert (+ h <= height and w <= width+ ), f"Conditioning item size {h}x{w} is larger than target size {height}x{width}"+ assert h % scale == 0 and w % scale == 0++ # Compute the start and end spatial positions of the media item+ x_start, y_start = conditioning_item.media_x, conditioning_item.media_y+ x_start = (width - w) // 2 if x_start is None else x_start+ y_start = (height - h) // 2 if y_start is None else y_start+ x_end, y_end = x_start + w, y_start + h+ assert (+ x_end <= width and y_end <= height+ ), f"Conditioning item {x_start}:{x_end}x{y_start}:{y_end} is out of bounds for target size {width}x{height}"++ if strip_latent_border:+ # Strip one latent from left/right and/or top/bottom, update x, y accordingly+ if x_start > 0:+ x_start += scale+ latents = latents[:, :, :, :, 1:]++ if y_start > 0:+ y_start += scale+ latents = latents[:, :, :, 1:, :]++ if x_end < width:+ latents = latents[:, :, :, :, :-1]++ if y_end < height:+ latents = latents[:, :, :, :-1, :]++ return latents, x_start // scale, y_start // scale+@staticmethoddef _handle_non_first_conditioning_sequence(init_latents: torch.Tensor,- conditioning_latent_frames_mask: torch.Tensor,+ init_conditioning_mask: torch.Tensor,latents: torch.Tensor,media_frame_number: int,strength: float,@@ -1362,8 +1615,7 @@ class LTXVideoPipeline(DiffusionPipeline):(or last) sequence in a longer video.Args:init_latents (torch.Tensor): The initial noise latents to be updated.- conditioning_latent_frames_mask (torch.Tensor): A mask indicating the conditioning-strength of each- latent token.+ init_conditioning_mask (torch.Tensor): The initial conditioning mask to be updated.latents (torch.Tensor): The encoded conditioning item.media_frame_number (int): The target frame number of the first frame in the conditioning sequence.strength (float): The conditioning strength for the conditioning latents.@@ -1391,7 +1643,7 @@ class LTXVideoPipeline(DiffusionPipeline):strength,)# Mark these latent frames as conditioning latents- conditioning_latent_frames_mask[:, f_l_start:f_l_end] = strength+ init_conditioning_mask[:, f_l_start:f_l_end] = strength# Handle the prefix-latentsif prefix_latents_mode == "soft":@@ -1406,7 +1658,7 @@ class LTXVideoPipeline(DiffusionPipeline):strength,)# Mark these latent frames as conditioning latents- conditioning_latent_frames_mask[:, f_l_start:f_l_end] = strength+ init_conditioning_mask[:, f_l_start:f_l_end] = strengthlatents = None # No more latents to handleelif prefix_latents_mode == "drop":# Drop the prefix latents@@ -1416,7 +1668,11 @@ class LTXVideoPipeline(DiffusionPipeline):latents = latents[:, :, :f_l_p]else:raise ValueError(f"Invalid prefix_latents_mode: {prefix_latents_mode}")- return init_latents, conditioning_latent_frames_mask, latents+ return (+ init_latents,+ init_conditioning_mask,+ latents,+ )def trim_conditioning_sequence(self, start_frame: int, sequence_num_frames: int, target_num_frames: int@@ -1437,3 +1693,77 @@ class LTXVideoPipeline(DiffusionPipeline):# Trim down to a multiple of temporal_scale_factor frames plus 1num_frames = (num_frames - 1) // scale_factor * scale_factor + 1return num_frames+++class LTXMultiScalePipeline:+ def _upsample_latents(+ self, latest_upsampler: LatentUpsampler, latents: torch.Tensor+ ):+ assert latents.device == latest_upsampler.device++ latents = un_normalize_latents(+ latents, self.vae, vae_per_channel_normalize=True+ )+ upsampled_latents = latest_upsampler(latents)+ upsampled_latents = normalize_latents(+ upsampled_latents, self.vae, vae_per_channel_normalize=True+ )+ return upsampled_latents++ def __init__(+ self, video_pipeline: LTXVideoPipeline, latent_upsampler: LatentUpsampler+ ):+ self.video_pipeline = video_pipeline+ self.vae = video_pipeline.vae+ self.latent_upsampler = latent_upsampler++ def __call__(+ self,+ downscale_factor: float,+ first_pass: dict,+ second_pass: dict,+ *args: Any,+ **kwargs: Any,+ ) -> Any:+ original_kwargs = kwargs.copy()+ original_output_type = kwargs["output_type"]+ original_width = kwargs["width"]+ original_height = kwargs["height"]++ x_width = int(kwargs["width"] * downscale_factor)+ downscaled_width = x_width - (x_width % self.video_pipeline.vae_scale_factor)+ x_height = int(kwargs["height"] * downscale_factor)+ downscaled_height = x_height - (x_height % self.video_pipeline.vae_scale_factor)++ kwargs["output_type"] = "latent"+ kwargs["width"] = downscaled_width+ kwargs["height"] = downscaled_height+ kwargs.update(**first_pass)+ result = self.video_pipeline(*args, **kwargs)+ latents = result.images++ upsampled_latents = self._upsample_latents(self.latent_upsampler, latents)++ kwargs = original_kwargs++ kwargs["latents"] = upsampled_latents+ kwargs["output_type"] = original_output_type+ kwargs["width"] = downscaled_width * 2+ kwargs["height"] = downscaled_height * 2+ kwargs.update(**second_pass)++ result = self.video_pipeline(*args, **kwargs)+ if original_output_type != "latent":+ num_frames = result.images.shape[2]+ videos = rearrange(result.images, "b c f h w -> (b f) c h w")++ videos = F.interpolate(+ videos,+ size=(original_height, original_width),+ mode="bilinear",+ align_corners=False,+ )+ videos = rearrange(videos, "(b f) c h w -> b c f h w", f=num_frames)+ result.images = videos++ return resultdiff --git a/ltx_video/schedulers/rf.py b/ltx_video/schedulers/rf.pyindex 5c56f9e..0e36e61 100644--- a/ltx_video/schedulers/rf.py+++ b/ltx_video/schedulers/rf.py@@ -23,10 +23,10 @@ from ltx_video.utils.diffusers_config_mapping import (def linear_quadratic_schedule(num_steps, threshold_noise=0.025, linear_steps=None):+ if num_steps == 1:+ return torch.tensor([1.0])if linear_steps is None:linear_steps = num_steps // 2- if num_steps < 2:- return torch.tensor([1.0])linear_sigma_schedule = [i * threshold_noise / linear_steps for i in range(linear_steps)]@@ -47,14 +47,14 @@ def linear_quadratic_schedule(num_steps, threshold_noise=0.025, linear_steps=Nondef simple_diffusion_resolution_dependent_timestep_shift(- samples: Tensor,+ samples_shape: torch.Size,timesteps: Tensor,n: int = 32 * 32,) -> Tensor:- if len(samples.shape) == 3:- _, m, _ = samples.shape- elif len(samples.shape) in [4, 5]:- m = math.prod(samples.shape[2:])+ if len(samples_shape) == 3:+ _, m, _ = samples_shape+ elif len(samples_shape) in [4, 5]:+ m = math.prod(samples_shape[2:])else:raise ValueError("Samples must have shape (b, t, c), (b, c, h, w) or (b, c, f, h, w)"@@ -110,7 +110,9 @@ def strech_shifts_to_terminal(shifts: Tensor, terminal=0.1):def sd3_resolution_dependent_timestep_shift(- samples: Tensor, timesteps: Tensor, target_shift_terminal: Optional[float] = None+ samples_shape: torch.Size,+ timesteps: Tensor,+ target_shift_terminal: Optional[float] = None,) -> Tensor:"""Shifts the timestep schedule as a function of the generated resolution.@@ -123,7 +125,7 @@ def sd3_resolution_dependent_timestep_shift(Args:- samples (Tensor): A batch of samples with shape (batch_size, channels, height, width) or+ samples_shape (torch.Size): The samples batch shape (batch_size, channels, height, width) or(batch_size, channels, frame, height, width).timesteps (Tensor): A batch of timesteps with shape (batch_size,).target_shift_terminal (float): The target terminal value for the shifted timesteps.@@ -131,10 +133,10 @@ def sd3_resolution_dependent_timestep_shift(Returns:Tensor: The shifted timesteps."""- if len(samples.shape) == 3:- _, m, _ = samples.shape- elif len(samples.shape) in [4, 5]:- m = math.prod(samples.shape[2:])+ if len(samples_shape) == 3:+ _, m, _ = samples_shape+ elif len(samples_shape) in [4, 5]:+ m = math.prod(samples_shape[2:])else:raise ValueError("Samples must have shape (b, t, c), (b, c, h, w) or (b, c, f, h, w)"@@ -149,7 +151,7 @@ def sd3_resolution_dependent_timestep_shift(class TimestepShifter(ABC):@abstractmethod- def shift_timesteps(self, samples: Tensor, timesteps: Tensor) -> Tensor:+ def shift_timesteps(self, samples_shape: torch.Size, timesteps: Tensor) -> Tensor:pass@@ -211,36 +213,50 @@ class RectifiedFlowScheduler(SchedulerMixin, ConfigMixin, TimestepShifter):shift, 1, torch.linspace(1, 1 / num_timesteps, num_timesteps))- def shift_timesteps(self, samples: Tensor, timesteps: Tensor) -> Tensor:+ def shift_timesteps(self, samples_shape: torch.Size, timesteps: Tensor) -> Tensor:if self.shifting == "SD3":return sd3_resolution_dependent_timestep_shift(- samples, timesteps, self.target_shift_terminal+ samples_shape, timesteps, self.target_shift_terminal)elif self.shifting == "SimpleDiffusion":return simple_diffusion_resolution_dependent_timestep_shift(- samples, timesteps, self.base_resolution+ samples_shape, timesteps, self.base_resolution)return timestepsdef set_timesteps(self,- num_inference_steps: int,- samples: Tensor,+ num_inference_steps: Optional[int] = None,+ samples_shape: Optional[torch.Size] = None,+ timesteps: Optional[Tensor] = None,device: Union[str, torch.device] = None,):"""Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.+ If `timesteps` are provided, they will be used instead of the scheduled timesteps.Args:- num_inference_steps (`int`): The number of diffusion steps used when generating samples.- samples (`Tensor`): A batch of samples with shape.+ num_inference_steps (`int` *optional*): The number of diffusion steps used when generating samples.+ samples_shape (`torch.Size` *optional*): The samples batch shape, used for shifting.+ timesteps ('torch.Tensor' *optional*): Specific timesteps to use instead of scheduled timesteps.device (`Union[str, torch.device]`, *optional*): The device to which the timesteps tensor will be moved."""- num_inference_steps = min(self.config.num_train_timesteps, num_inference_steps)- self.timesteps = self.get_initial_timesteps(- num_inference_steps, shift=self.shift- ).to(device)- self.timesteps = self.shift_timesteps(samples, self.timesteps)+ if timesteps is not None and num_inference_steps is not None:+ raise ValueError(+ "You cannot provide both `timesteps` and `num_inference_steps`."+ )+ if timesteps is None:+ num_inference_steps = min(+ self.config.num_train_timesteps, num_inference_steps+ )+ timesteps = self.get_initial_timesteps(+ num_inference_steps, shift=self.shift+ ).to(device)+ timesteps = self.shift_timesteps(samples_shape, timesteps)+ else:+ timesteps = torch.Tensor(timesteps).to(device)+ num_inference_steps = len(timesteps)+ self.timesteps = timestepsself.num_inference_steps = num_inference_stepsself.sigmas = self.timestepsdiff --git a/tests/test_inference.py b/tests/test_inference.pyindex 7fe5e1f..d7e1c08 100644--- a/tests/test_inference.py+++ b/tests/test_inference.py@@ -1,5 +1,6 @@import pytestimport torch+import yamlfrom inference import infer, create_ltx_video_pipelinefrom ltx_video.utils.skip_layer_strategy import SkipLayerStrategy@@ -15,7 +16,7 @@ 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(test_paths, conditioning_test_mode):+def test_infer_runs_on_real_path(tmp_path, test_paths, conditioning_test_mode):conditioning_params = {}if conditioning_test_mode == "unconditional":pass@@ -34,7 +35,7 @@ def test_infer_runs_on_real_path(test_paths, conditioning_test_mode):test_paths["input_video_path"],test_paths["input_image_path"],]- conditioning_params["conditioning_start_frames"] = [16, 32]+ conditioning_params["conditioning_start_frames"] = [16, 67]else:raise ValueError(f"Unknown conditioning mode: {conditioning_test_mode}")test_paths = {@@ -46,31 +47,98 @@ def test_infer_runs_on_real_path(test_paths, conditioning_test_mode):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,+ }++ 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",- "image_cond_noise_scale": 0.15,- "height": 288,- "width": 512,- "num_frames": 33,- "frame_rate": 25,"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",+ "strength": 0.95,"offload_to_cpu": False,- "prompt_enhancement_max_words": 1000,+ "input_media_path": test_paths["input_video_path"],}- infer(**{**conditioning_params, **test_paths, **params})+ config = {+ "num_inference_steps": 3,+ "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)- # test without prompt enhancement- params["prompt_enhancement_max_words"] = 0- infer(**{**conditioning_params, **test_paths, **params})+ infer(**{**test_paths, **params, "pipeline_config": temp_config_path})def get_device():@@ -81,17 +149,8 @@ def get_device():return "cpu"-def seed_everething(seed: int):- 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 test_pipeline_on_batch(test_paths):+def test_pipeline_on_batch(tmp_path, test_paths):device = get_device()-pipeline = create_ltx_video_pipeline(ckpt_path=test_paths["ckpt_path"],device=device,@@ -108,21 +167,11 @@ def test_pipeline_on_batch(test_paths):params = {"seed": 42,- "num_inference_steps": 2,- "num_images_per_prompt": 1,- "guidance_scale": 2.5,- "do_rescaling": True,- "stg_scale": 1,- "rescaling_scale": 0.7,- "skip_layer_strategy": SkipLayerStrategy.AttentionValues,- "skip_block_list": [1, 2],"image_cond_noise_scale": 0.15,- "height": 288,- "width": 512,+ "height": 512,+ "width": 768,"num_frames": 1,"frame_rate": 25,- "decode_timestep": 0.05,- "decode_noise_scale": 0.025,"offload_to_cpu": False,"output_type": "pt","is_video": False,@@ -130,6 +179,20 @@ def test_pipeline_on_batch(test_paths):"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."@@ -144,13 +207,14 @@ def test_pipeline_on_batch(test_paths):generators = [torch.Generator(device=device).manual_seed(params["seed"]) for _ in range(2)]- seed_everething(params["seed"])+ torch.manual_seed(params["seed"])images = pipeline(prompt=prompts,generator=generators,**sample,**params,+ pipeline_config=temp_config_path,).imagesreturn images@@ -168,7 +232,7 @@ def test_pipeline_on_batch(test_paths):assert torch.allclose(image2_not_same, image2_same)-def test_prompt_enhancement(test_paths, monkeypatch):+def test_prompt_enhancement(tmp_path, test_paths, monkeypatch):# Create pipeline with prompt enhancement enableddevice = get_device()pipeline = create_ltx_video_pipeline(@@ -201,21 +265,12 @@ def test_prompt_enhancement(test_paths, monkeypatch):# Set up minimal parameters for a quick testparams = {"seed": 42,- "num_inference_steps": 1,- "num_images_per_prompt": 1,- "guidance_scale": 2.5,- "do_rescaling": True,- "stg_scale": 1,- "rescaling_scale": 0.7,- "skip_layer_strategy": SkipLayerStrategy.AttentionValues,- "skip_block_list": [1, 2],"image_cond_noise_scale": 0.15,- "height": 288,- "width": 512,+ "height": 512,+ "width": 768,+ "skip_layer_strategy": SkipLayerStrategy.AttentionValues,"num_frames": 1,"frame_rate": 25,- "decode_timestep": 0.05,- "decode_noise_scale": 0.025,"offload_to_cpu": False,"output_type": "pt","is_video": False,@@ -223,12 +278,28 @@ def test_prompt_enhancement(test_paths, monkeypatch):"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,+ }++ temp_config_path = tmp_path / "config.yaml"+ with open(temp_config_path, "w") as f:+ yaml.dump(config, f)+# 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@@ -244,6 +315,7 @@ def test_prompt_enhancement(test_paths, monkeypatch):negative_prompt="worst quality",enhance_prompt=False,**params,+ pipeline_config=temp_config_path,)# Verify that the original prompt was useddiff --git a/tests/test_scheduler.py b/tests/test_scheduler.pyindex 1392438..2ef8e73 100644--- a/tests/test_scheduler.py+++ b/tests/test_scheduler.py@@ -10,7 +10,7 @@ def init_latents_and_scheduler(sampler):sampler=("Uniform" if sampler.lower() == "uniform" else "LinearQuadratic"))latents = torch.randn(size=(batch_size, n_tokens, n_channels))- scheduler.set_timesteps(num_inference_steps=num_steps, samples=latents)+ scheduler.set_timesteps(num_inference_steps=num_steps, samples_shape=latents.shape)return scheduler, latentsdiff --git a/tests/test_vae.py b/tests/test_vae.pynew file mode 100644index 0000000..0e72dec--- /dev/null+++ b/tests/test_vae.py@@ -0,0 +1,32 @@+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)+ latent = video_autoencoder.encode(input_videos).latent_dist.mode()+ assert latent.shape == (2, 16, 3, 2, 2)+ 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()++ # validate temporal causality in encoder+ 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)++ 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)