[Model] Add LTX-2.5 support (#6070)

Signed-off-by: lishunyang12 <lishunyang12@163.com>
This commit is contained in:
SYLAR authored and GitHub committed 2026-08-15 18:27:23 +08:00
1 parent f39b8684eb
commit ce6ab0ca46
47 files changed
+4558 -218

No files matched your search

@@ -8,21 +8,25 @@ from vllm_omni.diffusion.models.ltx2.ltx2_components import (
)
from vllm_omni.diffusion.models.ltx2.ltx2_transformer import LTX2VideoTransformer3DModel
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2 import (
LTX2DistilledOneStagePipeline,
LTX2I2VDMD2Pipeline,
LTX2Pipeline,
LTX2T2VDMD2Pipeline,
)
from vllm_omni.diffusion.models.ltx2.pipeline_ltx2_two_stage import (
LTX2DistilledPipeline,
LTX2DistilledTwoStagePipeline,
LTX2TwoStagePipeline,
)
__all__ = [
"LTX2Pipeline",
"LTX2DistilledOneStagePipeline",
"LTX2T2VDMD2Pipeline",
"LTX2I2VDMD2Pipeline",
"LTX2TwoStagePipeline",
"LTX2DistilledPipeline",
"LTX2DistilledTwoStagePipeline",
"get_ltx2_post_process_func",
"load_transformer_config",
"create_transformer_from_config",
@@ -22,7 +22,7 @@ from diffusers.video_processor import VideoProcessor
from huggingface_hub import hf_hub_download
from safetensors import safe_open
from safetensors.torch import load_file
from transformers import AutoTokenizer, Gemma3ForConditionalGeneration
from transformers import AutoModelForImageTextToText, AutoTokenizer, Gemma3ForConditionalGeneration
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.layer import Attention as OmniAttention
@@ -48,6 +48,14 @@ try:
except ImportError:
LTX2VocoderWithBWE = None
try:
from transformers import Gemma4UnifiedForConditionalGeneration as _Gemma4UnifiedForConditionalGeneration
except ImportError:
_Gemma4UnifiedForConditionalGeneration = None
_LTX25_TEXT_ENCODER_CLS = AutoModelForImageTextToText if _Gemma4UnifiedForConditionalGeneration is not None else None
_LTX_COMPONENT_SUBFOLDERS = (
"tokenizer",
@@ -73,10 +81,15 @@ class LTXComponentProfile:
resident_modules: tuple[str, ...] = ()
video_vae_cls: type = AutoencoderKLLTX2Video
vocoder_cls: type = LTX2Vocoder
text_encoder_cls: type | None = Gemma3ForConditionalGeneration
vocoder_fallback_cls: type | None = None
artifact_repo_id: str | None = None
latent_upsampler_filename: str | None = None
distilled_lora_filename: str | None = None
transformer_subfolder: str = "transformer"
scheduler_use_dynamic_shifting: bool = False
scheduler_shift_terminal: float | None = None
preserve_connector_attention_mask: bool = False
LTX2_COMPONENT_PROFILE = LTXComponentProfile(
@@ -99,6 +112,23 @@ LTX23_COMPONENT_PROFILE = LTXComponentProfile(
vocoder_fallback_cls=LTX2Vocoder,
)
LTX25_FULL_COMPONENT_PROFILE = LTXComponentProfile(
name="ltx2_5_full",
dit_modules=("transformer",),
encoder_modules=("text_encoder", "connectors"),
vae_modules=("vae", "audio_vae"),
resident_modules=("vocoder",),
video_vae_cls=DistributedAutoencoderKLLTX2Video,
vocoder_cls=LTX2VocoderWithBWE or LTX2Vocoder,
vocoder_fallback_cls=LTX2Vocoder,
text_encoder_cls=_LTX25_TEXT_ENCODER_CLS,
transformer_subfolder="transformer_full",
scheduler_use_dynamic_shifting=True,
scheduler_shift_terminal=0.1,
preserve_connector_attention_mask=True,
)
LTX2_DISTILLED_COMPONENT_PROFILE = LTXComponentProfile(
name="ltx2_distilled",
dit_modules=("transformer",),
@@ -108,6 +138,32 @@ LTX2_DISTILLED_COMPONENT_PROFILE = LTXComponentProfile(
video_vae_cls=DistributedAutoencoderKLLTX2Video,
)
LTX25_DISTILLED_COMPONENT_PROFILE = LTXComponentProfile(
name="ltx2_5_distilled",
dit_modules=("transformer",),
encoder_modules=("text_encoder", "connectors"),
vae_modules=("vae", "audio_vae"),
resident_modules=("vocoder", "latent_upsampler"),
video_vae_cls=DistributedAutoencoderKLLTX2Video,
vocoder_cls=LTX2VocoderWithBWE or LTX2Vocoder,
vocoder_fallback_cls=LTX2Vocoder,
text_encoder_cls=_LTX25_TEXT_ENCODER_CLS,
preserve_connector_attention_mask=True,
)
LTX2_DISTILLED_ONE_STAGE_COMPONENT_PROFILE = replace(
LTX2_DISTILLED_COMPONENT_PROFILE,
name="ltx2_distilled_one_stage",
resident_modules=LTX2_COMPONENT_PROFILE.resident_modules,
)
LTX25_DISTILLED_ONE_STAGE_COMPONENT_PROFILE = replace(
LTX25_DISTILLED_COMPONENT_PROFILE,
name="ltx2_5_distilled_one_stage",
resident_modules=LTX25_FULL_COMPONENT_PROFILE.resident_modules,
)
LTX23_DISTILLED_COMPONENT_PROFILE = replace(
LTX23_COMPONENT_PROFILE,
name="ltx2_3_distilled",
@@ -116,6 +172,12 @@ LTX23_DISTILLED_COMPONENT_PROFILE = replace(
latent_upsampler_filename="ltx-2.3-spatial-upscaler-x2-1.1.safetensors",
)
LTX23_DISTILLED_ONE_STAGE_COMPONENT_PROFILE = replace(
LTX23_DISTILLED_COMPONENT_PROFILE,
name="ltx2_3_distilled_one_stage",
resident_modules=LTX23_COMPONENT_PROFILE.resident_modules,
)
LTX2_TWO_STAGE_COMPONENT_PROFILE = replace(
LTX2_COMPONENT_PROFILE,
name="ltx2_two_stage",
@@ -135,18 +197,44 @@ LTX23_TWO_STAGE_COMPONENT_PROFILE = replace(
)
LTX25_TWO_STAGE_COMPONENT_PROFILE = replace(
LTX25_FULL_COMPONENT_PROFILE,
name="ltx2_5_two_stage",
resident_modules=(*LTX25_FULL_COMPONENT_PROFILE.resident_modules, "latent_upsampler"),
artifact_repo_id="Lightricks/LTX-2.5",
latent_upsampler_filename=("latent_upscale_models/ltx-2.5-latent-spatial-upscaler-x2-bf16-1.0.safetensors"),
distilled_lora_filename="loras/ltx-2.5-22b-distilled-lora-450-bf16.safetensors",
)
_COMPONENT_PROFILES: dict[tuple[str, str], LTXComponentProfile] = {
("one_stage", "2"): LTX2_COMPONENT_PROFILE,
("one_stage", "2.3"): LTX23_COMPONENT_PROFILE,
("one_stage", "2.5"): LTX25_FULL_COMPONENT_PROFILE,
("two_stage", "2"): LTX2_TWO_STAGE_COMPONENT_PROFILE,
("two_stage", "2.3"): LTX23_TWO_STAGE_COMPONENT_PROFILE,
("two_stage", "2.5"): LTX25_TWO_STAGE_COMPONENT_PROFILE,
("distilled_one_stage", "2"): LTX2_DISTILLED_ONE_STAGE_COMPONENT_PROFILE,
("distilled_one_stage", "2.3"): LTX23_DISTILLED_ONE_STAGE_COMPONENT_PROFILE,
("distilled_one_stage", "2.5"): LTX25_DISTILLED_ONE_STAGE_COMPONENT_PROFILE,
("distilled_two_stage", "2"): LTX2_DISTILLED_COMPONENT_PROFILE,
("distilled_two_stage", "2.3"): LTX23_DISTILLED_COMPONENT_PROFILE,
("distilled_two_stage", "2.5"): LTX25_DISTILLED_COMPONENT_PROFILE,
("dmd2", "2"): LTX2_COMPONENT_PROFILE,
("dmd2", "2.3"): LTX23_COMPONENT_PROFILE,
}
def resolve_ltx_checkpoint_kind(pipeline_kind: str) -> LTXCheckpointKind | None:
"""Derive checkpoint requirements from the execution contract."""
if pipeline_kind in {"one_stage", "two_stage"}:
return "regular"
if pipeline_kind in {"distilled_one_stage", "distilled_two_stage"}:
return "distilled"
if pipeline_kind == "dmd2":
return None
raise ValueError(f"Unsupported LTX pipeline kind: {pipeline_kind!r}.")
def resolve_ltx_artifact(
model: str,
repo_id: str,
@@ -206,7 +294,7 @@ def resolve_ltx_component_profile(pipeline_kind: str, model_version: str) -> LTX
raise ValueError(f"Unsupported LTX component kind/version: {pipeline_kind!r}/{model_version!r}.") from exc
def _load_ltx_metadata_json(model: str, filename: str) -> dict[str, Any]:
def _load_ltx_metadata_json(model: str, filename: str, revision: str | None = None) -> dict[str, Any]:
"""Load small checkpoint metadata without relying on repository names."""
if os.path.isdir(model):
path = os.path.join(model, filename)
@@ -214,7 +302,7 @@ def _load_ltx_metadata_json(model: str, filename: str) -> dict[str, Any]:
return {}
else:
try:
path = hf_hub_download(repo_id=model, filename=filename)
path = hf_hub_download(repo_id=model, filename=filename, revision=revision)
except Exception:
return {}
try:
@@ -225,17 +313,34 @@ def _load_ltx_metadata_json(model: str, filename: str) -> dict[str, Any]:
return value if isinstance(value, dict) else {}
def detect_ltx_model_version(model: str) -> str:
"""Detect LTX-2 versus LTX-2.3 from checkpoint component metadata.
def detect_ltx_model_version(model: str, revision: str | None = None) -> str:
"""Detect the LTX model version from checkpoint component metadata."""
model_index = _load_ltx_metadata_json(model, "model_index.json", revision)
model_version = str(model_index.get("model_version", ""))
if model_version.startswith("2.5"):
return "2.5"
Official checkpoints use ``model_version`` metadata. Diffusers repositories
expose the equivalent distinction through the BWE vocoder introduced by
LTX-2.3. Unknown conversions retain the official LTX-2 fallback.
"""
model_index = _load_ltx_metadata_json(model, "model_index.json")
if str(model_index.get("model_version", "")).startswith("2.3"):
text_encoder_entry = model_index.get("text_encoder")
if isinstance(text_encoder_entry, (list, tuple)) and text_encoder_entry:
text_encoder_class = str(text_encoder_entry[-1])
elif isinstance(text_encoder_entry, dict):
text_encoder_class = str(text_encoder_entry.get("_class_name", ""))
else:
text_encoder_class = ""
if text_encoder_class == "Gemma4UnifiedForConditionalGeneration":
return "2.5"
text_encoder_config = _load_ltx_metadata_json(model, "text_encoder/config.json", revision)
if text_encoder_config.get("model_type") in ("gemma4_unified", "gemma4"):
return "2.5"
if model_version.startswith("2.3"):
return "2.3"
transformer_config = _load_ltx_metadata_json(model, "transformer/config.json", revision)
if transformer_config.get("ff_bias") is False:
return "2.5"
vocoder_entry = model_index.get("vocoder")
if isinstance(vocoder_entry, (list, tuple)) and vocoder_entry:
vocoder_class = str(vocoder_entry[-1])
@@ -246,21 +351,32 @@ def detect_ltx_model_version(model: str) -> str:
if vocoder_class == "LTX2VocoderWithBWE":
return "2.3"
vocoder_config = _load_ltx_metadata_json(model, "vocoder/config.json")
vocoder_config = _load_ltx_metadata_json(model, "vocoder/config.json", revision)
if str(vocoder_config.get("model_version", "")).startswith("2.3"):
return "2.3"
if vocoder_config.get("_class_name") == "LTX2VocoderWithBWE":
return "2.3"
logger.info("Using LTX-2 defaults for checkpoint %s", model)
if "bwe" in vocoder_config or "bwe_config" in vocoder_config:
return "2.3"
return "2"
def preserves_reference_image_size(*, model: str | None, revision: str | None = None) -> bool:
"""Preserve source geometry only for the LTX-2.5 CRF-18 I2V path."""
return model is not None and detect_ltx_model_version(model, revision=revision) == "2.5"
class _LTXConnectorAttnProcessor:
"""Preserve official connector math around Omni attention dispatch."""
def __init__(self, *, has_learned_registers: bool) -> None:
def __init__(
self,
*,
has_learned_registers: bool = False,
preserve_learned_register_mask: bool = False,
) -> None:
self.has_learned_registers = has_learned_registers
self.preserve_learned_register_mask = preserve_learned_register_mask
def __call__(
self,
@@ -274,12 +390,20 @@ class _LTXConnectorAttnProcessor:
encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
gate_logits = attn.to_gate_logits(hidden_states) if attn.to_gate_logits is not None else None
query = attn.norm_q(attn.to_q(hidden_states))
key = attn.norm_k(attn.to_k(encoder_hidden_states))
query = attn.to_q(hidden_states)
key = attn.to_k(encoder_hidden_states)
value = attn.to_v(encoder_hidden_states)
# Offload hooks may execute affine-free Q/K norms in FP32. Restore the
# projection dtype before attention, matching the fully resident path.
query = attn.norm_q(query).to(dtype=value.dtype)
key = attn.norm_k(key).to(dtype=value.dtype)
if query_rotary_emb is not None:
# Diffusers builds connector RoPE in FP32, while the official
# connector materializes it in the hidden-state dtype.
query_rotary_emb = tuple(component.to(value.dtype) for component in query_rotary_emb)
key_rotary_emb = key_rotary_emb if key_rotary_emb is not None else query_rotary_emb
key_rotary_emb = tuple(component.to(value.dtype) for component in key_rotary_emb)
if attn.rope_type == "interleaved":
query = apply_interleaved_rotary_emb(query, query_rotary_emb)
key = apply_interleaved_rotary_emb(key, key_rotary_emb)
@@ -289,6 +413,10 @@ class _LTXConnectorAttnProcessor:
else:
raise ValueError(f"Unsupported LTX connector RoPE type: {attn.rope_type}")
# Keep Q/K in the projection dtype expected by the attention backend.
query = query.to(dtype=value.dtype)
key = key.to(dtype=value.dtype)
batch_size, _, inner_dim = query.shape
head_dim = inner_dim // attn.heads
kv_heads = attn.inner_kv_dim // attn.head_dim
@@ -296,10 +424,10 @@ class _LTXConnectorAttnProcessor:
key = key.view(batch_size, -1, kv_heads, head_dim)
value = value.view(batch_size, -1, kv_heads, head_dim)
# The connector replaces padding tokens with learned registers before
# entering its blocks, so every key is valid and the old padding mask
# becomes an all-keep no-op.
if self.has_learned_registers:
# LTX-2/2.3 replace padding tokens with learned registers, so their
# old padding mask becomes a no-op. LTX-2.5 preserves that all-zero
# additive mask to match the official masked-SDPA dispatch.
if self.has_learned_registers and not self.preserve_learned_register_mask:
attention_mask = None
elif attention_mask is not None and attn.omni_attention.attn_backend.get_name().upper() == "FLASH_ATTN":
attention_mask = to_ltx_padding_mask(attention_mask)
@@ -316,7 +444,11 @@ class _LTXConnectorAttnProcessor:
return attn.to_out[1](hidden_states)
def _install_connector_attention(connectors: LTX2TextConnectors) -> None:
def _install_connector_attention(
connectors: LTX2TextConnectors,
*,
preserve_learned_register_mask: bool = False,
) -> None:
for connector_name in ("video_connector", "audio_connector"):
connector = getattr(connectors, connector_name, None)
has_learned_registers = getattr(connector, "learnable_registers", None) is not None
@@ -335,15 +467,20 @@ def _install_connector_attention(connectors: LTX2TextConnectors) -> None:
skip_sequence_parallel=True,
disable_kv_quant=True,
)
attention.set_processor(_LTXConnectorAttnProcessor(has_learned_registers=has_learned_registers))
attention.set_processor(
_LTXConnectorAttnProcessor(
has_learned_registers=has_learned_registers,
preserve_learned_register_mask=preserve_learned_register_mask,
)
)
def _detect_vocoder_output_sample_rate(model: str) -> int | None:
def _detect_vocoder_output_sample_rate(model: str, revision: str | None = None) -> int | None:
"""Read the generated waveform sample rate from the vocoder config."""
vocoder_config_path = os.path.join(model, "vocoder", "config.json")
if not os.path.exists(vocoder_config_path):
try:
vocoder_config_path = hf_hub_download(model, "vocoder/config.json")
vocoder_config_path = hf_hub_download(model, "vocoder/config.json", revision=revision)
except Exception:
return None
try:
@@ -355,7 +492,10 @@ def _detect_vocoder_output_sample_rate(model: str) -> int | None:
def get_ltx2_post_process_func(od_config: Any):
"""Build the common LTX engine-output adapter."""
output_sample_rate = _detect_vocoder_output_sample_rate(od_config.model)
output_sample_rate = _detect_vocoder_output_sample_rate(
od_config.model,
revision=getattr(od_config, "revision", None),
)
def post_process_func(output: tuple[torch.Tensor, torch.Tensor] | torch.Tensor):
if not (isinstance(output, tuple) and len(output) == 2):
@@ -378,6 +518,7 @@ def _load_component(
*,
local_files_only: bool,
dtype: torch.dtype,
revision: str | None,
) -> Any:
return from_pretrained_with_prefetch(
component_cls.from_pretrained,
@@ -385,6 +526,7 @@ def _load_component(
subfolder=subfolder,
prefetch_list=_LTX_COMPONENT_SUBFOLDERS,
local_files_only=local_files_only,
revision=revision,
torch_dtype=dtype,
)
@@ -411,31 +553,36 @@ def initialize_pipeline_components(pipeline: Any, od_config: Any) -> None:
pipeline.device = get_local_device()
dtype = getattr(od_config, "dtype", torch.bfloat16)
model = od_config.model
revision = getattr(od_config, "revision", None)
local_files_only = os.path.exists(model)
pipeline.weights_sources = [
DiffusersPipelineLoader.ComponentSource(
model_or_path=model,
subfolder="transformer",
revision=None,
subfolder=profile.transformer_subfolder,
revision=revision,
prefix="transformer.",
fall_back_to_pt=True,
),
]
prefetch_subfolders(model, _LTX_COMPONENT_SUBFOLDERS, local_files_only=local_files_only)
prefetch_subfolders(model, _LTX_COMPONENT_SUBFOLDERS, local_files_only=local_files_only, revision=revision)
pipeline.tokenizer = AutoTokenizer.from_pretrained(
model,
subfolder="tokenizer",
local_files_only=local_files_only,
revision=revision,
)
if profile.text_encoder_cls is None:
raise ImportError("LTX-2.5 requires Gemma4UnifiedForConditionalGeneration; install transformers>=5.10.1,<5.15.")
with torch.device("cpu"):
pipeline.text_encoder = _load_component(
Gemma3ForConditionalGeneration,
profile.text_encoder_cls,
model,
"text_encoder",
local_files_only=local_files_only,
dtype=dtype,
revision=revision,
)
pipeline.connectors = _load_component(
LTX2TextConnectors,
@@ -443,14 +590,19 @@ def initialize_pipeline_components(pipeline: Any, od_config: Any) -> None:
"connectors",
local_files_only=local_files_only,
dtype=dtype,
revision=revision,
)
_install_connector_attention(
pipeline.connectors,
preserve_learned_register_mask=profile.preserve_connector_attention_mask,
)
_install_connector_attention(pipeline.connectors)
pipeline.vae = _load_component(
profile.video_vae_cls,
model,
"vae",
local_files_only=local_files_only,
dtype=dtype,
revision=revision,
)
pipeline.audio_vae = _load_component(
AutoencoderKLLTX2Audio,
@@ -458,6 +610,7 @@ def initialize_pipeline_components(pipeline: Any, od_config: Any) -> None:
"audio_vae",
local_files_only=local_files_only,
dtype=dtype,
revision=revision,
)
try:
pipeline.vocoder = _load_component(
@@ -466,6 +619,7 @@ def initialize_pipeline_components(pipeline: Any, od_config: Any) -> None:
"vocoder",
local_files_only=local_files_only,
dtype=dtype,
revision=revision,
)
except (TypeError, OSError, ValueError):
if profile.vocoder_fallback_cls is None or profile.vocoder_fallback_cls is profile.vocoder_cls:
@@ -476,6 +630,7 @@ def initialize_pipeline_components(pipeline: Any, od_config: Any) -> None:
"vocoder",
local_files_only=local_files_only,
dtype=dtype,
revision=revision,
)
if "latent_upsampler" in profile.resident_modules:
@@ -488,6 +643,7 @@ def initialize_pipeline_components(pipeline: Any, od_config: Any) -> None:
"latent_upsampler",
local_files_only=local_files_only,
dtype=dtype,
revision=revision,
)
except (OSError, ValueError):
if profile.latent_upsampler_filename is None or profile.artifact_repo_id is None:
@@ -508,7 +664,9 @@ def initialize_pipeline_components(pipeline: Any, od_config: Any) -> None:
)
pipeline.latent_upsampler = _load_ltx_latent_upsampler_single_file(upsampler_path, dtype)
transformer_config = load_transformer_config(model, "transformer", local_files_only)
transformer_config = load_transformer_config(
model, profile.transformer_subfolder, local_files_only, revision=revision
)
quant_config = getattr(od_config, "quantization_config", None)
pipeline.transformer = create_transformer_from_config(transformer_config, quant_config=quant_config)
_place_aux_components(pipeline)
@@ -516,15 +674,17 @@ def initialize_pipeline_components(pipeline: Any, od_config: Any) -> None:
model,
subfolder="scheduler",
local_files_only=local_files_only,
revision=revision,
)
expected_checkpoint_kind: LTXCheckpointKind | None = None
if pipeline.pipeline_kind == "two_stage":
expected_checkpoint_kind = "regular"
elif pipeline.pipeline_kind == "distilled_two_stage":
expected_checkpoint_kind = "distilled"
if profile.scheduler_use_dynamic_shifting:
pipeline.scheduler = FlowMatchEulerDiscreteScheduler.from_config(
pipeline.scheduler.config,
use_dynamic_shifting=True,
shift_terminal=profile.scheduler_shift_terminal,
)
validate_ltx_checkpoint(
pipeline.scheduler.config,
expected_kind=expected_checkpoint_kind,
expected_kind=resolve_ltx_checkpoint_kind(pipeline.pipeline_kind),
pipeline_name=type(pipeline).__name__,
)
@@ -553,6 +713,8 @@ def load_transformer_config(
model_path: str,
subfolder: str = "transformer",
local_files_only: bool = True,
*,
revision: str | None = None,
) -> dict:
"""Load an LTX transformer config from a local model or the HF Hub."""
if local_files_only:
@@ -563,6 +725,7 @@ def load_transformer_config(
config_path = hf_hub_download(
repo_id=model_path,
filename=f"{subfolder}/config.json",
revision=revision,
)
with open(config_path) as config_file:
return json.load(config_file)
@@ -7,6 +7,7 @@ from __future__ import annotations
import math
from dataclasses import dataclass
from io import BytesIO
from typing import TYPE_CHECKING, Any
import numpy as np
@@ -52,19 +53,18 @@ def _preprocess_i2v_pil_images(
*,
height: int,
width: int,
crf: int = 0,
device: torch.device | None = None,
dtype: torch.dtype | None = None,
) -> torch.Tensor:
"""Match official LTX aspect-preserving resize and center crop."""
"""Match the version-specific official LTX PIL preprocessing."""
image_list = images if isinstance(images, list) else [images]
processed = []
for image in image_list:
pixels = (
torch.from_numpy(np.array(image.convert("RGB"), copy=True))
.permute(2, 0, 1)
.unsqueeze(0)
.to(device=device, dtype=torch.float32)
)
image_array = np.array(image.convert("RGB"), copy=True)
if crf:
image_array = _apply_image_conditioning_crf(image_array, crf)
pixels = torch.from_numpy(image_array).permute(2, 0, 1).unsqueeze(0).to(device=device, dtype=torch.float32)
source_height, source_width = pixels.shape[-2:]
scale = max(height / source_height, width / source_width)
resized_height = math.ceil(source_height * scale)
@@ -82,6 +82,47 @@ def _preprocess_i2v_pil_images(
return torch.cat(processed, dim=0)
def _apply_image_conditioning_crf(image: np.ndarray, crf: int) -> np.ndarray:
"""Round-trip one RGB frame through H.264 to match LTX-2.5 training."""
if image.dtype != np.uint8 or image.ndim != 3 or image.shape[-1] != 3:
raise ValueError("LTX image-conditioning CRF expects a uint8 RGB image.")
if min(image.shape[:2]) < 2:
return image
try:
import av
except ImportError as exc:
raise ImportError("PyAV with a libx264 encoder is required for LTX-2.5 image conditioning (CRF 18).") from exc
with BytesIO() as output_file:
container = av.open(output_file, "w", format="mp4")
try:
stream = container.add_stream("libx264", rate=1, options={"crf": str(crf), "preset": "veryfast"})
height = image.shape[0] // 2 * 2
width = image.shape[1] // 2 * 2
stream.height = height
stream.width = width
frame = av.VideoFrame.from_ndarray(image[:height, :width], format="rgb24").reformat(format="yuv420p")
container.mux(stream.encode(frame))
container.mux(stream.encode())
except Exception as exc:
raise RuntimeError(
"The installed PyAV/FFmpeg build cannot encode libx264 video required "
"for LTX-2.5 image conditioning (CRF 18)."
) from exc
finally:
container.close()
video_bytes = output_file.getvalue()
with BytesIO(video_bytes) as video_file:
container = av.open(video_file)
try:
stream = next(stream for stream in container.streams if stream.type == "video")
frame = next(container.decode(stream))
finally:
container.close()
return frame.to_ndarray(format="rgb24")
class LTXTextConditioningMixin:
"""Shared Gemma encoding and text connector orchestration."""
@@ -106,13 +147,30 @@ class LTXTextConditioningMixin:
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
text_inputs = self.tokenizer(
[text.strip() for text in prompt],
bos_token_id = self.tokenizer.bos_token_id
if bos_token_id is None:
raise ValueError("Tokenizer is missing bos_token_id; LTX prompt encoding requires a leading BOS.")
input_ids = []
for text in prompt:
encoded = self.tokenizer(
text.strip(),
padding=False,
truncation=True,
max_length=max_sequence_length,
return_tensors=None,
)
ids = encoded.input_ids
if not ids or ids[0] != bos_token_id:
ids = [bos_token_id, *ids][:max_sequence_length]
input_ids.append(ids)
text_inputs = self.tokenizer.pad(
{"input_ids": input_ids},
padding="max_length",
max_length=max_sequence_length,
truncation=True,
add_special_tokens=True,
return_tensors="pt",
return_attention_mask=True,
)
text_input_ids = text_inputs.input_ids.to(device)
prompt_attention_mask = text_inputs.attention_mask.to(device)
@@ -121,7 +179,6 @@ class LTXTextConditioningMixin:
attention_mask=prompt_attention_mask,
output_hidden_states=True,
).hidden_states
prompt_embeds = torch.stack(hidden_states, dim=-1).flatten(2, 3).to(dtype=dtype)
prompt_embeds = _repeat_prompt_tensor_for_outputs(prompt_embeds, num_videos_per_prompt)
prompt_attention_mask = prompt_attention_mask.view(batch_size, -1)
@@ -501,6 +558,7 @@ class LTXI2VConditioningMixin:
vae_temporal_compression_ratio=self.vae_temporal_compression_ratio,
)
mask_shape = (batch_size, 1, num_frames, height, width)
is_ltx25 = getattr(self, "model_version", None) == "2.5"
if latents is not None:
unpacked_latents = latents.ndim == 5
@@ -518,6 +576,7 @@ class LTXI2VConditioningMixin:
self.vae.latents_std,
self.vae.config.scaling_factor,
)
clean_latents = latents
if image is not None:
image_latents = self._encode_i2v_image_latents(
image,
@@ -525,14 +584,19 @@ class LTXI2VConditioningMixin:
generator=generator,
dtype=dtype,
)
# Official distilled Stage 2 starts from the upsampled Stage 1
# state, then reapplies the source image at final resolution.
latents = self._replace_first_latent_frame(latents, image_latents)
# Official Stage 2 starts from the upsampled Stage 1 state,
# then reapplies the source image at final resolution.
clean_latents = self._replace_first_latent_frame(clean_latents, image_latents)
latents = latent_ops.pack_latents(
latents,
self.transformer_spatial_patch_size,
self.transformer_temporal_patch_size,
)
clean_latents = latent_ops.pack_latents(
clean_latents,
self.transformer_spatial_patch_size,
self.transformer_temporal_patch_size,
)
else:
conditioning_mask = latents.new_zeros(mask_shape)
conditioning_mask[:, :, 0] = 1.0
@@ -548,14 +612,14 @@ class LTXI2VConditioningMixin:
f" {latents.shape}, but the expected shape is {conditioning_mask.shape + (num_channels_latents,)}."
)
if unpacked_latents:
# Official LTX patchifies the latent state before drawing noise.
# Sampling the packed shape preserves its seed-to-output contract.
latents = latent_ops.create_noised_state(
latents = latent_ops.create_conditioned_noised_state(
latents,
noise_scale * (1 - conditioning_mask).unsqueeze(-1),
clean_latents,
(1 - conditioning_mask.float()).unsqueeze(-1),
noise_scale,
generator,
)
elif image is not None:
elif not unpacked_latents and image is not None:
image_latents = self._encode_i2v_image_latents(
image,
batch_size=batch_size,
@@ -595,13 +659,27 @@ class LTXI2VConditioningMixin:
self.transformer_spatial_patch_size,
self.transformer_temporal_patch_size,
)
conditioning_mask = latent_ops.pack_latents(
packed_conditioning_mask = latent_ops.pack_latents(
conditioning_mask,
self.transformer_spatial_patch_size,
self.transformer_temporal_patch_size,
).squeeze(-1)
noise = randn_tensor(init_latents.shape, generator=generator, device=device, dtype=dtype)
latents = init_latents * conditioning_mask.unsqueeze(-1) + noise * (1 - conditioning_mask).unsqueeze(-1)
if is_ltx25:
clean_latents = init_latents
init_latents = torch.zeros_like(init_latents)
latents = latent_ops.create_conditioned_noised_state(
init_latents,
clean_latents,
(1 - packed_conditioning_mask.float()).unsqueeze(-1),
noise_scale,
generator=generator,
)
else:
noise = randn_tensor(init_latents.shape, generator=generator, device=device, dtype=dtype)
latents = init_latents * packed_conditioning_mask.unsqueeze(-1) + noise * (
1 - packed_conditioning_mask
).unsqueeze(-1)
conditioning_mask = packed_conditioning_mask
return latents, conditioning_mask
def _step_video_latents_i2v(
@@ -665,6 +743,17 @@ class LTXI2VConditioningMixin:
)
if image is not None:
default_crf = 18 if getattr(self, "model_version", "2") == "2.5" else 0
image_crf = getattr(request_inputs, "image_crf", None)
image_crf = default_crf if image_crf is None else int(image_crf)
is_pil_input = isinstance(image, PIL.Image.Image) or (
isinstance(image, list) and image and all(isinstance(item, PIL.Image.Image) for item in image)
)
if image_crf != 0 and not is_pil_input:
raise ValueError(
"`image_crf` re-compression requires PIL images. Pass PIL images, or set `image_crf=0` "
"to skip re-compression."
)
if isinstance(image, torch.Tensor):
if image.ndim == 3:
image = image.unsqueeze(0)
@@ -677,6 +766,7 @@ class LTXI2VConditioningMixin:
image,
height=request_inputs.height,
width=request_inputs.width,
crf=image_crf,
device=device,
dtype=prompt_context.positive_connector_prompt_embeds.dtype,
)
+142 -9
View File
@@ -42,6 +42,7 @@ class LTXForwardContext:
original_audio_num_frames: int
padded_audio_num_frames: int
timesteps: torch.Tensor
sampler: str
audio_scheduler: Any
video_audio_step_adapter: Any
@@ -88,6 +89,11 @@ class LTXDenoisePipeline(Protocol):
LTXDenoiseStep = Callable[[int, torch.Tensor, LTXAVState], LTXAVState]
LTX_ANCESTRAL_ETA = 1.0
LTX_ANCESTRAL_S_NOISE = 1.0
LTX_ANCESTRAL_NOISE_SEED_OFFSET = 10000
LTX_OFFICIAL_DEFAULT_SEED = 10
class LTXDenoiseExecutor:
"""Run the one shared LTX denoise loop.
@@ -138,6 +144,9 @@ class LTXVideoAudioStepAdapter:
latent_width: int,
*,
image_conditioned: bool,
sampler: str = "euler",
generator: torch.Generator | list[torch.Generator] | None = None,
conditioning_mask: torch.Tensor | None = None,
) -> None:
self._pipeline = pipeline
self._audio_scheduler = audio_scheduler
@@ -145,11 +154,27 @@ class LTXVideoAudioStepAdapter:
self._latent_height = latent_height
self._latent_width = latent_width
self._image_conditioned = image_conditioned
self._sampler = sampler
self._conditioning_mask = conditioning_mask
self._ancestral_generators = (
_make_ancestral_generators(generator, pipeline.device) if sampler == "euler_ancestral" else None
)
self._step_index = 0
def step(self, noise_pred, t, latents, return_dict=False, generator=None):
del t, return_dict, generator
if self._image_conditioned:
if self._sampler == "euler_ancestral":
video_out = _ancestral_euler_step_from_velocity(
latents[0],
noise_pred[0],
self._pipeline.scheduler.sigmas,
self._step_index,
self._ancestral_generators,
)
if self._conditioning_mask is not None:
mask = self._conditioning_mask.unsqueeze(-1).to(video_out.dtype)
video_out = torch.lerp(video_out, latents[0], mask)
elif self._image_conditioned:
video_out = self._pipeline._step_video_latents_i2v(
noise_pred[0],
latents[0],
@@ -165,17 +190,96 @@ class LTXVideoAudioStepAdapter:
self._pipeline.scheduler.sigmas,
self._step_index,
)
audio_out = euler_step_from_velocity(
latents[1],
noise_pred[1],
self._audio_scheduler.sigmas,
self._step_index,
)
if self._sampler == "euler_ancestral":
audio_out = _ancestral_euler_step_from_velocity(
latents[1],
noise_pred[1],
self._audio_scheduler.sigmas,
self._step_index,
self._ancestral_generators,
)
else:
audio_out = euler_step_from_velocity(
latents[1],
noise_pred[1],
self._audio_scheduler.sigmas,
self._step_index,
)
self._step_index += 1
return ((video_out, audio_out),)
def _official_ltx_sigmas(scheduler: Any, steps: int, device: torch.device) -> torch.Tensor:
def _make_ancestral_generators(
generator: torch.Generator | list[torch.Generator] | None,
device: torch.device,
) -> torch.Generator | list[torch.Generator]:
"""Create the official independent ``seed + 10000`` noise stream."""
def _offset(source: torch.Generator | None) -> torch.Generator:
seed = LTX_OFFICIAL_DEFAULT_SEED if source is None else source.initial_seed()
return torch.Generator(device=device).manual_seed(seed + LTX_ANCESTRAL_NOISE_SEED_OFFSET)
if isinstance(generator, list):
return [_offset(item) for item in generator]
return _offset(generator)
def _randn_like_with_generators(
sample: torch.Tensor,
generators: torch.Generator | list[torch.Generator],
) -> torch.Tensor:
if not isinstance(generators, list):
return torch.randn(sample.shape, generator=generators, dtype=sample.dtype, device=sample.device)
if len(generators) != sample.shape[0]:
raise ValueError(
f"LTX ancestral sampling received {len(generators)} generators for batch size {sample.shape[0]}."
)
return torch.cat(
[
torch.randn((1, *sample.shape[1:]), generator=item, dtype=sample.dtype, device=sample.device)
for item in generators
]
)
def _ancestral_euler_step_from_velocity(
sample: torch.Tensor,
velocity: torch.Tensor,
sigmas: torch.Tensor,
step_index: int,
generators: torch.Generator | list[torch.Generator] | None,
) -> torch.Tensor:
"""Apply the official LTX-2.5 rectified-flow ancestral Euler step."""
sigma = sigmas[step_index].to(torch.float32)
sigma_next = sigmas[step_index + 1].to(torch.float32)
# Official X0Model materializes the denoised prediction in the model
# dtype before the ancestral step promotes it back to float32.
denoised_model_dtype = (sample.float() - velocity.float() * sigma).to(sample.dtype)
denoised = denoised_model_dtype.float()
if sigma_next == 0:
return denoised.to(sample.dtype)
if generators is None:
raise ValueError("LTX ancestral Euler sampling requires a noise generator.")
downstep_ratio = 1.0 + (sigma_next / sigma - 1.0) * LTX_ANCESTRAL_ETA
sigma_down = sigma_next * downstep_ratio
sigma_down_ratio = sigma_down / sigma
x_next = sigma_down_ratio * sample.float() + (1.0 - sigma_down_ratio) * denoised
alpha_next = 1.0 - sigma_next
alpha_down = 1.0 - sigma_down
renoise_coeff = (sigma_next**2 - sigma_down**2 * alpha_next**2 / alpha_down**2).clamp(min=0).sqrt()
noise = _randn_like_with_generators(sample, generators)
x_next = (alpha_next / alpha_down) * x_next + noise.float() * LTX_ANCESTRAL_S_NOISE * renoise_coeff
result = x_next.to(sample.dtype)
return result
def _official_ltx_sigmas(
scheduler: Any,
steps: int,
device: torch.device,
) -> torch.Tensor:
"""Build the official LTX one-stage sigma schedule in torch fp32."""
config = scheduler.config
base_anchor = config.get("base_image_seq_len", 1024)
@@ -185,7 +289,8 @@ def _official_ltx_sigmas(scheduler: Any, steps: int, device: torch.device) -> to
sigmas = torch.linspace(1.0, 0.0, steps + 1)
slope = (max_shift - base_shift) / (max_anchor - base_anchor)
# Official LTX2 one-stage intentionally uses the max sequence anchor, so the shift stays at max_shift.
# Official LTX one-stage pipelines omit the latent when constructing
# this schedule, so the shift stays at the max sequence anchor.
sigma_shift = max_anchor * slope + (base_shift - slope * base_anchor)
exp_shift = math.exp(sigma_shift)
sigmas = torch.where(sigmas != 0, exp_shift / (exp_shift + (1 / sigmas - 1)), 0)
@@ -224,6 +329,9 @@ def prepare_scheduler_stage(
latent_width: int,
use_official_sigma_schedule: bool,
image_conditioned: bool = False,
sampler: str = "euler",
generator: torch.Generator | list[torch.Generator] | None = None,
conditioning_mask: torch.Tensor | None = None,
) -> tuple[Any, Any, torch.Tensor]:
if sigmas is not None and timesteps is not None:
raise ValueError("Only one of `sigmas` or `timesteps` may be provided.")
@@ -236,6 +344,9 @@ def prepare_scheduler_stage(
latent_height,
latent_width,
image_conditioned=image_conditioned,
sampler=sampler,
generator=generator,
conditioning_mask=conditioning_mask,
)
if sigmas is not None:
scheduler_sigmas = torch.as_tensor(sigmas, dtype=torch.float32, device=device)
@@ -302,6 +413,20 @@ def prepare_rope_coords_stage(
return video_coords, audio_coords
def _first_frame_keyframes_mask(reference: torch.Tensor, latent_num_frames: int) -> torch.Tensor:
"""Mark the first causal latent frame, matching official LTX-2.5."""
if latent_num_frames <= 0:
raise ValueError(f"LTX latent frame count must be positive, got {latent_num_frames}.")
tokens_per_frame, remainder = divmod(reference.shape[1], latent_num_frames)
if remainder:
raise ValueError(
f"LTX video token count {reference.shape[1]} is not divisible by {latent_num_frames} latent frames."
)
mask = reference.new_zeros((reference.shape[0], reference.shape[1], 1))
mask[:, :tokens_per_frame] = 1
return mask
def build_transformer_kwargs(
pipeline: Any,
forward_ctx: LTXForwardContext,
@@ -317,9 +442,13 @@ def build_transformer_kwargs(
attention_kwargs: dict[str, Any] | None = None,
) -> dict[str, Any]:
del encoder_attention_mask, audio_encoder_attention_mask
keyframes_mask = None
if getattr(pipeline.transformer.config, "use_keyframes_abs_pos_embedding", False):
keyframes_mask = _first_frame_keyframes_mask(hidden_states, forward_ctx.latent_num_frames)
return {
"hidden_states": hidden_states,
"audio_hidden_states": audio_hidden_states,
"keyframes_mask": keyframes_mask,
"encoder_hidden_states": encoder_hidden_states,
"audio_encoder_hidden_states": audio_encoder_hidden_states,
**pipeline._denoise_timestep_kwargs(
@@ -426,6 +555,9 @@ class LTXPhaseExecutor:
latent_width=latent_width,
use_official_sigma_schedule=phase_recipe.use_official_sigma_schedule,
image_conditioned=conditioning_mask is not None,
sampler=phase_recipe.sampler,
generator=request_inputs.generator,
conditioning_mask=conditioning_mask,
)
forward_ctx = LTXForwardContext(
req=req,
@@ -441,6 +573,7 @@ class LTXPhaseExecutor:
original_audio_num_frames=original_audio_num_frames,
padded_audio_num_frames=padded_audio_num_frames,
timesteps=timesteps_tensor,
sampler=phase_recipe.sampler,
audio_scheduler=audio_scheduler,
video_audio_step_adapter=video_audio_step_adapter,
)
@@ -126,9 +126,9 @@ def x0_from_velocity(sample: torch.Tensor, velocity: torch.Tensor, sigma: torch.
def velocity_from_x0(sample: torch.Tensor, x0: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:
"""Convert x0 back to velocity using the official fp32 arithmetic order."""
# Official LTX converts the scalar scheduler sigma to a host value before
# division. A CUDA scalar tensor selects different kernel arithmetic and
# can cross bf16 rounding boundaries late in the denoise trajectory.
# Official LTX materializes the scalar schedule value on the host before
# dividing. CUDA tensor-scalar division can cross bfloat16 rounding bounds
# even when the scalar has the same float32 value.
sigma = sigma.to(torch.float32).item()
return ((sample.to(torch.float32) - x0.to(torch.float32)) / sigma).to(sample.dtype)
@@ -305,10 +305,17 @@ class LTXGuidanceExecutor:
ts: torch.Tensor,
video_token_count: int,
audio_token_count: int,
*,
expand_for_sequence_parallel: bool = False,
) -> dict[str, torch.Tensor]:
timestep = ts
audio_timestep = ts
if expand_for_sequence_parallel:
timestep = ts.reshape(-1, 1).expand(-1, video_token_count)
audio_timestep = ts.reshape(-1, 1).expand(-1, audio_token_count)
return {
"timestep": ts.reshape(-1, 1).expand(-1, video_token_count),
"audio_timestep": ts.reshape(-1, 1).expand(-1, audio_token_count),
"timestep": timestep,
"audio_timestep": audio_timestep,
"sigma": ts,
"audio_sigma": ts,
}
@@ -342,8 +349,11 @@ class LTXGuidanceExecutor:
guidance: LTXModalityGuidance,
*,
model_sigma: torch.Tensor | None = None,
preserve_positive_velocity: bool = False,
rescale_token_count: int | None = None,
) -> torch.Tensor:
if preserve_positive_velocity and tuple(splits) == ("cond",):
return splits["cond"]
model_sigma = sigma if model_sigma is None else model_sigma
# Official guidance reduces contiguous BSC tensors. The fused
# transformer output may be channel-major after splitting, which
@@ -368,6 +378,7 @@ class LTXGuidanceExecutor:
state: LTXAVState,
forward_ctx: LTXForwardContext,
denoise_ctx: LTXDenoiseContext,
preserve_positive_velocity: bool = False,
) -> tuple[torch.Tensor, torch.Tensor]:
guidance_world_size = get_guidance_parallel_world_size()
self.validate_guidance_world_size(plan, guidance_world_size)
@@ -450,12 +461,14 @@ class LTXGuidanceExecutor:
video_sigma,
plan.spec.video,
model_sigma=pipeline._video_guidance_model_sigma(video_sigma, denoise_ctx),
preserve_positive_velocity=preserve_positive_velocity,
),
self._guide_modality(
state.audio,
audio_splits,
forward_ctx.audio_scheduler.sigmas[index],
plan.spec.audio,
preserve_positive_velocity=preserve_positive_velocity,
rescale_token_count=forward_ctx.original_audio_num_frames,
),
)
@@ -469,9 +482,19 @@ class LTXGuidanceExecutor:
state: LTXAVState,
forward_ctx: LTXForwardContext,
denoise_ctx: LTXDenoiseContext,
preserve_positive_velocity: bool = False,
) -> tuple[torch.Tensor, torch.Tensor]:
if forward_ctx.guidance_parallel_ready:
return self.predict_parallel_guidance(pipeline, plan, index, timestep, state, forward_ctx, denoise_ctx)
return self.predict_parallel_guidance(
pipeline,
plan,
index,
timestep,
state,
forward_ctx,
denoise_ctx,
preserve_positive_velocity=preserve_positive_velocity,
)
prompt = forward_ctx.prompt_context
video_contexts: list[torch.Tensor] = []
@@ -526,12 +549,14 @@ class LTXGuidanceExecutor:
pipeline.scheduler.sigmas[index],
denoise_ctx,
),
preserve_positive_velocity=preserve_positive_velocity,
),
self._guide_modality(
state.audio,
audio_splits,
forward_ctx.audio_scheduler.sigmas[index],
plan.spec.audio,
preserve_positive_velocity=preserve_positive_velocity,
rescale_token_count=forward_ctx.original_audio_num_frames,
),
)
+26 -10
View File
@@ -20,6 +20,11 @@ class LTXAVState:
audio: torch.Tensor
def official_video_token_layout(latents: torch.Tensor) -> torch.Tensor:
"""Match the token-major view produced by the official LTX patchifier."""
return latents.transpose(1, 2).contiguous().transpose(1, 2)
def pack_latents(
latents: torch.Tensor,
patch_size: int = 1,
@@ -117,9 +122,23 @@ def create_noised_state(
device=latents.device,
dtype=latents.dtype,
)
if isinstance(noise_scale, torch.Tensor):
noise_scale = noise_scale.float()
return torch.lerp(latents.float(), noise.float(), noise_scale).to(latents.dtype)
# Official GaussianNoisier blends in fp32, then materializes the next
# latent state in the model dtype. Batched request weights may arrive in
# the model dtype, so promote tensor weights alongside both endpoints.
lerp_weight = noise_scale.float() if isinstance(noise_scale, torch.Tensor) else noise_scale
return torch.lerp(latents.float(), noise.float(), lerp_weight).to(latents.dtype)
def create_conditioned_noised_state(
latents: torch.Tensor,
clean_latents: torch.Tensor,
denoise_mask: torch.Tensor,
noise_scale: float | torch.Tensor,
generator: torch.Generator | list[torch.Generator] | None = None,
) -> torch.Tensor:
"""Match the official conditioned Gaussian noisier operation order."""
noised_latents = create_noised_state(latents, noise_scale, generator)
return torch.lerp(clean_latents.float(), noised_latents.float(), denoise_mask.float()).to(latents.dtype)
def pack_audio_latents(latents: torch.Tensor) -> torch.Tensor:
@@ -138,7 +157,7 @@ def unpad_audio_latents(latents: torch.Tensor, num_frames: int) -> torch.Tensor:
def clear_audio_padding(latents: torch.Tensor, num_frames: int) -> torch.Tensor:
"""Keep Omni's SP-only audio padding outside the sampler state."""
"""Keep SP-only audio padding outside the logical sampler state."""
if not 0 < num_frames <= latents.shape[1]:
raise ValueError(f"Audio frame count must be in [1, {latents.shape[1]}], got {num_frames}.")
if num_frames == latents.shape[1]:
@@ -196,7 +215,8 @@ def prepare_video_latents(
)
if latents.ndim != 3:
raise ValueError(f"Provided `latents` has shape {latents.shape}, expected [batch, seq, features].")
return create_noised_state(latents, noise_scale, generator).to(device=device, dtype=dtype)
latents = create_noised_state(latents, noise_scale, generator).to(device=device, dtype=dtype)
return official_video_token_layout(latents)
num_frames, height, width = resolve_video_latent_shape(
height,
@@ -218,11 +238,7 @@ def prepare_video_latents(
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
)
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
# Official LTX samples the 5D video latent first and then patchifies it,
# leaving token-major storage behind the [B, tokens, channels] view. The
# logical values are unchanged, but preserving that layout is important:
# CUDA selects a different bf16 GEMM path for a contiguous token tensor.
return latents.transpose(1, 2).contiguous().transpose(1, 2)
return official_video_token_layout(latents)
def prepare_audio_latents(
+101 -1
View File
@@ -3,7 +3,7 @@
"""Declarative execution recipes for the LTX model family."""
from dataclasses import dataclass
from dataclasses import dataclass, replace
from typing import Literal
from .ltx2_guidance import LTXGuidanceSpec, LTXModalityGuidance
@@ -22,6 +22,11 @@ LTX_DEFAULT_NEGATIVE_PROMPT = (
"inconsistent tone, cinematic oversaturation, stylized filters, or AI artifacts."
)
LTX25_DEFAULT_NEGATIVE_PROMPT = (
"has_subtitles, has_blurbox, transition from black, transition to black, speech_ending_short, "
+ LTX_DEFAULT_NEGATIVE_PROMPT
)
LTX_DISTILLED_SIGMAS = (1.0, 0.99375, 0.9875, 0.98125, 0.975, 0.909375, 0.725, 0.421875, 0.0)
LTX_STAGE_2_DISTILLED_SIGMAS = (0.909375, 0.725, 0.421875, 0.0)
LTX_DISTILLED_ADAPTER_SLOT = "ltx_distilled"
@@ -38,6 +43,7 @@ class LTXPhaseRecipe:
noise_scale: float = 0.0
input_transform: Literal["initial", "spatial_upsample"] = "initial"
adapter_slot: str | None = None
sampler: Literal["euler", "euler_ancestral"] = "euler"
allow_guidance_override: bool = True
use_official_sigma_schedule: bool = True
@@ -46,6 +52,8 @@ class LTXPhaseRecipe:
raise ValueError("LTX phase spatial_downscale must be positive.")
if self.sigmas is not None and len(self.sigmas) < 2:
raise ValueError("An explicit LTX sigma schedule must contain at least two denoise sigmas.")
if self.sampler not in ("euler", "euler_ancestral"):
raise ValueError(f"Unsupported LTX sampler: {self.sampler!r}.")
@property
def num_inference_steps(self) -> int | None:
@@ -66,9 +74,11 @@ class LTXPipelineRecipe:
video_output_phase: int = -1
audio_output_phase: int = -1
allow_request_sigmas: bool = True
allow_request_phase_sigmas: bool = False
allow_request_latents: bool = True
allow_negative_prompt: bool = True
fixed_num_inference_steps: bool = False
supports_cache_dit: bool = False
def __post_init__(self) -> None:
if not self.phases:
@@ -109,13 +119,29 @@ def _official_guidance(stg_block: int) -> LTXGuidanceSpec:
LTX2_ONE_STAGE_RECIPE = LTXPipelineRecipe(
supports_cache_dit=True,
phases=(LTXPhaseRecipe(name="generate", guidance=_official_guidance(29)),),
)
LTX23_ONE_STAGE_RECIPE = LTXPipelineRecipe(
supports_cache_dit=True,
num_inference_steps=30,
phases=(LTXPhaseRecipe(name="generate", guidance=_official_guidance(28)),),
)
LTX25_FULL_RECIPE = LTXPipelineRecipe(
height=544,
width=960,
num_inference_steps=30,
negative_prompt=LTX25_DEFAULT_NEGATIVE_PROMPT,
phases=(
LTXPhaseRecipe(
name="generate",
guidance=_official_guidance(28),
noise_scale=1.0,
),
),
)
LTX_POSITIVE_ONLY_RECIPE = LTXPipelineRecipe(
supports_cache_dit=True,
phases=(
LTXPhaseRecipe(
name="generate",
@@ -159,6 +185,41 @@ LTX2_DISTILLED_TWO_STAGE_RECIPE = LTXPipelineRecipe(
fixed_num_inference_steps=True,
)
LTX25_DISTILLED_TWO_STAGE_RECIPE = LTXPipelineRecipe(
height=1088,
width=1920,
num_inference_steps=len(LTX_DISTILLED_SIGMAS) - 1,
negative_prompt="",
phases=(
LTXPhaseRecipe(
name="generate_lowres",
guidance=LTXGuidanceSpec.positive_only(),
spatial_downscale=2,
sigmas=LTX_DISTILLED_SIGMAS,
noise_scale=1.0,
allow_guidance_override=False,
use_official_sigma_schedule=False,
sampler="euler_ancestral",
),
LTXPhaseRecipe(
name="refine",
guidance=LTXGuidanceSpec.positive_only(),
sigmas=LTX_STAGE_2_DISTILLED_SIGMAS,
noise_scale=LTX_STAGE_2_DISTILLED_SIGMAS[0],
input_transform="spatial_upsample",
allow_guidance_override=False,
use_official_sigma_schedule=False,
),
),
video_output_phase=1,
audio_output_phase=1,
allow_request_sigmas=False,
allow_request_phase_sigmas=True,
allow_request_latents=False,
allow_negative_prompt=False,
fixed_num_inference_steps=True,
)
# LTX-2.3 full-distilled uses the same official fixed 8 + 3 sigma schedules
# and request contract. Its distinct component profile selects the 22B merged
# distilled Transformer, BWE vocoder, and matching spatial upsampler; no
@@ -166,6 +227,37 @@ LTX2_DISTILLED_TWO_STAGE_RECIPE = LTXPipelineRecipe(
LTX23_DISTILLED_TWO_STAGE_RECIPE = LTX2_DISTILLED_TWO_STAGE_RECIPE
def _distilled_one_stage_recipe(
two_stage_recipe: LTXPipelineRecipe,
*,
supports_cache_dit: bool = True,
) -> LTXPipelineRecipe:
"""Run the merged-distilled checkpoint at its native Stage-1 resolution."""
generate_phase = replace(
two_stage_recipe.phases[0],
name="generate",
spatial_downscale=1,
)
return replace(
two_stage_recipe,
height=two_stage_recipe.height // 2,
width=two_stage_recipe.width // 2,
phases=(generate_phase,),
video_output_phase=0,
audio_output_phase=0,
allow_request_phase_sigmas=False,
supports_cache_dit=supports_cache_dit,
)
LTX2_DISTILLED_ONE_STAGE_RECIPE = _distilled_one_stage_recipe(LTX2_DISTILLED_TWO_STAGE_RECIPE)
LTX23_DISTILLED_ONE_STAGE_RECIPE = _distilled_one_stage_recipe(LTX23_DISTILLED_TWO_STAGE_RECIPE)
LTX25_DISTILLED_ONE_STAGE_RECIPE = _distilled_one_stage_recipe(
LTX25_DISTILLED_TWO_STAGE_RECIPE,
supports_cache_dit=False,
)
def _official_two_stage_recipe(one_stage_recipe: LTXPipelineRecipe) -> LTXPipelineRecipe:
return LTXPipelineRecipe(
height=one_stage_recipe.height * 2,
@@ -197,21 +289,29 @@ def _official_two_stage_recipe(one_stage_recipe: LTXPipelineRecipe) -> LTXPipeli
# discards its audio result. Decode the full-context Stage-1 audio.
audio_output_phase=0,
allow_request_sigmas=False,
allow_request_phase_sigmas=True,
allow_request_latents=False,
)
LTX2_TWO_STAGE_RECIPE = _official_two_stage_recipe(LTX2_ONE_STAGE_RECIPE)
LTX23_TWO_STAGE_RECIPE = _official_two_stage_recipe(LTX23_ONE_STAGE_RECIPE)
LTX25_TWO_STAGE_RECIPE = _official_two_stage_recipe(LTX25_FULL_RECIPE)
_PIPELINE_RECIPES: dict[tuple[str, str], LTXPipelineRecipe] = {
("one_stage", "2"): LTX2_ONE_STAGE_RECIPE,
("one_stage", "2.3"): LTX23_ONE_STAGE_RECIPE,
("one_stage", "2.5"): LTX25_FULL_RECIPE,
("two_stage", "2"): LTX2_TWO_STAGE_RECIPE,
("two_stage", "2.3"): LTX23_TWO_STAGE_RECIPE,
("two_stage", "2.5"): LTX25_TWO_STAGE_RECIPE,
("distilled_one_stage", "2"): LTX2_DISTILLED_ONE_STAGE_RECIPE,
("distilled_one_stage", "2.3"): LTX23_DISTILLED_ONE_STAGE_RECIPE,
("distilled_one_stage", "2.5"): LTX25_DISTILLED_ONE_STAGE_RECIPE,
("distilled_two_stage", "2"): LTX2_DISTILLED_TWO_STAGE_RECIPE,
("distilled_two_stage", "2.3"): LTX23_DISTILLED_TWO_STAGE_RECIPE,
("distilled_two_stage", "2.5"): LTX25_DISTILLED_TWO_STAGE_RECIPE,
("dmd2", "2"): LTX_POSITIVE_ONLY_RECIPE,
("dmd2", "2.3"): LTX_POSITIVE_ONLY_RECIPE,
}
@@ -43,6 +43,7 @@ class LTXRequestInputs:
output_type: str
max_sequence_length: int
audio_latents_normalized: bool = False
image_crf: int | None = None
@property
def guidance_scale(self) -> float:
@@ -86,6 +87,7 @@ def validate_pipeline_request(
vae_temporal_compression_ratio: int,
pipeline_name: str,
request_sigmas: list[float] | None = None,
request_phase_sigmas: tuple[list[float] | None, ...] | None = None,
) -> None:
"""Validate the request capabilities declared by an execution recipe."""
alignment = vae_spatial_compression_ratio * pipeline_recipe.max_spatial_downscale
@@ -108,9 +110,28 @@ def validate_pipeline_request(
if not pipeline_recipe.allow_request_sigmas and request_sigmas is not None:
raise ValueError(f"{pipeline_name} uses fixed phase sigma schedules.")
if request_sigmas is not None and len(request_sigmas) < 2:
raise ValueError("A custom LTX sigma schedule must contain at least two values.")
if pipeline_recipe.fixed_num_inference_steps and (
request_inputs.num_inference_steps != pipeline_recipe.num_inference_steps
has_phase_sigmas = request_phase_sigmas is not None and any(item is not None for item in request_phase_sigmas)
if request_sigmas is not None and has_phase_sigmas:
raise ValueError("Use either `sigmas` or per-stage sigma schedules, not both.")
if has_phase_sigmas and not pipeline_recipe.allow_request_phase_sigmas:
raise ValueError(f"{pipeline_name} does not accept per-stage sigma schedules.")
if request_phase_sigmas is not None and len(request_phase_sigmas) != len(pipeline_recipe.phases):
raise ValueError(
f"{pipeline_name} has {len(pipeline_recipe.phases)} phases but received "
f"{len(request_phase_sigmas)} per-stage sigma schedules."
)
for index, phase_sigmas in enumerate(request_phase_sigmas or ()):
if phase_sigmas is not None and len(phase_sigmas) < 2:
raise ValueError(f"`stage_{index + 1}_sigmas` must contain at least two values.")
if (
request_sigmas is None
and (request_phase_sigmas is None or request_phase_sigmas[0] is None)
and pipeline_recipe.fixed_num_inference_steps
and (request_inputs.num_inference_steps != pipeline_recipe.num_inference_steps)
):
raise ValueError(
f"{pipeline_name} uses {pipeline_recipe.num_inference_steps} fixed Stage 1 denoise steps; "
@@ -165,6 +186,16 @@ def _get_extra_arg(sampling: Any, *names: str) -> Any:
return None
def _normalize_image_crf(value: Any) -> int | None:
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError("`image_crf` must be an integer from 0 through 51.")
if not 0 <= value <= 51:
raise ValueError("`image_crf` must be an integer from 0 through 51.")
return value
def _normalize_stg_blocks(value: Any, default: tuple[int, ...]) -> tuple[int, ...]:
if value is None:
return default
@@ -274,6 +305,7 @@ class LTXRequestMixin:
req: DiffusionRequestBatch,
*,
image: Any | None = None,
image_crf: int | None = None,
prompt: str | list[str] | None = None,
negative_prompt: str | list[str] | None = None,
height: int | None = None,
@@ -282,6 +314,8 @@ class LTXRequestMixin:
frame_rate: float | None = None,
num_inference_steps: int | None = None,
sigmas: list[float] | None = None,
stage_1_sigmas: list[float] | None = None,
stage_2_sigmas: list[float] | None = None,
timesteps: list[int] | None = None,
guidance_scale: float | None = None,
guidance_rescale: float | None = None,
@@ -315,6 +349,7 @@ class LTXRequestMixin:
return self._forward_request(
req,
image=image,
image_crf=image_crf,
prompt=prompt,
negative_prompt=negative_prompt,
height=height,
@@ -323,6 +358,8 @@ class LTXRequestMixin:
frame_rate=frame_rate,
num_inference_steps=num_inference_steps,
sigmas=sigmas,
stage_1_sigmas=stage_1_sigmas,
stage_2_sigmas=stage_2_sigmas,
guidance_scale=guidance_scale,
num_videos_per_prompt=num_videos_per_prompt,
generator=generator,
@@ -343,12 +380,30 @@ class LTXRequestMixin:
req: DiffusionRequestBatch,
fallback: list[float] | None,
) -> list[float] | None:
request_sigmas = [sampling.sigmas for sampling in req.sampling_params_list]
request_sigmas = [
sampling.sigmas if sampling.sigmas is not None else _get_extra_arg(sampling, "sigmas")
for sampling in req.sampling_params_list
]
first = request_sigmas[0] if request_sigmas else None
if any(item != first for item in request_sigmas[1:]):
raise ValueError("Batched LTX requests must use identical custom sigmas.")
return first if first is not None else fallback
@staticmethod
def _resolve_request_phase_sigmas(
req: DiffusionRequestBatch,
stage_1_fallback: list[float] | None,
stage_2_fallback: list[float] | None,
) -> tuple[list[float] | None, list[float] | None] | None:
resolved: list[list[float] | None] = []
for name, fallback in (("stage_1_sigmas", stage_1_fallback), ("stage_2_sigmas", stage_2_fallback)):
values = [_get_extra_arg(sampling, name) for sampling in req.sampling_params_list]
first = values[0] if values else None
if any(item != first for item in values[1:]):
raise ValueError(f"Batched LTX requests must use identical `{name}` values.")
resolved.append(first if first is not None else fallback)
return tuple(resolved) if any(item is not None for item in resolved) else None
def check_inputs(
self,
prompt: str | list[str] | None,
@@ -408,6 +463,7 @@ class LTXRequestMixin:
decode_noise_scale: float | list[float] | None,
output_type: str,
max_sequence_length: int | None,
image_crf: int | None = None,
) -> LTXRequestInputs:
sampling_params_list = req.sampling_params_list
for sampling in sampling_params_list:
@@ -421,6 +477,12 @@ class LTXRequestMixin:
if _get_extra_arg(sampling, "flow_shift") is not None:
raise ValueError("LTX does not support `flow_shift`; use `sigmas` for a custom schedule.")
request_image_crfs = [_get_extra_arg(item, "image_crf") for item in sampling_params_list]
first_image_crf = request_image_crfs[0] if request_image_crfs else None
if any(item != first_image_crf for item in request_image_crfs[1:]):
raise ValueError("Batched LTX requests must use identical `image_crf` values.")
image_crf = _normalize_image_crf(first_image_crf if first_image_crf is not None else image_crf)
sampling = sampling_params_list[0]
is_dummy_run = req.is_dummy_run()
prompt = [item if isinstance(item, str) else (item.get("prompt") or "") for item in req.prompts] or prompt
@@ -551,4 +613,5 @@ class LTXRequestMixin:
decode_noise_scale=decode_noise_scale,
output_type=output_type,
max_sequence_length=int(max_sequence_length),
image_crf=image_crf,
)
+44 -11
View File
@@ -144,20 +144,19 @@ class LTXRuntime(
f"{self.__class__.__name__} does not support ulysses_mode='advanced_uaa'. "
"Use the default ulysses_mode='strict' for LTX sequence parallelism."
)
self.model_version = detect_ltx_model_version(od_config.model)
self.model_version = detect_ltx_model_version(od_config.model, revision=getattr(od_config, "revision", None))
self.component_profile = resolve_ltx_component_profile(self.pipeline_kind, self.model_version)
self.pipeline_recipe = resolve_ltx_pipeline_recipe(self.pipeline_kind, self.model_version)
if getattr(od_config, "cache_backend", "none") == "cache_dit" and len(self.pipeline_recipe.phases) > 1:
if getattr(od_config, "cache_backend", "none") == "cache_dit" and not self.pipeline_recipe.supports_cache_dit:
raise ValueError(
f"{self.__class__.__name__} does not support cache_backend='cache_dit'. "
"Cache-DiT currently supports only one-stage LTX recipes; multi-stage recipes require "
"phase-aware cache enable and refresh."
"Cache-DiT is not qualified for this LTX recipe."
)
self._dit_modules = list(self.component_profile.dit_modules)
self._encoder_modules = list(self.component_profile.encoder_modules)
self._vae_modules = list(self.component_profile.vae_modules)
self._resident_modules = list(self.component_profile.resident_modules)
if self.model_version == "2.3":
if self.model_version in ("2.3", "2.5"):
self.preserve_sp_padded_audio_duration = True
self.reports_stage_durations = True
super().__init__()
@@ -173,6 +172,7 @@ class LTXRuntime(
req: DiffusionRequestBatch,
*,
image: Any | None = None,
image_crf: int | None = None,
prompt: str | list[str] | None = None,
negative_prompt: str | list[str] | None = None,
height: int | None = None,
@@ -181,6 +181,8 @@ class LTXRuntime(
frame_rate: float | None = None,
num_inference_steps: int | None = None,
sigmas: list[float] | None = None,
stage_1_sigmas: list[float] | None = None,
stage_2_sigmas: list[float] | None = None,
guidance_scale: float | None = None,
num_videos_per_prompt: int | None = 1,
generator: torch.Generator | list[torch.Generator] | None = None,
@@ -217,11 +219,13 @@ class LTXRuntime(
decode_noise_scale=decode_noise_scale,
output_type=output_type,
max_sequence_length=max_sequence_length,
image_crf=image_crf,
)
image = self._resolve_request_image(req, image, request_inputs)
if image is not None and not self.support_image_input:
raise ValueError(f"{self.__class__.__name__} does not support `image` input.")
request_sigmas = self._resolve_request_sigmas(req, sigmas)
request_phase_sigmas = self._resolve_request_phase_sigmas(req, stage_1_sigmas, stage_2_sigmas)
validate_pipeline_request(
request_inputs,
pipeline_recipe=self.pipeline_recipe,
@@ -229,6 +233,7 @@ class LTXRuntime(
vae_temporal_compression_ratio=self.vae_temporal_compression_ratio,
pipeline_name=self.__class__.__name__,
request_sigmas=request_sigmas,
request_phase_sigmas=request_phase_sigmas,
)
phase_adapter = getattr(self, "_phase_adapter", None)
if phase_adapter is not None and any(
@@ -237,7 +242,13 @@ class LTXRuntime(
raise ValueError(
f"{self.__class__.__name__} cannot compose a request LoRA with its internal phase adapter."
)
return self._run_recipe(req, request_inputs, request_sigmas=request_sigmas, image=image)
return self._run_recipe(
req,
request_inputs,
request_sigmas=request_sigmas,
request_phase_sigmas=request_phase_sigmas,
image=image,
)
def _run_recipe(
self,
@@ -245,24 +256,39 @@ class LTXRuntime(
request_inputs: LTXRequestInputs,
*,
request_sigmas: list[float] | None,
request_phase_sigmas: tuple[list[float] | None, ...] | None = None,
image: Any | None = None,
) -> DiffusionOutput | list[DiffusionOutput]:
"""Execute one- and multi-phase recipes through the same control flow."""
phase_results: list[LTXPhaseResult] = []
prompt_context = None
for phase_recipe in self.pipeline_recipe.phases:
for phase_index, phase_recipe in enumerate(self.pipeline_recipe.phases):
override_sigmas = None if request_phase_sigmas is None else request_phase_sigmas[phase_index]
phase_sigmas = (
override_sigmas
if override_sigmas is not None
else (
request_sigmas
if request_sigmas is not None
else (list(phase_recipe.sigmas) if phase_recipe.sigmas is not None else None)
)
)
self._enter_phase(phase_recipe)
phase_inputs = self._build_phase_inputs(
request_inputs,
phase_recipe,
phase_results[-1] if phase_results else None,
)
if phase_sigmas is not None:
phase_inputs = replace(phase_inputs, num_inference_steps=len(phase_sigmas) - 1)
noise_scale = phase_recipe.noise_scale
if override_sigmas is not None and phase_recipe.input_transform == "spatial_upsample":
noise_scale = float(override_sigmas[0])
phase_result = self.run_phase(
req,
phase_inputs,
noise_scale=phase_recipe.noise_scale,
sigmas=list(phase_recipe.sigmas) if phase_recipe.sigmas is not None else request_sigmas,
noise_scale=noise_scale,
sigmas=phase_sigmas,
timesteps=None,
attention_kwargs=None,
phase_recipe=phase_recipe,
@@ -282,6 +308,7 @@ class LTXRuntime(
def _enter_phase(self, phase: LTXPhaseRecipe) -> None:
self._active_phase_name = phase.name
self._guidance_plan = LTXGuidancePlan.build(phase.guidance)
phase_adapter = getattr(self, "_phase_adapter", None)
if phase_adapter is None:
if phase.adapter_slot is not None:
@@ -645,7 +672,12 @@ class LTXRuntime(
audio_token_count: int,
) -> dict[str, torch.Tensor]:
del forward_ctx, denoise_ctx
return self.guidance_executor.timestep_kwargs(ts, video_token_count, audio_token_count)
return self.guidance_executor.timestep_kwargs(
ts,
video_token_count,
audio_token_count,
expand_for_sequence_parallel=True,
)
def _video_guidance_model_sigma(
self,
@@ -700,6 +732,7 @@ class LTXRuntime(
state,
forward_ctx,
denoise_ctx,
preserve_positive_velocity=forward_ctx.sampler == "euler_ancestral",
)
def _denoise_step(
@@ -55,6 +55,18 @@ logger = init_logger(__name__)
_RMSNORM_INIT_PARAMS = inspect.signature(RMSNorm.__init__).parameters
def apply_keyframes_absolute_embedding(
hidden_states: torch.Tensor,
keyframes_mask: torch.Tensor | None,
embedding: torch.Tensor | None,
) -> torch.Tensor:
"""Add the official learned marker to first-frame/keyframe tokens."""
if keyframes_mask is None or embedding is None:
return hidden_states
mask = (keyframes_mask > 0).to(dtype=hidden_states.dtype)
return hidden_states + mask * embedding.to(device=hidden_states.device, dtype=hidden_states.dtype)
def _make_rms_norm(hidden_size: int, *, eps: float, elementwise_affine: bool) -> nn.Module:
"""Bridge diffusers' RMSNorm API onto vLLM's `has_weight` variant."""
if not elementwise_affine:
@@ -82,15 +94,10 @@ def _make_rms_norm(hidden_size: int, *, eps: float, elementwise_affine: bool) ->
def apply_interleaved_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
cos, sin = freqs
if cos.dtype != x.dtype:
cos = cos.to(dtype=x.dtype)
if sin.dtype != x.dtype:
sin = sin.to(dtype=x.dtype)
# Concrete pair count instead of -1 keeps SDPA shape static under torch.compile.
x_real, x_imag = x.unflatten(2, (x.shape[2] // 2, 2)).unbind(-1) # [B, S, C // 2]
x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(2)
out = x * cos + x_rotated * sin
return out
return x * cos + x_rotated * sin
def apply_split_rotary_emb(
@@ -101,12 +108,6 @@ def apply_split_rotary_emb(
) -> torch.Tensor:
# `head_dim` is plumbed in (not inferred via `-1`) so SDPA shape stays static under torch.compile.
cos, sin = freqs
if cos.dtype != x.dtype:
cos = cos.to(dtype=x.dtype)
if sin.dtype != x.dtype:
sin = sin.to(dtype=x.dtype)
x_dtype = x.dtype
needs_reshape = False
if x.ndim != 4 and cos.ndim == 4:
# cos is (#b, h, t, r) -> reshape x to (b, h, t, dim_per_head)
@@ -142,7 +143,6 @@ def apply_split_rotary_emb(
if needs_reshape:
out = out.swapaxes(1, 2).reshape(b, t, h * head_dim)
out = out.to(dtype=x_dtype)
return out
@@ -269,6 +269,7 @@ class LTX2FeedForward(nn.Module):
RowParallelLinear(
inner_dim,
dim_out,
bias=bias,
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
@@ -517,8 +518,8 @@ class LTX2AudioVideoAttnProcessor:
is_self_attention=is_self_attention,
)
query = attn.norm_q(query)
key = attn.norm_k(key)
query = attn.norm_q(query).to(dtype=value.dtype)
key = attn.norm_k(key).to(dtype=value.dtype)
if query_rotary_emb is not None:
query_rotary_emb = self._slice_rope_for_tp(query_rotary_emb, attn)
@@ -537,6 +538,10 @@ class LTX2AudioVideoAttnProcessor:
head_dim=attn.head_dim,
)
# Keep FP32 RoPE computation while satisfying attention dtype contracts.
query = query.to(dtype=value.dtype)
key = key.to(dtype=value.dtype)
query = query.unflatten(2, (attn.heads, attn.head_dim))
key = key.unflatten(2, (attn.heads, attn.head_dim))
value_heads = value.unflatten(2, (attn.heads, attn.head_dim))
@@ -846,6 +851,8 @@ class LTX2VideoTransformerBlock(nn.Module):
elementwise_affine: bool = False,
rope_type: str = "interleaved",
perturbed_attn: bool = False,
ff_bias: bool = True,
audio_ff_bias: bool = True,
quant_config: "QuantizationConfig | None" = None,
prefix: str = "",
):
@@ -965,6 +972,7 @@ class LTX2VideoTransformerBlock(nn.Module):
self.ff = LTX2FeedForward(
dim,
activation_fn=activation_fn,
bias=ff_bias,
quant_config=quant_config,
prefix=f"{prefix}.ff" if prefix else "ff",
)
@@ -973,6 +981,7 @@ class LTX2VideoTransformerBlock(nn.Module):
self.audio_ff = LTX2FeedForward(
audio_dim,
activation_fn=activation_fn,
bias=audio_ff_bias,
quant_config=quant_config,
prefix=f"{prefix}.audio_ff" if prefix else "audio_ff",
)
@@ -1078,21 +1087,34 @@ class LTX2VideoTransformerBlock(nn.Module):
audio_hidden_states = audio_hidden_states + attn_audio_hidden_states * audio_gate_msa
# 2. Video and Audio Cross-Attention with text embeddings (Q: Video/Audio; K,V: Text)
# LTX-2.3: compute prompt modulation params for K/V
if self.cross_attn_adaln and temb_prompt is not None:
video_prompt_ada_params = self.get_mod_params(self.prompt_scale_shift_table, temb_prompt, batch_size)
shift_text_kv, scale_text_kv = video_prompt_ada_params
if self.cross_attn_adaln:
if temb_prompt is not None:
shift_text_kv, scale_text_kv = self.get_mod_params(
self.prompt_scale_shift_table, temb_prompt, batch_size
)
else:
shift_text_kv, scale_text_kv = (
self.prompt_scale_shift_table[None, None]
.to(device=hidden_states.device, dtype=hidden_states.dtype)
.unbind(dim=2)
)
audio_prompt_ada_params = self.get_mod_params(
self.audio_prompt_scale_shift_table, temb_prompt_audio, batch_size
)
audio_shift_text_kv, audio_scale_text_kv = audio_prompt_ada_params
if temb_prompt_audio is not None:
audio_shift_text_kv, audio_scale_text_kv = self.get_mod_params(
self.audio_prompt_scale_shift_table, temb_prompt_audio, batch_size
)
else:
audio_shift_text_kv, audio_scale_text_kv = (
self.audio_prompt_scale_shift_table[None, None]
.to(device=audio_hidden_states.device, dtype=audio_hidden_states.dtype)
.unbind(dim=2)
)
# 2.1. Video-Text Cross-Attention
norm_hidden_states = self.norm2(hidden_states)
if self.video_cross_attn_adaln:
norm_hidden_states = norm_hidden_states * (1 + scale_text_q) + shift_text_q
if self.cross_attn_adaln and temb_prompt is not None:
if self.cross_attn_adaln:
encoder_hidden_states = encoder_hidden_states * (1 + scale_text_kv) + shift_text_kv
attn_hidden_states = self.attn2(
@@ -1109,7 +1131,7 @@ class LTX2VideoTransformerBlock(nn.Module):
norm_audio_hidden_states = self.audio_norm2(audio_hidden_states)
if self.audio_cross_attn_adaln:
norm_audio_hidden_states = norm_audio_hidden_states * (1 + audio_scale_text_q) + audio_shift_text_q
if self.cross_attn_adaln and temb_prompt is not None:
if self.cross_attn_adaln:
audio_encoder_hidden_states = audio_encoder_hidden_states * (1 + audio_scale_text_kv) + audio_shift_text_kv
attn_audio_hidden_states = self.audio_attn2(
@@ -1508,7 +1530,10 @@ class LTX2VideoTransformer3DModel(nn.Module):
block_forward_patterns={
"transformer_blocks": ForwardPattern.Pattern_0,
},
has_separate_cfg=True,
# LTX fuses all guidance passes into the batch dimension and invokes
# the transformer once per denoise step. Cache-DiT must therefore
# advance its step counter for every transformer forward.
has_separate_cfg=False,
check_forward_pattern=False,
)
@@ -1546,6 +1571,7 @@ class LTX2VideoTransformer3DModel(nn.Module):
# Shard video/audio latents across sequence
"hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False),
"audio_hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False),
"keyframes_mask": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False),
# Shard prompt embeds across sequence
"encoder_hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False),
"audio_encoder_hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False),
@@ -1620,6 +1646,10 @@ class LTX2VideoTransformer3DModel(nn.Module):
cross_attn_mod: bool = False,
audio_gated_attn: bool = False,
audio_cross_attn_mod: bool = False,
ff_bias: bool = True,
audio_ff_bias: bool = True,
use_prompt_adaln_single: bool = True,
use_keyframes_abs_pos_embedding: bool = False,
quant_config: "QuantizationConfig | None" = None,
) -> None:
super().__init__()
@@ -1666,12 +1696,19 @@ class LTX2VideoTransformer3DModel(nn.Module):
timestep_scale_multiplier=timestep_scale_multiplier,
cross_attn_timestep_scale_multiplier=cross_attn_timestep_scale_multiplier,
rope_type=rope_type,
ff_bias=ff_bias,
audio_ff_bias=audio_ff_bias,
use_prompt_adaln_single=use_prompt_adaln_single,
use_keyframes_abs_pos_embedding=use_keyframes_abs_pos_embedding,
)
# 1. Patchification input projections
self.proj_in = nn.Linear(in_channels, inner_dim)
self.audio_proj_in = nn.Linear(audio_in_channels, audio_inner_dim)
if use_keyframes_abs_pos_embedding:
self.keyframes_abs_pos_embedding = nn.Parameter(torch.zeros(1, inner_dim))
# 2. Prompt embeddings
# LTX-2 (use_prompt_embeddings=True): caption projection in the transformer
# LTX-2.3 (use_prompt_embeddings=False): caption projection in the connectors
@@ -1695,7 +1732,7 @@ class LTX2VideoTransformer3DModel(nn.Module):
# 3.3. LTX-2.3: Prompt modulation from sigma
self.prompt_modulation = cross_attn_mod or audio_cross_attn_mod
if self.prompt_modulation:
if self.prompt_modulation and use_prompt_adaln_single:
self.prompt_adaln = LTX2AdaLayerNormSingle(inner_dim, num_mod_params=2, use_additional_conditions=False)
self.audio_prompt_adaln = LTX2AdaLayerNormSingle(
audio_inner_dim, num_mod_params=2, use_additional_conditions=False
@@ -1815,6 +1852,8 @@ class LTX2VideoTransformer3DModel(nn.Module):
elementwise_affine=norm_elementwise_affine,
rope_type=rope_type,
perturbed_attn=perturbed_attn,
ff_bias=ff_bias,
audio_ff_bias=audio_ff_bias,
quant_config=quant_config,
prefix=f"transformer_blocks.{layer_idx}",
)
@@ -1852,6 +1891,7 @@ class LTX2VideoTransformer3DModel(nn.Module):
audio_encoder_hidden_states: torch.Tensor,
timestep: torch.LongTensor,
audio_timestep: torch.LongTensor | None = None,
keyframes_mask: torch.Tensor | None = None,
sigma: torch.Tensor | None = None,
audio_sigma: torch.Tensor | None = None,
encoder_attention_mask: torch.Tensor | None = None,
@@ -1952,9 +1992,7 @@ class LTX2VideoTransformer3DModel(nn.Module):
video_rotary_emb = self.rope(video_coords, device=hidden_states.device, out_dtype=hidden_states.dtype)
audio_rotary_emb = self.audio_rope(
audio_coords,
device=audio_hidden_states.device,
out_dtype=audio_hidden_states.dtype,
audio_coords, device=audio_hidden_states.device, out_dtype=audio_hidden_states.dtype
)
video_cross_attn_rotary_emb = self.cross_attn_rope(
@@ -1970,6 +2008,11 @@ class LTX2VideoTransformer3DModel(nn.Module):
# 2. Patchify input projections
hidden_states = self.proj_in(hidden_states)
hidden_states = apply_keyframes_absolute_embedding(
hidden_states,
keyframes_mask,
getattr(self, "keyframes_abs_pos_embedding", None),
)
audio_hidden_states = self.audio_proj_in(audio_hidden_states)
# 3. Prepare timestep embeddings and modulation parameters
@@ -2028,7 +2071,7 @@ class LTX2VideoTransformer3DModel(nn.Module):
audio_cross_attn_v2a_gate = audio_cross_attn_v2a_gate.view(batch_size, -1, audio_cross_attn_v2a_gate.shape[-1])
# 3.3. LTX-2.3: Compute prompt modulation from sigma
if self.prompt_modulation and sigma is not None:
if self.prompt_modulation and self.config.use_prompt_adaln_single and sigma is not None:
temb_prompt, _ = self.prompt_adaln(sigma.flatten(), batch_size=batch_size, hidden_dtype=hidden_states.dtype)
temb_prompt_audio, _ = self.audio_prompt_adaln(
audio_sigma.flatten(), batch_size=batch_size, hidden_dtype=audio_hidden_states.dtype
@@ -10,15 +10,12 @@ from typing import ClassVar
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
from .ltx2_components import LTX2_COMPONENT_PROFILE
from .ltx2_components import LTX2_COMPONENT_PROFILE, LTX2_DISTILLED_ONE_STAGE_COMPONENT_PROFILE
from .ltx2_components import (
get_ltx2_post_process_func as get_ltx2_post_process_func, # noqa: F401
)
from .ltx2_conditioning import LTXI2VConditioningMixin
from .ltx2_recipes import (
LTX2_ONE_STAGE_RECIPE,
LTX_POSITIVE_ONLY_RECIPE,
)
from .ltx2_recipes import LTX2_DISTILLED_ONE_STAGE_RECIPE, LTX2_ONE_STAGE_RECIPE, LTX_POSITIVE_ONLY_RECIPE
from .ltx2_runtime import LTXRuntime
@@ -36,6 +33,14 @@ class LTX2Pipeline(LTXI2VConditioningMixin, LTXRuntime):
supports_request_batch = True
class LTX2DistilledOneStagePipeline(LTX2Pipeline):
"""Merged-distilled checkpoint at its native one-stage resolution."""
pipeline_kind = "distilled_one_stage"
component_profile = LTX2_DISTILLED_ONE_STAGE_COMPONENT_PROFILE
pipeline_recipe = LTX2_DISTILLED_ONE_STAGE_RECIPE
class LTX2T2VDMD2Pipeline(DMD2PipelineMixin, LTX2Pipeline):
"""LTX2 T2V entry for FastGen DMD2-distilled models."""
@@ -40,9 +40,13 @@ class LTX2TwoStagePipeline(_LTX2TwoStageBase):
pipeline_recipe = LTX2_TWO_STAGE_RECIPE
class LTX2DistilledPipeline(_LTX2TwoStageBase):
"""Unified LTX-2/LTX-2.3 full-distilled two-stage T2V/I2V entry."""
class LTX2DistilledTwoStagePipeline(_LTX2TwoStageBase):
"""Merged-distilled checkpoint with latent upsampling and refinement."""
pipeline_kind = "distilled_two_stage"
component_profile = LTX2_DISTILLED_COMPONENT_PROFILE
pipeline_recipe = LTX2_DISTILLED_TWO_STAGE_RECIPE
# Backwards-compatible name retained for existing LTX-2/LTX-2.3 recipes.
LTX2DistilledPipeline = LTX2DistilledTwoStagePipeline