Official Python inference and LoRA trainer package for the LTX-2 audio–video generative model.
Automated PR - 2026-09-29
github-actions[bot]70ee118e0d05
diff --git a/.gitignore b/.gitignoreindex 0a13e7c..26468ae 100644--- a/.gitignore+++ b/.gitignore@@ -48,7 +48,8 @@ wandb/!packages/ltx-pipelines/tests/assets/full_e2e/!packages/ltx-pipelines/tests/assets/full_e2e/*.mp4!packages/ltx-pipelines/tests/assets/full_e2e/*.wav-!packages/ltx-pipelines/tests/assets/full_e2e/expected_hdr_ic_lora_exr/frame_*.exr+!packages/ltx-pipelines/tests/assets/full_e2e/expected_hdr_ic_lora_acescct_*_exr/+!packages/ltx-pipelines/tests/assets/full_e2e/expected_hdr_ic_lora_acescct_*_exr/frame_*.exr!packages/ltx-pipelines/tests/assets/full_e2e/expected_native_hdr_*_exr/!packages/ltx-pipelines/tests/assets/full_e2e/expected_native_hdr_*_exr/frame_*.exr!packages/ltx-pipelines/tests/assets/full_e2e/native_hdr_cow_rain_retake_source_exr/@@ -59,8 +60,9 @@ wandb/!packages/ltx-pipelines/tests/assets/native_hdr_cow_rain_exr_small/!packages/ltx-pipelines/tests/assets/native_hdr_cow_rain_exr_small/frame_*.exr-# HDR IC-LoRA e2e test input clip (checked in via Git LFS)+# HDR IC-LoRA e2e inputs (checked in via Git LFS): 17-frame 8k+1 native, 9-frame 128² integration.!packages/ltx-pipelines/tests/assets/hdr_ic_lora_test_input.mp4+!packages/ltx-pipelines/tests/assets/hdr_ic_lora_test_input_small.mp4# DurationHead e2e test input (real connector-token output; checked in via Git LFS)!packages/ltx-core/tests/assets/duration_head_input.safetensors@@ -84,4 +86,5 @@ wandb/!packages/ltx-trainer/tests/assets/test_dataset/conditioning/audio_mask.pt# Binary files+*.o*.sodiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 55eb929..745395e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,67 @@# Changelog+## 1.4.0 - 2026-09-29++### Added++- `--chunked` on Distilled, TI2Vid two-stage, A2Vid, Dub-It, and IC-LoRA enables long-video generation with the default chunk layout (97-frame windows and 25-frame carry) without setting `--chunk-pixel-frames` or `--chunk-carry-frames`; `--chunk-blend-frames` controls decoded video seam crossfade length.+- `ltx-kernels` production `sm_100a` wheels now load precompiled LTX-2.5 diffusion-VAE CuTe DSL kernels, eliminating first-decode JIT for standard plain and keyframe decoding; custom kernel shapes still compile on first use.+- `ICLoraPipeline` accepts `stages`, a sequence of `ICLoraStageConfig` (resolution, IC-LoRA, sigmas, optional transformer tiling). Default remains half-res with IC-LoRA, then a full-res refinement without it. Consecutive stages must stay at the same resolution or upsample by exactly 2x.+- `spatial_tiled_ic_lora_stages()` builds that two-stage recipe with fixed-size spatial tiling so large canvases stay on a trained window; both stages keep the IC-LoRA and reference.+- `TiledDiffusionModel` and `FixedSizeSpatialTiling` in `ltx_pipelines.utils.tiled_diffusion` run sequential transformer tiles with trapezoidal blending. DFR's spatial epilogue uses the same wrapper.+- `--stage-2-ic-lora` on `ltx_pipelines.ic_lora` keeps the IC-LoRA and reference on stage 2. `--tile` enables transformer tiling (default window 1024x1536; override with `--tile-height` / `--tile-width`). The CLI is always the two-stage recipe; omit `--tile` at 1080-class sizes to keep today's untiled path. A GPU OOM from that CLI is re-raised with `--tile` / `--tile-height` / `--tile-width` and `--offload cpu`.+- `decode_with_keyframes` on `TI2VidOneStagePipeline`, `TI2VidTwoStagesPipeline`, `TI2VidTwoStagesHQPipeline`, and `DistilledPipeline`, plus the `distilled_mgpu`, `ti2vid_two_stages_mgpu`, and `ti2vid_two_stages_hq_mgpu` runners (CLI: `--decode-with-keyframes`). When set together with generated keyframe slots, the pipeline decodes through the keyframe-aware DiffVAE path using those slots as anchors. Two-stage pipelines re-attach seeded slots at stage 2 so the planes sit at final resolution before decode.+- `AudioConditionByLatentIndex` pins an audio latent at a given latent index, matching `VideoConditionByLatentIndex` for video.+- Added `ltx_pipelines.chunks`, a building block for long-video generation: plan a clip as temporal windows, run denoise → upsample → decode one window at a time, and stitch continuity across seams so VRAM stays bounded by window size rather than full clip length.+- Distilled, TI2Vid two-stage, A2Vid, Dub-It, and IC-LoRA can generate long clips in overlapping windows instead of holding the full timeline in memory. Pass `--chunk-pixel-frames` and optionally `--chunk-carry-frames` on the CLI (or `chunk_config` / `stream_chunks()` in Python) to tune window size and overlap; omit both flags for the existing one-shot path.+- Chunked long-video generation plans generated keyframes per window: an integer is a per-chunk slot budget with automatic stitch anchors; an explicit index list is merged with those anchors. Reference conditioning on continuation chunks appends only the suffix after the carried overlap while still encoding the full window for causal VAE alignment.+- DFR diffusion work is importable from `ltx_pipelines.dfr_stages` (`denoise_stage1`, `denoise_stage2`, `run_one_temporal_round`, `run_spatial_epilogue`) and helpers from `ltx_pipelines.dfr_helpers`, so an adapter can run the same path from a constructed `DiffusionStage` without wrapping `DFRPipeline` or instantiating Gemma.+- `--exr-colorspace` on `ltx_pipelines.hdr_ic_lora` (`acescg` / `acescct` / `srgb_linear`; default `acescg`). Only the EXR sidecar encoding changes; the HLG master stays BT.2020/HLG.+- `--transformer-path` on `ltx_pipelines.hdr_ic_lora`, which runs the pipeline from a split checkpoint pack instead of a distilled monolith. A split transformer carries no VAE weights, so `--video-vae-path` has to accompany it.+- `EXRColorSpace` / `VideoInput` in `ltx_pipelines` and an sRGB EOTF in `ltx_core.hdr`, which convert an SDR source into ACEScct.++### Changed++- The `ltx_kernels_inductor` compile backend batches the fp8-cast policy's per-forward weight and bias upcasts into a few grouped kernels instead of one per tensor. Outputs are bit-identical.+- Chunk planning owns generated-keyframe placement and appends slots after pipeline conditionings. Generated slots remain transformer conditioning across every stage; `decode_with_keyframes` now controls only whether the final slots anchor video decode.+- `ChunkConfig.overlap_blend_frames` defaults to the full carry overlap (crossfade over all carried frames). Pass `0` for a hard cut at chunk seams.+- `ChunkConfig.overlap_blend_frames` linearly crossfades a configurable suffix of each decoded overlap instead of cutting directly between windows, buffering only that suffix during streaming.+- DFR spatial epilogues run their first denoising step on a 2x2 tile grid before retiling any remaining steps to 4x4. A one-step schedule stays on the 2x2 grid.+- `create_initial_audio_latent` now takes a video latent and required `video_scale_factors`. Joint first stages use `create_initial_av_latents`, which also requires `video_scale_factors`. `create_initial_video_latent` requires `scale_factors` (no default). Pass the same video VAE factors used to size the video latent. Audio-only callers use `AudioLatentShape.from_duration`.+- Distilled and DFR sample with Euler ancestral (`eta=1.0`, `s_noise=1.0`) on LTX-2.5+ checkpoints -- distilled on both stages, DFR on stage 1, stage 2 and the spatial epilogue -- so generated output for those checkpoints differs from the previous release. Older generations sample with deterministic Euler. DFR's temporal densify tiles are unchanged at `eta=0.5`.+- `PipelineOutput` is again a four-field named tuple (`video`, `audio`, `num_frames`, `tiling_config`). Pipelines choose keyframe-aware decode internally; the returned `video` iterator reflects that choice.+- Conv, diffusion, and distributed `decode_video()` accept extra keyword arguments and ignore ones they do not use.+- Denoisers, denoising loops and `DiffusionStage.__call__` return `VideoAudio` instead of a plain `(video, audio)` tuple. It still unpacks as two values, and also exposes `.video` and `.audio`. Omit the absent side (`VideoAudio(video=...)`); constructing with both `None` raises.+- `DiffusionStage.__call__` is now a latent entry point. Pass `modalities=VideoAudio[ModalitySpec]` (either side may be omitted, but not both). Each `ModalitySpec` carries the latent to denoise, and that latent is the stage's only source of shape, so the stage never sizes a latent itself. Seed a pipeline's first stage with `create_initial_video_latent` / `create_initial_audio_latent` / `create_initial_av_latents` in `ltx_pipelines.utils.helpers`, and hand every later stage the previous stage's output, upscaled or not. Audio-only callers no longer need to pass placeholder video dimensions.+- `encode_video` and `encode_sdr_h264` accept streaming video frame iterators and can mux audio supplied as it becomes available, so long chunked runs can write a file without assembling the full clip first.+- One-shot `__call__` on Distilled, TI2Vid, A2Vid, and Dub-It still returns `PipelineOutput`; internally it uses the same chunked path with a single window. Reported `num_frames` is the stitched length on the causal grid.+- `ltx_pipelines.hdr_ic_lora` is a single-stage ACEScct SDR-to-HDR pipeline. It writes a 10-bit BT.2020/HLG master plus an EXR sequence whose colour space is `--exr-colorspace` (default ACEScg; `acescct` writes VAE log codes), where it previously ran two stages and returned linear float from a LogC3 inverse decode for the caller to tonemap and save. `--input-colorspace` selects the input transform, so the source may be an SDR MP4/MOV (`srgb_gamma`, `srgb`) or a directory of EXR frames (`srgb`, `acescg`, `acescct`); EXR directories also need `--frame-rate`, which a container source must not set.+- HDR EXR output directories are named for their colour space: `<output_stem>_acescct_exr`, `<output_stem>_acescg_exr` or `<output_stem>_srgb_linear_exr`. Every HDR run previously wrote `<output_stem>_exr`, so code that globs the old path will not find the frames.+- `--distilled-checkpoint-path` on `ltx_pipelines.hdr_ic_lora` is no longer required, since `--transformer-path` can supply the transformer instead. One of the two is still needed.+- DFR seam keyframes on `ltx_pipelines.hdr_ic_lora` are on by default. `--with-keyframes` is replaced by `--no-keyframes`. A 2.4 transformer fails the capability check unless `--no-keyframes` is passed; a 2.5 distilled monolith still needs `--video-vae-path` to a keyframe-trained VAE or the keyframe path is a silent no-op.+- `ltx-core` requires `colour-science`, which supplies the primaries, YUV matrix and HLG transfer definitions that were previously hand-written constants.++### Removed++- `stepper` on `DiffusionStage.__call__`, `denoise_chunks`, the DFR stage functions, and the denoising loops. Each loop constructs its own step. Pass `eta` and `s_noise` to `euler_ancestral_denoising_loop` and `euler_cfg_pp_denoising_loop`. `EulerAncestralDiffusionStep` and `EulerCfgPpDiffusionStep` no longer take those arguments; pass them to `step`.+- `TiledModelWrapper` in `ltx_pipelines.dfr_helpers.ops`; use `TiledDiffusionModel` from `ltx_pipelines.utils.tiled_diffusion`.+- `QuantizationPolicy.model_configurator`; pass the configurator directly to the model builder or `DiffusionStage.from_checkpoint(model_configurator=...)`.+- `All2All.set_rank_tokens`; All2All head exchange and AllGather now derive uniform token counts from their input tensors.+- `PipelineOutput.keyframes` and `PipelineOutput.video_latent`; use `decode_with_keyframes=True` (CLI: `--decode-with-keyframes`) on pipelines that support it.+- `width`, `height`, `frames` and `audio_fps` on `DiffusionStage.__call__`; size the latent yourself and pass it as `ModalitySpec(latent=...)`. Audio sized off a playback rate that differs from the video RoPE time base, which `audio_fps` covered in 1.3.0, is now done by building the audio latent at that rate with `create_initial_audio_latent(..., fps=...)`.+- Separate `video` and `audio` kwargs on `DiffusionStage.__call__`; pass `modalities=VideoAudio(...)`.+- `ModalitySpec.initial_latent`; use `ModalitySpec.latent`, which is required.+- `ImageConditioningInput` from `ltx_pipelines.utils.args`; import it from `ltx_pipelines.utils.types`.+- `--output-dir` on `ltx_pipelines.hdr_ic_lora`; use `--output-path`, which names the HLG master and places the EXR directory beside it.+- `--spatial-upsampler-path`, `--num-frames`, `--spatial-tile` and `--skip-mp4` on `ltx_pipelines.hdr_ic_lora`. The pipeline is single-stage and does not upsample, output length follows the source clip (whose frame count must be 8k+1), decode tiling is resolved automatically, and the HLG master is always written beside the EXR frames.++### Fixed++- Generated audio could outlast the decoded video when `num_frames` was not on the video VAE temporal grid (for example 87 frames at 24 fps decoded 81 picture frames against a longer soundtrack). Initial audio latents are now sized from the snapped video canvas.+- Chunked vocoded audio retains a 40 ms overlap and equal-power crossfades it at generation-window seams, avoiding clicks while keeping the causal decoder shortfall at stream startup.+- Multi-GPU sequence-parallel runs compiled with `torch.compile` could produce a corrupted, repeating texture instead of the prompted scene (seen with the `ltx_kernels_inductor` backend). The compiler could keep its own tensors in the All2All exchange buffer, which the next exchange overwrote. `torch.ops.ltx_kernels.send_recv_heads` and `gather_heads` now take that buffer as an argument they write in place and return nothing; `All2All.send_recv_heads` and `All2All.gather_heads` are unchanged.+- Pinned equal-size transformer windows reject an overlap above half the window and round the tile count down, so three tiles never cover one cell. This is the layout used by IC-LoRA `--tile`. The requested overlap is a target and the realized overlap may be smaller. Two tiles on a canvas only slightly larger than the window can still overlap by more than half, because there is no third tile.+## 1.3.0 - 2026-08-25### Added@@ -24,6 +86,11 @@- `VideoDecoder.decode_video()` takes `keyframes=` on every implementation. The diffusion decoder uses them; conv logs a warning and decodes without them; distributed splits them across ranks. Callers that never pass keyframes are unaffected; decoder implementations must accept the keyword.- NVFP4 quantization and CuTe DSL DiffVAE kernels (`blackwell_dsl`) now support Jetson Thor. Build NVFP4 with the arch-specific `110a` target.+- The DFR spatial epilogue now generates the keyframes it ships instead of shipping upscales. The planes it carries in are Lanczos x2 stretches of the previous stage, so anchoring the VAE decode on them blurred the very frames a keyframe is meant to sharpen; they are now conditioning only, and the epilogue attaches a slot a latent frame to the side of each (a slot cannot occupy the frame the plane holds) and ships those full-resolution results. `PipelineOutput.keyframes.pixel_frame_indices` therefore move 8 frames from the carried positions. A candidate that would land inside a temporal window's pinned prefix is skipped, so a few carried positions ship no plane at all.+- A DFR temporal tile (and epilogue window) begins on a **keyframe plane** rather than on a mid-canvas latent cell. A tile is denoised as its own clip, whose first cell the model reads as a single pixel frame under the causal convention, so starting it on an 8-frame cell put content and shape in disagreement and ran RoPE time 7 frames ahead of the canvas. Cell 0 is now the plane at the last keyframe before the seam, the cells between it and the seam are pinned to the previous tile's output, and the tile resumes after the seam -- the last pinned cell ends exactly on it, so the seam keyframe is absorbed and needs no conditioning of its own. The prefix length follows the keyframe grid rather than a configured overlap, so the tile split takes no overlap at all and kept runs are disjoint.+- DFR temporal tiles and the spatial epilogue now hand over through a **pinned prefix** instead of synchronising on a shared keyframe. A non-first tile's lead-in cells are conditioned on the previous tile's finished output at strength 1, so they are that output at every step rather than a re-denoised approximation of it. Keyframe conditionings inside a pinned prefix are dropped, because the pinned cells hold the current stage's content while the plane holds an earlier stage's. Anchors from the resume point onward are unchanged, so the tile that owns a stretch still generates it against its keyframes.+- The DFR spatial epilogue runs one denoising pass per temporal window, sequentially, instead of one pass over the whole canvas with every temporal tile re-run inside each Euler step. Spatial tiling and its per-step blending are unchanged. Temporal windows were already seam-cut, rectangular and never blended into each other, so this costs the same and is what gives each window a finished predecessor to pin its lead-in to.+### Removed- `DiffusionVideoDecoder.decode_video_with_keyframes`; use `decode_video(..., keyframes=)`.diff --git a/README.md b/README.mdindex 4e0b923..b69cbd7 100644--- a/README.md+++ b/README.md@@ -146,7 +146,7 @@ See **[LTX-2.3 models](MODELS-LTX-2.3.md)** for the full list.* **[KeyframeInterpolationPipeline](packages/ltx-pipelines/src/ltx_pipelines/keyframe_interpolation.py)** - Interpolate between keyframe images* **[A2VidPipelineTwoStage](packages/ltx-pipelines/src/ltx_pipelines/a2vid_two_stage.py)** - Audio-to-video generation conditioned on an input audio file* **[RetakePipeline](packages/ltx-pipelines/src/ltx_pipelines/retake.py)** - Regenerate a specific time region of an existing video-* **[HDRICLoraPipeline](packages/ltx-pipelines/src/ltx_pipelines/hdr_ic_lora.py)** - Video-to-video with HDR IC-LoRA output (linear float via LogC3 inverse decode, suitable for EXR export and tonemapping)+* **[HDRICLoraPipeline](packages/ltx-pipelines/src/ltx_pipelines/hdr_ic_lora.py)** - Video-to-video SDR→HDR with an HDR IC-LoRA, writing a BT.2020/HLG master plus an ACEScct EXR sequence for EXR export and grading* **[DubItPipeline](packages/ltx-pipelines/src/ltx_pipelines/dubit.py)** - Dub-It: rephrasing while matching speaker identity and lip movements (distilled model, single IC-LoRA, two stages).* **Native HDR / EXR** — standard pipelines accept EXR stills and EXR-frame folders with `--hdr {SRGB_LINEAR,ACESCG,ACESCCT}` and write half EXR frames plus a BT.2020/HLG master. See [HDR Support](packages/ltx-pipelines/docs/hdr.md).diff --git a/packages/ltx-core/pyproject.toml b/packages/ltx-core/pyproject.tomlindex 8254e7e..106970b 100644--- a/packages/ltx-core/pyproject.toml+++ b/packages/ltx-core/pyproject.toml@@ -1,6 +1,6 @@[project]name = "ltx-core"-version = "1.3.0"+version = "1.4.0"description = "Core implementation of Lightricks' LTX-2 model"readme = "README.md"requires-python = ">=3.10"@@ -12,6 +12,7 @@ dependencies = ["torchvision","einops","numpy",+ "colour-science","av",# Upper bound: transformers 5.15.0 routes config attribute access through the# heterogeneity layer, which raises AmbiguousGlobalPerLayerAttributeError on globaldiff --git a/packages/ltx-core/src/ltx_core/color/__init__.py b/packages/ltx-core/src/ltx_core/color/__init__.pyindex e5950b9..8dc0af8 100644--- a/packages/ltx-core/src/ltx_core/color/__init__.py+++ b/packages/ltx-core/src/ltx_core/color/__init__.py@@ -1,5 +1,5 @@"""Colour transforms, primaries, YUV packing, and HLG encode.-VAE working-space helpers (``HDRTransfer``, ``TransferEncoding``) live in+VAE working-space helpers (``to_acescct_working_space``, ``to_hdr_linear``, ``TransferEncoding``) live in:mod:`ltx_core.hdr` — import them from there. This package does not re-exporthdr symbols (that would cycle: ``hdr`` imports ``color.primaries``)."""diff --git a/packages/ltx-core/src/ltx_core/color/hlg.py b/packages/ltx-core/src/ltx_core/color/hlg.pyindex 3655e6f..4660fde 100644--- a/packages/ltx-core/src/ltx_core/color/hlg.py+++ b/packages/ltx-core/src/ltx_core/color/hlg.py@@ -1,17 +1,15 @@"""In-memory scene-linear HDR frames → BT.2020 / HLG / 10-bit HEVC MP4.-HLG = Hybrid Log-Gamma (ITU-R BT.2100, OETF per ARIB STD-B67). Output is HEVC Main10,-yuv420p10le, tagged BT.2020 primaries + arib-std-b67 transfer + bt2020nc matrix, limited-range.-Per frame: scene-linear RGB → primaries → BT.2020 → map linear light to HLG scene-signal (diffuse white at ``white_signal``, highlights rolled toward 1.0) → HLG OETF →-planar YUV420P10 → PyAV/libx265.+HLG = Hybrid Log-Gamma (ITU-R BT.2100 / ARIB STD-B67). Output is HEVC Main10+yuv420p10le, tagged BT.2020 + arib-std-b67 + bt2020nc, limited range.+Pipeline: scene-linear RGB → Rec.2020 → map diffuse white → HLG OETF →+YUV420P10 → PyAV/libx265. OETF constants / scalar inverse come from+``colour-science``; the tensor OETF stays in torch for GPU encode."""from __future__ import annotationsimport contextlibimport logging-import mathimport osimport threadingfrom collections.abc import Iterable, Iterator@@ -24,6 +22,8 @@ from typing import Anyimport avimport numpy as npimport torch+from colour.models import oetf_inverse_BT2100_HLG+from colour.models.rgb.transfer_functions.arib_std_b67 import CONSTANTS_ARIBSTDB67from ltx_core.color.audio_mux import prepare_audio_stream, validate_audio_waveform, write_audiofrom ltx_core.color.primaries import Primaries@@ -32,24 +32,34 @@ from ltx_core.types import Audiologger = logging.getLogger(__name__)-# FFmpeg AVColor* tags not covered by ColorSpace / ColorRange._AV_COLOR_PRIMARIES_BT2020 = 9_AV_COLOR_TRC_ARIB_STD_B67 = 18 # HLG-# ARIB STD-B67 (HLG) OETF constants.-HLG_A, HLG_B, HLG_C = 0.17883277, 0.28466892, 0.55991073+# ARIB STD-B67 / BT.2100 HLG OETF constants (colour-science).+_HLG_A = float(CONSTANTS_ARIBSTDB67["a"])+_HLG_B = float(CONSTANTS_ARIBSTDB67["b"])+_HLG_C = float(CONSTANTS_ARIBSTDB67["c"])def hlg_inverse_oetf(v: float) -> float:- """Inverse HLG OETF for a scalar signal value → scene-linear."""- return (v * v) / 3.0 if v <= 0.5 else (math.exp((v - HLG_C) / HLG_A) + HLG_B) / 12.0+ """Inverse HLG OETF: signal → scene-linear (colour ``oetf_inverse_BT2100_HLG``)."""+ return float(np.asarray(oetf_inverse_BT2100_HLG(v), dtype=np.float64))+++def _hlg_oetf(x: torch.Tensor) -> torch.Tensor:+ """HLG OETF on scene-linear ``x`` (torch; matches colour ``oetf_BT2100_HLG``)."""+ return torch.where(+ x <= 1.0 / 12.0,+ torch.sqrt((3.0 * x).clamp(min=0.0)),+ _HLG_A * torch.log((12.0 * x - _HLG_B).clamp(min=1e-12)) + _HLG_C,+ ).clamp(0.0, 1.0)@dataclassclass HlgGpuConverter:"""GPU linear-HDR ``[F,H,W,3]`` → planar uint16 YUV420P10 (BT.2020 / HLG / limited)."""- prim_mat: torch.Tensor # [3, 3] on device+ prim_mat: torch.Tensorwhite_x: floatroll_k: float@@ -67,27 +77,26 @@ class HlgGpuConverter:device = torch.device("cuda" if torch.cuda.is_available() else "cpu")white_x = hlg_inverse_oetf(white_signal)roll_k = rolloff_k if rolloff_k is not None else white_x / (1.0 - white_x)- prim = primaries.matrix_to_rec2020.to(device=device, dtype=dtype)- return cls(prim_mat=prim, white_x=float(white_x), roll_k=float(roll_k))+ return cls(+ prim_mat=primaries.matrix_to_rec2020.to(device=device, dtype=dtype),+ white_x=float(white_x),+ roll_k=float(roll_k),+ )def to_hlg_signal_(self, rgb_linear_chw: torch.Tensor) -> torch.Tensor:"""``(*, 3, H, W)`` scene-linear → HLG signal ``[0, 1]``."""lin = torch.nan_to_num(- (rgb_linear_chw.movedim(-3, -1) @ self.prim_mat.T).clamp(min=0.0),+ torch.einsum("...chw,dc->...dhw", rgb_linear_chw, self.prim_mat).clamp(min=0.0),nan=0.0,neginf=0.0,)+ # Diffuse white → white_x; highlights roll toward 1.0.x = torch.where(lin <= 1.0,lin * self.white_x,1.0 - (1.0 - self.white_x) * torch.exp(-self.roll_k * (lin - 1.0)),)- sig = torch.where(- x <= 1.0 / 12.0,- torch.sqrt((3.0 * x).clamp(min=0.0)),- HLG_A * torch.log((12.0 * x - HLG_B).clamp(min=1e-12)) + HLG_C,- )- return sig.clamp(0.0, 1.0).movedim(-1, -3)+ return _hlg_oetf(x)def __call__(self, frames_fhwc: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:"""``[F,H,W,3]`` scene-linear → planar uint16 Y, U, V on the same device."""@@ -105,6 +114,23 @@ def _resolve_x265_thread_count(thread_count: int) -> int:return max(1, min(os.cpu_count() or 8, 16))+def _x265_encode_params(threads: int, width: int, height: int) -> str:+ """libx265 ``x265-params`` for an HLG ``hvc1`` MP4.+ When width and height are both at most 32 (single CTU in each axis),+ default ``frame-threads=4`` plus ultrafast B-frames can flush packets the+ mp4 muxer rejects (``PatchWelcomeError``) on very short clips, and the+ failure is timing-sensitive when many libx265 thread pools run+ concurrently (multi-process or multi-threaded hosts).+ """+ base = (+ "colorprim=bt2020:transfer=arib-std-b67:colormatrix=bt2020nc:range=limited:"+ f"repeat-headers=1:info=0:pools={threads}"+ )+ if width <= 32 and height <= 32:+ return f"{base}:frame-threads=1:bframes=0:lookahead=0"+ return f"{base}:frame-threads=4"++@dataclassclass HlgPyAVEncoder:"""Open PyAV libx265 HLG encoder."""@@ -135,10 +161,7 @@ class HlgPyAVEncoder:stream.options = {"crf": str(crf),"preset": preset,- "x265-params": (- "colorprim=bt2020:transfer=arib-std-b67:colormatrix=bt2020nc:range=limited:"- f"repeat-headers=1:info=0:pools={threads}:frame-threads=4"- ),+ "x265-params": _x265_encode_params(threads, width, height),}ctx = stream.codec_contextctx.thread_count = threads@@ -265,14 +288,12 @@ def encode_linear_hdr_frames_to_hlg_mp4( # noqa: PLR0913except StopIteration as e:raise ValueError("No HDR frames to encode.") from e- first_t = _as_fhwc_torch(first)- # ``first_t`` is [F,H,W,C]; open() takes (width, height).- height, width = int(first_t.shape[1]), int(first_t.shape[2])+ first_t = _as_fhwc_torch(first) # [F, H, W, C]encoder = HlgPyAVEncoder.open(out_path,- width,- height,- fps,+ width=int(first_t.shape[2]),+ height=int(first_t.shape[1]),+ fps=fps,crf=crf,preset=preset,thread_count=thread_count,diff --git a/packages/ltx-core/src/ltx_core/color/primaries.py b/packages/ltx-core/src/ltx_core/color/primaries.pyindex aa22acf..39835ba 100644--- a/packages/ltx-core/src/ltx_core/color/primaries.py+++ b/packages/ltx-core/src/ltx_core/color/primaries.py@@ -1,47 +1,43 @@"""Linear primaries: gamut basis, conversion, and EXR chromaticity tags.Shared by the VAE HDR working-space path (AP1 ↔ Rec.709) and the HLG encodepath (Rec.709 / ACEScg → Rec.2020).+Matrices and chromaticities come from ``colour-science`` (Bradford CAT), the+same source OpenColorIO-Config-ACES uses for its utility CLFs."""from __future__ import annotationsimport enum+import colourimport torchfrom torch import Tensor-# ACEScg (AP1, D60-adapted) linear → linear sRGB / Rec.709 (D65) primaries.-_ACESCG_TO_SRGB = torch.tensor(- [- [1.70505000, -0.62179000, -0.08326000],- [-0.13026000, 1.14080000, -0.01055000],- [-0.02400000, -0.12897000, 1.15297000],- ],- dtype=torch.float32,-)--# Exact inverse of ``_ACESCG_TO_SRGB`` (float64) for a clean round-trip.-_SRGB_TO_ACESCG = torch.linalg.inv(_ACESCG_TO_SRGB.double()).to(torch.float32)+_CAT = "Bradford"+_CS_ACESCG = colour.RGB_COLOURSPACES["ACEScg"]+_CS_REC709 = colour.RGB_COLOURSPACES["ITU-R BT.709"]+_CS_REC2020 = colour.RGB_COLOURSPACES["ITU-R BT.2020"]+++def _rgb_to_rgb(src: colour.RGB_Colourspace, dst: colour.RGB_Colourspace) -> Tensor:+ """Linear RGB→RGB matrix from colour-science, as float32."""+ return torch.as_tensor(+ colour.matrix_RGB_to_RGB(src, dst, chromatic_adaptation_transform=_CAT),+ dtype=torch.float32,+ )+-# Rec.709 (D65) → Rec.2020 (D65) (ITU-R BT.2087).-_REC709_TO_2020 = torch.tensor(- [- [0.62740389, 0.32928304, 0.04331307],- [0.06909729, 0.91954040, 0.01136232],- [0.01639144, 0.08801331, 0.89559525],- ],- dtype=torch.float32,-)--# ACEScg (AP1, D60) → Rec.2020 (D65), Bradford CAT.-_ACESCG_TO_2020 = torch.tensor(- [- [1.02582475, -0.02005319, -0.00577156],- [-0.00223437, 1.00458650, -0.00235213],- [-0.00501335, -0.02529007, 1.03030342],- ],- dtype=torch.float32,-)+def _exr_chroma(cs: colour.RGB_Colourspace) -> tuple[float, ...]:+ """EXR ``chromaticities`` order: Rxy, Gxy, Bxy, Wxy."""+ r, g, b = cs.primaries+ w = cs.whitepoint+ return (float(r[0]), float(r[1]), float(g[0]), float(g[1]), float(b[0]), float(b[1]), float(w[0]), float(w[1]))+++_ACESCG_TO_SRGB = _rgb_to_rgb(_CS_ACESCG, _CS_REC709)+_SRGB_TO_ACESCG = torch.linalg.inv(_ACESCG_TO_SRGB.double()).to(torch.float32)+_REC709_TO_2020 = _rgb_to_rgb(_CS_REC709, _CS_REC2020)+_ACESCG_TO_2020 = _rgb_to_rgb(_CS_ACESCG, _CS_REC2020)# Public matrix aliases (tests / advanced callers). Prefer ``Primaries.to``.ACESCG_TO_SRGB = _ACESCG_TO_SRGB@@ -65,16 +61,20 @@ class Primaries(enum.Enum):"""REC709 = "rec709"- ACESCG = "acescg"+ AP1 = "ap1"@property- def exr_chromaticities(self) -> tuple[float, ...]:- """EXR ``chromaticities`` header (R/G/B/W x,y)."""+ def _colourspace(self) -> colour.RGB_Colourspace:match self:case Primaries.REC709:- return (0.64, 0.33, 0.30, 0.60, 0.15, 0.06, 0.3127, 0.3290)- case Primaries.ACESCG:- return (0.713, 0.293, 0.165, 0.830, 0.128, 0.044, 0.32168, 0.33767)+ return _CS_REC709+ case Primaries.AP1:+ return _CS_ACESCG++ @property+ def exr_chromaticities(self) -> tuple[float, ...]:+ """EXR ``chromaticities`` header (R/G/B/W x,y)."""+ return _exr_chroma(self._colourspace)@propertydef matrix_to_rec2020(self) -> Tensor:@@ -82,7 +82,7 @@ class Primaries(enum.Enum):match self:case Primaries.REC709:return _REC709_TO_2020- case Primaries.ACESCG:+ case Primaries.AP1:return _ACESCG_TO_2020def to(self, target: Primaries, video: Tensor) -> Tensor:@@ -90,9 +90,9 @@ class Primaries(enum.Enum):if self is target:return videomatch (self, target):- case (Primaries.REC709, Primaries.ACESCG):+ case (Primaries.REC709, Primaries.AP1):return _apply_primaries_matrix(video, _SRGB_TO_ACESCG)- case (Primaries.ACESCG, Primaries.REC709):+ case (Primaries.AP1, Primaries.REC709):return _apply_primaries_matrix(video, _ACESCG_TO_SRGB)raise ValueError(f"No primaries conversion from {self!r} to {target!r}.")@@ -104,22 +104,22 @@ class Primaries(enum.Enum):# Back-compat helpers used by older call sites / re-exports.def apply_acescg_to_srgb(video: Tensor) -> Tensor:"""Linear ACEScg (AP1) → linear sRGB/Rec.709 primaries."""- return Primaries.ACESCG.to(Primaries.REC709, video)+ return Primaries.AP1.to(Primaries.REC709, video)def apply_srgb_to_acescg(video: Tensor) -> Tensor:"""Linear sRGB/Rec.709 → linear ACEScg (AP1) primaries."""- return Primaries.REC709.to(Primaries.ACESCG, video)+ return Primaries.REC709.to(Primaries.AP1, video)# String-keyed maps for EXR tag lookup / transitional call sites.# Prefer ``Primaries.matrix_to_rec2020`` / ``Primaries.exr_chromaticities``.PRIMARY_MATRIX_TO_2020 = {Primaries.REC709.value: REC709_TO_2020,- Primaries.ACESCG.value: ACESCG_TO_2020,+ Primaries.AP1.value: ACESCG_TO_2020,}EXR_CHROMATICITIES = {Primaries.REC709.value: Primaries.REC709.exr_chromaticities,- Primaries.ACESCG.value: Primaries.ACESCG.exr_chromaticities,+ Primaries.AP1.value: Primaries.AP1.exr_chromaticities,}diff --git a/packages/ltx-core/src/ltx_core/color/yuv.py b/packages/ltx-core/src/ltx_core/color/yuv.pyindex b92c00e..81b5d9f 100644--- a/packages/ltx-core/src/ltx_core/color/yuv.py+++ b/packages/ltx-core/src/ltx_core/color/yuv.py@@ -1,27 +1,45 @@"""GPU RGB→YUV420 packing for PyAV video encode (SDR 8-bit and HDR 10-bit).Shared by ltx-pipelines and ltx-trainer. Runs between the VAE decoder (float RGBchunks) and encode / HLG paths, bypassing pyav's CPU-side libswscale.-``FrameConverter`` also carries codec metadata (pixel format, colour space,-colour range).+RGB→Y'CbCr matrices come from ``colour-science``. 4:2:0 subsampling and+I420 / planar packing stay here (not provided by colour)."""from __future__ import annotationsimport enum+import colourimport torchclass ColorSpace(enum.Enum):- """YUV color space standard."""+ """YUV color space standard (FFmpeg ``AVCOL_SPC_*`` + colour-science weights)."""BT_709 = "bt709"BT_2020_NCL = "bt2020ncl"@propertydef av_colorspace(self) -> int:- """FFmpeg ``AVCOL_SPC_*`` constant for ``codec_context.colorspace``."""- return _AV_COLORSPACE[self]+ """FFmpeg ``AVCOL_SPC_*`` for ``codec_context.colorspace``."""+ match self:+ case ColorSpace.BT_709:+ return 1 # AVCOL_SPC_BT709+ case ColorSpace.BT_2020_NCL:+ return 9 # AVCOL_SPC_BT2020_NCL++ @property+ def _weights_name(self) -> str:+ match self:+ case ColorSpace.BT_709:+ return "ITU-R BT.709"+ case ColorSpace.BT_2020_NCL:+ return "ITU-R BT.2020"++ @property+ def rgb_to_ycbcr_matrix(self) -> torch.Tensor:+ """Float RGB→Y'CbCr (full range, no code levels), float32 3x3."""+ return _RGB_TO_YCBCR[self]class ColorRange(enum.Enum):@@ -32,8 +50,12 @@ class ColorRange(enum.Enum):@propertydef av_color_range(self) -> int:- """FFmpeg ``AVCOL_RANGE_*`` constant for ``codec_context.color_range``."""- return _AV_COLOR_RANGE[self]+ """FFmpeg ``AVCOL_RANGE_*`` for ``codec_context.color_range``."""+ match self:+ case ColorRange.MPEG:+ return 1 # AVCOL_RANGE_MPEG (limited)+ case ColorRange.JPEG:+ return 2 # AVCOL_RANGE_JPEG (full)class PixelFormat(enum.Enum):@@ -48,36 +70,17 @@ class PixelFormat(enum.Enum):return self.value-_AV_COLORSPACE = {- ColorSpace.BT_709: 1, # AVCOL_SPC_BT709- ColorSpace.BT_2020_NCL: 9, # AVCOL_SPC_BT2020_NCL-}--_AV_COLOR_RANGE = {- ColorRange.MPEG: 1, # AVCOL_RANGE_MPEG (limited)- ColorRange.JPEG: 2, # AVCOL_RANGE_JPEG (full)-}--_KR_2020, _KG_2020, _KB_2020 = 0.2627, 0.6780, 0.0593-_COLOR_SPACE_MATRICES = {- ColorSpace.BT_709: torch.tensor(- [- [0.2126, 0.7152, 0.0722],- [-0.1146, -0.3854, 0.5],- [0.5, -0.4542, -0.0458],- ],- dtype=torch.float32,- ),- ColorSpace.BT_2020_NCL: torch.tensor(- [- [_KR_2020, _KG_2020, _KB_2020],- [-_KR_2020 / 1.8814, -_KG_2020 / 1.8814, 0.5],- [0.5, -_KG_2020 / 1.4746, -_KB_2020 / 1.4746],- ],- dtype=torch.float32,- ),-}+def _rgb_to_ycbcr_matrix(weights_name: str) -> torch.Tensor:+ """Float RGB→Y'CbCr from colour-science (``matrix_YCbCr`` inverted)."""+ ycbcr_to_rgb = torch.as_tensor(+ colour.matrix_YCbCr(colour.WEIGHTS_YCBCR[weights_name], is_legal=False, is_int=False),+ dtype=torch.float64,+ )+ return torch.linalg.inv(ycbcr_to_rgb).to(torch.float32)++# Built once; ``ColorSpace.rgb_to_ycbcr_matrix`` reads from here.+_RGB_TO_YCBCR = {cs: _rgb_to_ycbcr_matrix(cs._weights_name) for cs in ColorSpace}# cuBLAS GEMM dims are int32. PyTorch folds ``(F, H*W, 3) @ (3, 3)`` into one# ``mm`` of size ``F*H*W``, reported as ``n`` in column-major. ``n`` must be@@ -111,13 +114,14 @@ def frames_per_yuv_gemm(height: int, width: int) -> int:def rgb_to_yuv(image: torch.Tensor, color_space: ColorSpace) -> torch.Tensor:- """RGB ``[0, 1]`` ``(*, 3, H, W)`` → YUV ``(*, 3, H, W)``.- Long clips are converted in frame chunks of size ``< (2**31 - 1) // H // W``- so each 3x3 GEMM stays inside cuBLAS int32. When chunking, YUV is written- back over the RGB storage; otherwise chunks are concatenated.+ """RGB ``[0, 1]`` ``(*, 3, H, W)`` → YUV ``(*, 3, H, W)`` (float, no code levels).+ Matrix from colour-science. Long clips are converted in frame chunks of size+ ``< (2**31 - 1) // H // W`` so each 3x3 GEMM stays inside cuBLAS int32.+ When chunking, YUV is written back over the RGB storage; otherwise chunks+ are concatenated. (``colour.RGB_to_YCbCr`` is NumPy-only and not used here.)"""_require_rgb_chw(image)- mat = _COLOR_SPACE_MATRICES[color_space].to(device=image.device, dtype=image.dtype)+ mat = color_space.rgb_to_ycbcr_matrix.to(device=image.device, dtype=image.dtype)orig_shape = image.shapeheight, width = orig_shape[-2], orig_shape[-1]frames = image.reshape(-1, 3, height, width)@@ -160,22 +164,23 @@ def apply_color_range_(*,bits: int = 8,) -> tuple[torch.Tensor, torch.Tensor]:- """Scale Y/UV to 8- or 10-bit code levels in-place.- MPEG uses ``(219 * E' + 16) * 2^(bits-8)`` for Y and- ``(224 * E' + 128) * 2^(bits-8)`` for Cb/Cr.+ """Scale float Y/UV to 8- or 10-bit code levels in-place.+ MPEG (limited): Y ``(219·E'+16)·2^(bits-8)``, Cb/Cr ``(224·E'+128)·2^(bits-8)``.+ JPEG (full): Y ``E'·(2^bits-1)``, Cb/Cr ``(E'+0.5)·(2^bits-1)``."""if bits not in (8, 10):raise ValueError(f"Unsupported bit depth: {bits}")factor = 1 << (bits - 8)- if color_range == ColorRange.MPEG:- y.mul_(219 * factor).add_(16 * factor)- uv.mul_(224 * factor).add_(128 * factor)- elif color_range == ColorRange.JPEG:- max_code = (1 << bits) - 1- y.mul_(max_code)- uv.add_(0.5).mul_(max_code)- else:- raise ValueError(f"Unsupported color range: {color_range}")+ match color_range:+ case ColorRange.MPEG:+ y.mul_(219 * factor).add_(16 * factor)+ uv.mul_(224 * factor).add_(128 * factor)+ case ColorRange.JPEG:+ max_code = (1 << bits) - 1+ y.mul_(max_code)+ uv.add_(0.5).mul_(max_code)+ case _:+ raise ValueError(f"Unsupported color range: {color_range}")return y, uv@@ -233,15 +238,6 @@ def yuv420_planes_u16(y: torch.Tensor, uv: torch.Tensor) -> tuple[torch.Tensor,return y16, u16, v16-def _rgb_uint8_fn_(frames: torch.Tensor) -> torch.Tensor:- return frames.clamp_(0.0, 1.0).mul_(255.0).to(torch.uint8).movedim(-3, -1)---def _yuv420p_bt709_fn_(frames: torch.Tensor) -> torch.Tensor:- y, uv = rgb_to_yuv420(frames, ColorSpace.BT_709, ColorRange.MPEG)- return pack_i420(y, uv)--class FrameConverter(enum.Enum):"""Converts ``[*, C, H, W]`` float ``[0, 1]`` frames for encode.Carries encoding metadata so the caller can tag the output stream.@@ -256,9 +252,10 @@ class FrameConverter(enum.Enum):def __call__(self, frames: torch.Tensor) -> torch.Tensor:match self:case FrameConverter.RGB24:- return _rgb_uint8_fn_(frames)+ return frames.clamp_(0.0, 1.0).mul_(255.0).to(torch.uint8).movedim(-3, -1)case FrameConverter.YUV420P_BT709:- return _yuv420p_bt709_fn_(frames)+ y, uv = rgb_to_yuv420(frames, ColorSpace.BT_709, ColorRange.MPEG)+ return pack_i420(y, uv)@propertydef pixel_format(self) -> PixelFormat:diff --git a/packages/ltx-core/src/ltx_core/components/diffusion_steps.py b/packages/ltx-core/src/ltx_core/components/diffusion_steps.pyindex fea46f5..7d74ea3 100644--- a/packages/ltx-core/src/ltx_core/components/diffusion_steps.py+++ b/packages/ltx-core/src/ltx_core/components/diffusion_steps.py@@ -56,10 +56,6 @@ class EulerAncestralDiffusionStep(DiffusionStepProtocol):only at ``eta=0``."""- def __init__(self, eta: float = 1.0, s_noise: float = 1.0) -> None:- self.eta = eta- self.s_noise = s_noise-def step(self,sample: torch.Tensor,@@ -67,6 +63,8 @@ class EulerAncestralDiffusionStep(DiffusionStepProtocol):sigmas: torch.Tensor,step_index: int,noise: torch.Tensor | None = None,+ eta: float = 1.0,+ s_noise: float = 1.0,**_kwargs,) -> torch.Tensor:"""Advance one ancestral Euler step.@@ -77,6 +75,10 @@ class EulerAncestralDiffusionStep(DiffusionStepProtocol):step_index: Current step index.noise: Noise tensor for the renoise term. Required when ``eta > 0``;unused (and may be ``None``) when ``eta == 0``.+ eta: Stochastic noise injection strength. ``0`` is a plain Euler+ step; ``1`` is fully ancestral. Default ``1.0``.+ s_noise: Scale on the injected noise. Default ``1.0``. At ``0`` the+ step still applies its variance-preserving rescale.Returns:Updated latent x_{t-1}, or ``denoised_sample`` when the next sigma is 0."""@@ -84,25 +86,25 @@ class EulerAncestralDiffusionStep(DiffusionStepProtocol):sigma_next = sigmas[step_index + 1].to(torch.float32)if sigma_next == 0:return denoised_sample.to(sample.dtype)- if self.eta > 0 and noise is None:+ if eta > 0 and noise is None:raise ValueError("EulerAncestralDiffusionStep requires a noise tensor when eta > 0")x = sample.to(torch.float32)denoised = denoised_sample.to(torch.float32)- downstep_ratio = 1.0 + (sigma_next / sigma - 1.0) * self.eta+ downstep_ratio = 1.0 + (sigma_next / sigma - 1.0) * etasigma_down = sigma_next * downstep_ratio# Euler step to sigma_down, expressed as an interpolation between x and x_0.sigma_down_ratio = sigma_down / sigmax_next = sigma_down_ratio * x + (1.0 - sigma_down_ratio) * denoised- if self.eta > 0:+ if eta > 0:# Renoise from sigma_down back up to sigma_next.alpha_next = 1.0 - sigma_nextalpha_down = 1.0 - sigma_downrenoise_coeff = (sigma_next**2 - sigma_down**2 * alpha_next**2 / alpha_down**2).clamp(min=0) ** 0.5- x_next = (alpha_next / alpha_down) * x_next + noise.to(torch.float32) * self.s_noise * renoise_coeff+ x_next = (alpha_next / alpha_down) * x_next + noise.to(torch.float32) * s_noise * renoise_coeffreturn x_next.to(sample.dtype)@@ -201,10 +203,6 @@ class EulerCfgPpDiffusionStep(DiffusionStepProtocol):Reference: CFG++ (https://arxiv.org/abs/2406.08070)."""- def __init__(self, eta: float = 1.0, s_noise: float = 1.0) -> None:- self.eta = eta- self.s_noise = s_noise-def step(self,sample: torch.Tensor,@@ -213,6 +211,8 @@ class EulerCfgPpDiffusionStep(DiffusionStepProtocol):step_index: int,uncond_denoised: torch.Tensor,noise: torch.Tensor | None = None,+ eta: float = 1.0,+ s_noise: float = 1.0,**_kwargs,) -> torch.Tensor:"""Advance one CFG++ Euler step.@@ -225,6 +225,8 @@ class EulerCfgPpDiffusionStep(DiffusionStepProtocol):used to compute the ODE derivative direction.noise: Noise tensor for stochastic injection; ignored when``eta=0`` or ``s_noise=0``.+ eta: Stochastic noise injection strength. Default ``1.0``.+ s_noise: Scale on the injected noise. Default ``1.0``.Returns:Updated latent x_{t-1}."""@@ -243,10 +245,10 @@ class EulerCfgPpDiffusionStep(DiffusionStepProtocol):d = (x - alpha_s * uncond) / sigma_s# Ancestral step in rescaled sigma space (sigma / alpha)- sigma_down, sigma_up = _get_ancestral_step(sigma_s / alpha_s, sigma_t / alpha_t, eta=self.eta)+ sigma_down, sigma_up = _get_ancestral_step(sigma_s / alpha_s, sigma_t / alpha_t, eta=eta)sigma_down = alpha_t * sigma_downx_next = alpha_t * denoised + sigma_down * d- if noise is not None and self.eta > 0 and self.s_noise > 0:- x_next = x_next + alpha_t * noise.to(torch.float32) * self.s_noise * sigma_up+ if noise is not None and eta > 0 and s_noise > 0:+ x_next = x_next + alpha_t * noise.to(torch.float32) * s_noise * sigma_upreturn x_next.to(sample.dtype)diff --git a/packages/ltx-core/src/ltx_core/conditioning/__init__.py b/packages/ltx-core/src/ltx_core/conditioning/__init__.pyindex 6ef2982..60b553a 100644--- a/packages/ltx-core/src/ltx_core/conditioning/__init__.py+++ b/packages/ltx-core/src/ltx_core/conditioning/__init__.py@@ -3,6 +3,7 @@from ltx_core.conditioning.exceptions import ConditioningErrorfrom ltx_core.conditioning.item import ConditioningItemfrom ltx_core.conditioning.types import (+ AudioConditionByLatentIndex,AudioConditionByReferenceLatent,ConditioningItemAttentionStrengthWrapper,VideoConditionByKeyframeIndex,@@ -13,6 +14,7 @@ from ltx_core.conditioning.types import ()__all__ = [+ "AudioConditionByLatentIndex","AudioConditionByReferenceLatent","ConditioningError","ConditioningItem",diff --git a/packages/ltx-core/src/ltx_core/conditioning/types/__init__.py b/packages/ltx-core/src/ltx_core/conditioning/types/__init__.pyindex a22c633..f4da95a 100644--- a/packages/ltx-core/src/ltx_core/conditioning/types/__init__.py+++ b/packages/ltx-core/src/ltx_core/conditioning/types/__init__.py@@ -3,12 +3,13 @@from ltx_core.conditioning.types.attention_strength_wrapper import ConditioningItemAttentionStrengthWrapperfrom ltx_core.conditioning.types.keyframe_cond import VideoConditionByKeyframeIndexfrom ltx_core.conditioning.types.keyframe_slots import VideoGeneratedKeyframeSlots-from ltx_core.conditioning.types.latent_cond import VideoConditionByLatentIndex+from ltx_core.conditioning.types.latent_cond import AudioConditionByLatentIndex, VideoConditionByLatentIndexfrom ltx_core.conditioning.types.mask_cond import VideoConditionByMaskfrom ltx_core.conditioning.types.reference_audio_cond import AudioConditionByReferenceLatentfrom ltx_core.conditioning.types.reference_video_cond import VideoConditionByReferenceLatent__all__ = [+ "AudioConditionByLatentIndex","AudioConditionByReferenceLatent","ConditioningItemAttentionStrengthWrapper","VideoConditionByKeyframeIndex",diff --git a/packages/ltx-core/src/ltx_core/conditioning/types/latent_cond.py b/packages/ltx-core/src/ltx_core/conditioning/types/latent_cond.pyindex 00c1816..381f899 100644--- a/packages/ltx-core/src/ltx_core/conditioning/types/latent_cond.py+++ b/packages/ltx-core/src/ltx_core/conditioning/types/latent_cond.py@@ -29,15 +29,59 @@ class VideoConditionByLatentIndex(ConditioningItem):"the image and latent have the same spatial shape.")- tokens = latent_tools.patchifier.patchify(self.latent)- start_token = latent_tools.patchifier.get_token_count(- latent_tools.target_shape._replace(frames=self.latent_idx)+ return _apply_condition_by_latent_index(+ latent_state,+ latent_tools,+ latent=self.latent,+ strength=self.strength,+ latent_idx=self.latent_idx,)- stop_token = start_token + tokens.shape[1]- latent_state = latent_state.clone()- latent_state.clean_latent[:, start_token:stop_token] = tokens- latent_state.denoise_mask[:, start_token:stop_token] = 1.0 - self.strength+class AudioConditionByLatentIndex(ConditioningItem):+ """Inject audio latents at a latent-frame index and set denoise strength on that span.+ Audio counterpart of :class:`VideoConditionByLatentIndex`. Full-coverage freeze is+ ``latent_idx=0`` with ``strength=1.0`` over the whole audio latent.+ """++ def __init__(self, latent: torch.Tensor, strength: float, latent_idx: int):+ self.latent = latent+ self.strength = strength+ self.latent_idx = latent_idx++ def apply_to(self, latent_state: LatentState, latent_tools: LatentTools) -> LatentState:+ cond_batch, cond_channels, _, cond_mel = self.latent.shape+ tgt_batch, tgt_channels, _, tgt_mel = latent_tools.target_shape.to_torch_shape()++ if (cond_batch, cond_channels, cond_mel) != (tgt_batch, tgt_channels, tgt_mel):+ raise ConditioningError(+ f"Can't apply audio conditioning item to latent with shape {latent_tools.target_shape}, expected "+ f"matching batch/channels/mel (got conditioning {(cond_batch, cond_channels, cond_mel)})."+ )++ return _apply_condition_by_latent_index(+ latent_state,+ latent_tools,+ latent=self.latent,+ strength=self.strength,+ latent_idx=self.latent_idx,+ )+++def _apply_condition_by_latent_index(+ latent_state: LatentState,+ latent_tools: LatentTools,+ *,+ latent: torch.Tensor,+ strength: float,+ latent_idx: int,+) -> LatentState:+ """Inject patchified ``latent`` at ``latent_idx`` and set denoise strength on that span."""+ tokens = latent_tools.patchifier.patchify(latent)+ start_token = latent_tools.patchifier.get_token_count(latent_tools.target_shape._replace(frames=latent_idx))+ stop_token = start_token + tokens.shape[1]- return latent_state+ latent_state = latent_state.clone()+ latent_state.clean_latent[:, start_token:stop_token] = tokens+ latent_state.denoise_mask[:, start_token:stop_token] = 1.0 - strength+ return latent_statediff --git a/packages/ltx-core/src/ltx_core/conditioning/types/reference_video_cond.py b/packages/ltx-core/src/ltx_core/conditioning/types/reference_video_cond.pyindex 9e9f234..adf4775 100644--- a/packages/ltx-core/src/ltx_core/conditioning/types/reference_video_cond.py+++ b/packages/ltx-core/src/ltx_core/conditioning/types/reference_video_cond.py@@ -26,6 +26,7 @@ class VideoConditionByReferenceLatent(ConditioningItem):latent: Reference video latents [B, C, F, H, W].downscale_factor: Target/reference spatial ratio (e.g. 2 = half-res ref).temporal_scale_factor: Target/reference temporal ratio S (e.g. 4 = ref at 1/4 fps).+ first_latent_frame: Temporal-grid index assigned to the first frame of ``latent``.strength: Conditioning strength. 1.0 = full (reference kept clean),0.0 = none (reference denoised). Default 1.0."""@@ -36,11 +37,15 @@ class VideoConditionByReferenceLatent(ConditioningItem):downscale_factor: int = 1,temporal_scale_factor: int = 1,strength: float = 1.0,+ first_latent_frame: int = 0,):+ if first_latent_frame < 0:+ raise ValueError(f"first_latent_frame must be >= 0, got {first_latent_frame}")self.latent = latentself.downscale_factor = downscale_factorself.temporal_scale_factor = temporal_scale_factorself.strength = strength+ self.first_latent_frame = first_latent_framedef apply_to(self,@@ -54,6 +59,9 @@ class VideoConditionByReferenceLatent(ConditioningItem):output_shape=VideoLatentShape.from_torch_shape(self.latent.shape),device=self.latent.device,)+ if self.first_latent_frame:+ latent_coords = latent_coords.clone()+ latent_coords[:, 0, :, :] += self.first_latent_framepositions = get_pixel_coords(latent_coords=latent_coords,scale_factors=latent_tools.scale_factors,diff --git a/packages/ltx-core/src/ltx_core/devices.py b/packages/ltx-core/src/ltx_core/devices.pyindex faf0665..f33271b 100644--- a/packages/ltx-core/src/ltx_core/devices.py+++ b/packages/ltx-core/src/ltx_core/devices.py@@ -62,6 +62,16 @@ def highest_precision_float(device: DeviceSpec) -> torch.dtype:return torch.float64 if supports_float64(device) else torch.float32+def allow_async_transfer(device: torch.device) -> bool:+ """Whether a fused host-to-device + dtype-convert transfer to *device* may be non-blocking.+ Only CUDA orders a non-blocking transfer against the consuming kernel+ (same-stream ordering). On MPS the consumer is not fenced against it and+ may read the destination before the transfer lands, silently corrupting the+ consuming computation, so transfers block everywhere but CUDA.+ """+ return device.type == "cuda"++def synchronize_device(device: DeviceSpec = None) -> None:"""Synchronize CUDA or MPS work if the selected backend supports it."""resolved = resolve_device(device)diff --git a/packages/ltx-core/src/ltx_core/hdr.py b/packages/ltx-core/src/ltx_core/hdr.pyindex 7274b22..bcbf05f 100644--- a/packages/ltx-core/src/ltx_core/hdr.py+++ b/packages/ltx-core/src/ltx_core/hdr.py@@ -1,11 +1,5 @@-"""HDR working-space transfers: LogC3 and ACEScct.-Two transforms are supported:-* **LogC3** — ARRI LogC3 (EI 800) camera log curve (HDR IC-LoRA default).-* **ACEScct** — AMPAS S-2016-001 ACEScct log working space (EXR condition round-trip).-Both map linear HDR [0, ∞) <-> a compressed [0, 1] signal. Callers are responsible-for mapping the [0, 1] signal to/from the VAE's [-1, 1] range (``to_vae_range`` on-encode, the VAE decoder's ``to_rgb`` on decode). Used by ltx-pipelines for EXR-conditioning / HDR IC-LoRA and by ltx-trainer for HDR validation.+"""ACEScct working-space compress/decompress and sRGB EOTF.+ACEScct maps linear ACEScg HDR [0, ∞) <-> a compressed [0, 1] signal."""from __future__ import annotations@@ -18,8 +12,8 @@ from torch import Tensorfrom ltx_core.color.primaries import Primaries__all__ = [- "HDRTransfer","TransferEncoding",+ "srgb_eotf_to_linear","to_acescct_working_space","to_hdr_linear",]@@ -32,16 +26,6 @@ class TransferEncoding(enum.Enum):LOG = "log"-# --- curve helpers ------------------------------------------------------------------_LOGC3_A = 5.555556-_LOGC3_B = 0.052272-_LOGC3_C = 0.247190-_LOGC3_D = 0.385537-_LOGC3_E = 5.367655-_LOGC3_F = 0.092809-_LOGC3_CUT = 0.010591-_ACESCCT_A_LIN = 10.5402377416545_ACESCCT_B_LIN = 0.0729055341958355_ACESCCT_X_BRK = 0.0078125@@ -49,124 +33,52 @@ _ACESCCT_Y_BRK = 0.155251141552511_ACESCCT_LOG_M = 17.52_ACESCCT_LOG_B = 9.72--def _compress_logc3(hdr: Tensor) -> Tensor:- x = torch.clamp(hdr, min=0.0)- log_part = _LOGC3_C * torch.log10(_LOGC3_A * x + _LOGC3_B) + _LOGC3_D- lin_part = _LOGC3_E * x + _LOGC3_F- return torch.clamp(torch.where(x >= _LOGC3_CUT, log_part, lin_part), 0.0, 1.0)---def _decompress_logc3(logc: Tensor) -> Tensor:- logc = torch.clamp(logc, 0.0, 1.0)- cut_log = _LOGC3_E * _LOGC3_CUT + _LOGC3_F- lin_from_log = (torch.pow(10.0, (logc - _LOGC3_D) / _LOGC3_C) - _LOGC3_B) / _LOGC3_A- lin_from_lin = (logc - _LOGC3_F) / _LOGC3_E- return torch.where(logc >= cut_log, lin_from_log, lin_from_lin)+# IEC 61966-2-1 sRGB EOTF+_SRGB_A = 0.055+_SRGB_LINEAR_THRESHOLD = 0.04045+_SRGB_LINEAR_SLOPE = 12.92+_SRGB_GAMMA = 2.4-def _compress_acescct(hdr: Tensor) -> Tensor:+def _compress(hdr: Tensor) -> Tensor:+ """Compress linear ACEScg HDR [0, ∞) → ACEScct [0, 1]."""x = torch.clamp(hdr, min=0.0)log_part = (torch.log2(torch.clamp(x, min=1e-12)) + _ACESCCT_LOG_B) / _ACESCCT_LOG_Mlin_part = _ACESCCT_A_LIN * x + _ACESCCT_B_LINreturn torch.clamp(torch.where(x > _ACESCCT_X_BRK, log_part, lin_part), 0.0, 1.0)-def _decompress_acescct(ct: Tensor) -> Tensor:+def _decompress(ct: Tensor) -> Tensor:+ """Decompress ACEScct [0, 1] → linear ACEScg HDR [0, ∞)."""ct = torch.clamp(ct, 0.0, 1.0)lin_from_log = torch.pow(2.0, ct * _ACESCCT_LOG_M - _ACESCCT_LOG_B)lin_from_lin = (ct - _ACESCCT_B_LIN) / _ACESCCT_A_LINreturn torch.where(ct > _ACESCCT_Y_BRK, lin_from_log, lin_from_lin)-class HDRTransfer(enum.Enum):- """VAE HDR working-space transfer curve."""-- LOGC3 = "logc3"- ACESCCT = "acescct"-- @property- def display_name(self) -> str:- """Human / EXR ``colorSpace`` tag name (e.g. ``ACEScct``, ``LogC3``)."""- match self:- case HDRTransfer.LOGC3:- return "LogC3"- case HDRTransfer.ACESCCT:- return "ACEScct"-- @property- def native_primaries(self) -> Primaries:- """Linear primaries the curve is defined on (decompress lands here)."""- match self:- case HDRTransfer.LOGC3:- return Primaries.REC709- case HDRTransfer.ACESCCT:- return Primaries.ACESCG-- def compress(self, hdr: Tensor) -> Tensor:- """Compress linear HDR [0, ∞) → working-space [0, 1]."""- match self:- case HDRTransfer.LOGC3:- return _compress_logc3(hdr)- case HDRTransfer.ACESCCT:- return _compress_acescct(hdr)-- def decompress(self, compressed: Tensor) -> Tensor:- """Decompress working-space [0, 1] → linear HDR [0, ∞)."""- match self:- case HDRTransfer.LOGC3:- return _decompress_logc3(compressed)- case HDRTransfer.ACESCCT:- return _decompress_acescct(compressed)-- def compress_ldr(self, ldr: Tensor) -> Tensor:- """LDR [0, 1] → [0, 1] (identity clamp; transfer-agnostic)."""- return torch.clamp(ldr, 0.0, 1.0)-- def to_working_space(- self,- video: Tensor,- *,- source_primaries: Primaries = Primaries.REC709,- ) -> Tensor:- """Map scene-linear HDR into this transfer's compressed [0, 1] working space.- Rotates ``source_primaries`` into :attr:`native_primaries`, then compresses.- Callers that already have working-space codes should skip this and pass them- straight to ``to_vae_range``.- """- linear_native = source_primaries.to(self.native_primaries, video.float())- return self.compress(linear_native.clamp(min=0.0))-- def to_linear(- self,- working: Tensor,- *,- out_primaries: Primaries = Primaries.REC709,- ) -> Tensor:- """Decompress this transfer's [0, 1] working space to scene-linear HDR.- Decompresses into :attr:`native_primaries`, then converts into ``out_primaries``.- Callers that need to keep log codes (e.g. log-tagged EXR round-trip) should- skip this and write the working signal directly.- """- linear_native = self.decompress(working.float())- return self.native_primaries.to(out_primaries, linear_native).clamp(min=0.0)---# --- thin wrappers for transitional call sites --------------------------------------def to_acescct_working_space(video: Tensor,source_primaries: Primaries = Primaries.REC709,) -> Tensor:"""Compress scene-linear HDR into the ACEScct [0, 1] working space."""- return HDRTransfer.ACESCCT.to_working_space(video, source_primaries=source_primaries)+ linear_acescg = source_primaries.to(Primaries.AP1, video.float())+ return _compress(linear_acescg.clamp(min=0.0))def to_hdr_linear(working: Tensor,- transfer: HDRTransfer = HDRTransfer.LOGC3,out_primaries: Primaries = Primaries.REC709,) -> Tensor:- """Decompress a [0, 1] working-space signal to scene-linear HDR."""- return transfer.to_linear(working, out_primaries=out_primaries)+ """Decompress ACEScct [0, 1] to scene-linear HDR in ``out_primaries``."""+ linear_acescg = _decompress(working.float())+ return Primaries.AP1.to(out_primaries, linear_acescg).clamp(min=0.0)+++def srgb_eotf_to_linear(srgb: Tensor) -> Tensor:+ """sRGB-encoded [0, 1] -> display-linear Rec.709/sRGB (IEC 61966-2-1 EOTF)."""+ x = torch.clamp(srgb.float(), 0.0, 1.0)+ return torch.where(+ x <= _SRGB_LINEAR_THRESHOLD,+ x / _SRGB_LINEAR_SLOPE,+ torch.pow((x + _SRGB_A) / (1.0 + _SRGB_A), _SRGB_GAMMA),+ )diff --git a/packages/ltx-core/src/ltx_core/loader/fuse_loras.py b/packages/ltx-core/src/ltx_core/loader/fuse_loras.pyindex de8e9fc..490a5d8 100644--- a/packages/ltx-core/src/ltx_core/loader/fuse_loras.py+++ b/packages/ltx-core/src/ltx_core/loader/fuse_loras.py@@ -4,6 +4,7 @@ from typing import NamedTupleimport torch+from ltx_core.devices import allow_async_transferfrom ltx_core.loader.primitives import LoraStateDictWithStrength, StateDict@@ -196,9 +197,10 @@ def _products_for_sd_key(prefix = key[: -len(".weight")]key_a = f"{prefix}.lora_A.weight"key_b = f"{prefix}.lora_B.weight"+ non_blocking = allow_async_transfer(device)for lsd, coef in lora_sd_and_strengths:if key_a not in lsd.sd or key_b not in lsd.sd:continue- a = lsd.sd[key_a].to(device=device, dtype=dtype, non_blocking=True)- b = lsd.sd[key_b].to(device=device, dtype=dtype, non_blocking=True)+ a = lsd.sd[key_a].to(device=device, dtype=dtype, non_blocking=non_blocking)+ b = lsd.sd[key_b].to(device=device, dtype=dtype, non_blocking=non_blocking)yield LoraProduct(a, b, coef)diff --git a/packages/ltx-core/src/ltx_core/modality_tiling.py b/packages/ltx-core/src/ltx_core/modality_tiling.pyindex f5ecf5c..8d988ba 100644--- a/packages/ltx-core/src/ltx_core/modality_tiling.py+++ b/packages/ltx-core/src/ltx_core/modality_tiling.py@@ -21,6 +21,7 @@ from ltx_core.tiling import (SplitOperation,Tile,TileCountConfig,+ TileSizeConfig,create_tiles,identity_mapping_operation,split_at_seams,@@ -95,7 +96,7 @@ class VideoModalityTilingHelper:def __init__(self,- tiling: TileCountConfig,+ tiling: TileCountConfig | TileSizeConfig,video_tools: VideoLatentTools,seams: Sequence[int] = (),) -> None:@@ -104,7 +105,11 @@ class VideoModalityTilingHelper:self._num_generated_tokens = self._patchifier.get_token_count(self._latent_shape)frames, height, width = tiling.to_splitters(video_tools.scale_factors, causal_temporal=False)frames_mapper = identity_mapping_operation- seam_op = seam_split(seams, self._latent_shape.frames, tiling.frames)+ if seams and not isinstance(tiling, TileCountConfig):+ raise ValueError("Known temporal seams require count-based tiling")+ seam_op = (+ seam_split(seams, self._latent_shape.frames, tiling.frames) if isinstance(tiling, TileCountConfig) else None+ )if seam_op is not None:frames, frames_mapper = seam_op, partial(identity_mapping_operation, rectangular=True)self._tiles = create_tiles(diff --git a/packages/ltx-core/src/ltx_core/model/transformer/attention.py b/packages/ltx-core/src/ltx_core/model/transformer/attention.pyindex 8a38552..4d108c7 100644--- a/packages/ltx-core/src/ltx_core/model/transformer/attention.py+++ b/packages/ltx-core/src/ltx_core/model/transformer/attention.py@@ -7,13 +7,7 @@ from typing import Protocolimport torchfrom torch.nn.attention import SDPBackend, sdpa_kernel-from ltx_core.model.transformer.ops import (- GatedAttentionCallable,- PreAttentionCallable,- PytorchGatedAttention,- PytorchPreAttention,-)-from ltx_core.model.transformer.rope import LTXRopeType+from ltx_core.model.transformer.rope import LTXRopeType, apply_rotary_embdef _torch_default_sdpa_priority() -> list[SDPBackend]:@@ -471,8 +465,6 @@ class AttentionOps:masked_attention_function: MaskedAttentionCallable = field(default_factory=lambda: MaskedAttentionFunction.AUTOMATIC.to_callable())- preattention_function: PreAttentionCallable = field(default_factory=PytorchPreAttention)- gated_attention_function: GatedAttentionCallable = field(default_factory=PytorchGatedAttention)class Attention(torch.nn.Module):@@ -493,8 +485,6 @@ class Attention(torch.nn.Module):self.rope_type = rope_typeself.attention_function = ops.attention_functionself.masked_attention_function = ops.masked_attention_function- self.preattention_function = ops.preattention_function- self.gated_attention_function = ops.gated_attention_functioninner_dim = dim_head * headscontext_dim = query_dim if context_dim is None else context_dim@@ -563,7 +553,11 @@ class Attention(torch.nn.Module):else:q = self.to_q(x)k = self.to_k(context)- q, k = self.preattention_function(q, k, self, mask, pe, k_pe)+ q = self.q_norm(q)+ k = self.k_norm(k)+ if pe is not None:+ q = apply_rotary_emb(q, pe, self.rope_type)+ k = apply_rotary_emb(k, pe if k_pe is None else k_pe, self.rope_type)if mask is None:out = self.attention_function(q, k, v, self.heads) # (B, T, H*D)else:@@ -574,6 +568,11 @@ class Attention(torch.nn.Module):# Apply per-head gating if enabledif self.to_gate_logits is not None:- out = self.gated_attention_function(x, out, self)+ gate_logits = self.to_gate_logits(x)+ b, t, _ = out.shape+ out = out.view(b, t, self.heads, self.dim_head)+ gates = 2.0 * torch.sigmoid(gate_logits)+ out = out * gates.unsqueeze(-1)+ out = out.view(b, t, self.heads * self.dim_head)return self.to_out(out)diff --git a/packages/ltx-core/src/ltx_core/model/transformer/model.py b/packages/ltx-core/src/ltx_core/model/transformer/model.pyindex dc00164..9783d5b 100644--- a/packages/ltx-core/src/ltx_core/model/transformer/model.py+++ b/packages/ltx-core/src/ltx_core/model/transformer/model.py@@ -7,15 +7,10 @@ from ltx_core.guidance.perturbations import BatchedPerturbationConfig, Perturbatfrom ltx_core.model.disposable import Disposablefrom ltx_core.model.model_protocol import LTXModelProtocolfrom ltx_core.model.transformer.adaln import AdaLayerNormSingle, adaln_embedding_coefficient-from ltx_core.model.transformer.attention import attention_label+from ltx_core.model.transformer.attention import AttentionOps, attention_labelfrom ltx_core.model.transformer.modality import Modalityfrom ltx_core.model.transformer.rope import LTXRopeType-from ltx_core.model.transformer.transformer import (- DEFAULT_TRANSFORMER_OPS,- BasicAVTransformerBlock,- TransformerConfig,- TransformerOpsConfig,-)+from ltx_core.model.transformer.transformer import BasicAVTransformerBlock, TransformerConfigfrom ltx_core.model.transformer.transformer_args import (BlockPerturbationsProcessor,MultiModalTransformerArgsPreprocessor,@@ -56,7 +51,7 @@ class LTXModel(torch.nn.Module, Disposable):num_layers: int = 48,cross_attention_dim: int = 4096,norm_eps: float = 1e-06,- ops: TransformerOpsConfig = DEFAULT_TRANSFORMER_OPS,+ attention_ops: AttentionOps | None = None,positional_embedding_theta: float = 10000.0,positional_embedding_max_pos: list[int] | None = None,timestep_scale_multiplier: int = 1000,@@ -80,14 +75,15 @@ class LTXModel(torch.nn.Module, Disposable):use_keyframes_abs_pos_embedding: bool = False,):super().__init__()+ attention_ops = attention_ops or AttentionOps()# Log the attention backends this transformer is built with. Reading the resolved# ``label`` off the ops reports whatever was selected -- AUTOMATIC, an explicit pin# (PYTORCH/FA3/FA4/SDPA_*), or a directly supplied callable -- so this is the# single source of truth for which kernel a build uses. Fires once per build.logger.info("Building transformer with attention backends -- self: %s, masked: %s",- attention_label(ops.attention_ops.attention_function),- attention_label(ops.attention_ops.masked_attention_function),+ attention_label(attention_ops.attention_function),+ attention_label(attention_ops.masked_attention_function),)self._enable_gradient_checkpointing = Falseself.cross_attention_adaln = cross_attention_adaln@@ -141,7 +137,7 @@ class LTXModel(torch.nn.Module, Disposable):audio_attention_head_dim=audio_attention_head_dim if model_type.is_audio_enabled() else 0,audio_cross_attention_dim=audio_cross_attention_dim,norm_eps=norm_eps,- ops=ops,+ attention_ops=attention_ops,apply_gated_attention=apply_gated_attention,ff_bias=ff_bias,audio_ff_bias=audio_ff_bias,@@ -372,7 +368,7 @@ class LTXModel(torch.nn.Module, Disposable):audio_attention_head_dim: int,audio_cross_attention_dim: int,norm_eps: float,- ops: TransformerOpsConfig,+ attention_ops: AttentionOps | None,apply_gated_attention: bool,ff_bias: bool = True,audio_ff_bias: bool = True,@@ -411,7 +407,7 @@ class LTXModel(torch.nn.Module, Disposable):audio=audio_config,rope_type=self.rope_type,norm_eps=norm_eps,- ops=ops,+ attention_ops=attention_ops,)for _ in range(num_layers)]diff --git a/packages/ltx-core/src/ltx_core/model/transformer/model_configurator.py b/packages/ltx-core/src/ltx_core/model/transformer/model_configurator.pyindex 8661527..45f1342 100644--- a/packages/ltx-core/src/ltx_core/model/transformer/model_configurator.py+++ b/packages/ltx-core/src/ltx_core/model/transformer/model_configurator.py@@ -5,7 +5,6 @@ from ltx_core.model.model_protocol import ModelConfiguratorfrom ltx_core.model.transformer.model import LTXModel, LTXModelTypefrom ltx_core.model.transformer.rope import LTXRopeTypefrom ltx_core.model.transformer.text_projection import create_caption_projection-from ltx_core.model.transformer.transformer import DEFAULT_TRANSFORMER_OPS, TransformerOpsConfigfrom ltx_core.utils import check_config_value@@ -16,7 +15,7 @@ class LTXModelConfigurator(ModelConfigurator[LTXModel]):"""@classmethod- def from_metadata(cls, metadata: dict, ops: TransformerOpsConfig = DEFAULT_TRANSFORMER_OPS) -> LTXModel:+ def from_metadata(cls, metadata: dict) -> LTXModel:config = metadata.get("config", {})# Build caption projections for 19B models (projection handled in transformer).caption_projection, audio_caption_projection = _build_caption_projections(config, is_av=True)@@ -52,7 +51,6 @@ class LTXModelConfigurator(ModelConfigurator[LTXModel]):num_layers=config.get("num_layers", 48),cross_attention_dim=config.get("cross_attention_dim", 4096),norm_eps=config.get("norm_eps", 1e-06),- ops=ops,positional_embedding_theta=config.get("positional_embedding_theta", 10000.0),positional_embedding_max_pos=config.get("positional_embedding_max_pos", [20, 2048, 2048]),timestep_scale_multiplier=config.get("timestep_scale_multiplier", 1000),@@ -90,7 +88,7 @@ class LTXVideoOnlyModelConfigurator(ModelConfigurator[LTXModel]):"""@classmethod- def from_metadata(cls, metadata: dict, ops: TransformerOpsConfig = DEFAULT_TRANSFORMER_OPS) -> LTXModel:+ def from_metadata(cls, metadata: dict) -> LTXModel:config = metadata.get("config", {})# Build caption projection for 19B model (projection handled in transformer).caption_projection, _ = _build_caption_projections(config, is_av=False)@@ -122,7 +120,6 @@ class LTXVideoOnlyModelConfigurator(ModelConfigurator[LTXModel]):num_layers=config.get("num_layers", 48),cross_attention_dim=config.get("cross_attention_dim", 4096),norm_eps=config.get("norm_eps", 1e-06),- ops=ops,positional_embedding_theta=config.get("positional_embedding_theta", 10000.0),positional_embedding_max_pos=config.get("positional_embedding_max_pos", [20, 2048, 2048]),timestep_scale_multiplier=config.get("timestep_scale_multiplier", 1000),@@ -152,7 +149,7 @@ class LTXAudioOnlyModelConfigurator(ModelConfigurator[LTXModel]):"""@classmethod- def from_metadata(cls, metadata: dict, ops: TransformerOpsConfig = DEFAULT_TRANSFORMER_OPS) -> LTXModel:+ def from_metadata(cls, metadata: dict) -> LTXModel:config = metadata.get("config", {})# Build audio caption projection for 19B models (projection handled in transformer)._, audio_caption_projection = _build_caption_projections(config, is_av=True)@@ -179,7 +176,6 @@ class LTXAudioOnlyModelConfigurator(ModelConfigurator[LTXModel]):model_type=LTXModelType.AudioOnly,num_layers=config.get("num_layers", 48),norm_eps=config.get("norm_eps", 1e-06),- ops=ops,timestep_scale_multiplier=config.get("timestep_scale_multiplier", 1000),use_middle_indices_grid=config.get("use_middle_indices_grid", True),audio_num_attention_heads=config.get("audio_num_attention_heads", 32),diff --git a/packages/ltx-core/src/ltx_core/model/transformer/ops.py b/packages/ltx-core/src/ltx_core/model/transformer/ops.pydeleted file mode 100644index 02c86ec..0000000--- a/packages/ltx-core/src/ltx_core/model/transformer/ops.py+++ /dev/null@@ -1,106 +0,0 @@-from typing import List, Protocol--import torch-from torch import nn--from ltx_core.model.transformer.rope import apply_rotary_emb-from ltx_core.utils import rms_norm---class PreAttentionCallable(Protocol):- def __call__(- self,- q: torch.Tensor,- k: torch.Tensor,- attn_module: nn.Module,- mask: torch.Tensor | None,- pe: torch.Tensor | None,- k_pe: torch.Tensor | None,- ) -> tuple[torch.Tensor, torch.Tensor]: ...---class PytorchPreAttention(PreAttentionCallable):- def __call__(- self,- q: torch.Tensor,- k: torch.Tensor,- attn_module: nn.Module,- mask: torch.Tensor | None, # noqa: ARG002- pe: torch.Tensor | None,- k_pe: torch.Tensor | None,- ) -> tuple[torch.Tensor, torch.Tensor]:- q = attn_module.q_norm(q)- k = attn_module.k_norm(k)- if pe is not None:- q = apply_rotary_emb(q, pe, attn_module.rope_type)- k = apply_rotary_emb(k, pe if k_pe is None else k_pe, attn_module.rope_type)- return q, k---class AdaZeroCallable(Protocol):- def __call__(- self,- x: torch.Tensor,- eps: float,- scale: torch.Tensor,- shift: torch.Tensor,- ) -> torch.Tensor: ...---class PytorchAdaZeroFunction(AdaZeroCallable):- def __call__(- self,- x: torch.Tensor,- eps: float,- scale: torch.Tensor,- shift: torch.Tensor,- ) -> torch.Tensor:- return rms_norm(x, eps=eps) * (1 + scale) + shift---class PostSACallable(Protocol):- def __call__(- self,- x: torch.Tensor,- y: torch.Tensor,- norm_weights: torch.Tensor | None,- eps: float,- gate: torch.Tensor,- ) -> List[torch.Tensor]: ...---class PytorchPostSAFunction(PostSACallable):- def __call__(- self,- x: torch.Tensor,- y: torch.Tensor,- norm_weights: torch.Tensor | None,- eps: float,- gate: torch.Tensor,- ) -> List[torch.Tensor]:- x_fma = x + y * gate- return x_fma, rms_norm(x_fma, norm_weights, eps=eps)---class GatedAttentionCallable(Protocol):- def __call__(- self,- x: torch.Tensor,- attn_out: torch.Tensor,- attn_module: nn.Module,- ) -> torch.Tensor: ...---class PytorchGatedAttention(GatedAttentionCallable):- def __call__(- self,- x: torch.Tensor,- attn_out: torch.Tensor,- attn_module: nn.Module,- ) -> torch.Tensor:- gate_logits = attn_module.to_gate_logits(x) # (B, T, H)- b, t, _ = attn_out.shape- out = attn_out.view(b, t, attn_module.heads, attn_module.dim_head)- gates = 2.0 * torch.sigmoid(gate_logits) # (B, T, H)- out = out * gates.unsqueeze(-1) # (B, T, H, D) * (B, T, H, 1)- return out.view(b, t, attn_module.heads * attn_module.dim_head)diff --git a/packages/ltx-core/src/ltx_core/model/transformer/rope.py b/packages/ltx-core/src/ltx_core/model/transformer/rope.pyindex e66c5f0..5ebfbf8 100644--- a/packages/ltx-core/src/ltx_core/model/transformer/rope.py+++ b/packages/ltx-core/src/ltx_core/model/transformer/rope.py@@ -69,11 +69,9 @@ def apply_split_rotary_emb(second_half_input = split_input[..., 1:, :]output = split_input * cos_freqs.unsqueeze(-2)- first_half_output = output[..., :1, :]- second_half_output = output[..., 1:, :]-- first_half_output.addcmul_(-sin_freqs.unsqueeze(-2), second_half_input)- second_half_output.addcmul_(sin_freqs.unsqueeze(-2), first_half_input)+ first_half_output = output[..., :1, :].addcmul(-sin_freqs.unsqueeze(-2), second_half_input)+ second_half_output = output[..., 1:, :].addcmul(sin_freqs.unsqueeze(-2), first_half_input)+ output = torch.cat([first_half_output, second_half_output], dim=-2)output = rearrange(output, "... d r -> ... (d r)")if needs_reshape:@@ -86,7 +84,10 @@ def apply_split_rotary_emb(@functools.lru_cache(maxsize=5)def generate_freq_grid_np(- positional_embedding_theta: float, positional_embedding_max_pos_count: int, inner_dim: int+ positional_embedding_theta: float,+ positional_embedding_max_pos_count: int,+ inner_dim: int,+ device: torch.device | None = None,) -> torch.Tensor:theta = positional_embedding_thetastart = 1@@ -104,12 +105,15 @@ def generate_freq_grid_np()# as_tensor (not tensor): under torch.compile the numpy ops above are traced as tensors,# so torch.tensor() would copy-construct from a tensor (warns); as_tensor casts in place.- return torch.as_tensor(pow_indices * math.pi / 2, dtype=torch.float32)+ return torch.as_tensor(pow_indices * math.pi / 2, dtype=torch.float32).to(device=device)@functools.lru_cache(maxsize=5)def generate_freq_grid_pytorch(- positional_embedding_theta: float, positional_embedding_max_pos_count: int, inner_dim: int+ positional_embedding_theta: float,+ positional_embedding_max_pos_count: int,+ inner_dim: int,+ device: torch.device | None = None,) -> torch.Tensor:theta = positional_embedding_thetastart = 1@@ -128,7 +132,7 @@ def generate_freq_grid_pytorch(indices = indices * math.pi / 2- return indices+ return indices.to(device=device)def get_fractional_positions(indices_grid: torch.Tensor, max_pos: list[int]) -> torch.Tensor:@@ -209,7 +213,9 @@ def precompute_freqs_cis(if max_pos is None:max_pos = [20, 2048, 2048]- indices = freq_grid_generator(theta, indices_grid.shape[1], dim)+ # The grids are computed on the CPU and cached per device: a pageable host-to-device copy blocks+ # the host until the device drains, so repeating it every call keeps the host from running ahead.+ indices = freq_grid_generator(theta, indices_grid.shape[1], dim, indices_grid.device)freqs = generate_freqs(indices, indices_grid, max_pos, use_middle_indices_grid)if rope_type == LTXRopeType.SPLIT:diff --git a/packages/ltx-core/src/ltx_core/model/transformer/transformer.py b/packages/ltx-core/src/ltx_core/model/transformer/transformer.pyindex 1d874f1..02ab32d 100644--- a/packages/ltx-core/src/ltx_core/model/transformer/transformer.py+++ b/packages/ltx-core/src/ltx_core/model/transformer/transformer.py@@ -1,29 +1,13 @@-from dataclasses import dataclass, field, replace+from dataclasses import dataclass, replaceimport torchfrom ltx_core.model.transformer.adaln import adaln_embedding_coefficient-from ltx_core.model.transformer.attention import (- Attention,- AttentionCallable,- AttentionFunction,- AttentionOps,- MaskedAttentionCallable,- MaskedAttentionFunction,-)+from ltx_core.model.transformer.attention import Attention, AttentionCallable, AttentionOpsfrom ltx_core.model.transformer.feed_forward import FeedForward-from ltx_core.model.transformer.ops import (- AdaZeroCallable,- GatedAttentionCallable,- PostSACallable,- PreAttentionCallable,- PytorchAdaZeroFunction,- PytorchGatedAttention,- PytorchPostSAFunction,- PytorchPreAttention,-)from ltx_core.model.transformer.rope import LTXRopeTypefrom ltx_core.model.transformer.transformer_args import TransformerArgs+from ltx_core.utils import rms_norm@dataclass@@ -37,53 +21,6 @@ class TransformerConfig:ff_bias: bool = True-@dataclass(frozen=True)-class TransformerOpsConfig:- """Pluggable ops for :class:`BasicAVTransformerBlock`.- Use :meth:`from_functions` to construct from enum values or partial overrides- without spelling out a full :class:`AttentionOps`.- """-- attention_ops: AttentionOps = field(default_factory=AttentionOps)- ada_zero_function: AdaZeroCallable = field(default_factory=PytorchAdaZeroFunction)- post_sa_function: PostSACallable = field(default_factory=PytorchPostSAFunction)-- @classmethod- def from_functions(- cls,- attention: AttentionFunction | AttentionCallable = AttentionFunction.AUTOMATIC,- masked_attention: MaskedAttentionFunction | MaskedAttentionCallable = MaskedAttentionFunction.AUTOMATIC,- preattention: PreAttentionCallable | None = None,- gated_attention: GatedAttentionCallable | None = None,- ada_zero: AdaZeroCallable | None = None,- post_sa: PostSACallable | None = None,- ) -> "TransformerOpsConfig":- """Build a config from individual functions or enums. Each *None* slot- falls back to the standard PyTorch implementation."""- attention_callable = attention.to_callable() if isinstance(attention, AttentionFunction) else attention- masked_callable = (- masked_attention.to_callable()- if isinstance(masked_attention, MaskedAttentionFunction)- else masked_attention- )- attention_ops = AttentionOps(- attention_function=attention_callable,- masked_attention_function=masked_callable,- preattention_function=preattention if preattention is not None else PytorchPreAttention(),- gated_attention_function=(gated_attention if gated_attention is not None else PytorchGatedAttention()),- )- return cls(- attention_ops=attention_ops,- ada_zero_function=ada_zero if ada_zero is not None else PytorchAdaZeroFunction(),- post_sa_function=post_sa if post_sa is not None else PytorchPostSAFunction(),- )---# Frozen, so safe to share as a default argument across callers that want the-# stock PyTorch ops without explicit construction.-DEFAULT_TRANSFORMER_OPS = TransformerOpsConfig()--class BasicAVTransformerBlock(torch.nn.Module):def __init__(self,@@ -91,14 +28,12 @@ class BasicAVTransformerBlock(torch.nn.Module):audio: TransformerConfig | None = None,rope_type: LTXRopeType = LTXRopeType.SPLIT,norm_eps: float = 1e-6,- ops: TransformerOpsConfig | None = None,+ attention_ops: AttentionOps | None = None,):super().__init__()- if ops is None:- ops = TransformerOpsConfig()- self.ada_zero_function = ops.ada_zero_function- self.post_sa_function = ops.post_sa_function+ if attention_ops is None:+ attention_ops = AttentionOps()if video is not None:self.attn1 = Attention(query_dim=video.dim,@@ -107,7 +42,7 @@ class BasicAVTransformerBlock(torch.nn.Module):context_dim=None,rope_type=rope_type,norm_eps=norm_eps,- ops=ops.attention_ops,+ ops=attention_ops,apply_gated_attention=video.apply_gated_attention,)self.attn2 = Attention(@@ -117,7 +52,7 @@ class BasicAVTransformerBlock(torch.nn.Module):dim_head=video.d_head,rope_type=rope_type,norm_eps=norm_eps,- ops=ops.attention_ops,+ ops=attention_ops,apply_gated_attention=video.apply_gated_attention,)self.ff = FeedForward(video.dim, dim_out=video.dim, bias=video.ff_bias)@@ -132,7 +67,7 @@ class BasicAVTransformerBlock(torch.nn.Module):context_dim=None,rope_type=rope_type,norm_eps=norm_eps,- ops=ops.attention_ops,+ ops=attention_ops,apply_gated_attention=audio.apply_gated_attention,)self.audio_attn2 = Attention(@@ -142,7 +77,7 @@ class BasicAVTransformerBlock(torch.nn.Module):dim_head=audio.d_head,rope_type=rope_type,norm_eps=norm_eps,- ops=ops.attention_ops,+ ops=attention_ops,apply_gated_attention=audio.apply_gated_attention,)self.audio_ff = FeedForward(audio.dim, dim_out=audio.dim, bias=audio.ff_bias)@@ -158,7 +93,7 @@ class BasicAVTransformerBlock(torch.nn.Module):dim_head=audio.d_head,rope_type=rope_type,norm_eps=norm_eps,- ops=ops.attention_ops,+ ops=attention_ops,apply_gated_attention=video.apply_gated_attention,)@@ -170,7 +105,7 @@ class BasicAVTransformerBlock(torch.nn.Module):dim_head=audio.d_head,rope_type=rope_type,norm_eps=norm_eps,- ops=ops.attention_ops,+ ops=attention_ops,apply_gated_attention=audio.apply_gated_attention,)@@ -233,8 +168,8 @@ class BasicAVTransformerBlock(torch.nn.Module):cross_attention_adaln: bool = False,) -> torch.Tensor:"""Apply text cross-attention, with optional AdaLN modulation.- ``x_normed`` is the RMS-normalized self-attention output produced by- ``post_sa_function`` -- this method does not normalize again.+ ``x_normed`` is the RMS-normalized post-self-attention output (produced by+ the PostSA composite); this method does not normalize again."""if cross_attention_adaln:shift_q, scale_q, gate = self.get_ada_values(scale_shift_table, x_normed.shape[0], timestep, slice(6, 9))@@ -272,7 +207,7 @@ class BasicAVTransformerBlock(torch.nn.Module):vshift_msa, vscale_msa, vgate_msa = self.get_ada_values(self.scale_shift_table, vx.shape[0], video.timesteps, slice(0, 3))- norm_vx = self.ada_zero_function(vx, self.norm_eps, vscale_msa, vshift_msa)+ norm_vx = rms_norm(vx, eps=self.norm_eps) * (1 + vscale_msa) + vshift_msadel vshift_msa, vscale_msavx_msa_out = self.attn1(@@ -282,7 +217,8 @@ class BasicAVTransformerBlock(torch.nn.Module):perturbation_mask=video.self_attn_perturbation_mask,all_perturbed=video.self_attn_all_perturbed,)- vx, vx_normed = self.post_sa_function(vx, vx_msa_out, None, self.norm_eps, vgate_msa)+ vx = vx + vx_msa_out * vgate_msa+ vx_normed = rms_norm(vx, eps=self.norm_eps)del vgate_msa, norm_vx, vx_msa_outvx = vx + self._apply_text_cross_attention(vx_normed,@@ -302,7 +238,7 @@ class BasicAVTransformerBlock(torch.nn.Module):self.audio_scale_shift_table, ax.shape[0], audio.timesteps, slice(0, 3))- norm_ax = self.ada_zero_function(ax, self.norm_eps, ascale_msa, ashift_msa)+ norm_ax = rms_norm(ax, eps=self.norm_eps) * (1 + ascale_msa) + ashift_msadel ashift_msa, ascale_msaax_msa_out = self.audio_attn1(norm_ax,@@ -311,7 +247,8 @@ class BasicAVTransformerBlock(torch.nn.Module):perturbation_mask=audio.self_attn_perturbation_mask,all_perturbed=audio.self_attn_all_perturbed,)- ax, ax_normed = self.post_sa_function(ax, ax_msa_out, None, self.norm_eps, agate_msa)+ ax = ax + ax_msa_out * agate_msa+ ax_normed = rms_norm(ax, eps=self.norm_eps)del agate_msa, norm_ax, ax_msa_outax = ax + self._apply_text_cross_attention(ax_normed,@@ -340,7 +277,7 @@ class BasicAVTransformerBlock(torch.nn.Module):video.cross_gate_timestep,slice(0, 2),)- a2v_vx_scaled = self.ada_zero_function(vx_pre_av, self.norm_eps, scale_ca_video_a2v, shift_ca_video_a2v)+ a2v_vx_scaled = rms_norm(vx_pre_av, eps=self.norm_eps) * (1 + scale_ca_video_a2v) + shift_ca_video_a2vdel scale_ca_video_a2v, shift_ca_video_a2vscale_ca_audio_a2v, shift_ca_audio_a2v, _ = self.get_av_ca_ada_values(@@ -350,7 +287,7 @@ class BasicAVTransformerBlock(torch.nn.Module):audio.cross_gate_timestep,slice(0, 2),)- a2v_ax_scaled = self.ada_zero_function(ax_pre_av, self.norm_eps, scale_ca_audio_a2v, shift_ca_audio_a2v)+ a2v_ax_scaled = rms_norm(ax_pre_av, eps=self.norm_eps) * (1 + scale_ca_audio_a2v) + shift_ca_audio_a2vdel scale_ca_audio_a2v, shift_ca_audio_a2vvx = vx + (self.audio_to_video_attn(@@ -372,7 +309,7 @@ class BasicAVTransformerBlock(torch.nn.Module):audio.cross_gate_timestep,slice(2, 4),)- v2a_ax_scaled = self.ada_zero_function(ax_pre_av, self.norm_eps, scale_ca_audio_v2a, shift_ca_audio_v2a)+ v2a_ax_scaled = rms_norm(ax_pre_av, eps=self.norm_eps) * (1 + scale_ca_audio_v2a) + shift_ca_audio_v2adel scale_ca_audio_v2a, shift_ca_audio_v2ascale_ca_video_v2a, shift_ca_video_v2a, _ = self.get_av_ca_ada_values(self.scale_shift_table_a2v_ca_video,@@ -381,7 +318,7 @@ class BasicAVTransformerBlock(torch.nn.Module):video.cross_gate_timestep,slice(2, 4),)- v2a_vx_scaled = self.ada_zero_function(vx_pre_av, self.norm_eps, scale_ca_video_v2a, shift_ca_video_v2a)+ v2a_vx_scaled = rms_norm(vx_pre_av, eps=self.norm_eps) * (1 + scale_ca_video_v2a) + shift_ca_video_v2adel scale_ca_video_v2a, shift_ca_video_v2aax = ax + (self.video_to_audio_attn(@@ -400,7 +337,7 @@ class BasicAVTransformerBlock(torch.nn.Module):vshift_mlp, vscale_mlp, vgate_mlp = self.get_ada_values(self.scale_shift_table, vx.shape[0], video.timesteps, slice(3, 6))- vx_scaled = self.ada_zero_function(vx, self.norm_eps, vscale_mlp, vshift_mlp)+ vx_scaled = rms_norm(vx, eps=self.norm_eps) * (1 + vscale_mlp) + vshift_mlpvx = vx + self.ff(vx_scaled) * vgate_mlpdel vshift_mlp, vscale_mlp, vgate_mlp, vx_scaled@@ -409,7 +346,7 @@ class BasicAVTransformerBlock(torch.nn.Module):ashift_mlp, ascale_mlp, agate_mlp = self.get_ada_values(self.audio_scale_shift_table, ax.shape[0], audio.timesteps, slice(3, 6))- ax_scaled = self.ada_zero_function(ax, self.norm_eps, ascale_mlp, ashift_mlp)+ ax_scaled = rms_norm(ax, eps=self.norm_eps) * (1 + ascale_mlp) + ashift_mlpax = ax + self.audio_ff(ax_scaled) * agate_mlpdel ashift_mlp, ascale_mlp, agate_mlp, ax_scaled@@ -429,9 +366,8 @@ def apply_cross_attention_adaln(context_mask: torch.Tensor | None = None,) -> torch.Tensor:"""Apply query/key AdaLN modulation then cross-attention.- ``x_normed`` is already RMS-normalized by ``post_sa_function``; this only- applies the affine (scale/shift) modulation, so the normalization is not- repeated here.+ ``x_normed`` is already RMS-normalized by the PostSA composite; this only+ applies the affine (scale/shift) modulation, so normalization is not repeated."""batch_size = x_normed.shape[0]# K/V modulation. With the prompt-side AdaLN MLP disabled (use_prompt_adaln_single=False),diff --git a/packages/ltx-core/src/ltx_core/model/video_vae/conv_video_decoder.py b/packages/ltx-core/src/ltx_core/model/video_vae/conv_video_decoder.pyindex 93693c2..b537297 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/conv_video_decoder.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/conv_video_decoder.py@@ -493,6 +493,7 @@ class ConvVideoDecoder(nn.Module, Disposable, VideoDecoder):generator: torch.Generator | None = None,*,keyframes: DecodeKeyframes | None = None,+ **_kwargs: object,) -> Iterator[torch.Tensor]:"""Decode a video latent tensor, yielding float chunks ``[f, h, w, c]`` in ``[0, 1]``.Subclasses (e.g. ``DistributedVideoDecoder``) may override this todiff --git a/packages/ltx-core/src/ltx_core/model/video_vae/diffusion_video_decoder.py b/packages/ltx-core/src/ltx_core/model/video_vae/diffusion_video_decoder.pyindex 2dfb3d4..1ffd659 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/diffusion_video_decoder.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/diffusion_video_decoder.py@@ -1563,6 +1563,7 @@ class DiffusionVideoDecoder(nn.Module, Disposable, VideoDecoder):generator: torch.Generator | None = None,*,keyframes: DecodeKeyframes | None = None,+ **_kwargs: object,) -> Iterator[torch.Tensor]:"""Decode latent video, yielding float chunk(s) ``[f, h, w, c]`` in ``[0, 1]``.Untiled and tiled both go through ``_decode_pixels``. Tiled decode may yielddiff --git a/packages/ltx-core/src/ltx_core/model/video_vae/video_vae.py b/packages/ltx-core/src/ltx_core/model/video_vae/video_vae.pyindex 8359d87..c3f8d8d 100644--- a/packages/ltx-core/src/ltx_core/model/video_vae/video_vae.py+++ b/packages/ltx-core/src/ltx_core/model/video_vae/video_vae.py@@ -481,10 +481,11 @@ def prepare_tiles_for_encoding(return tiles-def _clip_generators(+def clip_generators(count: int,generator: torch.Generator | Sequence[torch.Generator | None] | None,) -> Sequence[torch.Generator | None]:+ """One generator per clip: broadcast a single generator (or ``None``), or check a sequence."""if generator is None:return (None,) * countif isinstance(generator, torch.Generator):@@ -494,6 +495,19 @@ def _clip_generators(return generator+def validate_single_frame_latents(latents: Sequence[torch.Tensor]) -> None:+ """Raise unless every entry is a ``(B, C, 1, H, W)`` single-frame latent.+ Checked over the whole list before any of it is decoded, so a decode that splits the list+ across ranks raises on every rank instead of only on the one that owns the bad plane -- a+ lone raiser leaves the rest of the group waiting on a collective that never comes.+ """+ for index, latent in enumerate(latents):+ if latent.ndim != 5 or latent.shape[2] != 1:+ raise ValueError(+ f"decode_single_frames expects (B, C, 1, H, W) latents, got {tuple(latent.shape)} at index {index}"+ )++def iter_decoded_single_frames(decoder: "VideoDecoder",latents: Sequence[torch.Tensor],@@ -503,12 +517,9 @@ def iter_decoded_single_frames(Dist must pass the inner SGPU decoder, not itself: ``decode_video`` on Dist splits thevolume and workers return an empty iterator."""- gens = _clip_generators(len(latents), generator)+ gens = clip_generators(len(latents), generator)+ validate_single_frame_latents(latents)for index, (latent, gen) in enumerate(zip(latents, gens, strict=True)):- if latent.ndim != 5 or latent.shape[2] != 1:- raise ValueError(- f"decode_single_frames expects (B, C, 1, H, W) latents, got {tuple(latent.shape)} at index {index}"- )chunks = list(decoder.decode_video(latent, tiling_config=None, generator=gen))if not chunks:raise RuntimeError(f"Decoder returned no pixels for single-frame latent {index}")@@ -531,6 +542,7 @@ class VideoDecoder(Protocol):generator: torch.Generator | None = None,*,keyframes: "DecodeKeyframes | None" = None,+ **kwargs: object,) -> Iterator[torch.Tensor]:"""Decode a video latent tensor, yielding float chunks ``[f, h, w, c]`` in ``[0, 1]``.``keyframes`` anchors the decode on already-encoded single-frame planes. It is a hint,@@ -546,7 +558,8 @@ class VideoDecoder(Protocol):) -> Iterator[torch.Tensor]:"""Decode each latent as its own one-frame clip, yielding one RGB tensor per latent.A causal VAE cannot decode stacked independent planes without bleeding neighbours.- Dist implementations decode locally on every rank; they do not split or gather.+ Dist implementations split the list across their ranks and gather the pixels back, so+ every rank still receives every frame, in the order the latents were given."""...diff --git a/packages/ltx-core/src/ltx_core/multigpu/transformer/attention.py b/packages/ltx-core/src/ltx_core/multigpu/transformer/attention.pyindex 8215285..2f9e7e2 100644--- a/packages/ltx-core/src/ltx_core/multigpu/transformer/attention.py+++ b/packages/ltx-core/src/ltx_core/multigpu/transformer/attention.py@@ -9,6 +9,8 @@ _DEFAULT_ALL2ALL_TIMEOUT_SECONDS = 10.0class AttentionManager:+ """Owns sequence-parallel attention state for an aggregate token capacity."""+def __init__(self,max_tokens: int,@@ -29,12 +31,12 @@ class AttentionManager:hidden_dim = num_heads * head_dimnum_sms = torch.cuda.get_device_properties(self.rank).multi_processor_countself.copy_out = copy_out_- buffer_seqlen = (max_tokens + self.world_size - 1) // self.world_size+ max_rank_tokens = (max_tokens + self.world_size - 1) // self.world_sizeself.all2all_heads, self.all2all_q = (All2All(rank=self.rank,world_size=self.world_size,- seqlen=buffer_seqlen,+ seqlen=max_rank_tokens,hidden_dim=hidden_dim,num_sms=num_sms,tensor_dtype=tensor_dtype,@@ -46,7 +48,7 @@ class AttentionManager:All2All(rank=self.rank,world_size=self.world_size,- seqlen=buffer_seqlen,+ seqlen=max_rank_tokens,hidden_dim=hidden_dim,num_sms=num_sms,tensor_dtype=tensor_dtype,@@ -59,14 +61,6 @@ class AttentionManager:self.group = groupself._all2all_timeout_seconds = _DEFAULT_ALL2ALL_TIMEOUT_SECONDS- def set_seqlen_all2all(self, seqlens: list[int]) -> None:- # Route through the wrappers so the registered custom ops' fake-impl- # shape info gets updated alongside the C++ runtime's rank_tokens.- self.all2all_q.set_rank_tokens(seqlens)- self.all2all_k.set_rank_tokens(seqlens)- self.all2all_v.set_rank_tokens(seqlens)- self.all2all_heads.set_rank_tokens(seqlens)-@propertydef all2all_timeout_seconds(self) -> float:"""The all2all barrier (deadlock-detection) timeout, in seconds, applied to every instance."""diff --git a/packages/ltx-core/src/ltx_core/multigpu/transformer/sequence_parallel.py b/packages/ltx-core/src/ltx_core/multigpu/transformer/sequence_parallel.pyindex a830513..6624263 100644--- a/packages/ltx-core/src/ltx_core/multigpu/transformer/sequence_parallel.py+++ b/packages/ltx-core/src/ltx_core/multigpu/transformer/sequence_parallel.py@@ -307,7 +307,6 @@ class SequenceParallelModelWrapper(torch.nn.Module):f"Total video token count ({total_tokens}) exceeds attention_manager max_tokens "f"({self.attention_manager.max_tokens}). Use a smaller resolution or fewer frames.")- self.attention_manager.set_seqlen_all2all(token_counts)torch.distributed.barrier(self.attention_manager.group)video, audio = self.model(video_tile, audio, perturbations)video = gather_output_tokens(video, token_counts, self.attention_manager.group)diff --git a/packages/ltx-core/src/ltx_core/multigpu/vae/distributed_decoder.py b/packages/ltx-core/src/ltx_core/multigpu/vae/distributed_decoder.pyindex 55b0574..20b73f6 100644--- a/packages/ltx-core/src/ltx_core/multigpu/vae/distributed_decoder.py+++ b/packages/ltx-core/src/ltx_core/multigpu/vae/distributed_decoder.py@@ -5,6 +5,9 @@ rank). Each rank decodes its assigned tiles sequentially. Workersput their list of decoded tiles into a ``mp.Queue`` (CUDA IPC —zero-copy handle sharing). The driver collects all tiles, blendsoverlap zones, and returns temporal batches distributed across devices.+``decode_single_frames`` splits a *list of independent one-frame clips* instead of one+volume: the planes go round-robin to the ranks and come back through an all-gather, so+each is decoded once and every rank still holds the whole list.The tiling configuration comes from ``MGPUConfig.vae_tiling`` (set atconstruction time), NOT from the pipeline's SGPU tiling kwarg. MGPUtiling controls parallelism; SGPU tiling controls single-GPU VRAM@@ -26,10 +29,12 @@ from ltx_core.model.disposable import Disposablefrom ltx_core.model.video_vae.keyframes import DecodeKeyframesfrom ltx_core.model.video_vae.video_vae import (VideoDecoder,+ clip_generators,iter_decoded_single_frames,map_spatial_slice,map_temporal_slice,to_mapping_operation,+ validate_single_frame_latents,)from ltx_core.tiling import (Tile,@@ -84,6 +89,20 @@ def dist_rank_tiles(return [t for i, t in enumerate(all_tiles) if i % world_size == rank]+def dist_rank_plane_indices(count: int, rank: int, world_size: int) -> list[int]:+ """Round-robin share of ``count`` independent single-frame clips owned by ``rank``.+ The same assignment rule as :func:`dist_rank_tiles`, on a list of whole clips instead of+ tiles of one volume. Fewer clips than ranks, or a ragged tail, simply leaves the trailing+ ranks with a shorter (possibly empty) share -- there is nothing to pad, because every rank+ still joins the gather that follows.+ """+ if world_size < 1:+ raise ValueError(f"world_size must be >= 1, got {world_size}")+ if not 0 <= rank < world_size:+ raise ValueError(f"rank must be in [0, {world_size}), got {rank}")+ return list(range(rank, count, world_size))++def dist_rank_tile_pixel_shape(vae_tiling: TileCountConfig,latent_shape: VideoLatentShape,@@ -278,9 +297,10 @@ class DistributedVideoDecoder(torch.nn.Module, Disposable):latent: torch.Tensor,tiling_config: TilingConfig | None = None,generator: torch.Generator | None = None,- device_fn: Callable[[int], str | torch.device] | None = None,*,keyframes: DecodeKeyframes | None = None,+ device_fn: Callable[[int], str | torch.device] | None = None,+ **_kwargs: object,) -> Iterator[torch.Tensor]:"""Distributed decode — all ranks decode, driver assembles.Not a generator so that worker side-effects (decode + queue.put)@@ -335,12 +355,68 @@ class DistributedVideoDecoder(torch.nn.Module, Disposable):latents: Sequence[torch.Tensor],generator: torch.Generator | Sequence[torch.Generator | None] | None = None,) -> Iterator[torch.Tensor]:- """Local SGPU decode of each T=1 clip on every rank. Does not Dist-split or gather.- ``decode_video`` on Dist is the wrong tool here: workers send their tile and yield- nothing. Carry-keyframe planes are independent one-frame clips, so every rank- decodes them on the inner decoder and keeps the pixels.+ """Split the one-frame clips round-robin over the group, then all-gather the pixels.+ Each plane is an independent clip, so there is nothing to tile and nothing to blend:+ rank ``r`` decodes planes ``r, r + W, r + 2W, ...`` on the inner SGPU decoder and every+ rank ends up holding the whole list, in the order the latents were given. A DiffVAE+ plane is expensive enough that decoding all of them on every rank -- what this used to+ do -- wastes ``W - 1`` GPUs per plane.+ ``decode_video`` is still the wrong tool here: it splits one volume, and its workers+ yield nothing after queueing their tile.+ Not a generator. The all-gather has to run on every rank whether or not the caller+ iterates the result, and a rank whose share is empty (fewer planes than ranks, or a+ ragged tail) still takes part with an empty payload instead of skipping the collective+ -- one absent participant blocks the group until the NCCL timeout.+ Pixels cross the group as CPU tensors: ``all_gather_object`` pickles a CUDA tensor with+ its source device index, so a plane decoded on ``cuda:3`` would be rebuilt on ``cuda:3``+ on every rank. Each plane is moved onto the device of its own latent on the way out, and+ a rank keeps the GPU copy of the planes it decoded itself.+ With a per-plane ``generator`` sequence the pixels do not depend on the world size. A+ single shared generator (or ``None``) is drawn from independently on each rank, so with+ those the noise a given plane gets does."""- yield from iter_decoded_single_frames(self.decoder, latents, generator)+ if not latents:+ return iter(())+ validate_single_frame_latents(latents)+ gens = clip_generators(len(latents), generator)+ if self.world_size == 1:+ return iter_decoded_single_frames(self.decoder, latents, gens)+ if len(latents) > 1 and not isinstance(generator, Sequence):+ logger.warning(+ "Dist single-frame decode is splitting %d planes over %d ranks with a shared "+ "generator; each rank draws its own noise, so the pixels depend on the world "+ "size. Pass one generator per latent to keep them world-size invariant.",+ len(latents),+ self.world_size,+ )++ my_indices = dist_rank_plane_indices(len(latents), self.rank, self.world_size)+ logger.info(+ "Dist single-frame decode: rank %d of %d takes %d of %d planes",+ self.rank,+ self.world_size,+ len(my_indices),+ len(latents),+ )+ decoded = iter_decoded_single_frames(+ self.decoder, [latents[i] for i in my_indices], [gens[i] for i in my_indices]+ )+ mine: dict[int, torch.Tensor] = dict(zip(my_indices, decoded, strict=True))++ payload = [(index, pixels.to("cpu")) for index, pixels in mine.items()]+ shares: list[list[tuple[int, torch.Tensor]] | None] = [None] * self.world_size+ dist.all_gather_object(shares, payload, group=self.vae_group)+ merged: dict[int, torch.Tensor] = {}+ for share in shares:+ merged.update(dict(share or ()))+ # This rank's own planes are already on the right device; prefer them over the round trip.+ merged.update(mine)+ missing = [index for index in range(len(latents)) if index not in merged]+ if missing:+ raise RuntimeError(f"Dist single-frame decode lost planes {missing} in the all-gather")+ # Lazy on the way out: the collective already ran, and the caller usually consumes one+ # plane at a time, so only the ranks' own planes stay resident on the GPU.+ return (merged[index].to(latents[index].device) for index in range(len(latents)))# ------------------------------------------------------------------# Private helpersdiff --git a/packages/ltx-core/src/ltx_core/quantization/blockwise/__init__.py b/packages/ltx-core/src/ltx_core/quantization/blockwise/__init__.pyindex 4e64f76..65f044e 100644--- a/packages/ltx-core/src/ltx_core/quantization/blockwise/__init__.py+++ b/packages/ltx-core/src/ltx_core/quantization/blockwise/__init__.py@@ -31,7 +31,6 @@ def build_fp8_policy() -> QuantizationPolicy:return QuantizationPolicy(sd_ops=impl.build_sd_ops_fp8(),module_ops=(impl.build_module_ops_fp8(),),- model_configurator=impl.BlockwiseFP8LTXModelConfigurator,fuse_rule=impl.fuse_rule_fp8,)@@ -42,6 +41,5 @@ def build_fp6_policy() -> QuantizationPolicy:return QuantizationPolicy(sd_ops=impl.build_sd_ops_fp6(),module_ops=(impl.build_module_ops_fp6(),),- model_configurator=impl.BlockwiseFP6LTXModelConfigurator,fuse_rule=impl.fuse_rule_fp6,)diff --git a/packages/ltx-core/src/ltx_core/quantization/blockwise/_impl.py b/packages/ltx-core/src/ltx_core/quantization/blockwise/_impl.pyindex 1e3d214..01e291c 100644--- a/packages/ltx-core/src/ltx_core/quantization/blockwise/_impl.py+++ b/packages/ltx-core/src/ltx_core/quantization/blockwise/_impl.py@@ -1,44 +1,32 @@"""Implementation of blockwise FP8/FP6 quantization. Depends on ``ltx_kernels``.-This module imports the compiled ``ltx_kernels.blockwise`` kernels at top level-— without them built, simply importing this file raises :class:`ImportError`.-The intended access path is through ``ltx_core.quantization.blockwise.__init__``-which catches that and re-raises as a clean :class:`RuntimeError`. Do not import-this module directly from non-quantization code.+The ``ltx_kernels`` blockwise activation ops import lazily (without the compiled+``ops_cpp`` / ``blockwise_cpp`` extensions), so this module probes those+extensions explicitly at top level: without them built, importing this file+raises :class:`ImportError`. The intended access path is through+``ltx_core.quantization.blockwise.__init__`` which catches that and re-raises as+a clean :class:`RuntimeError`. Do not import this module directly from+non-quantization code."""-from typing import Callable, ClassVar, List, NamedTuple, Protocol, Type+from typing import Callable, NamedTuple, Protocol, Type+import blockwise_cpp # noqa: F401 -- import-time probe so the gate fires when the kernels are not built+import ops_cpp # noqa: F401 -- import-time probe so the gate fires when the kernels are not builtimport torch-from ltx_kernels.blockwise.functional import (+from ltx_kernels.blockwise.linear import BlockwiseFP6Linear, BlockwiseFP8Linear+from ltx_kernels.blockwise.ops.fp6_pack import fp6_pack_tensor, fp6_unpack_tensor+from ltx_kernels.blockwise.ops.quantize import (blockwise_dequantize,- blockwise_quantize_adanorm_triton,- blockwise_quantize_rms_fma_triton,fp6_blockwise_quantize_weights_torch,- fp6_pack_tensor,- fp6_unpack_tensor,fp8_blockwise_quantize_weights_torch,- gated_attention_triton,- rms_norm_rope,- rms_norm_split_rope,)-from ltx_kernels.blockwise.linear import BlockwiseFP6Linear, BlockwiseFP8Linearfrom torch import nnfrom ltx_core.loader.fuse_loras import FuseRule, bf16_fuse_rulefrom ltx_core.loader.module_ops import ModuleOpsfrom ltx_core.loader.primitives import StateDictfrom ltx_core.loader.sd_ops import KeyValueOperationResult, SDOps-from ltx_core.model.model_protocol import ModelConfiguratorfrom ltx_core.model.transformer import LTXModel-from ltx_core.model.transformer.model_configurator import LTXModelConfigurator, LTXVideoOnlyModelConfigurator-from ltx_core.model.transformer.ops import (- AdaZeroCallable,- GatedAttentionCallable,- PostSACallable,- PreAttentionCallable,-)-from ltx_core.model.transformer.rope import LTXRopeType-from ltx_core.model.transformer.transformer import TransformerOpsConfigclass FromLinearProtocol(Protocol):@@ -178,81 +166,6 @@ def _create_bias_to_fp32_op(return bias_to_fp32-# ----------------------------------------------------------------------------# Q8 activation callables (formerly in model.transformer.ops)-# ------------------------------------------------------------------------------class Q8KernelsPreAttention(PreAttentionCallable):- def __call__(- self,- q: torch.Tensor,- k: torch.Tensor,- attn_module: nn.Module,- mask: torch.Tensor | None, # noqa: ARG002- pe: torch.Tensor | None,- k_pe: torch.Tensor | None,- ) -> tuple[torch.Tensor, torch.Tensor]:- if attn_module.rope_type == LTXRopeType.INTERLEAVED:- rope_func = rms_norm_rope- elif attn_module.rope_type == LTXRopeType.SPLIT:- rope_func = rms_norm_split_rope- else:- raise ValueError(f"Invalid rope type: {attn_module.rope_type}")-- if pe is not None:- k_pe = k_pe if k_pe is not None else pe- q = rope_func(q, pe[0], pe[1], attn_module.q_norm.weight, False)- k = rope_func(k, k_pe[0], k_pe[1], attn_module.k_norm.weight, False)- else:- q = attn_module.q_norm(q)- k = attn_module.k_norm(k)- return q, k---class Q8KernelsAdaZeroFunction(AdaZeroCallable):- def __call__(- self,- x: torch.Tensor,- eps: float, # noqa: ARG002- scale: torch.Tensor,- shift: torch.Tensor,- ) -> torch.Tensor:- return blockwise_quantize_adanorm_triton(x, None, scale, shift, torch.float8_e4m3fn, 1.0)---class Q8KernelsPostSAFunction(PostSACallable):- def __call__(- self,- x: torch.Tensor,- y: torch.Tensor,- norm_weights: torch.Tensor | None, # noqa: ARG002- eps: float, # noqa: ARG002- gate: torch.Tensor,- ) -> List[torch.Tensor]:- # Dequantize the fused result: the cross-attention AdaLN path applies a BF16- # scale/shift, which cannot operate on the (fp8, scales) payload.- normed_fp8 = blockwise_quantize_rms_fma_triton(x, y, gate)- return x, blockwise_dequantize(normed_fp8)---class Q8KernelsGatedAttention(GatedAttentionCallable):- def __call__(- self,- x: torch.Tensor,- attn_out: torch.Tensor,- attn_module: nn.Module,- ) -> torch.Tensor:- # Self-attention path: ``x`` arrives as the ``(fp8, scales)`` tuple- # produced by Q8KernelsAdaZeroFunction. Cross-attention path- # (apply_cross_attention_adaln) feeds plain BF16, so dequantize only- # when needed.- if isinstance(x, tuple):- x = blockwise_dequantize(x)- gate_logits = attn_module.to_gate_logits(x)- return gated_attention_triton(attn_out, gate_logits)--# ---------------------------------------------------------------------------# Fuse rules# ---------------------------------------------------------------------------@@ -264,14 +177,14 @@ _BLOCK = 128def _blockwise_dequantize_2d(weight_fp8: torch.Tensor, weight_scale: torch.Tensor) -> torch.Tensor:"""Dequantize a 2D blockwise-FP8 weight ``[out, in]`` with per-block scale``[out//128, in//128]`` to BF16.- ``ltx_kernels.blockwise.blockwise_dequantize`` is built for 3D activations where+ ``ltx_kernels.blockwise.ops.quantize.blockwise_dequantize`` is built for 3D activations wherescales are ``[b*s, in//128]`` — one row per token. Weights are block-quantized along the row dim too, so we expand the row axis 128x via``repeat_interleave`` and reuse the kernel."""out_features, in_features = weight_fp8.shapescales_per_row = weight_scale.repeat_interleave(_BLOCK, dim=0)- return blockwise_dequantize((weight_fp8.unsqueeze(0), scales_per_row)).view(out_features, in_features)+ return blockwise_dequantize(weight_fp8.unsqueeze(0), scales_per_row).view(out_features, in_features)def _blockwise_fp8_fuse(@@ -337,45 +250,6 @@ def _blockwise_fp6_fuse(}-# ----------------------------------------------------------------------------# Configurators (TransformerOpsConfig with Q8 activation callables)-# ------------------------------------------------------------------------------def _build_blockwise_ops_config() -> TransformerOpsConfig:- return TransformerOpsConfig.from_functions(- preattention=Q8KernelsPreAttention(),- gated_attention=Q8KernelsGatedAttention(),- ada_zero=Q8KernelsAdaZeroFunction(),- post_sa=Q8KernelsPostSAFunction(),- )---# FP6 is weight-only; activation ops match FP8.-_BLOCKWISE_OPS = _build_blockwise_ops_config()---class BlockwiseFP8LTXModelConfigurator(ModelConfigurator[LTXModel]):- BASE: ClassVar[type[ModelConfigurator[LTXModel]]] = LTXModelConfigurator- OPS: ClassVar[TransformerOpsConfig] = _BLOCKWISE_OPS-- @classmethod- def from_metadata(cls, metadata: dict) -> LTXModel:- return cls.BASE.from_metadata(metadata, ops=cls.OPS)---class BlockwiseFP8LTXVideoOnlyModelConfigurator(BlockwiseFP8LTXModelConfigurator):- BASE = LTXVideoOnlyModelConfigurator---class BlockwiseFP6LTXModelConfigurator(BlockwiseFP8LTXModelConfigurator):- pass---class BlockwiseFP6LTXVideoOnlyModelConfigurator(BlockwiseFP8LTXVideoOnlyModelConfigurator):- pass--# ---------------------------------------------------------------------------# SDOps / ModuleOps / FuseRule assembly# ---------------------------------------------------------------------------diff --git a/packages/ltx-core/src/ltx_core/quantization/policy.py b/packages/ltx-core/src/ltx_core/quantization/policy.pyindex 20e991b..e78cfd0 100644--- a/packages/ltx-core/src/ltx_core/quantization/policy.py+++ b/packages/ltx-core/src/ltx_core/quantization/policy.py@@ -3,8 +3,6 @@ from dataclasses import dataclassfrom ltx_core.loader.fuse_loras import FuseRule, bf16_fuse_rulefrom ltx_core.loader.module_ops import ModuleOpsfrom ltx_core.loader.sd_ops import SDOps-from ltx_core.model.model_protocol import ModelConfigurator-from ltx_core.model.transformer.model import LTXModel@dataclass(frozen=True)@@ -13,12 +11,10 @@ class QuantizationPolicy:Attributes:sd_ops: State-dict operations applied to each tensor during load.module_ops: Post-load module transformations applied to the meta model.- model_configurator: Configurator class to use when constructing the transformer.fuse_rule: How LoRA deltas merge into this policy's weight layout.Default ``bf16_fuse_rule`` is used when no policy is configured."""sd_ops: SDOps | None = Nonemodule_ops: tuple[ModuleOps, ...] = ()- model_configurator: type[ModelConfigurator[LTXModel]] | None = Nonefuse_rule: FuseRule = bf16_fuse_rulediff --git a/packages/ltx-core/src/ltx_core/tiling.py b/packages/ltx-core/src/ltx_core/tiling.pyindex f3995de..57f3f67 100644--- a/packages/ltx-core/src/ltx_core/tiling.py+++ b/packages/ltx-core/src/ltx_core/tiling.py@@ -222,6 +222,55 @@ def split_by_size(size: int, overlap: int, min_tile_size: int | None = None) ->return split+def split_by_size_pinned(size: int, min_overlap: int) -> SplitOperation:+ """Split into equal-size tiles with first and last origins pinned to the extent.+ Unlike :func:`split_by_size`, this operation never emits a short trailing+ tile. ``min_overlap`` is a target of at most half ``size``. The tile count+ grows until the target is met, capped so three tiles never cover one cell.+ The realized overlap therefore follows from the extent and can differ from+ the target in either direction: below it when the cap is hit, and up to+ ``size - 1`` when two tiles span an extent barely longer than one tile+ (33 cells, ``size=32``: overlap 31).+ This layout is intended for models trained on a fixed spatial window, where+ changing the final tile's shape changes the model's effective content scale.+ """+ if size <= 0:+ raise ValueError(f"size must be > 0, got {size}")+ if min_overlap < 0 or min_overlap * 2 > size:+ raise ValueError(f"min_overlap must be at most half the tile size, got min_overlap={min_overlap}, size={size}")++ def split(dimension_size: int) -> DimensionIntervals:+ if dimension_size <= size:+ return DEFAULT_SPLIT_OPERATION(dimension_size)++ # Cap so a tile and the one two steps away cannot overlap.+ limit = max(2, 1 + (dimension_size - size) // ((size + 1) // 2))+ tiles_count = 2+ while tiles_count < limit and (tiles_count * size - dimension_size) / (tiles_count - 1) < min_overlap:+ tiles_count += 1+ base, remainder = divmod(dimension_size - size, tiles_count - 1)+ origins = [0]+ for index in range(tiles_count - 1):+ origins.append(origins[-1] + base + (1 if index < remainder else 0))++ intervals: list[DimensionInterval] = []+ for index, start in enumerate(origins):+ left_overlap = 0 if index == 0 else origins[index - 1] + size - start+ right_overlap = 0 if index == tiles_count - 1 else start + size - origins[index + 1]+ intervals.append(+ DimensionInterval(+ start=start,+ end=start + size,+ left_ramp=left_overlap,+ right_ramp=right_overlap,+ )+ )+ _validate_tile_intervals(intervals, dim_size=dimension_size, min_tile_size=size)+ return DimensionIntervals(intervals=intervals)++ return split++def split_temporal_causal(size: int, overlap: int, min_tile_size: int | None = None) -> SplitOperation:"""Split a temporal axis into overlapping tiles with causal handling.Each tile after the first is shifted back by 1 and its left ramp isdiff --git a/packages/ltx-kernels/MANIFEST.in b/packages/ltx-kernels/MANIFEST.inindex bc44834..9528741 100644--- a/packages/ltx-kernels/MANIFEST.in+++ b/packages/ltx-kernels/MANIFEST.in@@ -1 +1,2 @@recursive-include csrc *.h *.cuh *.hpp *.cpp *.cu+recursive-include src/ltx_kernels/vae/_aot *.odiff --git a/packages/ltx-kernels/README.md b/packages/ltx-kernels/README.mdindex ba2b11b..ada0590 100644--- a/packages/ltx-kernels/README.md+++ b/packages/ltx-kernels/README.md@@ -21,14 +21,19 @@ Custom CUDA/C++ kernels for `ltx-core`. Four compiled extensions:The Python surface for blockwise quantization lives in`ltx_kernels.blockwise` (`functional`, `linear`, `triton_ops`).-`ltx_kernels.vae` adds two JIT-compiled CuTe DSL kernels for the diffusion VAE decoder-(no C++ extension; `nvidia-cutlass-dsl` compiles them on first call):+`ltx_kernels.vae` adds two CuTe DSL kernels for the diffusion VAE decoder:- **`na_attn_dsl`** -- standalone 3D neighborhood attention, a drop-in for`natten.na3d`, used by the decoder's deterministic stages.- **`block_fna_dsl`** -- a whole `DiffusionNABlock` in one launch, with no full-volumeQ/K/V, used by stage 5.+Production `sm_100a` wheels carry six CuTe AOT objects: plain and keyframe variants+for the two deterministic-stage kernels, plus plain and keyframe variants for the+LTX-2.5 stage-5 block. The launcher loads a matching object on first use, so a fresh+process does not compile those kernels. Non-production channel widths, custom kernel+or tile shapes, and the standalone context-only NA API keep the existing JIT fallback.+Both need a **datacenter Blackwell** GPU: they use `tcgen05` MMA *and* Tensor Memory(`sm_100`/`sm_101`/`sm_103`). Consumer Blackwell has the former but not the latter, andHopper and Ada have neither, so this is not a slower fallback -- the instructions are@@ -73,6 +78,20 @@ architecture (so `uv pip install` "just works" on a dev box); pin it on buildhosts to cut compile time. Any `9.0` entry enables the SM90 GEMM kernel, whichis compiled for `sm_90a` (the deep_gemm kernel uses wgmma/TMA).+To include the production VAE AOT bundle in a wheel, generate it in the package+tree before building. CuTe fake tensors make this an offline compile; the build+host does not need a GPU:++```bash+PYTHONPATH=packages/ltx-kernels/src python packages/ltx-kernels/scripts/build_vae_aot.py \+ --output-dir packages/ltx-kernels/src/ltx_kernels/vae/_aot/sm100a \+ --gpu-arch sm_100a --host-target linux-aarch64+```++CuTe's object-file format check decides whether the installed+`nvidia-cutlass-dsl` can load the object. Source/editable installs without a+bundle continue to JIT.+### cutlass headers`blockwise_cpp` includes cute/cutlass headers (header-only; compiled into the@@ -99,7 +118,7 @@ The `ltx_kernels.vae` and `ltx_kernels.nvfp4` tests additionally require a datacBlackwell GPU and skip elsewhere. NVFP4 layout/API docs: [`docs/NVFP4.md`](docs/NVFP4.md).```bash-uv run pytest packages/ltx-kernels/tests/test_nvfp4.py -v+uv run pytest packages/ltx-kernels/tests/ltx_kernels/test_nvfp4.py -v```## Operationsdiff --git a/packages/ltx-kernels/csrc/all2all/all2all.cpp b/packages/ltx-kernels/csrc/all2all/all2all.cppindex 614ed1e..d3ff803 100644--- a/packages/ltx-kernels/csrc/all2all/all2all.cpp+++ b/packages/ltx-kernels/csrc/all2all/all2all.cpp@@ -64,10 +64,6 @@ All2All::All2All(int rank, int world_size, int num_tokens, int hidden_dim, int nint64_t barrier_signal_bytes = MAX_NUM_PEERS * sizeof(int);int64_t barrier_signal_ptrs_bytes = MAX_NUM_PEERS * sizeof(int *);- // Allocate GPU memory for token count arrays (used by kernels)- CUDA_CHECK(cudaMalloc(reinterpret_cast<void **>(&rank_tokens_gpu), sizeof(int) * MAX_NUM_PEERS));- CUDA_CHECK(cudaMalloc(reinterpret_cast<void **>(&prefix_rank_tokens_gpu), sizeof(int) * MAX_NUM_PEERS));-// Allocate the main shared memory block and create IPC handle// Layout: [data_buffer | barrier_signals | buffer_ptrs | barrier_signal_ptrs]CUDA_CHECK(@@ -119,8 +115,6 @@ void All2All::destroy() {// Free local GPU memory allocationsCUDA_CHECK(cudaFree(buffer_ptrs[rank]));- CUDA_CHECK(cudaFree(rank_tokens_gpu));- CUDA_CHECK(cudaFree(prefix_rank_tokens_gpu));destroyed = true;}@@ -162,42 +156,9 @@ pybind11::bytearray All2All::get_local_ipc_handle() const {return {ipc_handlers[rank].reserved, CUDA_IPC_HANDLE_SIZE};}-/**- * Configures token distribution across ranks for the current batch.- *- * This method computes prefix sums needed by the kernels to calculate source- * and destination offsets. It must be called before any communication operation- * when the token distribution changes between batches.- *- * Example: For rank_num_tokens = {128, 96, 128, 64}- * - rank_tokens = {128, 96, 128, 64}- * - prefix_rank_tokens = {0, 128, 224, 352}- * - total_tokens = 416- */-void All2All::set_rank_tokens(const std::vector<int> &rank_num_tokens) {- EP_HOST_ASSERT(static_cast<int>(rank_num_tokens.size()) == world_size);-- // Initialize prefix sums to zero- for (int i = 0; i < world_size; i++) {- prefix_rank_tokens[i] = 0;- }-- // Compute prefix sums (exclusive scan)- for (int i = 0; i < world_size; i++) {- rank_tokens[i] = rank_num_tokens[i];- if (i > 0) {- prefix_rank_tokens[i] = prefix_rank_tokens[i - 1] + rank_tokens[i - 1];- }- }-- // Total tokens is the sum of all rank tokens- total_tokens = prefix_rank_tokens[world_size - 1] + rank_tokens[world_size - 1];-- // Copy to GPU for kernel access- CUDA_CHECK(cudaMemcpy(rank_tokens_gpu, rank_tokens, sizeof(int) * MAX_NUM_PEERS, cudaMemcpyHostToDevice));- CUDA_CHECK(- cudaMemcpy(prefix_rank_tokens_gpu, prefix_rank_tokens, sizeof(int) * MAX_NUM_PEERS, cudaMemcpyHostToDevice));- CUDA_CHECK(cudaDeviceSynchronize());+at::Tensor All2All::local_buffer() const {+ return torch::from_blob(buffer_ptrs[rank], {num_elems},+ torch::TensorOptions().dtype(tensor_dtype).device(torch::kCUDA, rank));}/**@@ -222,8 +183,8 @@ at::Tensor All2All::get_local_buffer_tensor(at::Tensor &x, int batch_size, int oreturn out_tensor;} else {// Return a view directly into the IPC buffer (zero-copy)- auto out_tensor = torch::from_blob(ptr, {batch_size, out_tokens, out_heads, head_size}, x.options());- return out_tensor;+ int64_t numel = int64_t(batch_size) * int64_t(out_tokens) * int64_t(out_heads) * int64_t(head_size);+ return local_buffer().narrow(0, 0, numel).view({batch_size, out_tokens, out_heads, head_size});}}@@ -253,8 +214,8 @@ at::Tensor All2All::send_recv_heads(at::Tensor &x, bool copy_output) {int num_heads = x.size(2);int head_size = x.size(3);- // Output dimensions after redistribution- int out_tokens = total_tokens; // All tokens from all ranks+ // Sequence parallelism pads each rank to the same token count.+ int out_tokens = num_tokens * world_size;int out_heads = num_heads / world_size; // Each rank gets 1/world_size of headsEP_HOST_ASSERT(int64_t(batch_size) * int64_t(out_tokens) * int64_t(out_heads) * int64_t(head_size) *@@ -265,9 +226,9 @@ at::Tensor All2All::send_recv_heads(at::Tensor &x, bool copy_output) {auto stream = at::cuda::getCurrentCUDAStream().stream();// Launch the All2All kernel- all2all_cuda::all2all_head_launch(buffer_ptrs_gpu, barrier_signal_ptrs_gpu, x.data_ptr(), prefix_rank_tokens_gpu,- rank, world_size, batch_size, total_tokens, num_tokens, num_heads, head_size,- stream, num_sms, tensor_dtype, timeout_cycles_);+ all2all_cuda::all2all_head_launch(buffer_ptrs_gpu, barrier_signal_ptrs_gpu, x.data_ptr(), rank, world_size,+ batch_size, out_tokens, num_tokens, num_heads, head_size, stream, num_sms,+ tensor_dtype, timeout_cycles_);return get_local_buffer_tensor(x, batch_size, out_tokens, out_heads, head_size, copy_output, stream);}@@ -296,11 +257,12 @@ at::Tensor All2All::gather_heads(at::Tensor &x, bool copy_output) {auto stream = at::cuda::getCurrentCUDAStream().stream();int batch_size = x.size(0);+ int total_tokens = x.size(1);int num_heads = x.size(2) * world_size; // Reconstruct total head countint head_size = x.size(3);- // Output dimensions: this rank's tokens with all heads- int out_tokens = rank_tokens[rank];+ EP_HOST_ASSERT(total_tokens % world_size == 0);+ int out_tokens = total_tokens / world_size;int out_heads = num_heads;EP_HOST_ASSERT(int64_t(batch_size) * int64_t(out_tokens) * int64_t(out_heads) * int64_t(head_size) *@@ -308,9 +270,9 @@ at::Tensor All2All::gather_heads(at::Tensor &x, bool copy_output) {tensor_bytes);// Launch the gather kernel- all2all_cuda::all2all_head_gather_launch(buffer_ptrs_gpu, barrier_signal_ptrs_gpu, x.data_ptr(), rank_tokens_gpu,- prefix_rank_tokens_gpu, rank, world_size, batch_size, total_tokens,- num_heads, head_size, stream, num_sms, tensor_dtype, timeout_cycles_);+ all2all_cuda::all2all_head_gather_launch(buffer_ptrs_gpu, barrier_signal_ptrs_gpu, x.data_ptr(), rank, world_size,+ batch_size, total_tokens, num_heads, head_size, stream, num_sms,+ tensor_dtype, timeout_cycles_);return get_local_buffer_tensor(x, batch_size, out_tokens, out_heads, head_size, copy_output, stream);}@@ -326,7 +288,7 @@ at::Tensor All2All::gather_heads(at::Tensor &x, bool copy_output) {* Input: [batch, local_seqlen, heads, head_size] per GPU* Output: [batch, total_seqlen, heads, head_size] per GPU (identical on all GPUs)*- * Each GPU's tokens are placed at offset prefix_rank_tokens[rank] in the output.+ * Each GPU's tokens are placed at offset rank * local_seqlen in the output.*/at::Tensor All2All::allgather(at::Tensor &x, bool copy_output) {// Validate input tensor properties@@ -343,8 +305,7 @@ at::Tensor All2All::allgather(at::Tensor &x, bool copy_output) {int num_heads = x.size(2);int head_size = x.size(3);- // Output contains all tokens from all ranks- int out_tokens = total_tokens;+ int out_tokens = seqlen * world_size;int out_heads = num_heads;int hidden_dim = num_heads * head_size;@@ -353,9 +314,8 @@ at::Tensor All2All::allgather(at::Tensor &x, bool copy_output) {tensor_bytes);// Launch the allgather kernel- all2all_cuda::allgather_launch(buffer_ptrs_gpu, barrier_signal_ptrs_gpu, x.data_ptr(), prefix_rank_tokens_gpu, rank,- world_size, batch_size, seqlen, hidden_dim, total_tokens, stream, num_sms,- tensor_dtype, timeout_cycles_);+ all2all_cuda::allgather_launch(buffer_ptrs_gpu, barrier_signal_ptrs_gpu, x.data_ptr(), rank, world_size, batch_size,+ seqlen, hidden_dim, out_tokens, stream, num_sms, tensor_dtype, timeout_cycles_);return get_local_buffer_tensor(x, batch_size, out_tokens, out_heads, head_size, copy_output, stream);}@@ -377,9 +337,6 @@ at::Tensor All2All::allgather(at::Tensor &x, bool copy_output) {* # ... gather handles via NCCL ...* comm.sync(all_handles)*- * # Set token distribution- * comm.set_rank_tokens([128, 128, 128, 128])- ** # Perform operations* output = comm.send_recv_heads(input_tensor, copy_output=False)*@@ -410,6 +367,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {.def("get_local_ipc_handle", <x_kernels::all2all::All2All::get_local_ipc_handle,"Returns the IPC handle for this rank's buffer.").def("sync", <x_kernels::all2all::All2All::sync, "Opens IPC mappings to all peer GPUs using gathered handles.")+ .def("local_buffer", <x_kernels::all2all::All2All::local_buffer,+ "Returns the local data buffer, which every operation writes its output into, as a flat tensor.").def("destroy", <x_kernels::all2all::All2All::destroy,"Releases all GPU resources. Must be called before destruction.").def("send_recv_heads", <x_kernels::all2all::All2All::send_recv_heads,@@ -417,8 +376,6 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {.def("gather_heads", <x_kernels::all2all::All2All::gather_heads,"Inverse All2All to gather heads back to original distribution.").def("allgather", <x_kernels::all2all::All2All::allgather, "Gathers sequence tokens from all ranks.")- .def("set_rank_tokens", <x_kernels::all2all::All2All::set_rank_tokens,- "Sets token counts per rank for the current batch.").def("set_timeout_seconds", <x_kernels::all2all::All2All::set_timeout_seconds,"Sets the barrier timeout in seconds (converted to cycles via the device peak SM clock).");}diff --git a/packages/ltx-kernels/csrc/all2all/all2all.hpp b/packages/ltx-kernels/csrc/all2all/all2all.hppindex 2111cf5..34b0efc 100644--- a/packages/ltx-kernels/csrc/all2all/all2all.hpp+++ b/packages/ltx-kernels/csrc/all2all/all2all.hpp@@ -49,9 +49,6 @@* // ... gather all handles ...* comm.sync(all_handles);*- * // Set token distribution for current batch- * comm.set_rank_tokens({128, 128, 128, 128}); // tokens per rank- ** // Perform All2All on attention heads* auto result = comm.send_recv_heads(input_tensor, copy_output=false);*@@ -109,12 +106,6 @@ private:at::ScalarType tensor_dtype; ///< Data type of tensors (BFloat16 or Float8_e4m3fn)bool destroyed = false; ///< Flag to track if resources have been released- int total_tokens; ///< Sum of tokens across all ranks for current batch- int rank_tokens[MAX_NUM_PEERS]; ///< Number of tokens on each rank- int prefix_rank_tokens[MAX_NUM_PEERS]; ///< Cumulative sum of tokens (for offset calculation)- int *rank_tokens_gpu = nullptr; ///< Device copy of rank_tokens- int *prefix_rank_tokens_gpu = nullptr; ///< Device copy of prefix_rank_tokens-/// Device peak SM clock in Hz (from cudaDeviceGetAttribute(cudaDevAttrClockRate)), queried/// once at construction. Used to convert a wall-clock timeout in seconds to barrier cycles.double sm_clock_hz_ = 0.0;@@ -171,6 +162,16 @@ public:*/pybind11::bytearray get_local_ipc_handle() const;+ /**+ * @brief Returns the local data buffer as a flat tensor of num_elems elements.+ *+ * The tensor does not own the memory: it is valid until destroy(). Every operation writes+ * its output here, and peers write into it remotely, so its contents change with each call.+ *+ * @return 1-D tensor of dtype tensor_dtype on this rank's device+ */+ at::Tensor local_buffer() const;+/*** @brief Creates a tensor view or copy of the local output buffer.*@@ -198,12 +199,13 @@ public:* @brief Performs All2All communication to redistribute attention heads.** Redistributes tensor from [batch, local_tokens, all_heads, head_size] to- * [batch, all_tokens, local_heads, head_size]. Each rank sends its portion- * of heads to the corresponding target rank.+ * [batch, local_tokens * world_size, local_heads, head_size]. Each rank sends+ * its portion of heads to the corresponding target rank. Token counts must be+ * uniform across ranks.** @param x Input tensor with shape [batch, num_tokens, num_heads, head_size]* @param copy_output If true, returns a copy; if false, returns a view of the IPC buffer- * @return Tensor with shape [batch, total_tokens, num_heads/world_size, head_size]+ * @return Tensor with shape [batch, local_tokens * world_size, num_heads/world_size, head_size]*/at::Tensor send_recv_heads(at::Tensor &x, bool copy_output);@@ -211,37 +213,27 @@ public:* @brief Performs inverse All2All to gather heads back to original distribution.** Inverse of send_recv_heads(). Redistributes from [batch, all_tokens, local_heads, head_size]- * back to [batch, local_tokens, all_heads, head_size].+ * back to [batch, all_tokens / world_size, all_heads, head_size]. Token counts must be+ * uniform across ranks.** @param x Input tensor with shape [batch, total_tokens, heads_per_rank, head_size]* @param copy_output If true, returns a copy; if false, returns a view of the IPC buffer- * @return Tensor with shape [batch, rank_tokens[rank], num_heads, head_size]+ * @return Tensor with shape [batch, total_tokens/world_size, num_heads, head_size]*/at::Tensor gather_heads(at::Tensor &x, bool copy_output);/*** @brief Gathers sequence tokens from all ranks.*- * Each rank contributes its local sequence tokens, which are gathered into- * a complete sequence on all ranks.+ * Each rank contributes the same number of local sequence tokens, which are+ * gathered into a complete sequence on all ranks.** @param x Input tensor with shape [batch, seqlen, num_heads, head_size]* @param copy_output If true, returns a copy; if false, returns a view of the IPC buffer- * @return Tensor with shape [batch, total_tokens, num_heads, head_size]+ * @return Tensor with shape [batch, seqlen * world_size, num_heads, head_size]*/at::Tensor allgather(at::Tensor &x, bool copy_output);- /**- * @brief Sets the token count for each rank in the current batch.- *- * Must be called before send_recv_heads(), gather_heads(), or allgather()- * to configure the token distribution. This allows variable-length sequences- * across ranks.- *- * @param rank_num_tokens Vector of token counts, one per rank (must have world_size elements)- */- void set_rank_tokens(const std::vector<int> &rank_num_tokens);-/*** @brief Sets the all2all barrier timeout in seconds.*diff --git a/packages/ltx-kernels/csrc/all2all/cuda/all2all_heads.cu b/packages/ltx-kernels/csrc/all2all/cuda/all2all_heads.cuindex 678f4dc..93eb2e1 100644--- a/packages/ltx-kernels/csrc/all2all/cuda/all2all_heads.cu+++ b/packages/ltx-kernels/csrc/all2all/cuda/all2all_heads.cu@@ -48,7 +48,7 @@ namespace all2all_cuda {* Dest: [batch, total_tokens, heads_per_rank, head_size]** Each GPU writes heads [target_rank * heads_per_rank : (target_rank+1) * heads_per_rank]- * to target_rank's buffer at token offset prefix_rank_tokens[rank].+ * to target_rank's buffer at token offset rank * num_tokens.** ## Memory Layout*@@ -60,7 +60,7 @@ namespace all2all_cuda {** Output buffer (per target rank):* - Similar layout but with heads_per_rank instead of num_heads- * - Tokens from this rank placed at offset prefix_rank_tokens[rank]+ * - Tokens from this rank placed at offset rank * num_tokens** ## Thread Block Organization*@@ -81,12 +81,11 @@ namespace all2all_cuda {* @param num_heads Total number of attention heads* @param head_size Size of each attention head* @param total_tokens Sum of tokens across all ranks- * @param prefix_rank_tokens Cumulative token counts for offset calculation*/template <typename ELEM_T>__global__ void send_recv_all2all(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, int rank, int world_size,int batch_size, int num_tokens, int num_heads, int head_size, int total_tokens,- int *prefix_rank_tokens, uint64_t timeout_cycles) {+ uint64_t timeout_cycles) {// Grid dimensionsint num_sms = gridDim.x;int sm_id = blockIdx.x;@@ -133,7 +132,7 @@ __global__ void send_recv_all2all(void **buffer_ptrs, int **barrier_signal_ptrs,token_idx += num_tokens_per_copy * num_sms_for_this_rank) {int64_t copy_token_idx = token_idx + copy_thr_row_idx;// Destination token index accounts for this rank's offset in the global sequence- int64_t dst_token_idx = prefix_rank_tokens[rank] + copy_token_idx;+ int64_t dst_token_idx = int64_t(rank) * num_tokens + copy_token_idx;if (copy_token_idx >= num_tokens)break;@@ -176,7 +175,7 @@ __global__ void send_recv_all2all(void **buffer_ptrs, int **barrier_signal_ptrs,** Data layout transformation:* Source: [batch, total_tokens, heads_per_rank, head_size] (per GPU)- * Dest: [batch, rank_tokens[target], num_heads, head_size] (per target GPU)+ * Dest: [batch, total_tokens/world_size, num_heads, head_size] (per target GPU)** ## Memory Layout*@@ -186,7 +185,7 @@ __global__ void send_recv_all2all(void **buffer_ptrs, int **barrier_signal_ptrs,** Output buffer (per target rank):* - Contains only that rank's tokens but all heads- * - Layout: [batch, rank_tokens[target], num_heads, head_size]+ * - Layout: [batch, total_tokens/world_size, num_heads, head_size]* - This rank writes heads [rank * heads_per_rank : (rank+1) * heads_per_rank]** @tparam ELEM_T Element type (at::BFloat16 or at::Float8_e4m3fn)@@ -198,14 +197,11 @@ __global__ void send_recv_all2all(void **buffer_ptrs, int **barrier_signal_ptrs,* @param batch_size Number of batches* @param num_heads Total number of heads (reconstructed)* @param head_size Size of each attention head- * @param rank_tokens Number of tokens for each rank* @param total_tokens Sum of tokens across all ranks- * @param prefix_rank_tokens Cumulative token counts for offset calculation*/template <typename ELEM_T>__global__ void gather_heads(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, int rank, int world_size,- int batch_size, int num_heads, int head_size, const int *__restrict__ rank_tokens,- int total_tokens, int *prefix_rank_tokens, uint64_t timeout_cycles) {+ int batch_size, int num_heads, int head_size, int total_tokens, uint64_t timeout_cycles) {// Grid dimensionsint num_sms = gridDim.x;int sm_id = blockIdx.x;@@ -227,7 +223,7 @@ __global__ void gather_heads(void **buffer_ptrs, int **barrier_signal_ptrs, voidint64_t copy_thr_row_idx = threadIdx.x / num_threads_per_token;// Number of tokens owned by target rank- const int64_t tgt_tokens = int64_t(rank_tokens[target_rank]);+ const int64_t tgt_tokens = int64_t(total_tokens / world_size);// This rank writes its heads at offset [rank * heads_per_rank] in the outputint64_t head_idx = rank * heads_per_rank;@@ -248,7 +244,7 @@ __global__ void gather_heads(void **buffer_ptrs, int **barrier_signal_ptrs, voidbreak;// Source: Read from global token position (target rank's tokens in our buffer)- int64_t src_token_idx = prefix_rank_tokens[target_rank] + copy_token;+ int64_t src_token_idx = target_rank * tgt_tokens + copy_token;// Destination: Write to local token position in target's bufferint64_t dst_token_idx = copy_token;@@ -285,8 +281,6 @@ __global__ void gather_heads(void **buffer_ptrs, int **barrier_signal_ptrs, void* @param buffer_ptrs Device array of buffer pointers* @param barrier_signal_ptrs Device array of barrier signal pointers* @param x Input tensor data pointer- * @param rank_tokens Token count per rank (device memory)- * @param prefix_rank_tokens Cumulative token counts (device memory)* @param rank This GPU's rank* @param world_size Total number of GPUs* @param batch_size Number of batches@@ -297,19 +291,18 @@ __global__ void gather_heads(void **buffer_ptrs, int **barrier_signal_ptrs, void* @param num_sms Number of SMs to launch* @param tensor_dtype Data type (BFloat16 or Float8_e4m3fn)*/-void all2all_head_gather_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, const int *rank_tokens,- int *prefix_rank_tokens, int rank, int world_size, int batch_size, int total_tokens,- int num_heads, int head_size, cudaStream_t stream, int num_sms,- at::ScalarType tensor_dtype, uint64_t timeout_cycles) {+void all2all_head_gather_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, int rank, int world_size,+ int batch_size, int total_tokens, int num_heads, int head_size, cudaStream_t stream,+ int num_sms, at::ScalarType tensor_dtype, uint64_t timeout_cycles) {do {if (tensor_dtype == at::ScalarType::BFloat16) {gather_heads<at::BFloat16><<<num_sms, DEFAULT_KERNEL_THREADS, 0, stream>>>(- buffer_ptrs, barrier_signal_ptrs, x, rank, world_size, batch_size, num_heads, head_size, rank_tokens,- total_tokens, prefix_rank_tokens, timeout_cycles);+ buffer_ptrs, barrier_signal_ptrs, x, rank, world_size, batch_size, num_heads, head_size, total_tokens,+ timeout_cycles);} else if (tensor_dtype == at::ScalarType::Float8_e4m3fn) {gather_heads<at::Float8_e4m3fn><<<num_sms, DEFAULT_KERNEL_THREADS, 0, stream>>>(- buffer_ptrs, barrier_signal_ptrs, x, rank, world_size, batch_size, num_heads, head_size, rank_tokens,- total_tokens, prefix_rank_tokens, timeout_cycles);+ buffer_ptrs, barrier_signal_ptrs, x, rank, world_size, batch_size, num_heads, head_size, total_tokens,+ timeout_cycles);}// Check for kernel launch errors@@ -331,7 +324,6 @@ void all2all_head_gather_launch(void **buffer_ptrs, int **barrier_signal_ptrs, v* @param buffer_ptrs Device array of buffer pointers* @param barrier_signal_ptrs Device array of barrier signal pointers* @param x Input tensor data pointer- * @param prefix_rank_tokens Cumulative token counts (device memory)* @param rank This GPU's rank* @param world_size Total number of GPUs* @param batch_size Number of batches@@ -343,18 +335,18 @@ void all2all_head_gather_launch(void **buffer_ptrs, int **barrier_signal_ptrs, v* @param num_sms Number of SMs to launch* @param tensor_dtype Data type (BFloat16 or Float8_e4m3fn)*/-void all2all_head_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, int *prefix_rank_tokens, int rank,- int world_size, int batch_size, int total_tokens, int num_tokens, int num_heads, int head_size,+void all2all_head_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, int rank, int world_size,+ int batch_size, int total_tokens, int num_tokens, int num_heads, int head_size,cudaStream_t stream, int num_sms, at::ScalarType tensor_dtype, uint64_t timeout_cycles) {do {if (tensor_dtype == at::ScalarType::BFloat16) {send_recv_all2all<at::BFloat16><<<num_sms, DEFAULT_KERNEL_THREADS, 0, stream>>>(buffer_ptrs, barrier_signal_ptrs, x, rank, world_size, batch_size, num_tokens, num_heads, head_size,- total_tokens, prefix_rank_tokens, timeout_cycles);+ total_tokens, timeout_cycles);} else if (tensor_dtype == at::ScalarType::Float8_e4m3fn) {send_recv_all2all<at::Float8_e4m3fn><<<num_sms, DEFAULT_KERNEL_THREADS, 0, stream>>>(buffer_ptrs, barrier_signal_ptrs, x, rank, world_size, batch_size, num_tokens, num_heads, head_size,- total_tokens, prefix_rank_tokens, timeout_cycles);+ total_tokens, timeout_cycles);}// Check for kernel launch errorsdiff --git a/packages/ltx-kernels/csrc/all2all/cuda/allgather.cu b/packages/ltx-kernels/csrc/all2all/cuda/allgather.cuindex e2514b2..50295c6 100644--- a/packages/ltx-kernels/csrc/all2all/cuda/allgather.cu+++ b/packages/ltx-kernels/csrc/all2all/cuda/allgather.cu@@ -10,7 +10,7 @@* ## Algorithm Overview** Each GPU broadcasts its local tokens to all other GPUs' buffers:- * - GPU i writes its tokens to position [prefix_rank_tokens[i]] in each buffer+ * - GPU i writes its tokens to position [i * seqlen] in each buffer* - After completion, all buffers contain the full sequence [0:total_tokens]** ## Use Case@@ -46,7 +46,7 @@ namespace all2all_cuda {** Output buffer (per target rank, after gather):* - Shape: [batch, total_tokens, hidden_dim]- * - This rank's tokens placed at offset rank_tokens_prefix[rank]+ * - This rank's tokens placed at offset rank * seqlen** ## Thread Mapping*@@ -65,12 +65,10 @@ namespace all2all_cuda {* @param world_size Total number of GPUs* @param rank This GPU's rank* @param total_tokens Sum of tokens across all ranks- * @param rank_tokens_prefix Cumulative token counts (device memory)*/template <typename ELEM_T>__global__ void allgather(void *x, void **buffer_ptrs, int **barrier_signal_ptrs, int batch_size, int seqlen,- int hidden_dim, int world_size, int rank, int total_tokens, int *rank_tokens_prefix,- uint64_t timeout_cycles) {+ int hidden_dim, int world_size, int rank, int total_tokens, uint64_t timeout_cycles) {// Grid dimensionsint num_sms = gridDim.x;@@ -116,8 +114,7 @@ __global__ void allgather(void *x, void **buffer_ptrs, int **barrier_signal_ptrs// Source: local token index in input tensorint64_t src_token_idx = copy_token;// Destination: global token index in output buffer- // This rank's tokens start at prefix_rank_tokens[rank]- int64_t dst_token_idx = copy_token + rank_tokens_prefix[rank];+ int64_t dst_token_idx = copy_token + int64_t(rank) * seqlen;// Source pointer: input tensor at [batch, src_token, :]int4 *shuffled_x_ptr = reinterpret_cast<int4 *>(reinterpret_cast<uint8_t *>(x) +@@ -154,7 +151,6 @@ __global__ void allgather(void *x, void **buffer_ptrs, int **barrier_signal_ptrs* @param buffer_ptrs Device array of buffer pointers* @param barrier_signal_ptrs Device array of barrier signal pointers* @param x Input tensor data pointer- * @param prefix_rank_tokens Cumulative token counts (device memory)* @param rank This GPU's rank* @param world_size Total number of GPUs* @param batch_size Number of batches@@ -165,18 +161,18 @@ __global__ void allgather(void *x, void **buffer_ptrs, int **barrier_signal_ptrs* @param num_sms Number of SMs to launch* @param tensor_dtype Data type (BFloat16 or Float8_e4m3fn)*/-void allgather_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, int *prefix_rank_tokens, int rank,- int world_size, int batch_size, int seqlen, int hidden_dim, int total_tokens, cudaStream_t stream,- int num_sms, at::ScalarType tensor_dtype, uint64_t timeout_cycles) {+void allgather_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, int rank, int world_size, int batch_size,+ int seqlen, int hidden_dim, int total_tokens, cudaStream_t stream, int num_sms,+ at::ScalarType tensor_dtype, uint64_t timeout_cycles) {do {if (tensor_dtype == at::ScalarType::BFloat16) {allgather<at::BFloat16><<<num_sms, ALLGATHER_KERNEL_THREADS, 0, stream>>>(x, buffer_ptrs, barrier_signal_ptrs, batch_size, seqlen, hidden_dim, world_size, rank, total_tokens,- prefix_rank_tokens, timeout_cycles);+ timeout_cycles);} else if (tensor_dtype == at::ScalarType::Float8_e4m3fn) {allgather<at::Float8_e4m3fn><<<num_sms, ALLGATHER_KERNEL_THREADS, 0, stream>>>(x, buffer_ptrs, barrier_signal_ptrs, batch_size, seqlen, hidden_dim, world_size, rank, total_tokens,- prefix_rank_tokens, timeout_cycles);+ timeout_cycles);} else {EPException dtype_exception("allgather_launch", __FILE__, __LINE__, "Unsupported dtype");fprintf(stderr, "%s\n", dtype_exception.what());diff --git a/packages/ltx-kernels/csrc/all2all/cuda/api.cuh b/packages/ltx-kernels/csrc/all2all/cuda/api.cuhindex 711672c..3d1bb35 100644--- a/packages/ltx-kernels/csrc/all2all/cuda/api.cuh+++ b/packages/ltx-kernels/csrc/all2all/cuda/api.cuh@@ -26,7 +26,6 @@ namespace all2all_cuda {* @param buffer_ptrs Device array of pointers to each rank's data buffer* @param barrier_signal_ptrs Device array of pointers to barrier signals* @param x Source tensor data pointer- * @param prefix_rank_tokens Cumulative token counts per rank (device memory)* @param rank This GPU's rank (0 to world_size-1)* @param world_size Total number of GPUs* @param batch_size Batch dimension size@@ -38,8 +37,8 @@ namespace all2all_cuda {* @param num_sms Number of SMs to use for the kernel* @param tensor_dtype Data type (BFloat16 or Float8_e4m3fn)*/-void all2all_head_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, int *prefix_rank_tokens, int rank,- int world_size, int batch_size, int total_tokens, int num_tokens, int num_heads, int head_size,+void all2all_head_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, int rank, int world_size,+ int batch_size, int total_tokens, int num_tokens, int num_heads, int head_size,cudaStream_t stream, int num_sms, at::ScalarType tensor_dtype, uint64_t timeout_cycles);/**@@ -47,13 +46,11 @@ void all2all_head_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x,** Redistributes tokens back to original head distribution:* Input: [batch, total_tokens, heads_per_rank, head_size] per GPU- * Output: [batch, rank_tokens[rank], num_heads, head_size] per GPU+ * Output: [batch, total_tokens/world_size, num_heads, head_size] per GPU** @param buffer_ptrs Device array of pointers to each rank's data buffer* @param barrier_signal_ptrs Device array of pointers to barrier signals* @param x Source tensor data pointer- * @param rank_tokens Token count for each rank (device memory)- * @param prefix_rank_tokens Cumulative token counts (device memory)* @param rank This GPU's rank* @param world_size Total number of GPUs* @param batch_size Batch dimension size@@ -64,10 +61,9 @@ void all2all_head_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x,* @param num_sms Number of SMs to use for the kernel* @param tensor_dtype Data type (BFloat16 or Float8_e4m3fn)*/-void all2all_head_gather_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, const int *rank_tokens,- int *prefix_rank_tokens, int rank, int world_size, int batch_size, int total_tokens,- int num_heads, int head_size, cudaStream_t stream, int num_sms,- at::ScalarType tensor_dtype, uint64_t timeout_cycles);+void all2all_head_gather_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, int rank, int world_size,+ int batch_size, int total_tokens, int num_heads, int head_size, cudaStream_t stream,+ int num_sms, at::ScalarType tensor_dtype, uint64_t timeout_cycles);/*** @brief Launches the AllGather kernel for sequence tokens.@@ -79,7 +75,6 @@ void all2all_head_gather_launch(void **buffer_ptrs, int **barrier_signal_ptrs, v* @param buffer_ptrs Device array of pointers to each rank's data buffer* @param barrier_signal_ptrs Device array of pointers to barrier signals* @param x Source tensor data pointer- * @param prefix_rank_tokens Cumulative token counts (device memory)* @param rank This GPU's rank* @param world_size Total number of GPUs* @param batch_size Batch dimension size@@ -90,9 +85,9 @@ void all2all_head_gather_launch(void **buffer_ptrs, int **barrier_signal_ptrs, v* @param num_sms Number of SMs to use for the kernel* @param tensor_dtype Data type (BFloat16 or Float8_e4m3fn)*/-void allgather_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, int *prefix_rank_tokens, int rank,- int world_size, int batch_size, int seqlen, int hidden_dim, int total_tokens, cudaStream_t stream,- int num_sms, at::ScalarType tensor_dtype, uint64_t timeout_cycles);+void allgather_launch(void **buffer_ptrs, int **barrier_signal_ptrs, void *x, int rank, int world_size, int batch_size,+ int seqlen, int hidden_dim, int total_tokens, cudaStream_t stream, int num_sms,+ at::ScalarType tensor_dtype, uint64_t timeout_cycles);} // namespace all2all_cuda} // namespace all2alldiff --git a/packages/ltx-kernels/csrc/ops/ops_api.cpp b/packages/ltx-kernels/csrc/ops/ops_api.cppindex 98d0c27..a387afa 100644--- a/packages/ltx-kernels/csrc/ops/ops_api.cpp+++ b/packages/ltx-kernels/csrc/ops/ops_api.cpp@@ -16,6 +16,7 @@ at::Tensor rms_norm_split_rope(at::Tensor &sin_freqs,at::Tensor &cos_freqs,at::Tensor &weights,+ double eps,bool out_fp8);diff --git a/packages/ltx-kernels/csrc/ops/rms_norm_split_rope.cpp b/packages/ltx-kernels/csrc/ops/rms_norm_split_rope.cppindex bdce9dd..a9c6518 100644--- a/packages/ltx-kernels/csrc/ops/rms_norm_split_rope.cpp+++ b/packages/ltx-kernels/csrc/ops/rms_norm_split_rope.cpp@@ -12,6 +12,7 @@ void rms_norm_split_rope_cuda(void* sin_freqs,void* cos_freqs,void* weights,+ float eps,int b,int s,int n,@@ -27,6 +28,7 @@ at::Tensor rms_norm_split_rope(at::Tensor &sin_freqs,at::Tensor &cos_freqs,at::Tensor &weights,+ double eps,bool out_fp8) {TORCH_CHECK(x.scalar_type() == at::ScalarType::BFloat16, "Input must be BFloat16");@@ -50,15 +52,22 @@ at::Tensor rms_norm_split_rope(int d = h / n;+ // The kernel walks x row-major from one base pointer, so it must be contiguous.+ if (!x.is_contiguous()) { x = x.contiguous(); }+// Require a contiguous innermost (d/2) dim for the vectorized int4 freq load,// but keep the outer (b, n, s) strides: apply_split_rotary_emb hands us a// swapaxes view (logical [b, n, s, d/2], physical [b, s, n, d/2]) whose inner// stride is already 1, so this never copies it. The strides are forwarded to// the kernel so the read is correct regardless of the physical layout.- if (x.stride(-1) != 1) { x = x.contiguous(); }if (cos_freqs.stride(-1) != 1) { cos_freqs = cos_freqs.contiguous(); }if (sin_freqs.stride(-1) != 1) { sin_freqs = sin_freqs.contiguous(); }+ // A table shared across the batch is expanded rather than copied: the kernel+ // indexes it by batch through the forwarded stride, which expand sets to 0.+ if (cos_freqs.size(0) == 1 && b > 1) { cos_freqs = cos_freqs.expand({b, n, cos_freqs.size(2), cos_freqs.size(3)}); }+ if (sin_freqs.size(0) == 1 && b > 1) { sin_freqs = sin_freqs.expand({b, n, sin_freqs.size(2), sin_freqs.size(3)}); }+long cos_sb = cos_freqs.stride(0), cos_sn = cos_freqs.stride(1), cos_ss = cos_freqs.stride(2);long sin_sb = sin_freqs.stride(0), sin_sn = sin_freqs.stride(1), sin_ss = sin_freqs.stride(2);@@ -81,6 +90,7 @@ at::Tensor rms_norm_split_rope(sin_freqs.data_ptr(),cos_freqs.data_ptr(),weights.data_ptr(), // weights (optional, not used yet)+ (float)eps,b,s,n,@@ -96,6 +106,7 @@ at::Tensor rms_norm_split_rope(sin_freqs.data_ptr(),cos_freqs.data_ptr(),weights.data_ptr(), // weights (optional, not used yet)+ (float)eps,b,s,n,diff --git a/packages/ltx-kernels/csrc/ops/rms_norm_split_rope_cuda.cu b/packages/ltx-kernels/csrc/ops/rms_norm_split_rope_cuda.cuindex c2c2bf9..928065b 100644--- a/packages/ltx-kernels/csrc/ops/rms_norm_split_rope_cuda.cu+++ b/packages/ltx-kernels/csrc/ops/rms_norm_split_rope_cuda.cu@@ -10,150 +10,128 @@using bf16 = __nv_bfloat16;using fp8 = __nv_fp8_e4m3;-__device__ __forceinline__ void _load_x(bf16* x, float x_vals[8], int h){- bf16 x_tmp[8];- const size_t row = static_cast<size_t>(blockIdx.x) * static_cast<size_t>(h);- *reinterpret_cast<int4*>(x_tmp) = reinterpret_cast<int4*>(x + row)[threadIdx.x];- #pragma unroll- for(int i = 0; i < 8; i++){- x_vals[i] = float(x_tmp[i]);- }-}-// Load 8 freq values for this thread from a table laid out logically as-// [b, n, s, d/2] (what apply_split_rotary_emb produces -- a swapaxes view whose-// physical layout is [b, s, n, d/2]). The strides (sb, sn, ss; inner d/2 stride-// is 1) are forwarded from the host so the read is correct for both that-// non-contiguous view and a genuinely contiguous [b, n, s, d/2] tensor. Both-// head-halves map to the same freq element (mirrors the eager cos.unsqueeze(-2)).-__device__ __forceinline__ void _load_freqs(- const bf16* freqs, float x_vals[8], int s, int d, long sb, long sn, long ss-){- bf16 x_tmp[8];- int threads_per_head = d / 8;- int head_idx = threadIdx.x / threads_per_head;- int lane = threadIdx.x % (threads_per_head / 2);- int b_idx = blockIdx.x / s;- int t_idx = blockIdx.x % s;- long off = b_idx * sb + head_idx * sn + t_idx * ss + (long)lane * 8;- *reinterpret_cast<int4*>(x_tmp) = *reinterpret_cast<const int4*>(freqs + off);++// One thread owns kPairsPerThread rotation pairs of a single head -- both halves of+// every pair it owns. The alternative, a contiguous channel run per thread, puts a+// pair's two halves in different threads: it then needs a shuffle to reach the partner+// and reads each cos/sin cache line twice, once per half. This layout has neither, and+// measures 1.6x the channel-run layout at h=4096 (6.8 vs 4.3 TB/s on GB200).+//+// kPairsPerThread must divide d/2, so a thread never straddles two heads, and+// kPairsPerThread * threads_per_row * 2 must equal h.+constexpr int kPairsPerThread = 16;++template<int N>+__device__ __forceinline__ void _load_run(const bf16* source, bf16 values[N]) {#pragma unroll- for(int i = 0; i < 8; i++){- x_vals[i] = float(x_tmp[i]);+ for (int i = 0; i < N / 8; i++) {+ reinterpret_cast<int4*>(values)[i] = reinterpret_cast<const int4*>(source)[i];}}-template<typename out_t>-__global__ void _rms_norm_split_rope_kernel(bf16* x, bf16* sin_freqs, bf16* cos_freqs, void* out, bf16* weights, int b, int s, int n, int h,- long cos_sb, long cos_sn, long cos_ss, long sin_sb, long sin_sn, long sin_ss){- size_t token_idx = blockIdx.x;- int tid = threadIdx.x;- int lane_id = tid % 32;- // freqs have shape [b, s, h/2]- // each thread block calculate one row- // there are h/8 threads in thread block, each thread processes 8 values- // num_of_rows = b * s- // freqs have h/2 dim- // gridDim is (num_of_rows, 1, 1)- // calculate rms norm x_normed = x/x_norm * weights. x_norm is calculated across row, it means thread block wide sum reduction-- extern __shared__ float smem[];-- // Step 1: Load input values (8 per thread)- float x_vals[8];- _load_x(x, x_vals, h);-- float sum_sq = 0.0f;+// Frequency tables are laid out logically as [b, n, s, d/2] (what+// apply_split_rotary_emb produces -- a swapaxes view whose physical layout is+// [b, s, n, d/2]). The strides (sb, sn, ss; inner d/2 stride is 1) are forwarded from+// the host so the read is correct for both that non-contiguous view and a genuinely+// contiguous [b, n, s, d/2] tensor.+template<typename out_t, int PAIRS, int THREADS_PER_ROW, int ROWS_PER_CTA>+__global__ void _rms_norm_split_rope_kernel(+ const bf16* __restrict__ x,+ const bf16* __restrict__ sin_freqs,+ const bf16* __restrict__ cos_freqs,+ void* __restrict__ out,+ const bf16* __restrict__ weights,+ float eps,+ int b, int s, int n, int h,+ long cos_sb, long cos_sn, long cos_ss, long sin_sb, long sin_sn, long sin_ss+){+ constexpr int kWarpsPerRow = THREADS_PER_ROW / 32;+ __shared__ float smem[ROWS_PER_CTA * kWarpsPerRow];++ const int row_in_block = threadIdx.x / THREADS_PER_ROW;+ const int lane_in_row = threadIdx.x % THREADS_PER_ROW;+ const int token_idx = blockIdx.x * ROWS_PER_CTA + row_in_block;+ const bool active = token_idx < b * s;+ const int safe_token = active ? token_idx : 0;++ const int d = h / n;+ const int half = d / 2;+ const int pair0 = lane_in_row * PAIRS; // first rotation pair of this thread+ const int head = pair0 / half;+ const int freq0 = pair0 - head * half;+ const int first_channel = head * d + freq0;+ const int second_channel = first_channel + half;++ const size_t row = static_cast<size_t>(safe_token) * static_cast<size_t>(h);+ const long freq_offset = static_cast<long>(safe_token / s) * cos_sb+ + static_cast<long>(head) * cos_sn+ + static_cast<long>(safe_token % s) * cos_ss + freq0;+ const long sin_offset = static_cast<long>(safe_token / s) * sin_sb+ + static_cast<long>(head) * sin_sn+ + static_cast<long>(safe_token % s) * sin_ss + freq0;++ bf16 first_raw[PAIRS], second_raw[PAIRS];+ bf16 cos_raw[PAIRS], sin_raw[PAIRS];+ bf16 first_weight[PAIRS], second_weight[PAIRS];+ _load_run<PAIRS>(x + row + first_channel, first_raw);+ _load_run<PAIRS>(x + row + second_channel, second_raw);+ _load_run<PAIRS>(cos_freqs + freq_offset, cos_raw);+ _load_run<PAIRS>(sin_freqs + sin_offset, sin_raw);+ _load_run<PAIRS>(weights + first_channel, first_weight);+ _load_run<PAIRS>(weights + second_channel, second_weight);++ float first[PAIRS], second[PAIRS], sum_sq = 0.0f;#pragma unroll- for(int i = 0; i < 8; i++){- sum_sq += x_vals[i] * x_vals[i];+ for (int i = 0; i < PAIRS; i++) {+ first[i] = float(first_raw[i]);+ second[i] = float(second_raw[i]);+ sum_sq += first[i] * first[i] + second[i] * second[i];}-- // Warp-level reduction#pragma unroll- for(int offset = 16; offset > 0; offset >>= 1){+ for (int offset = 16; offset > 0; offset >>= 1) {sum_sq += __shfl_xor_sync(0xffffffff, sum_sq, offset);}- if(tid % 32 == 0){- smem[tid / 32] = sum_sq;+ // One barrier: every thread re-sums the per-warp partials itself. Electing one+ // thread to sum them and publish the result back needs a second barrier.+ if ((lane_in_row & 31) == 0) {+ smem[row_in_block * kWarpsPerRow + lane_in_row / 32] = sum_sq;}__syncthreads();-- // Final reduction across warps- if(tid == 0){- float total_sum = 0.0f;- int num_warps = blockDim.x / 32;- for(int i = 0; i < num_warps; i++){- total_sum += smem[i];- }- // RMS: sqrt(mean(x^2))- float rms = rsqrtf(total_sum / h + 1e-6f); // Add epsilon for numerical stability- smem[0] = rms;- }- __syncthreads();-- float inv_rms = smem[0];-- // Step 3: Apply RMS normalization (and weights if provided)+ float total_sum = 0.0f;#pragma unroll- for(int i = 0; i < 8; i++){- x_vals[i] *= inv_rms;- // TODO: Apply weights if provided- if(weights != nullptr) x_vals[i] *= float(weights[tid * 8 + i]);+ for (int i = 0; i < kWarpsPerRow; i++) {+ total_sum += smem[row_in_block * kWarpsPerRow + i];}+ const float inv_rms = rsqrtf(total_sum / h + eps);- // Step 4: Calculate dimensions for split RoPE- // Conceptually: [b, s, h] -> [b, s, n, 2*d] -> [b, s, n, 2, d]- // where h = n * 2 * d- int d = h / n;- float x_other_vals[8];-- int threads_per_head = d / 8;- int head_idx = tid / threads_per_head;- int idx_in_head = tid % threads_per_head;- bool is_first_half = idx_in_head < (threads_per_head / 2);-- // LT-PATCH: full-warp mask. The original (1u << threads_per_head) - 1 only marks- // the first head's lanes active, so lanes belonging to heads beyond the first are- // not in the mask -> __shfl_xor_sync result is undefined and can corrupt RoPE. The- // XOR pattern keeps data within each power-of-two head group, so a full-warp mask- // is correct for every lane.- const unsigned mask = 0xffffffffu;- const int laneMask = threads_per_head / 2; // 4, 8, or 16+ // at::Float8_e4m3fn / at::BFloat16 do not convert from the native CUDA types, so+ // the staging arrays and the output pointer both use the native one.+ using store_t = std::conditional_t<std::is_same_v<out_t, at::Float8_e4m3fn>, fp8, bf16>;+ store_t first_out[PAIRS], second_out[PAIRS];#pragma unroll- for (int i = 0; i < 8; i++) {- x_other_vals[i] = __shfl_xor_sync(mask, x_vals[i], laneMask);- }-- float cos_vals[8], sin_vals[8];- _load_freqs(cos_freqs, cos_vals, s, d, cos_sb, cos_sn, cos_ss);- _load_freqs(sin_freqs, sin_vals, s, d, sin_sb, sin_sn, sin_ss);- #pragma unroll- for(int i = 0; i < 8; i++){- x_vals[i] = cos_vals[i]*x_vals[i];- }--- float sign = is_first_half ? -1.0f : 1.0f;- for(int i = 0; i < 8; i++){- x_vals[i] += sign*sin_vals[i]*x_other_vals[i];- }-- // Step 6: Convert and store output- if constexpr (std::is_same_v<out_t, at::Float8_e4m3fn>){- fp8 out_tmp[8];- #pragma unroll- for(int i = 0; i < 8; i++){- out_tmp[i] = fp8(x_vals[i]);+ for (int i = 0; i < PAIRS; i++) {+ const float a = first[i] * inv_rms * float(first_weight[i]);+ const float c = second[i] * inv_rms * float(second_weight[i]);+ const float cs = float(cos_raw[i]);+ const float sn = float(sin_raw[i]);+ if constexpr (std::is_same_v<out_t, at::Float8_e4m3fn>) {+ first_out[i] = fp8(a * cs - c * sn);+ second_out[i] = fp8(c * cs + a * sn);+ } else {+ first_out[i] = __float2bfloat16(a * cs - c * sn);+ second_out[i] = __float2bfloat16(c * cs + a * sn);}- *reinterpret_cast<int64_t*>((fp8*)out + token_idx * h + tid * 8) = *reinterpret_cast<int64_t*>(out_tmp);- } else {- bf16 out_tmp[8];+ }+ if (active) {+ constexpr int kBytes = PAIRS * sizeof(store_t);+ static_assert(kBytes % 16 == 0, "a pair run must be a whole number of 16B stores");+ auto* base = static_cast<store_t*>(out) + row;#pragma unroll- for(int i = 0; i < 8; i++){- out_tmp[i] = __float2bfloat16(x_vals[i]);+ for (int i = 0; i < kBytes / 16; i++) {+ reinterpret_cast<int4*>(base + first_channel)[i] = reinterpret_cast<int4*>(first_out)[i];+ reinterpret_cast<int4*>(base + second_channel)[i] = reinterpret_cast<int4*>(second_out)[i];}- *reinterpret_cast<int4*>((bf16*)out + token_idx * h + tid * 8) = *reinterpret_cast<int4*>(out_tmp);}}@@ -163,6 +141,7 @@ void rms_norm_split_rope_cuda(void* sin_freqs, // Sin frequencies: [b, n, s, d]void* cos_freqs, // Cos frequencies: [b, n, s, d]void* weights,+ float eps, // Added to the mean square before the rsqrtint b, // Batch sizeint s, // Sequence lengthint n, // Number of heads (32)@@ -172,32 +151,53 @@ void rms_norm_split_rope_cuda(void* out, // Output: [b, s, h]cudaStream_t stream) {- int num_tokens = b * s;- int num_threads = h / 8; // Each thread processes 8 elements- int smem_size = (num_threads / 32 + 1) * sizeof(float); // Shared memory for reductions-- dim3 grid(num_tokens);- dim3 block(num_threads);-- _rms_norm_split_rope_kernel<out_t><<<grid, block, smem_size, stream>>>(- reinterpret_cast<bf16*>(x),- reinterpret_cast<bf16*>(sin_freqs),- reinterpret_cast<bf16*>(cos_freqs),- out,- reinterpret_cast<bf16*>(weights),- b, s, n, h,- cos_sb, cos_sn, cos_ss,- sin_sb, sin_sn, sin_ss- );+ const int num_tokens = b * s;+ TORCH_CHECK(n > 0 && h % n == 0, "hidden dimension must divide by the head count");+ TORCH_CHECK((h / n) % (2 * kPairsPerThread) == 0,+ "head_dim/2 must be a multiple of ", kPairsPerThread);++ // One row per CTA. Sharing a CTA across rows only widens the reduction and was+ // measured slower at every hidden size.+ constexpr int kRowsPerCta = 1;+#define LAUNCH_SPLIT_ROPE(THREADS_PER_ROW) \+ do { \+ static_assert(kPairsPerThread * (THREADS_PER_ROW) * 2 == kHidden, \+ "threads_per_row must cover exactly half the row"); \+ _rms_norm_split_rope_kernel<out_t, kPairsPerThread, (THREADS_PER_ROW), kRowsPerCta> \+ <<<(num_tokens + kRowsPerCta - 1) / kRowsPerCta, \+ (THREADS_PER_ROW) * kRowsPerCta, 0, stream>>>( \+ reinterpret_cast<bf16*>(x), \+ reinterpret_cast<bf16*>(sin_freqs), \+ reinterpret_cast<bf16*>(cos_freqs), \+ out, \+ reinterpret_cast<bf16*>(weights), \+ eps, \+ b, s, n, h, \+ cos_sb, cos_sn, cos_ss, \+ sin_sb, sin_sn, sin_ss); \+ } while (0)++ if (h == 2048) {+ constexpr int kHidden = 2048;+ LAUNCH_SPLIT_ROPE(64);+ } else if (h == 4096) {+ constexpr int kHidden = 4096;+ LAUNCH_SPLIT_ROPE(128);+ } else {+ TORCH_CHECK(h == 8192, "Hidden dimension must be 2048, 4096, or 8192");+ constexpr int kHidden = 8192;+ LAUNCH_SPLIT_ROPE(256);+ }+#undef LAUNCH_SPLIT_ROPEC10_CUDA_KERNEL_LAUNCH_CHECK();}// Explicit template instantiationstemplate void rms_norm_split_rope_cuda<at::BFloat16>(- void*, void*, void*, void*, int, int, int, int, long, long, long, long, long, long, void*, cudaStream_t+ void*, void*, void*, void*, float, int, int, int, int, long, long, long, long, long, long, void*, cudaStream_t);template void rms_norm_split_rope_cuda<at::Float8_e4m3fn>(- void*, void*, void*, void*, int, int, int, int, long, long, long, long, long, long, void*, cudaStream_t+ void*, void*, void*, void*, float, int, int, int, int, long, long, long, long, long, long, void*, cudaStream_t);diff --git a/packages/ltx-kernels/docs/NVFP4.md b/packages/ltx-kernels/docs/NVFP4.mdindex 0c448aa..ba2cc2f 100644--- a/packages/ltx-kernels/docs/NVFP4.md+++ b/packages/ltx-kernels/docs/NVFP4.md@@ -28,7 +28,7 @@ Reconstruction: `x ≈ data * s_b * s_t`.`hi_first=False` puts it in the low nibble. Pre-quantized checkpoints used with`nvfp4-prequant` are expected in the default (`hi_first=True`) order.-Measured fact (see `tests/test_nvfp4.py::test_nibble_order_is_gemm_invariant`): the block+Measured fact (see `tests/ltx_kernels/test_nvfp4.py::test_nibble_order_is_gemm_invariant`): the blockscale covers all 16 elements of a block, so swapping nibble order in **both** operandsonly permutes the terms of each dot product — the result is bit-identical. A nibble swapis only needed when *mixing* layouts.diff --git a/packages/ltx-kernels/pyproject.toml b/packages/ltx-kernels/pyproject.tomlindex 01146bc..a510a77 100644--- a/packages/ltx-kernels/pyproject.toml+++ b/packages/ltx-kernels/pyproject.toml@@ -8,14 +8,22 @@ build-backend = "setuptools.build_meta"[project]name = "ltx-kernels"-version = "1.3.0"+version = "1.4.0"dependencies = ["torch",+ "triton>=3.0","nvidia-cutlass-dsl>=4.6.0.dev0,<5; sys_platform == 'linux'",]+[project.entry-points."torch_dynamo_backends"]+ltx_kernels_eager = "ltx_kernels.compile.backend:ltx_kernels_eager_backend"+ltx_kernels_inductor = "ltx_kernels.compile.backend:ltx_kernels_inductor_backend"+[tool.setuptools]package-dir = {"" = "src"}[tool.setuptools.packages.find]where = ["src"]++[tool.setuptools.package-data]+"ltx_kernels.vae" = ["_aot/sm100a/*.o"]diff --git a/packages/ltx-kernels/scripts/build_vae_aot.py b/packages/ltx-kernels/scripts/build_vae_aot.pynew file mode 100644index 0000000..c381fed--- /dev/null+++ b/packages/ltx-kernels/scripts/build_vae_aot.py@@ -0,0 +1,48 @@+"""Export the production DiffVAE CuTe DSL AOT bundle."""++from __future__ import annotations++import argparse+import sys+import types+from collections.abc import Callable+from pathlib import Path+++def _load_exporter() -> Callable[..., None]:+ """Import the exporter without executing ``ltx_kernels/__init__.py``.+ This script runs before the wheel exists, so the package's eager ``All2All``+ import would require the unbuilt ``all2all_cpp`` extension. Seeding the+ package module lets the VAE submodules load from this source tree on their own.+ """+ package_dir = Path(__file__).resolve().parents[1] / "src" / "ltx_kernels"+ package = types.ModuleType("ltx_kernels")+ package.__path__ = [str(package_dir)] # type: ignore[attr-defined]+ package.__package__ = "ltx_kernels"+ package.__file__ = str(package_dir / "__init__.py")+ sys.modules["ltx_kernels"] = package+ from ltx_kernels.vae.aot import export_production_artifacts # noqa: PLC0415++ return export_production_artifacts+++def _parse_args() -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--output-dir", type=Path, required=True)+ parser.add_argument("--gpu-arch", required=True)+ parser.add_argument("--host-target", required=True)+ return parser.parse_args()+++def main() -> None:+ args = _parse_args()+ export_production_artifacts = _load_exporter()+ export_production_artifacts(+ args.output_dir,+ gpu_arch=args.gpu_arch,+ host_target=args.host_target,+ )+++if __name__ == "__main__":+ main()diff --git a/packages/ltx-kernels/src/ltx_kernels/all_to_all.py b/packages/ltx-kernels/src/ltx_kernels/all_to_all.pyindex f5ad10b..8fa5677 100644--- a/packages/ltx-kernels/src/ltx_kernels/all_to_all.py+++ b/packages/ltx-kernels/src/ltx_kernels/all_to_all.py@@ -3,8 +3,8 @@ The C++ kernels are exposed via ``torch.library.custom_op`` so that``torch.compile`` (and CUDA Graph capture under ``mode="reduce-overhead"``)can trace through them without a graph break. Each :class:`All2All`instance registers itself in a class-level registry indexed by an integer-``comm_id``; the custom op takes that id plus an input tensor and dispatches-to the appropriate C++ runtime.+``comm_id``; the custom op takes that id, an input tensor, and the instance's+IPC buffer, and dispatches to the appropriate C++ runtime."""import math@@ -16,58 +16,32 @@ import torch.distributed as distfrom all2all_cpp import All2All as All2AllCppfrom torch.library import custom_op-# Output shapes are derived symbolically from the input tensor's shape under-# the assumption of *uniform* sharding (caller pads up-front so-# `total_tokens % world_size == 0`). `world_size` travels through the op as an int-# so it enters the traced graph: the fake needs it for the output shape, and since-# it is constant per process the Dynamo guard it installs never triggers a-# within-run recompile -- it only keys the compile cache by world size, so a graph-# compiled under one GPU count is never replayed under another. Per-rank token-# counts, which do vary per call, stay in the C++ runtime state (`set_rank_tokens`)-# and never travel through the op.---@custom_op("ltx_kernels::send_recv_heads", mutates_args=(), device_types="cuda")-def _send_recv_heads_op(- x: torch.Tensor,- comm_id: int,- world_size: int, # noqa: ARG001- copy_out: bool,-) -> torch.Tensor:- # copy_out=False returns a view into the IPC buffer (zero-copy). Safe under- # cudagraph_trees because the IPC buffer is cudaMalloc'd inside All2All, not- # in the static graph pool, so it isn't subject to graph-pool aliasing.- return All2All._runtime_registry[comm_id].send_recv_heads(x, copy_out)+# Output shapes and kernel offsets are derived from the input tensor under uniform+# sharding. Callers pad before sharding, so every rank has the same token count.+# Each op writes its result into the instance's local IPC buffer, which it takes as a+# mutated argument, and returns nothing; All2All returns a view of that buffer. Returning+# the view from the op instead would declare storage the compiler may reuse for other+# tensors, while the next op on the same instance, from any rank, overwrites it.+++@custom_op("ltx_kernels::send_recv_heads", mutates_args=("buffer",), device_types="cuda")+def _send_recv_heads_op(x: torch.Tensor, buffer: torch.Tensor, comm_id: int) -> None: # noqa: ARG001+ All2All._runtime_registry[comm_id].send_recv_heads(x, False)@_send_recv_heads_op.register_fake-def _send_recv_heads_fake(- x: torch.Tensor,- comm_id: int, # noqa: ARG001- world_size: int,- copy_out: bool, # noqa: ARG001-) -> torch.Tensor:- return x.new_empty((x.shape[0], x.shape[1] * world_size, x.shape[2] // world_size, x.shape[3]))+def _send_recv_heads_fake(x: torch.Tensor, buffer: torch.Tensor, comm_id: int) -> None: # noqa: ARG001+ return None-@custom_op("ltx_kernels::gather_heads", mutates_args=(), device_types="cuda")-def _gather_heads_op(- x: torch.Tensor,- comm_id: int,- world_size: int, # noqa: ARG001- copy_out: bool,-) -> torch.Tensor:- return All2All._runtime_registry[comm_id].gather_heads(x, copy_out)+@custom_op("ltx_kernels::gather_heads", mutates_args=("buffer",), device_types="cuda")+def _gather_heads_op(x: torch.Tensor, buffer: torch.Tensor, comm_id: int) -> None: # noqa: ARG001+ All2All._runtime_registry[comm_id].gather_heads(x, False)@_gather_heads_op.register_fake-def _gather_heads_fake(- x: torch.Tensor,- comm_id: int, # noqa: ARG001- world_size: int,- copy_out: bool, # noqa: ARG001-) -> torch.Tensor:- return x.new_empty((x.shape[0], x.shape[1] // world_size, x.shape[2] * world_size, x.shape[3]))+def _gather_heads_fake(x: torch.Tensor, buffer: torch.Tensor, comm_id: int) -> None: # noqa: ARG001+ return Noneclass All2All:@@ -133,10 +107,7 @@ class All2All:dist.all_gather_object(ipc_handles, local_ipc_handle, group)self.runtime.sync(ipc_handles)-- def set_rank_tokens(self, rank_num_tokens: list[int]) -> None:- """Sets per-rank token counts on the C++ runtime."""- self.runtime.set_rank_tokens(rank_num_tokens)+ self._buffer = self.runtime.local_buffer()def set_timeout_seconds(self, seconds: float) -> None:"""Set the all2all barrier (deadlock-detection) timeout, in seconds.@@ -154,9 +125,13 @@ class All2All:x: Input tensor of shape [batch, tokens, heads, head_dim].copy_out: If True, copy result to a new tensor instead of using buffer.Returns:- Output tensor with redistributed heads.+ Output tensor with redistributed heads. Unless ``copy_out``, a view of the IPC+ buffer that the next call on this instance overwrites."""- return torch.ops.ltx_kernels.send_recv_heads(x, self._comm_id, self.world_size, copy_out)+ torch.ops.ltx_kernels.send_recv_heads(x, self._buffer, self._comm_id)+ batch, tokens, heads, head_dim = x.shape+ out = self._buffer[: x.numel()].view(batch, tokens * self.world_size, heads // self.world_size, head_dim)+ return out.clone() if copy_out else outdef gather_heads(self, x: torch.Tensor, *, copy_out: bool = False) -> torch.Tensor:"""Gather heads back to original distribution (reverse All2All).@@ -164,9 +139,13 @@ class All2All:x: Input tensor with distributed heads.copy_out: If True, copy result to a new tensor instead of using buffer.Returns:- Output tensor with gathered heads.+ Output tensor with gathered heads. Unless ``copy_out``, a view of the IPC buffer+ that the next call on this instance overwrites."""- return torch.ops.ltx_kernels.gather_heads(x, self._comm_id, self.world_size, copy_out)+ torch.ops.ltx_kernels.gather_heads(x, self._buffer, self._comm_id)+ batch, tokens, heads, head_dim = x.shape+ out = self._buffer[: x.numel()].view(batch, tokens // self.world_size, heads * self.world_size, head_dim)+ return out.clone() if copy_out else outdef allgather(self, x: torch.Tensor, *, copy_out: bool = False) -> torch.Tensor:"""Allgather operation across all ranks.diff --git a/packages/ltx-kernels/src/ltx_kernels/blockwise/__init__.py b/packages/ltx-kernels/src/ltx_kernels/blockwise/__init__.pyindex f082446..4449662 100644--- a/packages/ltx-kernels/src/ltx_kernels/blockwise/__init__.py+++ b/packages/ltx-kernels/src/ltx_kernels/blockwise/__init__.py@@ -1,36 +1,31 @@-"""Blockwise FP8/FP6 quantization kernels.-Importing this subpackage pulls in the compiled ``ops_cpp`` / ``blockwise_cpp``-extensions (via :mod:`.functional` and :mod:`.linear`) and ``triton``, so it-raises :class:`ImportError` on hosts where the kernels were not built. Callers-that want a soft dependency should guard the import (e.g. ``pytest.importorskip``-or the lazy gate in ``ltx_core.quantization.blockwise``).+"""Blockwise FP8/FP6 quantization: activation quantize/dequantize, weight+quantizers, FP6 pack/unpack, the FP8 GEMM, and the quantized linear layers.+Importing this subpackage needs ``triton`` (pulled in by ``torch`` on Linux) but+not the compiled ``ops_cpp`` / ``blockwise_cpp`` extensions -- those are resolved+lazily on first kernel call. The ``ltx_core.quantization.blockwise`` gate+surfaces a clean error when the extensions are absent."""-from ltx_kernels.blockwise.functional import (+from ltx_kernels.blockwise.linear import BlockwiseFP6Linear, BlockwiseFP8Linear+from ltx_kernels.blockwise.ops.fp6_pack import fp6_pack_tensor, fp6_unpack_tensor+from ltx_kernels.blockwise.ops.gemm import blockwise_fp8_gemm+from ltx_kernels.blockwise.ops.quantize import (blockwise_dequantize,- blockwise_quantize_adanorm_triton,- blockwise_quantize_rms_fma_triton,+ blockwise_quantize,+ blockwise_quantize_weights,fp6_blockwise_quantize_weights_torch,- fp6_pack_tensor,- fp6_unpack_tensor,fp8_blockwise_quantize_weights_torch,- gated_attention_triton,- rms_norm_rope,- rms_norm_split_rope,)-from ltx_kernels.blockwise.linear import BlockwiseFP6Linear, BlockwiseFP8Linear__all__ = ["BlockwiseFP6Linear","BlockwiseFP8Linear","blockwise_dequantize",- "blockwise_quantize_adanorm_triton",- "blockwise_quantize_rms_fma_triton",+ "blockwise_fp8_gemm",+ "blockwise_quantize",+ "blockwise_quantize_weights","fp6_blockwise_quantize_weights_torch","fp6_pack_tensor","fp6_unpack_tensor","fp8_blockwise_quantize_weights_torch",- "gated_attention_triton",- "rms_norm_rope",- "rms_norm_split_rope",]diff --git a/packages/ltx-kernels/src/ltx_kernels/blockwise/_common.py b/packages/ltx-kernels/src/ltx_kernels/blockwise/_common.pynew file mode 100644index 0000000..478bb68--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/blockwise/_common.py@@ -0,0 +1,44 @@+# ruff: noqa: N803, ANN001, ANN202+# Triton @jit kernels follow conventions that conflict with Python's lint rules:+# pointer args are CapWord (``X``), constexprs are UPPER_CASE (``BLOCK_SIZE``),+# pointer args carry no Python-level type, and the return type is opaque.+"""Shared blockwise-quant constants and Triton helpers.+Single home for the per-128-element FP8 quantize device function and the TMA+alignment math, reused by the blockwise quantize op (:mod:`.ops.quantize`) and+by the fused activation ops that quantize their output+(:mod:`ltx_kernels.ops.ada_zero`, :mod:`ltx_kernels.ops.gated_attention`).+"""++import torch+from triton import jit+from triton import language as tl++_BLOCK_SIZE = 128+_FP8_SCALE_MAX = 448.0+_FP6_SCALE_MAX = 0.1172+++def _get_tma_aligned_size(n: int, element_size: int) -> int:+ """Round ``n`` up to the TMA element-count multiple for ``element_size`` bytes."""+ num_elems_tma = 16 // element_size+ return ((n + num_elems_tma - 1) // num_elems_tma) * num_elems_tma+++def _empty_tma_aligned_scales(num_rows: int, num_blocks: int, device: torch.device) -> tuple[torch.Tensor, int]:+ """Allocate MN-major FP32 scales with TMA-padded row storage."""+ tma_aligned_mn = _get_tma_aligned_size(num_rows, 4)+ scales = torch.empty((num_blocks, tma_aligned_mn), dtype=torch.float, device=device).t()[:num_rows]+ return scales, tma_aligned_mn+++@jit+def _quantize(x, scale_max: tl.constexpr, NUM_BLOCKS: tl.constexpr, BLOCK_SIZE: tl.constexpr):+ """Per-block FP8 quantize: returns (fp8 codes, 1/scale per block)."""+ x = tl.reshape(x, (NUM_BLOCKS, BLOCK_SIZE))+ x_abs = tl.abs(x)+ x_abs = tl.broadcast_to(x_abs, (NUM_BLOCKS, BLOCK_SIZE))+ x_absmax = tl.max(x_abs, axis=1)[:, None]+ x_scales = scale_max / x_absmax+ x_quant = (x_scales * x).to(tl.float8e4nv)+ x_out_scales = 1.0 / x_scales+ return x_quant, x_out_scalesdiff --git a/packages/ltx-kernels/src/ltx_kernels/blockwise/functional.py b/packages/ltx-kernels/src/ltx_kernels/blockwise/functional.pydeleted file mode 100644index 72a7f1d..0000000--- a/packages/ltx-kernels/src/ltx_kernels/blockwise/functional.py+++ /dev/null@@ -1,234 +0,0 @@-"""Blockwise FP8/FP6 functional ops.-The CUDA kernels live in the ``ops_cpp`` extension.-"""--from typing import Optional, Tuple--import torch-from ops_cpp import fp6_pack, fp6_unpack-from ops_cpp import rms_norm_rope as rms_norm_rope_cuda-from ops_cpp import rms_norm_split_rope as rms_norm_split_rope_cuda--from ltx_kernels.blockwise.triton_ops import (- blockwise_dequantize_triton,- blockwise_quantize_adanorm_triton, # noqa: F401 (re-exported for consumers)- blockwise_quantize_rms_fma_triton, # noqa: F401 (re-exported for consumers)- blockwise_quantize_triton, # noqa: F401 (used by linear.BlockwiseGemmLinearFunc)- gated_attention_triton, # noqa: F401 (re-exported for consumers)-)--# Quantization scale constants for different precisions-FP8_SCALE_MAX = 448.0-FP6_SCALE_MAX = 0.1172--[email protected]_op("q8_kernels_ops::rms_norm_rope", mutates_args=())-def _rms_norm_rope_cuda(- x: torch.Tensor,- weights: Optional[torch.Tensor],- cos_freqs: torch.Tensor,- sin_freqs: torch.Tensor,- out_16bit: bool,-) -> torch.Tensor:- return rms_norm_rope_cuda(x, weights, cos_freqs, sin_freqs, out_16bit)--[email protected]_fake("q8_kernels_ops::rms_norm_rope")-def _rms_norm_rope_cuda_fake(- x: torch.Tensor,- weights: Optional[torch.Tensor],- cos_freqs: torch.Tensor,- sin_freqs: torch.Tensor,- out_16bit: bool,-) -> torch.Tensor:- out = torch.empty_like(x)- if out_16bit:- return out.to(torch.bfloat16)- else:- return out.to(torch.float8_e4m3fn)--[email protected]_op("q8_kernels_ops::rms_norm_split_rope", mutates_args=())-def _rms_norm_split_rope_cuda(- x: torch.Tensor,- sin_freqs: torch.Tensor,- cos_freqs: torch.Tensor,- weights: torch.Tensor,- out_fp8: bool,-) -> torch.Tensor:- return rms_norm_split_rope_cuda(x, sin_freqs, cos_freqs, weights, out_fp8)--[email protected]_fake("q8_kernels_ops::rms_norm_split_rope")-def _rms_norm_split_rope_cuda_fake(- x: torch.Tensor,- sin_freqs: torch.Tensor,- cos_freqs: torch.Tensor,- weights: torch.Tensor,- out_fp8: bool,-) -> torch.Tensor:- out = torch.empty_like(x)- if out_fp8:- return out.to(torch.float8_e4m3fn)- else:- return out.to(torch.bfloat16)---class RMSNormRope(torch.autograd.Function):- @staticmethod- def forward(ctx, x, weights, cos_freqs, sin_freqs, out_16bit):- return torch.ops.q8_kernels_ops.rms_norm_rope(- x, weights, cos_freqs, sin_freqs, out_16bit- )---class RMSNormSplitRope(torch.autograd.Function):- @staticmethod- def forward(ctx, x, sin_freqs, cos_freqs, weights, out_fp8):- return torch.ops.q8_kernels_ops.rms_norm_split_rope(- x, sin_freqs, cos_freqs, weights, out_fp8- )---def rms_norm_rope(- x: torch.Tensor,- cos_freqs: torch.Tensor,- sin_freqs: torch.Tensor,- weights: Optional[torch.Tensor] = None,- out_fp8: bool = False,-) -> torch.Tensor:- # weights=None flows through to the kernel's no-affine path (nullptr); see- # rms_norm_rope.cpp, which dispatches the norm_affine template on has_value().- return RMSNormRope.apply(x, weights, cos_freqs, sin_freqs, not out_fp8)---def rms_norm_split_rope(- x: torch.Tensor,- cos_freqs: torch.Tensor,- sin_freqs: torch.Tensor,- weights: Optional[torch.Tensor] = None,- out_fp8: bool = False,-) -> torch.Tensor:- """- Apply RMS normalization followed by split RoPE (Rotary Position Embedding).- Args:- x: Input tensor of shape [b, s, h] where h can be 2048, 4096, or 8192- cos_freqs: Cos frequencies of shape [b, n, s, d] where n=32 and n*d = h/2- sin_freqs: Sin frequencies of shape [b, n, s, d] where n=32- weights: Optional RMS norm weights of shape [h]- out_fp8: If True, output in float8_e4m3fn, otherwise bfloat16- Returns:- Output tensor of shape [b, s, h] with dtype based on out_fp8 parameter- """- if weights is None:- weights = torch.ones(x.shape[-1], dtype=x.dtype, device=x.device)- return RMSNormSplitRope.apply(x, sin_freqs, cos_freqs, weights, out_fp8)---def blockwise_quantize_weights(w: torch.Tensor, block_size=128, scale_max=FP8_SCALE_MAX) -> tuple[torch.Tensor, torch.Tensor]:- w = w.view(w.shape[0]//block_size, block_size, w.shape[1]//block_size, block_size).transpose(1, 2).contiguous()- w_absmax = w.float().abs().view(w.shape[0], w.shape[1], block_size*block_size).max(dim=-1, keepdim=False).values- w_scales = scale_max/w_absmax- w_quant = (w.float()*w_scales[:, :, None, None].float()).to(torch.float8_e4m3fn)- w_quant = w_quant.transpose(1, 2).contiguous()- w_quant = w_quant.view(w.shape[0]*block_size, -1)- return w_quant, (1/w_scales).contiguous()---def blockwise_quantize_torch(x: torch.Tensor, block_size=128, scale_max=FP8_SCALE_MAX) -> tuple[torch.Tensor, torch.Tensor]:- b, n, h = x.shape- x = x.view(-1, x.shape[-1]//block_size, block_size)- x_absmax = x.float().abs().max(dim=-1, keepdim=True).values- x_scales = scale_max/x_absmax- x_scaled = (x * x_scales).to(torch.float8_e4m3fn)- return x_scaled.view(b, n, h), 1/x_scales.view(b*n, h//block_size).t().contiguous().float()---# Precision-specific convenience functions--def fp8_blockwise_quantize_weights_torch(x: torch.Tensor, block_size=128) -> tuple[torch.Tensor, torch.Tensor]:- return blockwise_quantize_weights(x, block_size, FP8_SCALE_MAX)---def fp6_blockwise_quantize_weights_torch(x: torch.Tensor, block_size=128) -> tuple[torch.Tensor, torch.Tensor]:- return blockwise_quantize_weights(x, block_size, FP6_SCALE_MAX)---def blockwise_dequantize(x: Tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:- x_fp8, scales = x- return blockwise_dequantize_triton(x_fp8, scales)---# FP6 Pack/Unpack operations[email protected]_op("q8_kernels_ops::fp6_pack", mutates_args=())-def _fp6_pack(x: torch.Tensor) -> torch.Tensor:- """Pack 8-bit tensor to 6-bit by dropping e_1 and e_2 bits.- Args:- x: Input tensor of shape [m, n] with dtype uint8 or float8_e4m3fn- Returns:- Packed tensor of shape [m, n*3/4] with dtype uint8- """- return fp6_pack(x)--[email protected]_fake("q8_kernels_ops::fp6_pack")-def _fp6_pack_fake(x: torch.Tensor) -> torch.Tensor:- m, n = x.shape- n_packed = (n * 3) // 4- return torch.empty(m, n_packed, dtype=torch.uint8, device=x.device)--[email protected]_op("q8_kernels_ops::fp6_unpack", mutates_args=())-def _fp6_unpack(x: torch.Tensor, original_n: int) -> torch.Tensor:- """Unpack 6-bit tensor back to 8-bit (with e_1 and e_2 set to 0).- Args:- x: Packed tensor of shape [m, n_packed] with dtype uint8- original_n: Original dimension size (unpacked)- Returns:- Unpacked tensor of shape [m, original_n] with dtype uint8- """- return fp6_unpack(x, original_n)--[email protected]_fake("q8_kernels_ops::fp6_unpack")-def _fp6_unpack_fake(x: torch.Tensor, original_n: int) -> torch.Tensor:- m = x.shape[0]- return torch.empty(m, original_n, dtype=torch.uint8, device=x.device)---# Convenience wrapper functions-def fp6_pack_tensor(x: torch.Tensor) -> torch.Tensor:- """Pack 8-bit tensor to 6-bit by dropping e_1 and e_2 bits.- This function packs FP8 weights into a more memory-efficient FP6 format- by dropping the two highest exponent bits (e_1 and e_2). This achieves- 25% memory reduction (4 bytes -> 3 bytes per 4 elements).- Args:- x: Input tensor of shape [m, n] with dtype uint8 or float8_e4m3fn.- n must be divisible by 8.- Returns:- Packed tensor of shape [m, n*3/4] with dtype uint8- Example:- >>> w_fp8 = torch.randn(1024, 4096, dtype=torch.float8_e4m3fn, device='cuda')- >>> w_fp8_uint8 = w_fp8.view(torch.uint8)- >>> w_packed = fp6_pack_tensor(w_fp8_uint8)- >>> print(w_packed.shape) # [1024, 3072]- """- return torch.ops.q8_kernels_ops.fp6_pack(x)---def fp6_unpack_tensor(x: torch.Tensor, original_n: int) -> torch.Tensor:- """Unpack 6-bit tensor back to 8-bit (with e_1 and e_2 set to 0).- This function unpacks FP6 weights back to FP8 format. Note that the- two dropped exponent bits (e_1 and e_2) are restored as 0.- Args:- x: Packed tensor of shape [m, n_packed] with dtype uint8- original_n: Original dimension size before packing (must be divisible by 8)- Returns:- Unpacked tensor of shape [m, original_n] with dtype uint8- Example:- >>> w_packed = torch.randint(0, 256, (1024, 3072), dtype=torch.uint8, device='cuda')- >>> w_unpacked = fp6_unpack_tensor(w_packed, 4096)- >>> w_fp8 = w_unpacked.view(torch.float8_e4m3fn)- >>> print(w_fp8.shape) # [1024, 4096]- """- return torch.ops.q8_kernels_ops.fp6_unpack(x, original_n)diff --git a/packages/ltx-kernels/src/ltx_kernels/blockwise/linear.py b/packages/ltx-kernels/src/ltx_kernels/blockwise/linear.pyindex 63987b9..da86632 100644--- a/packages/ltx-kernels/src/ltx_kernels/blockwise/linear.py+++ b/packages/ltx-kernels/src/ltx_kernels/blockwise/linear.py@@ -1,128 +1,61 @@-"""Blockwise FP8/FP6 quantized linear layers and the FP8 GEMM custom op.-The FP8 GEMM kernels live in the ``blockwise_cpp`` extension.+"""Blockwise FP8/FP6 quantized linear layers.+Both store quantized weights with per-128-block FP32 scales and quantize the+bf16 activation through ``ltx_kernels::blockwise_quantize`` before dispatching to+the ``blockwise::fp8_gemm`` op (:mod:`.ops.gemm`). ``forward`` always quantizes+its bf16 input; under the compile backend a pass fuses that quantize node into+the preceding op. FP6 stores 6-bit-packed weights and unpacks them to fp8 on the+fly."""-from typing import List, Optional-import torch-import torch.nn as nn-from ops_cpp import fp6_pack, fp6_unpack+from torch import nnfrom ltx_kernels.arch import get_device_arch-from ltx_kernels.blockwise.functional import (- blockwise_quantize_triton,- blockwise_quantize_weights,+from ltx_kernels.blockwise.ops.fp6_pack import fp6_pack_tensor, fp6_unpack_tensor+from ltx_kernels.blockwise.ops.gemm import blockwise_fp8_gemm+from ltx_kernels.blockwise.ops.quantize import (+ blockwise_quantize,fp6_blockwise_quantize_weights_torch,+ fp8_blockwise_quantize_weights_torch,)-# Lazily-initialized, architecture-specific FP8 GEMM callable. Importing this-# module must not require a CUDA device or the compiled extension; the kernel is-# only resolved on first use (matching the lazy-import gate in ltx-core's-# blockwise.__init__).-_fp8_gemm = None---def get_fp8_gemm_nt():- """Runtime GPU architecture dispatch for FP8 GEMM."""- arch = get_device_arch()- if arch in ["ada", "blackwell"]:- # Ada/Blackwell use SM89 kernels (GeForce path)- from blockwise_cpp import fp8_gemm_nt_sm89-- def _func(a, b, d, bias=None, c=None, num_sms=132, use_fast_accum=True):- return fp8_gemm_nt_sm89(a, b, d, bias=bias, use_fast_accum=use_fast_accum)-- return _func- elif arch == "hopper":- # Hopper uses SM90 kernels (H100 path)- from blockwise_cpp import fp8_gemm_nt_sm90-- def _func(a, b, d, bias=None, c=None, num_sms=132, use_fast_accum=True):- return fp8_gemm_nt_sm90(a, b, d, bias=bias, c=c, num_sms=num_sms)-- return _func- else:- raise RuntimeError(f"Unsupported GPU architecture: {arch}")---def _fp8_gemm_dispatch(a, b, d, bias=None, c=None, num_sms=132, use_fast_accum=True):- global _fp8_gemm- if _fp8_gemm is None:- _fp8_gemm = get_fp8_gemm_nt()- return _fp8_gemm(a, b, d, bias=bias, c=c, num_sms=num_sms, use_fast_accum=use_fast_accum)--[email protected]_op("blockwise::fp8_gemm", mutates_args=())-def blockwise_fp8_gemm(- a: List[torch.Tensor],- b: List[torch.Tensor],- bias: Optional[torch.Tensor],- use_fast_accum: bool,-) -> torch.Tensor:- d = torch.empty(a[0].shape[0], b[0].shape[0], dtype=torch.bfloat16, device=b[0].device)- _fp8_gemm_dispatch(a, b, d, bias=bias, use_fast_accum=use_fast_accum)- return d---@blockwise_fp8_gemm.register_fake-def blockwise_fp8_gemm_fake(- a: List[torch.Tensor],- b: List[torch.Tensor],- bias: Optional[torch.Tensor],- use_fast_accum: bool,-) -> torch.Tensor:- o = torch.empty(a[0].shape[0], b[0].shape[0], dtype=torch.bfloat16, device=b[0].device)- return o---def is_16bit(x) -> bool:- return x.dtype == torch.float16 or x.dtype == torch.bfloat16---class BlockwiseGemmLinearFunc(torch.autograd.Function):- @staticmethod- def forward(- ctx,- a: tuple[torch.Tensor, torch.Tensor],- w: tuple[torch.Tensor],- bias: Optional[torch.Tensor],- ) -> torch.Tensor:-- is_16bit_a = is_16bit(a[0])- if is_16bit_a:- a = blockwise_quantize_triton(a[0])-- b, n, h = a[0].shape- out_h, _ = w[0].shape- new_a = (a[0].view(-1, h), a[1])- # Fast accum sums raw (pre-dequant-scale) e4m3 products in a fp16 accumulator; on- # Blackwell those partial sums overflow fp16 range and the GEMM returns NaN, so fall- # back to the fp32 accumulator there. Verified on GB200 (sm_100a). Non-CUDA- # (meta / CPU fake) paths skip the capability query — get_device_arch requires CUDA.- use_fast_accum = (not a[0].is_cuda) or get_device_arch() != "blackwell"- d = blockwise_fp8_gemm(new_a, w, bias, use_fast_accum=use_fast_accum)- return d.view(b, n, out_h)+_BLOCK_SIZE = 128-def blockwise_linear_func(a, b, bias=None):- return BlockwiseGemmLinearFunc.apply(a, b, bias)+def _blockwise_fp8_matmul(x, fp8_weight, weight_scale, bias):+ """Quantize the bf16 activation and run the FP8 GEMM.+ Always quantizes ``x``. Under the compile backend, FuseTrailingQuantize+ rewrites the ``blockwise_quantize`` node into the preceding op's quantized+ twin wherever that producer feeds only FP8 consumers -- so there is no+ runtime tuple-input path to handle here.+ """+ fp8_x, scales = blockwise_quantize(x)+ b, n, _ = fp8_x.shape+ out_h = fp8_weight.shape[0]+ flat = (fp8_x.view(-1, fp8_x.shape[-1]), scales)+ use_fast_accum = (not fp8_x.is_cuda) or get_device_arch() != "blackwell"+ out = blockwise_fp8_gemm(flat, [fp8_weight, weight_scale], bias, use_fast_accum)+ return out.view(b, n, out_h)-class BlockwiseLinear(nn.Module):- """Base class for blockwise quantized linear layers."""+class BlockwiseFP8Linear(nn.Module):+ """Drop-in ``nn.Linear`` replacement with FP8 weights + bf16 activations.+ ``forward(x)`` takes bf16 ``(B, T, H)`` and returns bf16+ ``(B, T, out_features)``; the activation is quantized internally.+ """- def __init__(- self,- in_features: int,- out_features: int,- bias: bool = True,- device=None,- dtype=None, # for compatibility with nn.Linear- ):+ def __init__(self, in_features, out_features, bias=True, device=None, dtype=None):super().__init__()self.in_features = in_featuresself.out_features = out_features-+ self.weight = nn.Parameter(+ torch.empty(out_features, in_features, device=device, dtype=torch.float8_e4m3fn),+ requires_grad=False,+ )+ self.weight_scale = nn.Parameter(+ torch.ones(out_features // _BLOCK_SIZE, in_features // _BLOCK_SIZE, device=device, dtype=torch.float32),+ requires_grad=False,+ )if bias:# FP32 to match the SM89/SM90 GEMM bias contract (the kernels take float*).self.bias = nn.Parameter(@@ -132,153 +65,108 @@ class BlockwiseLinear(nn.Module):else:self.register_parameter("bias", None)- @property- def fp8weight(self):- """Should be implemented by subclasses."""- raise NotImplementedError("Subclasses must implement the weight property")-def forward(self, x):- if not isinstance(x, tuple):- x = (x, None)- return blockwise_linear_func(x, (self.fp8weight, self.weight_scale), self.bias)+ bias = self.bias.data if self.bias is not None else None+ return _blockwise_fp8_matmul(x, self.weight, self.weight_scale, bias)@classmethod- def from_linear(cls, linear: nn.Linear, transform_weights=True):- """Should be implemented by subclasses."""- raise NotImplementedError("Subclasses must implement from_linear method")---class BlockwiseFP8Linear(BlockwiseLinear):- """Blockwise quantized linear layer using FP8 weights."""-- def __init__(- self,- in_features: int,- out_features: int,- bias: bool = True,- device=None,- dtype=None,- ):- super().__init__(in_features, out_features, bias, device, dtype)-- assert in_features % 128 == 0, f"in_features must be divisible by 128, got {in_features}"- assert out_features % 128 == 0, f"out_features must be divisible by 128, got {out_features}"-- self.weight = nn.Parameter(- torch.empty(- out_features, in_features, device=device, dtype=torch.float8_e4m3fn- ),- requires_grad=False,- )- self.weight_scale = nn.Parameter(- torch.ones(out_features//128, in_features//128, device=device, dtype=torch.float32),- requires_grad=False,- )-- @property- def fp8weight(self):- """Return FP8 weight directly."""- return self.weight-- @classmethod- def from_linear(cls, linear: nn.Linear, transform_weights=True):+ def from_linear(cls, linear, transform_weights=True):+ """Construct an FP8 module from a regular ``nn.Linear``.+ ``transform_weights=False`` allocates empty quantized buffers (the caller+ loads ``.weight`` / ``.weight_scale`` via state-dict); ``True``+ blockwise-quantizes the source linear's weight.+ """layer = cls(linear.in_features,linear.out_features,- linear.bias is not None,+ bias=linear.bias is not None,device=linear.weight.device,)-if transform_weights:- w_fp8, w_scales = blockwise_quantize_weights(linear.weight.data.cuda())+ w_fp8, w_scales = fp8_blockwise_quantize_weights_torch(linear.weight.data.cuda())else:- w_fp8 = torch.empty(linear.out_features, linear.in_features, dtype=torch.float8_e4m3fn, device=linear.weight.device)+ w_fp8 = torch.empty(+ linear.out_features, linear.in_features, device=linear.weight.device, dtype=torch.float8_e4m3fn+ )w_scales = torch.ones(- w_fp8.shape[0]//128,- w_fp8.shape[1]//128,+ w_fp8.shape[0] // _BLOCK_SIZE,+ w_fp8.shape[1] // _BLOCK_SIZE,device=w_fp8.device,dtype=torch.float32,)-layer.weight.data = w_fp8layer.weight_scale.data = w_scales-if linear.bias is not None:layer.bias.data = linear.bias.data.to(torch.float32)-return layer-class BlockwiseFP6Linear(BlockwiseLinear):- """Blockwise quantized linear layer using FP6 weights with 6-bit packing."""+class BlockwiseFP6Linear(nn.Module):+ """``nn.Linear`` replacement with 6-bit-packed weights, unpacked to fp8 per call.+ FP6 is weight-only: the activation path is identical to FP8.+ """- def __init__(- self,- in_features: int,- out_features: int,- bias: bool = True,- device=None,- dtype=None,- ):- assert in_features % 4 == 0, f"in_features must be divisible by 4, got {in_features}"+ def __init__(self, in_features, out_features, bias=True, device=None, dtype=None):+ super().__init__()assert in_features % 8 == 0, f"in_features must be divisible by 8 for fp6_pack, got {in_features}"assert in_features % 128 == 0, f"in_features must be divisible by 128, got {in_features}"assert out_features % 128 == 0, f"out_features must be divisible by 128, got {out_features}"-- super().__init__(in_features, out_features, bias, device, dtype)-- # Store packed weight: [out_features, (in_features // 4)*3]+ self.in_features = in_features+ self.out_features = out_features+ # Packed weight: [out_features, (in_features // 4) * 3] uint8.self.weight = nn.Parameter(- torch.empty(- out_features, (in_features // 4)*3, device=device, dtype=torch.uint8- ),+ torch.empty(out_features, (in_features // 4) * 3, device=device, dtype=torch.uint8),requires_grad=False,)-- # Scales are based on unpacked dimensions+ # Scales are based on the unpacked dimensions.self.weight_scale = nn.Parameter(- torch.ones(out_features//128, in_features//128, device=device, dtype=torch.float32),+ torch.ones(out_features // _BLOCK_SIZE, in_features // _BLOCK_SIZE, device=device, dtype=torch.float32),requires_grad=False,)+ if bias:+ self.bias = nn.Parameter(+ torch.empty(out_features, device=device, dtype=torch.float32),+ requires_grad=False,+ )+ else:+ self.register_parameter("bias", None)@propertydef fp8weight(self):- """Unpack the 6-bit weights to 8-bit format on-the-fly."""- # Unpack from [out_features, (in_features // 4)*3] to [out_features, in_features]- unpacked = fp6_unpack(self.weight, self.in_features)- # Convert uint8 back to float8_e4m3fn view+ """Unpack the 6-bit weights to float8_e4m3fn on the fly.+ Uses the ``ltx_kernels::fp6_unpack`` custom op so the call survives+ torch.compile without a graph break.+ """+ unpacked = fp6_unpack_tensor(self.weight, self.in_features)return unpacked.view(torch.float8_e4m3fn)+ def forward(self, x):+ bias = self.bias.data if self.bias is not None else None+ return _blockwise_fp8_matmul(x, self.fp8weight, self.weight_scale, bias)+@classmethod- def from_linear(cls, linear: nn.Linear, transform_weights=True):+ def from_linear(cls, linear, transform_weights=True):layer = cls(linear.in_features,linear.out_features,- linear.bias is not None,+ bias=linear.bias is not None,device=linear.weight.device,)-if transform_weights:- # Quantize to FP6 (actually FP8 with restricted range)+ # Quantize to FP6 (FP8 with a restricted range), then pack [out, in] -> [out, in*3/4].w_fp6, w_scales = fp6_blockwise_quantize_weights_torch(linear.weight.data.cuda())-- # Pack the FP6 weights from [out, in] uint8 to [out, in*3/4] uint8- w_fp6_uint8 = w_fp6.view(torch.uint8)- w_packed = fp6_pack(w_fp6_uint8)-- layer.weight.data = w_packed+ layer.weight.data = fp6_pack_tensor(w_fp6.view(torch.uint8))layer.weight_scale.data = w_scaleselse:- # If not transforming, assume weights are already in packed format- layer.weight.data = torch.empty(linear.out_features, (linear.in_features // 4) * 3, dtype=torch.uint8, device=linear.weight.device)+ layer.weight.data = torch.empty(+ linear.out_features, (linear.in_features // 4) * 3, device=linear.weight.device, dtype=torch.uint8+ )layer.weight_scale.data = torch.ones(- linear.weight.shape[0]//128,- linear.in_features//128,+ linear.out_features // _BLOCK_SIZE,+ linear.in_features // _BLOCK_SIZE,device=linear.weight.device,dtype=torch.float32,)-if linear.bias is not None:layer.bias.data = linear.bias.data.to(torch.float32)-return layerdiff --git a/packages/ltx-kernels/src/ltx_kernels/blockwise/ops/__init__.py b/packages/ltx-kernels/src/ltx_kernels/blockwise/ops/__init__.pynew file mode 100644index 0000000..a7118bc--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/blockwise/ops/__init__.py@@ -0,0 +1,4 @@+"""Blockwise FP8/FP6 quantization ops.+Per-op modules: ``quantize`` (activation quantize/dequantize + torch weight+quantizers), ``fp6_pack`` (FP6 pack/unpack), and ``gemm`` (the FP8 GEMM).+"""diff --git a/packages/ltx-kernels/src/ltx_kernels/blockwise/ops/fp6_pack.py b/packages/ltx-kernels/src/ltx_kernels/blockwise/ops/fp6_pack.pynew file mode 100644index 0000000..d960d9d--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/blockwise/ops/fp6_pack.py@@ -0,0 +1,46 @@+"""FP6 weight pack / unpack ops.+Wraps the ``ops_cpp`` pack/unpack pybind kernels as ``torch.library.custom_op``+so they trace as opaque ``call_function`` nodes (the raw pybind builtins+graph-break Dynamo, splitting the compiled ``BlockwiseFP6Linear.forward``). FP6+packing drops the two highest exponent bits (e_1, e_2) for a 25% weight memory+saving; unpack restores them as 0.+"""++import torch++[email protected]_op("ltx_kernels::fp6_pack", mutates_args=())+def fp6_pack(x: torch.Tensor) -> torch.Tensor:+ """Pack an 8-bit tensor ``[m, n]`` to 6-bit ``[m, n*3//4]`` uint8 (``n % 8 == 0``)."""+ import ops_cpp # noqa: PLC0415++ return ops_cpp.fp6_pack(x)+++@fp6_pack.register_fake+def _fp6_pack_fake(x: torch.Tensor) -> torch.Tensor:+ m, n = x.shape+ return torch.empty(m, (n * 3) // 4, dtype=torch.uint8, device=x.device)++[email protected]_op("ltx_kernels::fp6_unpack", mutates_args=())+def fp6_unpack(x: torch.Tensor, original_n: int) -> torch.Tensor:+ """Unpack a 6-bit tensor ``[m, n_packed]`` back to 8-bit ``[m, original_n]`` uint8."""+ import ops_cpp # noqa: PLC0415++ return ops_cpp.fp6_unpack(x, original_n)+++@fp6_unpack.register_fake+def _fp6_unpack_fake(x: torch.Tensor, original_n: int) -> torch.Tensor:+ return torch.empty(x.shape[0], original_n, dtype=torch.uint8, device=x.device)+++def fp6_pack_tensor(x: torch.Tensor) -> torch.Tensor:+ """Pack FP8 weights (uint8 view) to FP6; see :func:`fp6_pack`."""+ return torch.ops.ltx_kernels.fp6_pack(x)+++def fp6_unpack_tensor(x: torch.Tensor, original_n: int) -> torch.Tensor:+ """Unpack FP6 weights back to FP8 layout (uint8); see :func:`fp6_unpack`."""+ return torch.ops.ltx_kernels.fp6_unpack(x, original_n)diff --git a/packages/ltx-kernels/src/ltx_kernels/blockwise/ops/gemm.py b/packages/ltx-kernels/src/ltx_kernels/blockwise/ops/gemm.pynew file mode 100644index 0000000..010a4f3--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/blockwise/ops/gemm.py@@ -0,0 +1,66 @@+"""Blockwise FP8 GEMM custom op + architecture dispatch.+The FP8 GEMM kernels live in the ``blockwise_cpp`` extension. The kernel is+resolved on first call (architecture-specific) so importing this module needs+neither a CUDA device nor the compiled extension.+"""++from typing import List, Optional++import torch++from ltx_kernels.arch import get_device_arch++# Lazily-initialized, architecture-specific FP8 GEMM callable.+_fp8_gemm = None+++def get_fp8_gemm_nt():+ """Runtime GPU architecture dispatch for FP8 GEMM."""+ arch = get_device_arch()+ if arch in ["ada", "blackwell"]:+ # Ada/Blackwell use SM89 kernels (GeForce path)+ from blockwise_cpp import fp8_gemm_nt_sm89++ def _func(a, b, d, bias=None, c=None, num_sms=132, use_fast_accum=True):+ return fp8_gemm_nt_sm89(a, b, d, bias=bias, use_fast_accum=use_fast_accum)++ return _func+ elif arch == "hopper":+ # Hopper uses SM90 kernels (H100 path)+ from blockwise_cpp import fp8_gemm_nt_sm90++ def _func(a, b, d, bias=None, c=None, num_sms=132, use_fast_accum=True):+ return fp8_gemm_nt_sm90(a, b, d, bias=bias, c=c, num_sms=num_sms)++ return _func+ else:+ raise RuntimeError(f"Unsupported GPU architecture: {arch}")+++def _fp8_gemm_dispatch(a, b, d, bias=None, c=None, num_sms=132, use_fast_accum=True):+ global _fp8_gemm+ if _fp8_gemm is None:+ _fp8_gemm = get_fp8_gemm_nt()+ return _fp8_gemm(a, b, d, bias=bias, c=c, num_sms=num_sms, use_fast_accum=use_fast_accum)++[email protected]_op("blockwise::fp8_gemm", mutates_args=())+def blockwise_fp8_gemm(+ a: List[torch.Tensor],+ b: List[torch.Tensor],+ bias: Optional[torch.Tensor],+ use_fast_accum: bool,+) -> torch.Tensor:+ d = torch.empty(a[0].shape[0], b[0].shape[0], dtype=torch.bfloat16, device=b[0].device)+ _fp8_gemm_dispatch(a, b, d, bias=bias, use_fast_accum=use_fast_accum)+ return d+++@blockwise_fp8_gemm.register_fake+def blockwise_fp8_gemm_fake(+ a: List[torch.Tensor],+ b: List[torch.Tensor],+ bias: Optional[torch.Tensor],+ use_fast_accum: bool,+) -> torch.Tensor:+ return torch.empty(a[0].shape[0], b[0].shape[0], dtype=torch.bfloat16, device=b[0].device)diff --git a/packages/ltx-kernels/src/ltx_kernels/blockwise/ops/quantize.py b/packages/ltx-kernels/src/ltx_kernels/blockwise/ops/quantize.pynew file mode 100644index 0000000..86dfd0e--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/blockwise/ops/quantize.py@@ -0,0 +1,157 @@+# ruff: noqa: N803, ANN001, ANN202+"""Blockwise FP8 activation quantize / dequantize, and torch weight quantizers.+The activation ops are registered via :func:`torch.library.triton_op` so they+appear as single FX nodes (``torch.ops.ltx_kernels.blockwise_quantize`` /+``...blockwise_dequantize``) -- the compile passes need stable identities to+bind against. The torch weight quantizers run at load time (not in the compiled+graph) and produce the FP8/FP6 ``.weight`` + ``.weight_scale`` buffers that+:class:`ltx_kernels.blockwise.linear.BlockwiseFP8Linear` / ``BlockwiseFP6Linear``+expect.+"""++import logging+from typing import Tuple++import torch+from torch.library import triton_op, wrap_triton+from triton import jit+from triton import language as tl++from ltx_kernels.blockwise._common import (+ _BLOCK_SIZE,+ _FP6_SCALE_MAX,+ _FP8_SCALE_MAX,+ _empty_tma_aligned_scales,+ _quantize,+)++logger = logging.getLogger(__name__)+++@jit+def _block_quantize_kernel(+ X,+ Out_scales,+ X_out,+ H: tl.constexpr,+ NUM_BLOCKS: tl.constexpr,+ BLOCK_SIZE: tl.constexpr,+ TMA_ALIGNED_MN: tl.constexpr,+ SCALE_MAX: tl.constexpr,+):+ token_idx = tl.program_id(0).to(tl.int64)+ x_ptr = X + token_idx * H + BLOCK_SIZE * tl.arange(0, NUM_BLOCKS)[:, None] + tl.arange(0, BLOCK_SIZE)[None, :]+ x = tl.load(x_ptr).to(tl.float32)++ o_quant, o_scales = _quantize(x, SCALE_MAX, NUM_BLOCKS, BLOCK_SIZE)+ x_out_ptr = (+ X_out + token_idx * H + BLOCK_SIZE * tl.arange(0, NUM_BLOCKS)[:, None] + tl.arange(0, BLOCK_SIZE)[None, :]+ )+ tl.store(x_out_ptr, o_quant)+ out_scales_ptr = Out_scales + token_idx + TMA_ALIGNED_MN * tl.arange(0, NUM_BLOCKS)[:, None]+ tl.store(out_scales_ptr, o_scales)+++@triton_op("ltx_kernels::blockwise_quantize", mutates_args=())+def blockwise_quantize(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ """Per-128-element blockwise FP8 quantization of a bf16 activation.+ Args:+ x: ``(B, T, H)`` bf16 input. ``H`` must be divisible by 128.+ Returns:+ ``(fp8_e4m3fn (B, T, H), fp32 scales (B*T, H//128))`` -- the scales+ tensor has TMA-padded backing storage for downstream FP8 GEMM consumers.+ """+ b, s, h = x.shape+ num_rows = b * s+ num_blocks = h // _BLOCK_SIZE+ out = torch.empty((num_rows, h), device=x.device, dtype=torch.float8_e4m3fn)+ scales, tma_aligned_mn = _empty_tma_aligned_scales(num_rows, num_blocks, x.device)+ wrap_triton(_block_quantize_kernel)[(num_rows,)](+ x,+ scales,+ out,+ H=h,+ BLOCK_SIZE=_BLOCK_SIZE,+ NUM_BLOCKS=num_blocks,+ TMA_ALIGNED_MN=tma_aligned_mn,+ SCALE_MAX=_FP8_SCALE_MAX,+ )+ return out.view(b, s, h), scales+++@jit+def _blockwise_dequantize_kernel(+ X,+ Scales,+ Out,+ scales_row_stride: int,+ scales_col_stride: int,+ H: tl.constexpr,+ NUM_BLOCKS: tl.constexpr,+ BLOCK_SIZE: tl.constexpr,+):+ token_idx = tl.program_id(0)+ scales = tl.load(Scales + token_idx * scales_row_stride + scales_col_stride * tl.arange(0, NUM_BLOCKS)).to(+ tl.float32+ )+ scales = tl.broadcast_to(scales[:, None], (NUM_BLOCKS, BLOCK_SIZE))+ x_offsets = BLOCK_SIZE * tl.arange(0, NUM_BLOCKS)[:, None] + tl.arange(0, BLOCK_SIZE)[None, :]+ x = tl.load(X + token_idx * H + x_offsets).to(tl.float32)+ tl.store(Out + token_idx * H + x_offsets, (x * scales).to(tl.bfloat16))+++@triton_op("ltx_kernels::blockwise_dequantize", mutates_args=())+def blockwise_dequantize(x: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:+ """Inverse of :func:`blockwise_quantize`.+ Args:+ x: ``(B, T, H)`` fp8_e4m3fn input.+ scales: ``(B*T, H//128)`` fp32 per-block scales.+ Returns:+ ``(B, T, H)`` bf16 output.+ """+ b, s, h = x.shape+ block_size = _BLOCK_SIZE+ num_blocks = h // block_size+ num_rows = b * s+ out = torch.empty((num_rows, h), device=x.device, dtype=torch.bfloat16)+ wrap_triton(_blockwise_dequantize_kernel)[(num_rows,)](+ x,+ scales,+ out,+ scales_row_stride=scales.stride(0),+ scales_col_stride=scales.stride(1),+ H=h,+ NUM_BLOCKS=num_blocks,+ BLOCK_SIZE=block_size,+ )+ return out.view(b, s, h)+++# ---------------------------------------------------------------------------+# Torch weight quantizers (load-time; not part of the compiled graph)+# ---------------------------------------------------------------------------+++def blockwise_quantize_weights(+ w: torch.Tensor, block_size: int = _BLOCK_SIZE, scale_max: float = _FP8_SCALE_MAX+) -> tuple[torch.Tensor, torch.Tensor]:+ """Blockwise-quantize a 2D weight ``[out, in]`` to fp8 + per-128-block fp32 scale."""+ w = w.view(w.shape[0] // block_size, block_size, w.shape[1] // block_size, block_size).transpose(1, 2).contiguous()+ w_absmax = w.float().abs().view(w.shape[0], w.shape[1], block_size * block_size).max(dim=-1, keepdim=False).values+ w_scales = scale_max / w_absmax+ w_quant = (w.float() * w_scales[:, :, None, None].float()).to(torch.float8_e4m3fn)+ w_quant = w_quant.transpose(1, 2).contiguous()+ w_quant = w_quant.view(w.shape[0] * block_size, -1)+ return w_quant, (1 / w_scales).contiguous()+++def fp8_blockwise_quantize_weights_torch(+ x: torch.Tensor, block_size: int = _BLOCK_SIZE+) -> tuple[torch.Tensor, torch.Tensor]:+ return blockwise_quantize_weights(x, block_size, _FP8_SCALE_MAX)+++def fp6_blockwise_quantize_weights_torch(+ x: torch.Tensor, block_size: int = _BLOCK_SIZE+) -> tuple[torch.Tensor, torch.Tensor]:+ return blockwise_quantize_weights(x, block_size, _FP6_SCALE_MAX)diff --git a/packages/ltx-kernels/src/ltx_kernels/blockwise/triton_ops.py b/packages/ltx-kernels/src/ltx_kernels/blockwise/triton_ops.pydeleted file mode 100644index 365869c..0000000--- a/packages/ltx-kernels/src/ltx_kernels/blockwise/triton_ops.py+++ /dev/null@@ -1,460 +0,0 @@-from typing import *--import torch-from triton import jit-from triton import language as tl-from triton import next_power_of_2-from torch.library import triton_op, wrap_triton--def get_tma_aligned_size(n, element_size):- num_elems_tma = 16 // element_size- return ((n + num_elems_tma - 1) // num_elems_tma) * num_elems_tma--def empty_tma_aligned_scales(num_rows: int, num_blocks: int, device: torch.device) -> tuple[torch.Tensor, int]:- """Allocate MN-major fp32 scales with TMA-padded row storage.- TMA descriptors treat the padded M (16-byte aligned) as the tensor dimension, so- the allocation must include those extra rows. ``empty_strided((num_rows, n),- (1, aligned_m))`` only pads the stride and under-allocates when ``num_rows`` is- not already aligned -- the GEMM then reads past the buffer.- """- tma_aligned_mn = get_tma_aligned_size(num_rows, 4)- # (num_blocks, aligned_m).t()[:num_rows] keeps the full padded storage under a- # (num_rows, num_blocks) view with stride (1, aligned_m).- scales = torch.empty((num_blocks, tma_aligned_mn), dtype=torch.float, device=device).t()[:num_rows]- return scales, tma_aligned_mn--@jit-def _quantize(x, scale_max: tl.constexpr, NUM_BLOCKS: tl.constexpr, BLOCK_SIZE: tl.constexpr):- x = tl.reshape(x, (NUM_BLOCKS, BLOCK_SIZE))- x_abs = tl.abs(x)- x_abs = tl.broadcast_to(x_abs, (NUM_BLOCKS, BLOCK_SIZE))- x_absmax = tl.max(x_abs, axis=1)[:, None]- x_scales = scale_max / x_absmax- x_quant = (x_scales * x).to(tl.float8e4nv)- x_out_scales = 1.0/x_scales- return x_quant, x_out_scales--@jit-def _kernel(X, OUT, SCALES, HDIM, BLOCK_SIZE: tl.constexpr):- row_idx = tl.program_id(0)- x_ptr = X + row_idx * HDIM- out_ptr = OUT + row_idx * HDIM-- h_offset = tl.arange(0, BLOCK_SIZE)-- x = tl.load(x_ptr + h_offset, mask=h_offset < HDIM).to(tl.float32)- x_scale = 127.0 / tl.max(tl.abs(x))- x_scaled = x * x_scale- x_scaled += (0.5 * tl.where(x_scaled >= 0, 1, -1)).to(tl.int8)-- tl.store(out_ptr + h_offset, x_scaled, mask=h_offset < HDIM)- tl.store(SCALES + row_idx, 1 / x_scale)--def run_quantize_kernel(x: torch.Tensor, out_dtype: Optional[torch.dtype] = None):- x_shape_orig = x.shape- x = x.view(-1, x_shape_orig[-1])- out = torch.empty(x_shape_orig, dtype=torch.int8, device=x.device)- scales = torch.empty(x.shape[0], dtype=torch.float, device=x.device)-- BLOCK_SIZE = next_power_of_2(x_shape_orig[-1])- grid = (x.shape[0],)- _kernel[grid](x, out, scales, x_shape_orig[-1], BLOCK_SIZE, num_warps=4)-- return out.view(x_shape_orig), scales.view(x_shape_orig[:-1])--@jit-def _block_quant_norm_kernel(- X,- Norm_Scale,- Norm_Shift,- Out_scales,- X_out,- norm_scale_batch_stride: int,- norm_shift_batch_stride: int,- norm_scale_token_stride: int,- norm_shift_token_stride: int,- seqlen: int,- H: tl.constexpr,- BROADCAST_SEQLEN: tl.constexpr,- NUM_BLOCKS: tl.constexpr,- BLOCK_SIZE: tl.constexpr,- TMA_ALIGNED_MN: tl.constexpr,- SCALE_MAX: tl.constexpr,-):- token_idx = tl.program_id(0).to(tl.int64)- batch_id = token_idx // seqlen-- x_ptr = X + token_idx*H + tl.arange(0, H)- if BROADCAST_SEQLEN:- norm_scale_ptr = Norm_Scale + batch_id*norm_scale_batch_stride + tl.arange(0, H)- norm_shift_ptr = Norm_Shift + batch_id*norm_shift_batch_stride + tl.arange(0, H)- else:- norm_scale_ptr = Norm_Scale + batch_id*norm_scale_batch_stride + (token_idx % seqlen) * norm_scale_token_stride + tl.arange(0, H)- norm_shift_ptr = Norm_Shift + batch_id*norm_shift_batch_stride + (token_idx % seqlen) * norm_shift_token_stride + tl.arange(0, H)-- norm_scales = tl.load(norm_scale_ptr)- norm_shift = tl.load(norm_shift_ptr)- x = tl.load(x_ptr)-- x_sqr = x*x- x_norm = tl.sum(x_sqr) / H- x_norm = tl.rsqrt(x_norm + 0.00001)- x = (x * x_norm).to(tl.bfloat16)- x = x * (1.0+norm_scales) + norm_shift-- o_quant, o_scales = _quantize(x, SCALE_MAX, NUM_BLOCKS, BLOCK_SIZE)- x_out_ptr = X_out + token_idx*H + BLOCK_SIZE*tl.arange(0, NUM_BLOCKS)[:, None] + tl.arange(0, BLOCK_SIZE)[None, :]- tl.store(x_out_ptr, o_quant)- out_scales_ptr = Out_scales + token_idx + TMA_ALIGNED_MN*tl.arange(0, NUM_BLOCKS)[:, None]- tl.store(out_scales_ptr, o_scales)--@jit-def _gelu(x):- return x * tl.sigmoid(1.702*x)--@jit-def _block_quant_kernel(- X,- Out_scales,- X_out,- H: tl.constexpr,- NUM_BLOCKS: tl.constexpr,- BLOCK_SIZE: tl.constexpr,- TMA_ALIGNED_MN: tl.constexpr,- USE_GELU: tl.constexpr,- SCALE_MAX: tl.constexpr,-):- # 1D grid over tokens: a (batch, seq) grid overflows CUDA gridDim.y at seq > 65535.- token_idx = tl.program_id(0).to(tl.int64)- x_ptr = X + token_idx*H + BLOCK_SIZE*tl.arange(0, NUM_BLOCKS)[:, None] + tl.arange(0, BLOCK_SIZE)[None, :]- x = tl.load(x_ptr).to(tl.float32)- if USE_GELU:- x = _gelu(x)-- o_quant, o_scales = _quantize(x, SCALE_MAX, NUM_BLOCKS, BLOCK_SIZE)- x_out_ptr = X_out + token_idx*H + BLOCK_SIZE*tl.arange(0, NUM_BLOCKS)[:, None] + tl.arange(0, BLOCK_SIZE)[None, :]- tl.store(x_out_ptr, o_quant)- out_scales_ptr = Out_scales + token_idx + TMA_ALIGNED_MN*tl.arange(0, NUM_BLOCKS)[:, None]- tl.store(out_scales_ptr, o_scales)--@triton_op("blockwise::quantize", mutates_args=())-def _quant_blockwise_tma_aligned_func(x: torch.Tensor, use_gelu: bool) -> Tuple[torch.Tensor, torch.Tensor]:- b, s, h = x.shape- num_rows = b*s- block_size = 128- num_blocks = h // block_size- out = torch.empty((num_rows, h), device=x.device, dtype=torch.float8_e4m3fn)- scales, tma_aligned_mn = empty_tma_aligned_scales(num_rows, num_blocks, x.device)- scale_max: float = 448.0- wrap_triton(_block_quant_kernel)[(num_rows,)](- x,- scales,- out,- H=h,- BLOCK_SIZE=128,- NUM_BLOCKS=num_blocks,- TMA_ALIGNED_MN=tma_aligned_mn,- USE_GELU=use_gelu,- SCALE_MAX=scale_max- )-- return out.view(b, s, h), scales--def run_quant_blockwise_tma_aligned(x):- return _quant_blockwise_tma_aligned_func(x, False)--def run_quant_blockwise_gelu_tma_aligned(x):- return _quant_blockwise_tma_aligned_func(x, True)--@triton_op("blockwise::adanorm", mutates_args=())-def run_quant_blockwise_norm_tma_aligned(x: torch.Tensor, w: Optional[torch.Tensor], norm_scale: torch.Tensor, norm_shift: torch.Tensor, out_dtype: torch.dtype, hd_scale: Optional[float]) -> Tuple[torch.Tensor, torch.Tensor]:- b, s, h = x.shape- is_broadcast = (norm_scale.shape[1] == 1)- num_rows = b*s- block_size = 128- num_blocks = h // block_size- out = torch.empty((num_rows, h), device=x.device, dtype=torch.float8_e4m3fn)- scales, tma_aligned_mn = empty_tma_aligned_scales(num_rows, num_blocks, x.device)- norm_scale_batch_stride = norm_scale.stride(0)- norm_shift_batch_stride = norm_shift.stride(0)-- scale_max: float = 448.0- wrap_triton(_block_quant_norm_kernel)[(num_rows, 1, 1)](- x,- norm_scale,- norm_shift,- scales,- out,- norm_scale_batch_stride=norm_scale_batch_stride,- norm_shift_batch_stride=norm_shift_batch_stride,- norm_scale_token_stride=norm_scale.stride(1),- norm_shift_token_stride=norm_shift.stride(1),- H=h,- seqlen=s,- BROADCAST_SEQLEN=is_broadcast,- BLOCK_SIZE=128,- NUM_BLOCKS=num_blocks,- TMA_ALIGNED_MN=tma_aligned_mn,- SCALE_MAX=scale_max- )-- return out.view(b, s, h), scales--@jit-def _quant_rms_sum_mult_kernel(- X,- Y,- Z,- Out,- Out_scales,- seqlen: int,- z_batch_stride: int,- z_token_stride: int,- TMA_ALIGNED_MN: int,- H: tl.constexpr,- NUM_BLOCKS: tl.constexpr,- BLOCK_SIZE: tl.constexpr,- IS_Z_BROADCAST: tl.constexpr,- QUANTIZE: tl.constexpr,- SCALE_MAX: tl.constexpr,-):- token_idx = tl.program_id(0).to(tl.int64)- batch_id = token_idx // seqlen-- x_ptr = X + token_idx*H + tl.arange(0, H)- y_ptr = Y + token_idx*H + tl.arange(0, H)- if IS_Z_BROADCAST:- z_ptr = Z + batch_id*z_batch_stride + tl.arange(0, H)- else:- z_ptr = Z + batch_id*z_batch_stride + (token_idx % seqlen) * z_token_stride + tl.arange(0, H)- x = tl.load(x_ptr)- y = tl.load(y_ptr)- z = tl.load(z_ptr)-- o = x + y*z-- tl.store(x_ptr, o)-- o_sqr = o * o- o_norm = tl.sum(o_sqr, axis=0) / H- o_inv = tl.rsqrt(o_norm)- o *= o_inv-- if QUANTIZE:- o_quant, o_scales = _quantize(o, SCALE_MAX, NUM_BLOCKS, BLOCK_SIZE)- x_out_ptr = Out + token_idx*H + BLOCK_SIZE*tl.arange(0, NUM_BLOCKS)[:, None] + tl.arange(0, BLOCK_SIZE)[None, :]- tl.store(x_out_ptr, o_quant)- out_scales_ptr = Out_scales + token_idx + TMA_ALIGNED_MN*tl.arange(0, NUM_BLOCKS)[:, None]- tl.store(out_scales_ptr, o_scales)- else:- x_out_ptr = Out + token_idx*H + tl.arange(0, H)- tl.store(x_out_ptr, o)--@triton_op("blockwise::quant_rms_fma", mutates_args=("x", ))-def run_quant_blockwise_rms_fma(x: torch.Tensor, y: torch.Tensor, z: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:- b, s, h = x.shape- scale_max: float = 448.0- is_z_broadcast = (z.shape[1] == 1)- num_rows = b*s- block_size = 128- num_blocks = h // block_size- out = torch.empty((num_rows, h), device=x.device, dtype=torch.float8_e4m3fn)- scales, tma_aligned_mn = empty_tma_aligned_scales(num_rows, num_blocks, x.device)- z_batch_stride = z.stride(0)-- wrap_triton(_quant_rms_sum_mult_kernel)[(num_rows, 1, 1)](- x,- y,- z,- out,- scales,- seqlen=s,- z_batch_stride=z_batch_stride,- z_token_stride=z.stride(1),- TMA_ALIGNED_MN=tma_aligned_mn,- H=h,- NUM_BLOCKS=num_blocks,- BLOCK_SIZE=128,- IS_Z_BROADCAST=is_z_broadcast,- QUANTIZE=True,- SCALE_MAX=scale_max- )-- return out.view(b, s, h), scales---@triton_op("blockwise::rms_fma", mutates_args=("x", ))-def run_rms_fma(x: torch.Tensor, y: torch.Tensor, z: torch.Tensor) -> torch.Tensor:- b, s, h = x.shape- is_z_broadcast = (z.shape[1] == 1)- num_rows = b*s- block_size = 128- num_blocks = h // block_size- out = torch.empty((num_rows, h), device=x.device, dtype=torch.bfloat16)- z_batch_stride = z.stride(0)-- wrap_triton(_quant_rms_sum_mult_kernel)[(num_rows, 1, 1)](- x,- y,- z,- out,- None,- seqlen=s,- z_batch_stride=z_batch_stride,- z_token_stride=z.stride(1),- TMA_ALIGNED_MN=0,- H=h,- NUM_BLOCKS=num_blocks,- BLOCK_SIZE=128,- IS_Z_BROADCAST=is_z_broadcast,- QUANTIZE=False,- SCALE_MAX=448.0- )-- return out.view(b, s, h)---@jit-def _gated_attention_kernel(- X,- Gate_Logits,- Out,- Out_scales,- H: tl.constexpr,- NUM_HEADS: tl.constexpr,- DIM_HEAD: tl.constexpr,- NUM_BLOCKS: tl.constexpr,- BLOCK_SIZE: tl.constexpr,- TMA_ALIGNED_MN: tl.constexpr,- QUANTIZE: tl.constexpr,- SCALE_MAX: tl.constexpr,-):- token_idx = tl.program_id(0).to(tl.int64)-- # Load gate logits for all heads: shape [NUM_HEADS]- gate_logits = tl.load(Gate_Logits + token_idx * NUM_HEADS + tl.arange(0, NUM_HEADS)).to(tl.float32)- # 2*sigmoid so that zero-init gives identity (2 * 0.5 = 1.0)- gates = 2.0 * tl.sigmoid(gate_logits) # [NUM_HEADS]- gates = tl.broadcast_to(gates[:, None], (NUM_HEADS, DIM_HEAD)) # [NUM_HEADS, DIM_HEAD]-- # Load x viewed as [NUM_HEADS, DIM_HEAD]- offsets = tl.arange(0, NUM_HEADS)[:, None] * DIM_HEAD + tl.arange(0, DIM_HEAD)[None, :]- x = tl.load(X + token_idx * H + offsets).to(tl.float32)-- # Apply per-head gating- gated = x * gates # [NUM_HEADS, DIM_HEAD]-- if QUANTIZE:- o_quant, o_scales = _quantize(gated, SCALE_MAX, NUM_BLOCKS, BLOCK_SIZE)- out_ptr = Out + token_idx * H + BLOCK_SIZE * tl.arange(0, NUM_BLOCKS)[:, None] + tl.arange(0, BLOCK_SIZE)[None, :]- tl.store(out_ptr, o_quant)- scales_ptr = Out_scales + token_idx + TMA_ALIGNED_MN * tl.arange(0, NUM_BLOCKS)[:, None]- tl.store(scales_ptr, o_scales)- else:- out_ptr = Out + token_idx * H + offsets- tl.store(out_ptr, gated)---@triton_op("blockwise::gated_attention", mutates_args=())-def run_gated_attention(x: torch.Tensor, gate_logits: torch.Tensor, quantize: bool = True) -> Tuple[torch.Tensor, torch.Tensor]:- b, t, h = x.shape- num_heads = gate_logits.shape[-1]- dim_head = h // num_heads- block_size = 128- num_blocks = h // block_size- num_rows = b * t- scale_max: float = 448.0-- if quantize:- out = torch.empty((num_rows, h), device=x.device, dtype=torch.float8_e4m3fn)- scales, tma_aligned_mn = empty_tma_aligned_scales(num_rows, num_blocks, x.device)- else:- out = torch.empty((num_rows, h), device=x.device, dtype=torch.bfloat16)- tma_aligned_mn = 0- scales = None-- wrap_triton(_gated_attention_kernel)[(num_rows,)](- x,- gate_logits,- out,- scales,- H=h,- NUM_HEADS=num_heads,- DIM_HEAD=dim_head,- NUM_BLOCKS=num_blocks,- BLOCK_SIZE=128,- TMA_ALIGNED_MN=tma_aligned_mn,- QUANTIZE=quantize,- SCALE_MAX=scale_max,- )-- return out.view(b, t, h), scales---@jit-def _blockwise_dequantize_kernel(- X,- Scales,- Out,- scales_row_stride: int,- scales_col_stride: int,- H: tl.constexpr,- NUM_BLOCKS: tl.constexpr,- BLOCK_SIZE: tl.constexpr,-):- token_idx = tl.program_id(0).to(tl.int64)-- # Load per-block scales [NUM_BLOCKS] respecting the actual tensor strides- scales = tl.load(- Scales + token_idx * scales_row_stride + scales_col_stride * tl.arange(0, NUM_BLOCKS)- ).to(tl.float32)- scales = tl.broadcast_to(scales[:, None], (NUM_BLOCKS, BLOCK_SIZE))-- # Load fp8 input viewed as [NUM_BLOCKS, BLOCK_SIZE]- x_offsets = BLOCK_SIZE * tl.arange(0, NUM_BLOCKS)[:, None] + tl.arange(0, BLOCK_SIZE)[None, :]- x = tl.load(X + token_idx * H + x_offsets).to(tl.float32)-- # Dequantize and store as bf16- tl.store(Out + token_idx * H + x_offsets, (x * scales).to(tl.bfloat16))---@triton_op("blockwise::dequantize", mutates_args=())-def run_blockwise_dequantize(x: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:- b, s, h = x.shape- block_size = 128- num_blocks = h // block_size- num_rows = b * s- out = torch.empty((num_rows, h), device=x.device, dtype=torch.bfloat16)-- wrap_triton(_blockwise_dequantize_kernel)[(num_rows,)](- x,- scales,- out,- scales_row_stride=scales.stride(0),- scales_col_stride=scales.stride(1),- H=h,- NUM_BLOCKS=num_blocks,- BLOCK_SIZE=128,- )-- return out.view(b, s, h)---rowwise_int_quantize_triton = run_quantize_kernel-blockwise_quantize_adanorm_triton = run_quant_blockwise_norm_tma_aligned-blockwise_quantize_triton = run_quant_blockwise_tma_aligned-blockwise_quantize_gelu_triton = run_quant_blockwise_gelu_tma_aligned-blockwise_quantize_rms_fma_triton = run_quant_blockwise_rms_fma-rms_fma_triton = run_rms_fma-gated_attention_triton = run_gated_attention-blockwise_dequantize_triton = run_blockwise_dequantize--# # Precision-specific convenience functions for Triton kernels-# def fp8_blockwise_quantize_triton(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:-# return run_quant_blockwise_tma_aligned(x, scale_max=FP8_SCALE_MAX)--# def fp7_blockwise_quantize_triton(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:-# return run_quant_blockwise_tma_aligned(x, scale_max=FP7_SCALE_MAX)--# def fp6_blockwise_quantize_triton(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:-# return run_quant_blockwise_tma_aligned(x, scale_max=FP6_SCALE_MAX)\ No newline at end of filediff --git a/packages/ltx-kernels/src/ltx_kernels/compile/__init__.py b/packages/ltx-kernels/src/ltx_kernels/compile/__init__.pynew file mode 100644index 0000000..6f90330--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/compile/__init__.py@@ -0,0 +1,17 @@+"""``torch.compile`` integration: custom backend shim + FX graph passes."""++from ltx_kernels.compile.backend import (+ ltx_kernels_eager_backend,+ ltx_kernels_inductor_backend,+ make_ltx_kernels_backend,+)+from ltx_kernels.compile.passes import GatedAttentionPass+from ltx_kernels.compile.subgraph_rewrite_pass import SubgraphRewritePass++__all__ = [+ "GatedAttentionPass",+ "SubgraphRewritePass",+ "ltx_kernels_eager_backend",+ "ltx_kernels_inductor_backend",+ "make_ltx_kernels_backend",+]diff --git a/packages/ltx-kernels/src/ltx_kernels/compile/backend.py b/packages/ltx-kernels/src/ltx_kernels/compile/backend.pynew file mode 100644index 0000000..bef9f77--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/compile/backend.py@@ -0,0 +1,65 @@+"""Custom ``torch.compile`` backend that applies ltx-kernels passes.+The shim:+1. Runs the passes from :mod:`ltx_kernels.compile.passes` via+ :class:`torch.fx.passes.infra.pass_manager.PassManager` over the Dynamo+ :class:`torch.fx.GraphModule` directly -- no AOT autograd round-trip.+2. Delegates the (possibly-rewritten) graph to a registered backend named by+ ``inner_backend``, resolved via :func:`torch._dynamo.lookup_backend`.+Operating on the Dynamo graph (instead of the AOT-lowered ATen graph) keeps+us off ``torch._dynamo.backends.common.aot_autograd``'s per-call inference+runtime wrapper, which on transformer-block-sized graphs adds ~28% wall+time when the inner backend is ``"eager"`` (the wrapper costs are amortized+when the inner backend is ``"inductor"``, but punishing on ``"eager"``).+The passes in :mod:`ltx_kernels.compile.passes` are written to match the+Dynamo IR op forms accordingly.+Two pre-built backends are exposed via ``torch_dynamo_backends`` setuptools+entry points (see ``pyproject.toml``) and resolve automatically once the+package is installed:+- ``ltx_kernels_eager`` -- inner backend ``"eager"``, :func:`eager_passes`.+ Default for inference.+- ``ltx_kernels_inductor`` -- inner backend ``"inductor"``,+ :func:`inductor_passes`. Pays compile time for inductor's whole-graph fusion of+ non-matched ops.+For a custom pass list or other inner backend use+:func:`make_ltx_kernels_backend`::+ torch.compile(model, backend=make_ltx_kernels_backend(passes=[...], inner_backend="..."))+"""++import logging+from collections.abc import Callable++import torch+from torch._dynamo.backends.registry import lookup_backend+from torch.fx.passes.infra.pass_base import PassBase+from torch.fx.passes.infra.pass_manager import PassManager++from ltx_kernels.compile.passes import eager_passes, inductor_passes++logger = logging.getLogger(__name__)+++def make_ltx_kernels_backend(+ passes: list[PassBase],+ inner_backend: str = "eager",+) -> Callable:+ """Build an ltx-kernels backend with a chosen pass list and inner backend.+ Args:+ passes: List of :class:`PassBase` instances to apply, in the order given.+ inner_backend: Name of the backend to dispatch to after passes run,+ resolved via :func:`torch._dynamo.lookup_backend`. Examples:+ ``"eager"``, ``"inductor"``.+ """+ pass_manager = PassManager(passes=list(passes))++ def _compile(gm: torch.fx.GraphModule, example_inputs: list[torch.Tensor]) -> Callable:+ result = pass_manager(gm)+ return lookup_backend(inner_backend)(result.graph_module, example_inputs)++ return _compile+++# Entry-point targets in pyproject.toml. ``torch.compile`` resolves+# ``backend="ltx_kernels_eager"`` / ``"ltx_kernels_inductor"`` to these+# automatically once the package is installed.+ltx_kernels_eager_backend = make_ltx_kernels_backend(passes=eager_passes(), inner_backend="eager")+ltx_kernels_inductor_backend = make_ltx_kernels_backend(passes=inductor_passes(), inner_backend="inductor")diff --git a/packages/ltx-kernels/src/ltx_kernels/compile/passes/__init__.py b/packages/ltx-kernels/src/ltx_kernels/compile/passes/__init__.pynew file mode 100644index 0000000..e224521--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/compile/passes/__init__.py@@ -0,0 +1,76 @@+"""Concrete FX passes applied by the ltx-kernels backend."""++from torch.fx.passes.infra.pass_base import PassBase++from ltx_kernels.compile.passes.ada_zero import AdaZeroPass+from ltx_kernels.compile.passes.blockwise_quantize_cse import BlockwiseQuantizeCSE+from ltx_kernels.compile.passes.fuse_trailing_quantize import (+ AdaZeroTrailingQuantizePass,+ GatedAttentionTrailingQuantizePass,+)+from ltx_kernels.compile.passes.gated_attention import GatedAttentionPass+from ltx_kernels.compile.passes.grouped_upcast import GroupedUpcastPass+from ltx_kernels.compile.passes.linear_gelu import LinearGELUPass+from ltx_kernels.compile.passes.pre_attention import PreAttentionPass+from ltx_kernels.compile.passes.rms_fma import RMSFmaAdaLNPass, RMSFmaPass+++def inductor_passes() -> list[PassBase]:+ """The passes worth running when inductor compiles what is left.+ :class:`PreAttentionPass` + :class:`GatedAttentionPass` + :class:`LinearGELUPass`+ is the fastest combination measured end to end; the passes :func:`eager_passes`+ adds cost more there than they save, alone and together, by cutting inductor's own+ fusion across the block. The quantize passes are inert unless+ ``ltx_core.quantization.blockwise`` installs the linears that emit+ ``ltx_kernels::blockwise_quantize``. :class:`GroupedUpcastPass` is inert outside the+ fp8-cast policy.+ One instance per stream shape (LTX-2.3: video 4096, audio 2048), since a pass pins+ the ``hidden_dim`` and ``heads`` literals its pattern carries.+ """+ return [+ PreAttentionPass(hidden_dim=4096, heads=32, eps=1e-6),+ PreAttentionPass(hidden_dim=2048, heads=32, eps=1e-6),+ GatedAttentionPass(),+ LinearGELUPass(),+ BlockwiseQuantizeCSE(),+ AdaZeroTrailingQuantizePass(hidden_dim=4096, eps=1e-6),+ AdaZeroTrailingQuantizePass(hidden_dim=2048, eps=1e-6),+ GatedAttentionTrailingQuantizePass(),+ GroupedUpcastPass(),+ ]+++def eager_passes() -> list[PassBase]:+ """Every pass, for an inner backend that fuses nothing itself.+ The passes :func:`inductor_passes` leaves out lose to inductor's fusion, not to+ the ops they replace, so they are kept here -- reasoned from the inductor+ measurements rather than measured on eager.+ The tail is in claim order: the quantize passes precede the RMSFma passes, which+ have no quantized twin and would otherwise take those sites, and+ :class:`AdaZeroPass` is last because RMSFma claims its subgraph.+ """+ return [+ *inductor_passes(),+ RMSFmaAdaLNPass(hidden_dim=4096, eps=1e-6),+ RMSFmaAdaLNPass(hidden_dim=2048, eps=1e-6),+ RMSFmaPass(hidden_dim=4096, eps=1e-6),+ RMSFmaPass(hidden_dim=2048, eps=1e-6),+ AdaZeroPass(hidden_dim=4096, eps=1e-6),+ AdaZeroPass(hidden_dim=2048, eps=1e-6),+ ]+++__all__ = [+ "AdaZeroPass",+ "AdaZeroTrailingQuantizePass",+ "BlockwiseQuantizeCSE",+ "GatedAttentionPass",+ "GatedAttentionTrailingQuantizePass",+ "GroupedUpcastPass",+ "LinearGELUPass",+ "PreAttentionPass",+ "RMSFmaAdaLNPass",+ "RMSFmaPass",+ "eager_passes",+ "inductor_passes",+]diff --git a/packages/ltx-kernels/src/ltx_kernels/compile/passes/ada_zero.py b/packages/ltx-kernels/src/ltx_kernels/compile/passes/ada_zero.pynew file mode 100644index 0000000..d7aa5c4--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/compile/passes/ada_zero.py@@ -0,0 +1,84 @@+"""Pass that rewrites the eager AdaZero composite to a single custom op."""++from typing import ClassVar++import torch+from torch.fx.passes.utils.matcher_utils import InternalMatch++from ltx_kernels.compile.subgraph_rewrite_pass import SubgraphRewritePass, is_cuda_bf16, static_dim+++class AdaZeroPass(SubgraphRewritePass):+ """Rewrites the bf16 AdaZero composite::+ normed = F.rms_norm(x, (H,), None, eps)+ return normed * (1 + scale) + shift+ to a single ``ltx_kernels::ada_zero(x, scale, shift, eps)`` call. Matches+ the inlined ``rms_norm(...) * (1 + scale) + shift`` sites in+ :class:`BasicAVTransformerBlock.forward` (MSA, A-V cross-attention, MLP).+ PostSA residual + RMSNorm (+ query modulation when AdaLN is on) is a+ larger pattern claimed first by :class:`RMSFmaAdaLNPass` /+ :class:`RMSFmaPass`.+ Uses ``ignore_literals=False`` because the pattern contains a bare+ ``1 + scale`` whose literal ``1`` would be wildcarded under the default+ setting and confuse placeholder binding. Both ``hidden_dim`` and ``eps``+ are accordingly baked as literals in the captured pattern; the+ constructor takes them so callers register one instance per distinct+ ``(hidden_dim, eps)`` pair encountered in the user graph (LTX-2.3:+ video ``hidden_dim=4096``, audio ``hidden_dim=2048``, both+ ``eps=1e-6``).+ """++ ignore_literals: ClassVar[bool] = False++ def __init__(self, hidden_dim: int, eps: float = 1e-6) -> None:+ super().__init__()+ self._hidden_dim = hidden_dim++ # Bake ``eps`` into pattern/replacement via closures. Dynamo bakes+ # Python scalar function args as graph literals (not placeholders),+ # so per-instance pattern_gms with the right literal are the only+ # way to match a particular ``eps`` value.+ def pattern_fn(x: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor) -> torch.Tensor:+ normed = torch.nn.functional.rms_norm(x, (x.shape[-1],), None, eps)+ return normed * (1 + scale) + shift++ def replacement_fn(x: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor) -> torch.Tensor:+ return torch.ops.ltx_kernels.ada_zero.default(x, scale, shift, eps)++ # Shadow the ``pattern_fn`` / ``replacement_fn`` ``ClassVar``+ # declarations on the base class with these instance-bound closures.+ self.pattern_fn = pattern_fn+ self.replacement_fn = replacement_fn++ def _is_match_eligible(self, match: InternalMatch) -> bool:+ inputs = self._matched_inputs(match)+ if not super()._is_match_eligible(match) or not inputs:+ return False+ x, scale, shift = inputs+ if not is_cuda_bf16(x, scale, shift) or x.ndim != 3 or scale.ndim != 3 or shift.ndim != 3:+ return False+ # H is a ``tl.constexpr`` the kernel spans a whole row with, via+ # ``tl.arange(0, H)``, so it must be a power of two and must be the row length+ # of the affine tensors too.+ hidden = static_dim(x.shape[-1])+ return (+ hidden is not None+ and hidden & (hidden - 1) == 0+ and static_dim(scale.shape[-1]) == hidden+ and static_dim(shift.shape[-1]) == hidden+ )++ def example_inputs(self) -> tuple:+ # ``batch`` and ``seq`` are immaterial -- the pattern doesn't bake+ # them as literals. Only ``hidden_dim`` shows up in the captured+ # ``F.rms_norm(x, (hidden_dim,), ...)``.+ batch, seq = 2, 64+ hidden = self._hidden_dim+ return (+ torch.empty(batch, seq, hidden, dtype=torch.bfloat16, device="cuda"),+ torch.empty(batch, 1, hidden, dtype=torch.bfloat16, device="cuda"),+ torch.empty(batch, 1, hidden, dtype=torch.bfloat16, device="cuda"),+ )++ def _register_ops(self) -> None:+ from ltx_kernels.ops import ada_zero as _ada_zero_ops # noqa: F401, PLC0415diff --git a/packages/ltx-kernels/src/ltx_kernels/compile/passes/blockwise_quantize_cse.py b/packages/ltx-kernels/src/ltx_kernels/compile/passes/blockwise_quantize_cse.pynew file mode 100644index 0000000..546bbcd--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/compile/passes/blockwise_quantize_cse.py@@ -0,0 +1,48 @@+"""CSE for identical ``ltx_kernels::blockwise_quantize`` nodes."""++import logging++import torch+from torch.fx import GraphModule, Node+from torch.fx.passes.infra.pass_base import PassBase, PassResult++logger = logging.getLogger(__name__)+++class BlockwiseQuantizeCSE(PassBase):+ """Dedup identical ``ltx_kernels::blockwise_quantize(x)`` nodes.+ The op is a pure ``triton_op`` (``mutates_args=()``), so two calls on the+ same input node are interchangeable. Self-attention emits three identical+ quantizes (``to_q`` / ``to_k`` / ``to_v`` share the normed input); collapse+ them to one. Run before the trailing-quantize fusion passes so a fusible+ producer is left with a single quantize consumer.+ """++ def __init__(self) -> None:+ self.match_count = 0++ def call(self, graph_module: GraphModule) -> PassResult:+ # Importing registers ltx_kernels::blockwise_quantize so the target below resolves.+ from ltx_kernels.blockwise.ops import quantize as _quantize_ops # noqa: F401, PLC0415++ target = torch.ops.ltx_kernels.blockwise_quantize.default+ graph = graph_module.graph+ seen: dict[object, Node] = {}+ modified = False+ for node in list(graph.nodes):+ if node.op != "call_function" or node.target is not target:+ continue+ key = (node.args, tuple(sorted(node.kwargs.items())))+ canonical = seen.get(key)+ if canonical is None:+ seen[key] = node+ continue+ node.replace_all_uses_with(canonical)+ graph.erase_node(node)+ self.match_count += 1+ modified = True+ if modified:+ graph.lint()+ graph_module.recompile()+ logger.info("BlockwiseQuantizeCSE merged %d duplicate quantize(s)", self.match_count)+ return PassResult(graph_module, modified)diff --git a/packages/ltx-kernels/src/ltx_kernels/compile/passes/fuse_trailing_quantize.py b/packages/ltx-kernels/src/ltx_kernels/compile/passes/fuse_trailing_quantize.pynew file mode 100644index 0000000..84183c4--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/compile/passes/fuse_trailing_quantize.py@@ -0,0 +1,122 @@+"""Fuse a trailing ``blockwise_quantize`` into the producer's quantized twin.+Each pass matches a producer together with the ``blockwise_quantize`` that consumes+it, and replaces the pair with the producer's ``*_quantized`` twin, which returns+the same ``(fp8, scales)`` tuple.+Assumes :class:`BlockwiseQuantizeCSE` has run, so a fusible producer has a single+quantize consumer. A producer that also feeds a bf16 consumer (e.g. the+FP8-excluded ``to_gate_logits``) is left alone, because the matcher rejects a match+whose internal nodes have outside consumers -- no dequant is ever introduced.+"""++from typing import ClassVar++import torch+from torch.fx.passes.utils.matcher_utils import InternalMatch++from ltx_kernels.blockwise._common import _BLOCK_SIZE+from ltx_kernels.compile.subgraph_rewrite_pass import SubgraphRewritePass, is_cuda_bf16, static_dim+++class AdaZeroTrailingQuantizePass(SubgraphRewritePass):+ """``blockwise_quantize(rms_norm(x) * (1 + scale) + shift)`` -> ``ada_zero_quantized(...)``.+ Carries the eager composite because :class:`AdaZeroPass` does not run under every+ backend, so there may be no ``ada_zero`` node to bind. ``hidden_dim`` and ``eps``+ are baked as pattern literals, as there; one instance per pair.+ """++ ignore_literals: ClassVar[bool] = False++ def __init__(self, hidden_dim: int, eps: float = 1e-6) -> None:+ super().__init__()+ self._hidden_dim = hidden_dim++ def pattern_fn(x: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ normed = torch.nn.functional.rms_norm(x, (x.shape[-1],), None, eps)+ fp8, scales = torch.ops.ltx_kernels.blockwise_quantize.default(normed * (1 + scale) + shift)+ return fp8, scales++ def replacement_fn(+ x: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor+ ) -> tuple[torch.Tensor, torch.Tensor]:+ return torch.ops.ltx_kernels.ada_zero_quantized.default(x, scale, shift, eps)++ self.pattern_fn = pattern_fn+ self.replacement_fn = replacement_fn++ def _is_match_eligible(self, match: InternalMatch) -> bool:+ inputs = self._matched_inputs(match)+ if not super()._is_match_eligible(match) or not inputs:+ return False+ x, scale, shift = inputs+ if not is_cuda_bf16(x, scale, shift) or x.ndim != 3 or scale.ndim != 3 or shift.ndim != 3:+ return False+ # H is a ``tl.constexpr`` the kernel spans a whole row with, via+ # ``tl.arange(0, H)``, so it must be a power of two and must be the row length+ # of the affine tensors too. The twin quantizes internally, so a row must also+ # split into whole 128-element blocks.+ hidden = static_dim(x.shape[-1])+ return (+ hidden is not None+ and hidden & (hidden - 1) == 0+ and hidden % _BLOCK_SIZE == 0+ and static_dim(scale.shape[-1]) == hidden+ and static_dim(shift.shape[-1]) == hidden+ )++ def example_inputs(self) -> tuple:+ batch, seq = 2, 128+ hidden = self._hidden_dim+ return (+ torch.empty(batch, seq, hidden, dtype=torch.bfloat16, device="cuda"),+ torch.empty(batch, 1, hidden, dtype=torch.bfloat16, device="cuda"),+ torch.empty(batch, 1, hidden, dtype=torch.bfloat16, device="cuda"),+ )++ def _register_ops(self) -> None:+ from ltx_kernels.blockwise.ops import quantize as _quantize_ops # noqa: F401, PLC0415+ from ltx_kernels.ops import ada_zero as _ada_zero_ops # noqa: F401, PLC0415+++class GatedAttentionTrailingQuantizePass(SubgraphRewritePass):+ """``blockwise_quantize(gated_attention(attn_out, gate_logits))`` -> ``gated_attention_quantized(...)``.+ Binds the fused op :class:`GatedAttentionPass` leaves behind, so it must run+ after it. Fires at ``gated_attention -> to_out``.+ """++ @staticmethod+ def pattern_fn(attn_out: torch.Tensor, gate_logits: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ gated = torch.ops.ltx_kernels.gated_attention.default(attn_out, gate_logits)+ fp8, scales = torch.ops.ltx_kernels.blockwise_quantize.default(gated)+ return fp8, scales++ @staticmethod+ def replacement_fn(attn_out: torch.Tensor, gate_logits: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ return torch.ops.ltx_kernels.gated_attention_quantized.default(attn_out, gate_logits)++ def _is_match_eligible(self, match: InternalMatch) -> bool:+ inputs = self._matched_inputs(match)+ if not super()._is_match_eligible(match) or not inputs:+ return False+ attn_out, gate_logits = inputs+ if not is_cuda_bf16(attn_out, gate_logits) or attn_out.ndim != 3 or gate_logits.ndim != 3:+ return False+ hidden = static_dim(attn_out.shape[-1])+ heads = static_dim(gate_logits.shape[-1])+ if hidden is None or heads is None or hidden % heads:+ return False+ # The head count and head dim are ``tl.constexpr`` the kernel spans a whole row+ # with, via ``tl.arange``, so both must be powers of two. The twin quantizes+ # internally, so a row must also split into whole 128-element blocks.+ dim_head = hidden // heads+ return heads & (heads - 1) == 0 and dim_head & (dim_head - 1) == 0 and hidden % _BLOCK_SIZE == 0++ def example_inputs(self) -> tuple:+ # Production LTX-2.3 shapes (heads=32, dim_head=128 for video, B=2 for CFG).+ return (+ torch.empty(2, 64, 32 * 128, dtype=torch.bfloat16, device="cuda"),+ torch.empty(2, 64, 32, dtype=torch.bfloat16, device="cuda"),+ )++ def _register_ops(self) -> None:+ from ltx_kernels.blockwise.ops import quantize as _quantize_ops # noqa: F401, PLC0415+ from ltx_kernels.ops import gated_attention as _gated_attention_ops # noqa: F401, PLC0415diff --git a/packages/ltx-kernels/src/ltx_kernels/compile/passes/gated_attention.py b/packages/ltx-kernels/src/ltx_kernels/compile/passes/gated_attention.pynew file mode 100644index 0000000..d0f1c88--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/compile/passes/gated_attention.py@@ -0,0 +1,55 @@+"""Pass that rewrites the bf16 gated-attention composite to a single custom op."""++import torch+from torch.fx.passes.utils.matcher_utils import InternalMatch++from ltx_kernels.compile.subgraph_rewrite_pass import SubgraphRewritePass, is_cuda_bf16, static_dim+++class GatedAttentionPass(SubgraphRewritePass):+ """Rewrites the bf16 gated-attention composite::+ out = attn_out.view(B, T, H, D)+ out = out * (2 * sigmoid(gate_logits)).unsqueeze(-1)+ return out.view(B, T, H * D)+ to a single ``ltx_kernels::gated_attention(attn_out, gate_logits)`` call.+ """++ @staticmethod+ def pattern_fn(attn_out: torch.Tensor, gate_logits: torch.Tensor) -> torch.Tensor:+ b, t, hd = attn_out.shape+ h = gate_logits.shape[-1]+ d = hd // h+ out = attn_out.view(b, t, h, d)+ gates = 2.0 * torch.sigmoid(gate_logits)+ out = out * gates.unsqueeze(-1)+ return out.view(b, t, hd)++ @staticmethod+ def replacement_fn(attn_out: torch.Tensor, gate_logits: torch.Tensor) -> torch.Tensor:+ return torch.ops.ltx_kernels.gated_attention.default(attn_out, gate_logits)++ def _is_match_eligible(self, match: InternalMatch) -> bool:+ inputs = self._matched_inputs(match)+ if not super()._is_match_eligible(match) or not inputs:+ return False+ attn_out, gate_logits = inputs+ if not is_cuda_bf16(attn_out, gate_logits) or attn_out.ndim != 3 or gate_logits.ndim != 3:+ return False+ hidden = static_dim(attn_out.shape[-1])+ heads = static_dim(gate_logits.shape[-1])+ if hidden is None or heads is None or hidden % heads:+ return False+ # The head count and head dim are ``tl.constexpr`` the kernel spans a whole row+ # with, via ``tl.arange``, so both must be powers of two.+ dim_head = hidden // heads+ return heads & (heads - 1) == 0 and dim_head & (dim_head - 1) == 0++ def example_inputs(self) -> tuple:+ # Production LTX-2.3 shapes (heads=32, dim_head=128 for video, B=2 for CFG).+ return (+ torch.empty(2, 64, 32 * 128, dtype=torch.bfloat16, device="cuda"),+ torch.empty(2, 64, 32, dtype=torch.bfloat16, device="cuda"),+ )++ def _register_ops(self) -> None:+ from ltx_kernels.ops import gated_attention as _gated_attention_ops # noqa: F401, PLC0415diff --git a/packages/ltx-kernels/src/ltx_kernels/compile/passes/grouped_upcast.py b/packages/ltx-kernels/src/ltx_kernels/compile/passes/grouped_upcast.pynew file mode 100644index 0000000..55357bd--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/compile/passes/grouped_upcast.py@@ -0,0 +1,94 @@+"""Pass that merges a graph's fp8 parameter upcasts into one ``ltx_kernels::grouped_upcast``."""++import logging++import torch+from torch.fx import GraphModule, Node+from torch.fx.passes.infra.pass_base import PassBase, PassResult++logger = logging.getLogger(__name__)+++def _upcast_source(node: Node) -> Node | None:+ """The fp8 graph input ``node`` upcasts, if it is ``input.to(torch.bfloat16)`` of a static-shaped one."""+ is_to = node.op == "call_method" and node.target == "to" and not set(node.kwargs) - {"dtype"}+ dtype = node.kwargs.get("dtype", node.args[1] if len(node.args) == 2 else None) if is_to else None+ source = node.args[0] if is_to and len(node.args) <= 2 else None+ if dtype is not torch.bfloat16 or not isinstance(source, Node) or source.op != "placeholder":+ return None+ value = source.meta.get("example_value")+ eligible = (+ isinstance(value, torch.Tensor)+ and value.dtype == torch.float8_e4m3fn+ and value.is_cuda+ and value.is_contiguous()+ and all(isinstance(d, int) for d in value.shape)+ )+ return source if eligible else None+++class GroupedUpcastPass(PassBase):+ """Batch the graph's ``param.to(torch.bfloat16)`` upcasts of fp8 inputs into ``grouped_upcast`` calls.+ Targets the per-forward weight and bias upcasts of ``Fp8CastLinear``. Upcasts are taken in the+ order of their first use and packed greedily into groups whose bf16 output is at most the+ largest single upcast in the graph; each group runs right before its first consumer, and each+ former upcast becomes a view of its group's output. A group's buffer lives until its last+ consumer, so bounding a group by the largest upcast bounds the added live memory by the same+ amount the ungrouped graph already holds for that tensor.+ """++ def __init__(self) -> None:+ self.match_count = 0++ def call(self, graph_module: GraphModule) -> PassResult:+ from ltx_kernels.ops import grouped_upcast as _grouped_upcast_ops # noqa: F401, PLC0415++ graph = graph_module.graph+ upcasts: dict[Node, list[Node]] = {}+ upcast_sources: dict[Node, Node] = {}+ # Nodes are in topological order, so a source's first consumer follows its upcasts, and the+ # insertion order of ``first_use`` is the order of first use.+ first_use: dict[Node, Node] = {}+ for node in graph.nodes:+ for input_node in node.all_input_nodes:+ if input_node in upcast_sources:+ first_use.setdefault(upcast_sources[input_node], node)+ source = _upcast_source(node)+ if source is not None:+ upcasts.setdefault(source, []).append(node)+ upcast_sources[node] = source++ sources = list(first_use)+ budget = max((source.meta["example_value"].numel() for source in sources), default=0)+ groups: list[list[Node]] = [[]]+ size = 0+ for source in sources:+ numel = source.meta["example_value"].numel()+ if groups[-1] and size + numel > budget:+ groups.append([])+ size = 0+ groups[-1].append(source)+ size += numel+ # A single-tensor group keeps its plain upcast.+ groups = [group for group in groups if len(group) > 1]+ if not groups:+ return PassResult(graph_module, modified=False)++ for group in groups:+ # Sources are in first-use order, so the group's first consumer is its first source's.+ with graph.inserting_before(first_use[group[0]]):+ flat = graph.call_function(torch.ops.ltx_kernels.grouped_upcast.default, (group,))+ offset = 0+ for source in group:+ value = source.meta["example_value"]+ narrowed = graph.call_function(torch.narrow, (flat, 0, offset, value.numel()))+ view = graph.call_method("view", (narrowed, *value.shape))+ offset += value.numel()+ for node in upcasts[source]:+ node.replace_all_uses_with(view)+ graph.erase_node(node)+ self.match_count += 1+ graph.lint()+ graph_module.recompile()+ logger.info("GroupedUpcastPass grouped %d fp8 upcast(s) into %d group(s)", self.match_count, len(groups))+ return PassResult(graph_module, modified=True)diff --git a/packages/ltx-kernels/src/ltx_kernels/compile/passes/linear_gelu.py b/packages/ltx-kernels/src/ltx_kernels/compile/passes/linear_gelu.pynew file mode 100644index 0000000..dd9e93a--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/compile/passes/linear_gelu.py@@ -0,0 +1,40 @@+"""Pass that fuses bf16 linear projections with approximate GELU."""++from typing import ClassVar++import torch+from torch.fx.passes.utils.matcher_utils import InternalMatch++from ltx_kernels.compile.subgraph_rewrite_pass import SubgraphRewritePass, is_cuda_bf16+++class LinearGELUPass(SubgraphRewritePass):+ """Rewrite bf16 ``linear`` + tanh GELU to ``ltx_kernels::linear_gelu``."""++ ignore_literals: ClassVar[bool] = False++ @staticmethod+ def pattern_fn(x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:+ return torch.nn.functional.gelu(torch.nn.functional.linear(x, weight, bias), approximate="tanh")++ @staticmethod+ def replacement_fn(x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:+ return torch.ops.ltx_kernels.linear_gelu.default(x, weight, bias)++ def _is_match_eligible(self, match: InternalMatch) -> bool:+ inputs = self._matched_inputs(match)+ if not super()._is_match_eligible(match) or not inputs:+ return False+ x, weight, bias = inputs+ # ``_addmm_activation`` takes a 2D mat1, which the op flattens x into.+ return is_cuda_bf16(x, weight, bias) and x.ndim >= 2 and weight.ndim == 2 and bias.ndim == 1++ def example_inputs(self) -> tuple:+ return (+ torch.empty(2, 64, 4096, dtype=torch.bfloat16, device="cuda"),+ torch.empty(16384, 4096, dtype=torch.bfloat16, device="cuda"),+ torch.empty(16384, dtype=torch.bfloat16, device="cuda"),+ )++ def _register_ops(self) -> None:+ from ltx_kernels.ops import linear_gelu as _linear_gelu_ops # noqa: F401, PLC0415diff --git a/packages/ltx-kernels/src/ltx_kernels/compile/passes/pre_attention.py b/packages/ltx-kernels/src/ltx_kernels/compile/passes/pre_attention.pynew file mode 100644index 0000000..2a6147f--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/compile/passes/pre_attention.py@@ -0,0 +1,105 @@+"""Pass that rewrites the eager RMSNorm + split-RoPE composite to a single custom op."""++from typing import ClassVar++import torch+from einops import rearrange+from torch.fx.passes.utils.matcher_utils import InternalMatch++from ltx_kernels.compile.subgraph_rewrite_pass import SubgraphRewritePass, is_cuda_bf16, static_dim+++class PreAttentionPass(SubgraphRewritePass):+ """Rewrites the bf16 PreAttention composite::+ normed = F.rms_norm(x, (H,), weight, eps)+ return apply_split_rotary_emb(normed, cos, sin)+ to a single ``ltx_kernels::rms_norm_split_rope(x, weight, cos, sin, eps)``+ call. Fires once per (q, q_norm) and (k, k_norm) call in+ ``Attention.forward``.+ Pattern mirrors the Dynamo IR ``apply_split_rotary_emb`` emits in+ production (the ``needs_reshape=True`` branch: ``(B, T, H)`` input ++ ``(B, N, T, D//2)`` cos/sin), in its non-in-place form.+ Uses ``ignore_literals=False`` so ``eps`` is compared rather than wildcarded:+ the replacement passes this instance's ``eps`` to the kernel, so a site normed+ with a different one is not this pass's. That also pins the ``hidden_dim`` and+ ``heads`` literals the pattern carries, so callers register one instance per+ triple (LTX-2.3: video 4096 x 32, audio 2048 x 32, both ``eps=1e-6``).+ """++ # The CUDA kernel is instantiated for these hidden sizes only.+ supported_hidden: ClassVar[tuple[int, ...]] = (2048, 4096, 8192)+ ignore_literals: ClassVar[bool] = False++ def __init__(self, hidden_dim: int, heads: int, eps: float = 1e-6) -> None:+ super().__init__()+ self._hidden_dim = hidden_dim+ self._heads = heads++ def pattern_fn(+ x: torch.Tensor,+ weight: torch.Tensor,+ cos_freqs: torch.Tensor,+ sin_freqs: torch.Tensor,+ ) -> torch.Tensor:+ normed = torch.nn.functional.rms_norm(x, (x.shape[-1],), weight, eps)+ # Inlined apply_split_rotary_emb (needs_reshape=True branch only).+ h = cos_freqs.shape[1]+ input_tensor = normed.unflatten(-1, (h, -1)).transpose(1, 2)+ split_input = rearrange(input_tensor, "... (d r) -> ... d r", d=2)+ first_half_input = split_input[..., :1, :]+ second_half_input = split_input[..., 1:, :]+ output = split_input * cos_freqs.unsqueeze(-2)+ first_half_output = output[..., :1, :].addcmul(-sin_freqs.unsqueeze(-2), second_half_input)+ second_half_output = output[..., 1:, :].addcmul(sin_freqs.unsqueeze(-2), first_half_input)+ output = torch.cat([first_half_output, second_half_output], dim=-2)+ output = rearrange(output, "... d r -> ... (d r)")+ return output.transpose(1, 2).flatten(-2)++ def replacement_fn(+ x: torch.Tensor,+ weight: torch.Tensor,+ cos_freqs: torch.Tensor,+ sin_freqs: torch.Tensor,+ ) -> torch.Tensor:+ return torch.ops.ltx_kernels.rms_norm_split_rope.default(x, weight, cos_freqs, sin_freqs, eps)++ self.pattern_fn = pattern_fn+ self.replacement_fn = replacement_fn++ def _is_match_eligible(self, match: InternalMatch) -> bool:+ inputs = self._matched_inputs(match)+ if not super()._is_match_eligible(match) or not inputs:+ return False+ x, weight, cos_freqs, sin_freqs = inputs+ if not is_cuda_bf16(x, weight, cos_freqs, sin_freqs):+ return False+ if x.ndim != 3 or weight.ndim != 1 or cos_freqs.ndim != 4 or sin_freqs.ndim != 4:+ return False+ hidden = static_dim(x.shape[-1])+ heads = static_dim(cos_freqs.shape[1])+ if hidden not in self.supported_hidden or heads is None or hidden % (2 * heads):+ return False+ # One thread owns 16 rotation pairs of a single head, so head_dim/2 must be a+ # multiple of 16, and the frequency tables must be exactly half a head wide.+ # Layout is the op's problem, not this check's: it makes x contiguous, the freq+ # tables innermost-contiguous, and expands a batch-shared table.+ half = hidden // (2 * heads)+ return (+ (hidden // heads) % 32 == 0+ and static_dim(cos_freqs.shape[-1]) == half+ and static_dim(sin_freqs.shape[-1]) == half+ )++ def example_inputs(self) -> tuple:+ batch, seq = 2, 64+ hidden, heads = self._hidden_dim, self._heads+ half = hidden // (2 * heads)+ return (+ torch.empty(batch, seq, hidden, dtype=torch.bfloat16, device="cuda"),+ torch.empty(hidden, dtype=torch.bfloat16, device="cuda"),+ torch.empty(batch, heads, seq, half, dtype=torch.bfloat16, device="cuda"),+ torch.empty(batch, heads, seq, half, dtype=torch.bfloat16, device="cuda"),+ )++ def _register_ops(self) -> None:+ from ltx_kernels.ops import rms_norm_split_rope as _rms_norm_split_rope_ops # noqa: F401, PLC0415diff --git a/packages/ltx-kernels/src/ltx_kernels/compile/passes/rms_fma.py b/packages/ltx-kernels/src/ltx_kernels/compile/passes/rms_fma.pynew file mode 100644index 0000000..85d23da--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/compile/passes/rms_fma.py@@ -0,0 +1,139 @@+"""Pass that fuses the post-self-attention residual update and RMSNorm."""++from typing import ClassVar++import torch+from torch.fx.passes.utils.matcher_utils import InternalMatch++from ltx_kernels.compile.subgraph_rewrite_pass import SubgraphRewritePass, is_cuda_bf16, static_dim+++def _supports_residual(x: torch.Tensor, y: torch.Tensor, gate: torch.Tensor) -> bool:+ """Whether ``_rms_sum_mult_kernel`` handles these residual inputs."""+ if not is_cuda_bf16(x, y, gate) or x.ndim != 3 or y.ndim != 3 or gate.ndim not in (2, 3):+ return False+ # The kernel spans a whole row with ``tl.arange(0, H)``, so H must be a power+ # of two, and reaches x and y row-major from one base pointer each.+ hidden = static_dim(x.shape[-1])+ if hidden is None or hidden & (hidden - 1) or not x.is_contiguous() or not y.is_contiguous():+ return False+ # ``gate`` is indexed by batch (and by token unless broadcast); it is+ # broadcast over H only when its last dim is 1.+ return (+ static_dim(y.shape[-1]) == hidden+ and static_dim(gate.shape[0]) == static_dim(x.shape[0])+ and static_dim(gate.shape[-1]) in (hidden, 1)+ )+++class RMSFmaAdaLNPass(SubgraphRewritePass):+ """Rewrite PostSA and cross-attention query modulation together.+ This is the largest PostSA pattern and must run before both+ :class:`RMSFmaPass` and :class:`AdaZeroPass`.+ """++ ignore_literals: ClassVar[bool] = False++ def __init__(self, hidden_dim: int, eps: float = 1e-6) -> None:+ super().__init__()+ self._hidden_dim = hidden_dim++ def pattern_fn(+ x: torch.Tensor,+ y: torch.Tensor,+ gate: torch.Tensor,+ scale: torch.Tensor,+ shift: torch.Tensor,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ residual = x + y * gate+ normed = torch.nn.functional.rms_norm(residual, (x.shape[-1],), None, eps)+ attn_input = normed * (1 + scale) + shift+ return residual, attn_input++ def replacement_fn(+ x: torch.Tensor,+ y: torch.Tensor,+ gate: torch.Tensor,+ scale: torch.Tensor,+ shift: torch.Tensor,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ return torch.ops.ltx_kernels.rms_fma_adaln.default(x, y, gate, scale, shift, eps)++ self.pattern_fn = pattern_fn+ self.replacement_fn = replacement_fn++ def _is_match_eligible(self, match: InternalMatch) -> bool:+ inputs = self._matched_inputs(match)+ if not super()._is_match_eligible(match) or not inputs:+ return False+ x, y, gate, scale, shift = inputs+ if not _supports_residual(x, y, gate) or not is_cuda_bf16(scale, shift):+ return False+ # ``scale`` / ``shift`` are indexed by batch and, unless broadcast over+ # the seq dim, by token -- and the broadcast flag is read off ``scale``+ # alone, so ``shift`` has to agree with it.+ hidden = static_dim(x.shape[-1])+ batch = static_dim(x.shape[0])+ return (+ scale.ndim == shift.ndim+ and scale.ndim in (2, 3)+ and static_dim(scale.shape[0]) == batch+ and static_dim(shift.shape[0]) == batch+ and static_dim(scale.shape[1]) == static_dim(shift.shape[1])+ and static_dim(scale.shape[-1]) == hidden+ and static_dim(shift.shape[-1]) == hidden+ )++ def example_inputs(self) -> tuple:+ batch, seq = 2, 64+ return (+ torch.empty(batch, seq, self._hidden_dim, dtype=torch.bfloat16, device="cuda"),+ torch.empty(batch, seq, self._hidden_dim, dtype=torch.bfloat16, device="cuda"),+ torch.empty(batch, 1, self._hidden_dim, dtype=torch.bfloat16, device="cuda"),+ torch.empty(batch, 1, self._hidden_dim, dtype=torch.bfloat16, device="cuda"),+ torch.empty(batch, 1, self._hidden_dim, dtype=torch.bfloat16, device="cuda"),+ )++ def _register_ops(self) -> None:+ from ltx_kernels.ops import rms_fma as _rms_fma_ops # noqa: F401, PLC0415+++class RMSFmaPass(SubgraphRewritePass):+ """Rewrite the PostSA composite to ``ltx_kernels::rms_fma``.+ This pass must run before :class:`AdaZeroPass`. With cross-attention AdaLN,+ AdaZero's pattern is a subgraph of PostSA followed by query modulation.+ """++ ignore_literals: ClassVar[bool] = False++ def __init__(self, hidden_dim: int, eps: float = 1e-6) -> None:+ super().__init__()+ self._hidden_dim = hidden_dim++ def pattern_fn(x: torch.Tensor, y: torch.Tensor, gate: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ residual = x + y * gate+ normed = torch.nn.functional.rms_norm(residual, (x.shape[-1],), None, eps)+ return residual, normed++ def replacement_fn(x: torch.Tensor, y: torch.Tensor, gate: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ return torch.ops.ltx_kernels.rms_fma.default(x, y, gate, eps)++ self.pattern_fn = pattern_fn+ self.replacement_fn = replacement_fn++ def _is_match_eligible(self, match: InternalMatch) -> bool:+ inputs = self._matched_inputs(match)+ if not super()._is_match_eligible(match) or not inputs:+ return False+ return _supports_residual(*inputs)++ def example_inputs(self) -> tuple:+ batch, seq = 2, 64+ return (+ torch.empty(batch, seq, self._hidden_dim, dtype=torch.bfloat16, device="cuda"),+ torch.empty(batch, seq, self._hidden_dim, dtype=torch.bfloat16, device="cuda"),+ torch.empty(batch, 1, self._hidden_dim, dtype=torch.bfloat16, device="cuda"),+ )++ def _register_ops(self) -> None:+ from ltx_kernels.ops import rms_fma as _rms_fma_ops # noqa: F401, PLC0415diff --git a/packages/ltx-kernels/src/ltx_kernels/compile/subgraph_rewrite_pass.py b/packages/ltx-kernels/src/ltx_kernels/compile/subgraph_rewrite_pass.pynew file mode 100644index 0000000..ddc336d--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/compile/subgraph_rewrite_pass.py@@ -0,0 +1,266 @@+"""Reusable base class for FX passes that rewrite a single subgraph pattern."""++import logging+import warnings+from collections.abc import Callable+from typing import Any, ClassVar++import torch+from torch.fx import GraphModule, Node+from torch.fx.passes.infra.pass_base import PassBase, PassResult+from torch.fx.passes.utils.matcher_utils import InternalMatch, SubgraphMatcher++logger = logging.getLogger(__name__)+++def is_cuda_bf16(*values: torch.Tensor) -> bool:+ """Whether every matched input is a cuda bf16 tensor."""+ return all(value.is_cuda and value.dtype == torch.bfloat16 for value in values)+++def static_dim(dim: int | torch.SymInt) -> int | None:+ """A tensor dim as a plain ``int``, or ``None`` when it is dynamic.+ A dim marked dynamic reaches a pass as a ``SymInt``, and comparing one+ installs a guard outside the tracing context -- so an eligibility check+ treats it as unknown rather than reading it.+ """+ return dim if isinstance(dim, int) else None+++class SubgraphRewritePass(PassBase):+ """Rewrites a single subgraph pattern via+ :class:`torch.fx.passes.utils.matcher_utils.SubgraphMatcher`.+ Both pattern and replacement are captured via Dynamo (using a+ capture-only inner backend) -- the same tracer the user graph goes+ through. This keeps op identities aligned: ``call_method`` with string+ targets for ``.view`` / ``.unsqueeze``, ``call_function`` with library+ specials like ``einops_einops_rearrange``, and in-place ops like+ ``addcmul_`` all survive intact.+ The pass operates at the Dynamo IR level (no AOT lowering), so the+ backend shim that drives it does not have to wrap calls in+ :func:`torch._dynamo.backends.common.aot_autograd` -- avoiding the+ per-call inference runtime wrapper overhead.+ Subclass contract:+ - ``pattern_fn`` -- ``@staticmethod`` Python function whose body is the+ composite to match.+ - ``replacement_fn`` -- ``@staticmethod`` Python function whose body is+ the rewritten subgraph. Same signature as ``pattern_fn``.+ - ``example_inputs()`` -- tuple of tensors (on cuda + bf16 where the+ replacement needs them) used to drive Dynamo capture of both+ ``pattern_fn`` and ``replacement_fn``.+ - ``_register_ops()`` (optional) -- hook called once before the first+ capture; override to lazily import op modules whose decorators populate+ ``torch.ops.<ns>``.+ Match counts are exposed via the public ``match_count`` attribute.+ """++ # ``Any`` here covers both single-tensor patterns and multi-output+ # ones (see the trailing-quantize passes, which return a 2-tuple).+ pattern_fn: ClassVar[Callable[..., Any]]+ replacement_fn: ClassVar[Callable[..., Any]]+ # Whether the matcher should treat scalar literals (ints, floats) in+ # the pattern as wildcards. ``True`` lets one pattern match user graphs+ # with different baked-in shape constants (e.g. H=4096 vs H=2048), but+ # can confuse the matcher when a literal value (like a bare ``1``)+ # could plausibly map to a placeholder slot.+ ignore_literals: ClassVar[bool] = True++ def __init__(self) -> None:+ self.match_count = 0+ self._pattern_gm: GraphModule | None = None+ self._replacement_gm: GraphModule | None = None+ self._capture_error: Exception | None = None++ def call(self, graph_module: GraphModule) -> PassResult:+ if self._capture_error is not None:+ return PassResult(graph_module, modified=False)+ if self._pattern_gm is None:+ try:+ self._register_ops()+ self._pattern_gm = self._capture_via_dynamo(self.pattern_fn)+ except Exception as error:+ self._disable(error)+ return PassResult(graph_module, modified=False)++ replaced = self._rewrite_matches(graph_module)+ if replaced:+ logger.info("%s replaced %d subgraph(s)", type(self).__name__, replaced)+ self.match_count += replaced+ return PassResult(graph_module, modified=bool(replaced))++ def _rewrite_matches(self, graph_module: GraphModule) -> int: # noqa: PLR0912, PLR0915+ """Replace every eligible match and return how many were replaced, which is+ fewer than were matched when a match has no valid insertion point.+ A replacement goes before the earliest user of the match's outputs that lies+ outside the match; a match whose latest input is produced after that point has+ no valid insertion point and is skipped. Matching restarts after each+ replacement, and pattern and replacement placeholders are bound by name, since+ Dynamo orders placeholders by first use and the two captures can differ.+ The replacement is captured on the first eligible match, not up front, because+ capturing runs the replacement op.+ """+ if self._pattern_gm is None:+ raise AssertionError("pattern must be captured before rewriting")++ pattern_graph = self._pattern_gm.graph+ pattern_placeholders = {node.target: node for node in pattern_graph.nodes if node.op == "placeholder"}++ replaced = 0+ ineligible = 0+ blocked_anchors: set[Node] = set()+ while True:+ matcher = SubgraphMatcher(+ pattern_graph,+ match_output=False,+ match_placeholder=False,+ remove_overlapping_matches=True,+ ignore_literals=self.ignore_literals,+ )+ found = [match for match in matcher.match(graph_module.graph) if match.anchors[0] not in blocked_anchors]+ matches = [match for match in found if self._is_match_eligible(match)]+ # Rematching re-sees every rejected match, so only the last round's count+ # is meaningful: it is what the pattern still matches and the kernel cannot+ # take.+ ineligible = len(found) - len(matches)+ if not matches:+ break+ match = matches[0]++ if self._replacement_gm is None:+ try:+ self._replacement_gm = self._capture_via_dynamo(self.replacement_fn)+ except Exception as error:+ self._disable(error)+ break+ replacement_graph = self._replacement_gm.graph+ replacement_placeholders = [node for node in replacement_graph.nodes if node.op == "placeholder"]+ if set(pattern_placeholders) != {node.target for node in replacement_placeholders}:+ raise AssertionError("pattern and replacement placeholder names must match")++ val_map: dict[Node, Node | object] = {}+ for replacement_placeholder in replacement_placeholders:+ pattern_placeholder = pattern_placeholders[replacement_placeholder.target]+ val_map[replacement_placeholder] = match.nodes_map[pattern_placeholder]++ matched_nodes = {+ graph_node+ for pattern_node, graph_node in match.nodes_map.items()+ if pattern_node.op not in ("placeholder", "output") and isinstance(graph_node, Node)+ }+ external_users = {+ user+ for returning_node in match.returning_nodes+ for user in returning_node.users+ if user not in matched_nodes+ }++ ordered_nodes = list(graph_module.graph.nodes)+ node_index = {node: index for index, node in enumerate(ordered_nodes)}+ mapped_inputs = [node for node in val_map.values() if isinstance(node, Node)]+ latest_input_index = max(node_index[node] for node in mapped_inputs)+ if external_users:+ insert_point = min(external_users, key=node_index.__getitem__)+ else:+ insert_point = next(node for node in ordered_nodes if node.op == "output")++ if latest_input_index >= node_index[insert_point]:+ logger.warning(+ "%s skipped a match with no valid insertion point",+ type(self).__name__,+ )+ blocked_anchors.add(match.anchors[0])+ continue++ with graph_module.graph.inserting_before(insert_point):+ copied_outputs = graph_module.graph.graph_copy(replacement_graph, val_map)+ if isinstance(copied_outputs, Node):+ copied_outputs = (copied_outputs,)+ if len(match.returning_nodes) != len(copied_outputs):+ raise AssertionError(+ f"returning node count mismatch: {len(match.returning_nodes)} vs {len(copied_outputs)}"+ )++ for old_output, new_output in zip(match.returning_nodes, copied_outputs, strict=True):+ for user in list(old_output.users):+ if user not in matched_nodes:+ user.replace_input_with(old_output, new_output)++ for node in reversed(ordered_nodes):+ if node in matched_nodes:+ graph_module.graph.erase_node(node)++ replaced += 1++ if replaced:+ graph_module.graph.lint()+ graph_module.recompile()+ logger.debug(+ "%s rewrote %d subgraph(s), left %d ineligible pattern match(es)",+ type(self).__name__,+ replaced,+ ineligible,+ )+ return replaced++ def _is_match_eligible(self, match: InternalMatch) -> bool: # noqa: ARG002+ """Whether the replacement op can serve this match.+ Passes override this to state what their kernel handles, usually over+ ``_matched_inputs``, and call ``super()`` for the one condition they+ share: no replacement op has a backward, so none fires under grad.+ """+ return not torch.is_grad_enabled()++ def _matched_inputs(self, match: InternalMatch) -> tuple[torch.Tensor, ...]:+ """The traced example values bound to the pattern's placeholders, in order.+ Placeholder order is ``pattern_fn``'s signature order, since Dynamo+ orders placeholders by first use. Empty when a placeholder is bound to+ anything other than a traced tensor.+ """+ if self._pattern_gm is None:+ return ()++ values = []+ for placeholder in (node for node in self._pattern_gm.graph.nodes if node.op == "placeholder"):+ bound = match.nodes_map[placeholder]+ value = bound.meta.get("example_value") if isinstance(bound, Node) else None+ if not isinstance(value, torch.Tensor):+ return ()+ values.append(value)+ return tuple(values)++ def example_inputs(self) -> tuple:+ raise NotImplementedError++ def _capture_via_dynamo(self, fn: Callable) -> GraphModule:+ captured: list[GraphModule] = []++ def _capture(gm: GraphModule, _example_inputs: list[torch.Tensor]) -> Callable:+ captured.append(gm)+ return gm.forward++ # Inference mode mirrors the user pipeline's execution mode so the+ # captured graph uses the same dispatch path as the production code.+ # ``dynamic=False`` forces a static capture: the pattern is a shape-agnostic+ # op structure, and capturing it inside the dynamic-shape outer compile would+ # otherwise leak symbolic seq-dim placeholders into the pattern graph, which+ # ``SubgraphMatcher`` cannot map onto the user graph (KeyError on the symbol).+ with torch.inference_mode():+ torch.compile(fn, backend=_capture, fullgraph=True, dynamic=False)(*self.example_inputs())+ return captured[0]++ def _disable(self, error: Exception) -> None:+ """Retire the pass after a capture failure, warning once.+ A pass whose ops this build cannot run must not break the compile: the+ graph it would have rewritten stays as it is. Keeping the error is what+ makes the pass inert -- it is never retried.+ """+ self._capture_error = error+ warnings.warn(+ f"{type(self).__name__} is unusable on this build and will be skipped: {error}",+ RuntimeWarning,+ stacklevel=2,+ )++ def _register_ops(self) -> None:+ """Override to import the modules whose decorators register the+ ``ltx_kernels`` ops that ``pattern_fn`` / ``replacement_fn`` reference."""diff --git a/packages/ltx-kernels/src/ltx_kernels/ops/__init__.py b/packages/ltx-kernels/src/ltx_kernels/ops/__init__.pynew file mode 100644index 0000000..0cb7a3d--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/ops/__init__.py@@ -0,0 +1 @@+"""Triton kernel definitions + ``torch.library.triton_op`` wrappers."""diff --git a/packages/ltx-kernels/src/ltx_kernels/ops/ada_zero.py b/packages/ltx-kernels/src/ltx_kernels/ops/ada_zero.pynew file mode 100644index 0000000..d4f0670--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/ops/ada_zero.py@@ -0,0 +1,183 @@+# ruff: noqa: N803, ANN001, ANN202+"""AdaZero: fused RMSNorm + per-token affine (AdaLN-Zero style).+Computes::+ out = rms_norm(x, eps) * (1 + scale) + shift+where ``scale`` and ``shift`` are broadcast either across the seq dim (shape+``(B, 1, H)``) or per-token (shape ``(B, T, H)``).+Two custom ops are registered:+- ``ltx_kernels::ada_zero`` -- bf16 in, bf16 out.+- ``ltx_kernels::ada_zero_quantized`` -- bf16 in, returns+ ``(float8_e4m3fn, fp32 scales)`` with per-128-element blockwise scales for+ downstream blockwise-FP8 consumers.+The bf16 ``ada_zero`` is the structural-fusion target; the compile backend's+FuseTrailingQuantize pass rewrites ``blockwise_quantize(ada_zero(...))`` into+``ada_zero_quantized(...)`` wherever the normed output feeds only FP8 consumers+(both share one ``@jit`` kernel via its ``QUANTIZE`` flag).+"""++from typing import Tuple++import torch+from torch.library import triton_op, wrap_triton+from triton import jit+from triton import language as tl++from ltx_kernels.blockwise._common import _BLOCK_SIZE, _FP8_SCALE_MAX, _empty_tma_aligned_scales, _quantize+++@jit+def _ada_zero_kernel( # noqa: PLR0913+ X,+ Norm_Scale,+ Norm_Shift,+ Out_scales,+ X_out,+ norm_scale_batch_stride: int,+ norm_shift_batch_stride: int,+ norm_scale_token_stride: int,+ norm_shift_token_stride: int,+ seqlen: int,+ eps: float,+ H: tl.constexpr,+ NUM_BLOCKS: tl.constexpr,+ BLOCK_SIZE: tl.constexpr,+ TMA_ALIGNED_MN: tl.constexpr,+ QUANTIZE: tl.constexpr,+ SCALE_MAX: tl.constexpr,+):+ token_idx = tl.program_id(0).to(tl.int64)+ batch_id = token_idx // seqlen++ # Both affine tensors are addressed purely through forwarded strides, so a batch-+ # or seq-broadcast one arrives expanded with a 0 stride and needs no special case.+ x_ptr = X + token_idx * H + tl.arange(0, H)+ norm_scale_ptr = (+ Norm_Scale+ + batch_id * norm_scale_batch_stride+ + (token_idx % seqlen) * norm_scale_token_stride+ + tl.arange(0, H)+ )+ norm_shift_ptr = (+ Norm_Shift+ + batch_id * norm_shift_batch_stride+ + (token_idx % seqlen) * norm_shift_token_stride+ + tl.arange(0, H)+ )++ norm_scales = tl.load(norm_scale_ptr)+ norm_shift = tl.load(norm_shift_ptr)+ x = tl.load(x_ptr)++ x_sqr = x * x+ x_norm = tl.sum(x_sqr) / H+ x_norm = tl.rsqrt(x_norm + eps)+ x = (x * x_norm).to(tl.bfloat16)+ x = x * (1.0 + norm_scales) + norm_shift++ if QUANTIZE:+ o_quant, o_scales = _quantize(x, SCALE_MAX, NUM_BLOCKS, BLOCK_SIZE)+ x_out_ptr = (+ X_out + token_idx * H + BLOCK_SIZE * tl.arange(0, NUM_BLOCKS)[:, None] + tl.arange(0, BLOCK_SIZE)[None, :]+ )+ tl.store(x_out_ptr, o_quant)+ out_scales_ptr = Out_scales + token_idx + TMA_ALIGNED_MN * tl.arange(0, NUM_BLOCKS)[:, None]+ tl.store(out_scales_ptr, o_scales)+ else:+ x_out_ptr = X_out + token_idx * H + tl.arange(0, H)+ tl.store(x_out_ptr, x)+++@triton_op("ltx_kernels::ada_zero", mutates_args=())+def ada_zero(+ x: torch.Tensor,+ scale: torch.Tensor,+ shift: torch.Tensor,+ eps: float,+) -> torch.Tensor:+ """BF16 RMSNorm + per-token affine.+ Args:+ x: ``(B, T, H)`` bf16 input.+ scale: ``(B, 1, H)`` or ``(B, T, H)`` bf16 per-token scale.+ shift: ``(B, 1, H)`` or ``(B, T, H)`` bf16 per-token shift.+ eps: RMSNorm epsilon.+ Returns:+ ``(B, T, H)`` bf16 output.+ """+ b, s, h = x.shape+ num_rows = b * s+ # The kernel walks x row-major from one base pointer, and reads an affine row as+ # ``ptr + arange(0, H)`` off forwarded batch and token strides: x has to be+ # contiguous, the affine tensors need an innermost stride of 1, and a broadcast one+ # has to arrive expanded so its stride is 0 rather than its dim short.+ x = x.contiguous()+ if scale.stride(-1) != 1:+ scale = scale.contiguous()+ if shift.stride(-1) != 1:+ shift = shift.contiguous()+ scale = scale.expand(b, s, h)+ shift = shift.expand(b, s, h)+ out = torch.empty_like(x)+ wrap_triton(_ada_zero_kernel)[(num_rows,)](+ x,+ scale,+ shift,+ None,+ out,+ norm_scale_batch_stride=scale.stride(0),+ norm_shift_batch_stride=shift.stride(0),+ norm_scale_token_stride=scale.stride(1),+ norm_shift_token_stride=shift.stride(1),+ seqlen=s,+ eps=eps,+ H=h,+ NUM_BLOCKS=0,+ BLOCK_SIZE=_BLOCK_SIZE,+ TMA_ALIGNED_MN=0,+ QUANTIZE=False,+ SCALE_MAX=_FP8_SCALE_MAX,+ )+ return out+++@triton_op("ltx_kernels::ada_zero_quantized", mutates_args=())+def ada_zero_quantized(+ x: torch.Tensor,+ scale: torch.Tensor,+ shift: torch.Tensor,+ eps: float,+) -> Tuple[torch.Tensor, torch.Tensor]:+ """FP8-output RMSNorm + per-token affine.+ Returns ``(fp8_e4m3fn output, fp32 per-128-element blockwise scales)``.+ """+ b, s, h = x.shape+ num_rows = b * s+ num_blocks = h // _BLOCK_SIZE+ x = x.contiguous()+ if scale.stride(-1) != 1:+ scale = scale.contiguous()+ if shift.stride(-1) != 1:+ shift = shift.contiguous()+ scale = scale.expand(b, s, h)+ shift = shift.expand(b, s, h)+ out = torch.empty((num_rows, h), device=x.device, dtype=torch.float8_e4m3fn)+ scales, tma_aligned_mn = _empty_tma_aligned_scales(num_rows, num_blocks, x.device)+ wrap_triton(_ada_zero_kernel)[(num_rows,)](+ x,+ scale,+ shift,+ scales,+ out,+ norm_scale_batch_stride=scale.stride(0),+ norm_shift_batch_stride=shift.stride(0),+ norm_scale_token_stride=scale.stride(1),+ norm_shift_token_stride=shift.stride(1),+ seqlen=s,+ eps=eps,+ H=h,+ NUM_BLOCKS=num_blocks,+ BLOCK_SIZE=_BLOCK_SIZE,+ TMA_ALIGNED_MN=tma_aligned_mn,+ QUANTIZE=True,+ SCALE_MAX=_FP8_SCALE_MAX,+ )+ return out.view(b, s, h), scalesdiff --git a/packages/ltx-kernels/src/ltx_kernels/ops/gated_attention.py b/packages/ltx-kernels/src/ltx_kernels/ops/gated_attention.pynew file mode 100644index 0000000..32f95a6--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/ops/gated_attention.py@@ -0,0 +1,172 @@+# ruff: noqa: N803, ANN001, ANN202+# Triton @jit kernels follow conventions that conflict with Python's lint+# rules: pointer args are CapWord (``X``, ``Out``), constexprs are UPPER_CASE+# (``NUM_HEADS``, ``BLOCK_SIZE``), pointer args have no Python-level type, and+# the return type is opaque at the Python level.+"""Per-head gated attention.+Applies a per-head sigmoid gate to a multi-head attention output::+ gates = 2 * sigmoid(gate_logits) # (B, T, H)+ out = attn_out.view(B, T, H, D) * gates.unsqueeze(-1)+ return out.view(B, T, H * D)+The ``2 *`` factor keeps zero-init at identity: ``2 * sigmoid(0) = 1``.+Two custom ops are registered:+- ``ltx_kernels::gated_attention`` -- bf16 in, bf16 out.+- ``ltx_kernels::gated_attention_quantized`` -- bf16 in, returns+ ``(float8_e4m3fn, fp32 scales)`` with per-128-element blockwise scales for+ downstream blockwise-FP8 consumers.+The bf16 op is the structural-fusion target; the compile backend's+FuseTrailingQuantize pass rewrites ``blockwise_quantize(gated_attention(...))``+into ``gated_attention_quantized(...)`` where the gated output feeds only FP8+consumers (e.g. ``to_out``). Both share one ``@jit`` kernel via its ``QUANTIZE``+flag.+"""++from typing import Tuple++import torch+from torch.library import triton_op, wrap_triton+from triton import jit+from triton import language as tl++from ltx_kernels.blockwise._common import _BLOCK_SIZE, _FP8_SCALE_MAX, _empty_tma_aligned_scales, _quantize+++@jit+def _gated_attention_kernel( # noqa: PLR0913+ X,+ Gate_Logits,+ Out,+ Out_scales,+ gate_batch_stride: int,+ gate_token_stride: int,+ seqlen: int,+ H: tl.constexpr,+ NUM_HEADS: tl.constexpr,+ DIM_HEAD: tl.constexpr,+ NUM_BLOCKS: tl.constexpr,+ BLOCK_SIZE: tl.constexpr,+ TMA_ALIGNED_MN: tl.constexpr,+ QUANTIZE: tl.constexpr,+ SCALE_MAX: tl.constexpr,+):+ token_idx = tl.program_id(0).to(tl.int64)++ # Gates are addressed through forwarded strides, so a batch- or seq-broadcast+ # gate arrives expanded with a 0 stride and needs no special case.+ gate_ptr = (+ Gate_Logits+ + (token_idx // seqlen) * gate_batch_stride+ + (token_idx % seqlen) * gate_token_stride+ + tl.arange(0, NUM_HEADS)+ )+ gate_logits = tl.load(gate_ptr).to(tl.float32)+ gates = 2.0 * tl.sigmoid(gate_logits)+ gates = tl.broadcast_to(gates[:, None], (NUM_HEADS, DIM_HEAD))++ offsets = tl.arange(0, NUM_HEADS)[:, None] * DIM_HEAD + tl.arange(0, DIM_HEAD)[None, :]+ x = tl.load(X + token_idx * H + offsets).to(tl.float32)++ gated = x * gates++ if QUANTIZE:+ o_quant, o_scales = _quantize(gated, SCALE_MAX, NUM_BLOCKS, BLOCK_SIZE)+ out_ptr = (+ Out + token_idx * H + BLOCK_SIZE * tl.arange(0, NUM_BLOCKS)[:, None] + tl.arange(0, BLOCK_SIZE)[None, :]+ )+ tl.store(out_ptr, o_quant)+ scales_ptr = Out_scales + token_idx + TMA_ALIGNED_MN * tl.arange(0, NUM_BLOCKS)[:, None]+ tl.store(scales_ptr, o_scales)+ else:+ out_ptr = Out + token_idx * H + offsets+ tl.store(out_ptr, gated)+++@triton_op("ltx_kernels::gated_attention", mutates_args=())+def gated_attention(x: torch.Tensor, gate_logits: torch.Tensor) -> torch.Tensor:+ """BF16 per-head gated attention.+ Args:+ x: ``(B, T, H * D)`` bf16 attention output.+ gate_logits: ``(B, T, H)`` per-head gate logits.+ Returns:+ ``(B, T, H * D)`` bf16 gated output.+ """+ b, t, h = x.shape+ num_heads = gate_logits.shape[-1]+ dim_head = h // num_heads+ num_blocks = h // _BLOCK_SIZE+ num_rows = b * t++ # The kernel walks x row-major from one base pointer and reads a gate row as+ # ``ptr + arange(0, NUM_HEADS)`` off forwarded strides: x has to be contiguous, the+ # gate needs an innermost stride of 1, and a broadcast gate has to arrive expanded+ # so its stride is 0 rather than its dim short.+ x = x.contiguous()+ if gate_logits.stride(-1) != 1:+ gate_logits = gate_logits.contiguous()+ gate_logits = gate_logits.expand(b, t, num_heads)++ out = torch.empty((num_rows, h), device=x.device, dtype=torch.bfloat16)++ wrap_triton(_gated_attention_kernel)[(num_rows,)](+ x,+ gate_logits,+ out,+ None,+ gate_batch_stride=gate_logits.stride(0),+ gate_token_stride=gate_logits.stride(1),+ seqlen=t,+ H=h,+ NUM_HEADS=num_heads,+ DIM_HEAD=dim_head,+ NUM_BLOCKS=num_blocks,+ BLOCK_SIZE=_BLOCK_SIZE,+ TMA_ALIGNED_MN=0,+ QUANTIZE=False,+ SCALE_MAX=_FP8_SCALE_MAX,+ )++ return out.view(b, t, h)+++@triton_op("ltx_kernels::gated_attention_quantized", mutates_args=())+def gated_attention_quantized(x: torch.Tensor, gate_logits: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ """FP8-output per-head gated attention. Pair with a blockwise-FP8 consumer.+ Args:+ x: ``(B, T, H * D)`` bf16 attention output.+ gate_logits: ``(B, T, H)`` per-head gate logits.+ Returns:+ ``(fp8_e4m3fn output, fp32 per-128-element blockwise scales)``.+ """+ b, t, h = x.shape+ num_heads = gate_logits.shape[-1]+ dim_head = h // num_heads+ num_blocks = h // _BLOCK_SIZE+ num_rows = b * t++ x = x.contiguous()+ if gate_logits.stride(-1) != 1:+ gate_logits = gate_logits.contiguous()+ gate_logits = gate_logits.expand(b, t, num_heads)++ out = torch.empty((num_rows, h), device=x.device, dtype=torch.float8_e4m3fn)+ scales, tma_aligned_mn = _empty_tma_aligned_scales(num_rows, num_blocks, x.device)++ wrap_triton(_gated_attention_kernel)[(num_rows,)](+ x,+ gate_logits,+ out,+ scales,+ gate_batch_stride=gate_logits.stride(0),+ gate_token_stride=gate_logits.stride(1),+ seqlen=t,+ H=h,+ NUM_HEADS=num_heads,+ DIM_HEAD=dim_head,+ NUM_BLOCKS=num_blocks,+ BLOCK_SIZE=_BLOCK_SIZE,+ TMA_ALIGNED_MN=tma_aligned_mn,+ QUANTIZE=True,+ SCALE_MAX=_FP8_SCALE_MAX,+ )++ return out.view(b, t, h), scalesdiff --git a/packages/ltx-kernels/src/ltx_kernels/ops/grouped_upcast.py b/packages/ltx-kernels/src/ltx_kernels/ops/grouped_upcast.pynew file mode 100644index 0000000..697e09c--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/ops/grouped_upcast.py@@ -0,0 +1,106 @@+# ruff: noqa: N803, ANN001, ANN202+"""Upcast many fp8 tensors to bf16 in one launch, into one flat buffer.+``Fp8CastLinear`` upcasts its weight and bias on every forward. Compiled, that is one+elementwise kernel per tensor -- about fifty per transformer block, a third of them biases of a+few thousand elements whose cost is launch latency rather than traffic. This op converts a whole+list in a single launch: every program converts one ``_BLOCK``-element chunk of one tensor,+located through a device-side table of source addresses.+The table is keyed by the sources' addresses and built on the first eager call, so it must exist+before a CUDA graph is captured over the op (the transformer's capture runs eager warmups first).+A list first seen during capture is converted tensor by tensor instead, since building the table+needs a host-to-device copy.+The upcast is exact: every float8_e4m3fn value is representable in bf16.+"""++import torch+import triton+from triton import language as tl++_BLOCK = 4096+++def _grouped_upcast_kernel(+ Src_ptrs,+ Dst,+ Dst_offsets,+ Numels,+ Chunk_starts,+ NUM_SEGS: tl.constexpr,+ BLOCK: tl.constexpr,+):+ pid = tl.program_id(0)+ # Padding entries of ``Chunk_starts`` hold INT64_MAX, so they never count.+ starts = tl.load(Chunk_starts + tl.arange(0, NUM_SEGS))+ seg = tl.sum((starts <= pid).to(tl.int32)) - 1+ # Every source address and destination offset is 16-element aligned (checked on the host);+ # without the hints the loads through a table-read pointer are not vectorized.+ src = tl.multiple_of(tl.load(Src_ptrs + seg).to(tl.pointer_type(tl.float8e4nv)), 16)+ numel = tl.multiple_of(tl.load(Numels + seg), 16)+ dst_offset = tl.multiple_of(tl.load(Dst_offsets + seg), 16)+ chunk = (pid - tl.load(Chunk_starts + seg)).to(tl.int64)+ idx = chunk * BLOCK + tl.arange(0, BLOCK)+ mask = idx < numel+ x = tl.load(src + idx, mask=mask, eviction_policy="evict_first")+ tl.store(Dst + dst_offset + idx, x.to(tl.bfloat16), mask=mask)+++class _Table:+ """Device-side segment table for one list of sources."""++ def __init__(self, sources: list[torch.Tensor]) -> None:+ numels = torch.tensor([t.numel() for t in sources], dtype=torch.int64)+ chunks = (numels + _BLOCK - 1) // _BLOCK+ self.num_chunks = int(chunks.sum())+ self.num_segs = triton.next_power_of_2(len(sources))+ pad = self.num_segs - len(sources)++ def padded(values: torch.Tensor, fill: int = 0) -> torch.Tensor:+ return torch.cat([values, values.new_full((pad,), fill)]).to(sources[0].device)++ self.src_ptrs = padded(torch.tensor([t.data_ptr() for t in sources], dtype=torch.int64))+ self.dst_offsets = padded(numels.cumsum(0) - numels)+ self.numels = padded(numels)+ self.chunk_starts = padded(chunks.cumsum(0) - chunks, fill=2**63 - 1)+++# Keyed by the sources' addresses and sizes -- freed memory is handed to new tensors of other sizes --+# and holding nothing but their own few bytes.+_tables: dict[tuple[tuple[int, int], ...], _Table] = {}++[email protected]_op("ltx_kernels::grouped_upcast", mutates_args=(), device_types="cuda")+def grouped_upcast(sources: list[torch.Tensor]) -> torch.Tensor:+ """Concatenate the flattened ``float8_e4m3fn`` ``sources``, upcast to bf16, as one 1-D tensor."""+ total = sum(t.numel() for t in sources)+ out = torch.empty(total, dtype=torch.bfloat16, device=sources[0].device)+ # The table reads each source as flat contiguous storage, so an unaligned list must not be served+ # by the table of an aligned one at the same addresses (a transposed view, say).+ table = None+ if all(t.is_contiguous() and t.data_ptr() % 16 == 0 and t.numel() % 16 == 0 for t in sources):+ key = tuple((t.data_ptr(), t.numel()) for t in sources)+ table = _tables.get(key)+ if table is None and not torch.cuda.is_current_stream_capturing():+ table = _tables[key] = _Table(sources)+ if table is None:+ offset = 0+ for t in sources:+ out[offset : offset + t.numel()].copy_(t.reshape(-1))+ offset += t.numel()+ return out+ _grouped_upcast_kernel[(table.num_chunks,)](+ table.src_ptrs,+ out,+ table.dst_offsets,+ table.numels,+ table.chunk_starts,+ NUM_SEGS=table.num_segs,+ BLOCK=_BLOCK,+ num_warps=4,+ )+ return out+++@grouped_upcast.register_fake+def _grouped_upcast_fake(sources: list[torch.Tensor]) -> torch.Tensor:+ return sources[0].new_empty(sum(t.numel() for t in sources), dtype=torch.bfloat16)diff --git a/packages/ltx-kernels/src/ltx_kernels/ops/linear_gelu.py b/packages/ltx-kernels/src/ltx_kernels/ops/linear_gelu.pynew file mode 100644index 0000000..6b0ae86--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/ops/linear_gelu.py@@ -0,0 +1,21 @@+"""BF16 linear projection with a fused approximate GELU epilogue."""++import torch++[email protected]_op("ltx_kernels::linear_gelu", mutates_args=(), device_types="cuda")+def linear_gelu(x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor) -> torch.Tensor:+ """Apply a BF16 linear projection and tanh-approximate GELU."""+ batch_shape = x.shape[:-1]+ out = torch.ops.aten._addmm_activation.default(+ bias,+ x.flatten(0, -2),+ weight.t(),+ use_gelu=True,+ )+ return out.unflatten(0, batch_shape)+++@linear_gelu.register_fake+def _linear_gelu_fake(x: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor) -> torch.Tensor: # noqa: ARG001+ return x.new_empty((*x.shape[:-1], weight.shape[0]))diff --git a/packages/ltx-kernels/src/ltx_kernels/ops/rms_fma.py b/packages/ltx-kernels/src/ltx_kernels/ops/rms_fma.pynew file mode 100644index 0000000..672f32f--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/ops/rms_fma.py@@ -0,0 +1,153 @@+# ruff: noqa: N803, ANN001, ANN202, PLR0913+"""Fused residual update and RMS normalization."""++from typing import Tuple++import torch+from torch.library import triton_op, wrap_triton+from triton import jit+from triton import language as tl+++@jit+def _rms_sum_mult_kernel(+ X,+ Y,+ Z,+ Norm_Scale,+ Norm_Shift,+ Residual_out,+ Normed_out,+ seqlen: int,+ z_batch_stride: int,+ z_token_stride: int,+ norm_scale_batch_stride: int,+ norm_shift_batch_stride: int,+ norm_scale_token_stride: int,+ norm_shift_token_stride: int,+ eps: float,+ H: tl.constexpr,+ IS_Z_BROADCAST: tl.constexpr,+ IS_Z_H_BROADCAST: tl.constexpr,+ BROADCAST_ADALN_SEQLEN: tl.constexpr,+ APPLY_ADALN: tl.constexpr,+):+ token_idx = tl.program_id(0).to(tl.int64)+ batch_id = token_idx // seqlen++ x_ptr = X + token_idx * H + tl.arange(0, H)+ y_ptr = Y + token_idx * H + tl.arange(0, H)+ if IS_Z_BROADCAST:+ z_ptr = Z + batch_id * z_batch_stride+ else:+ z_ptr = Z + batch_id * z_batch_stride + (token_idx % seqlen) * z_token_stride+ z_ptr += 0 if IS_Z_H_BROADCAST else tl.arange(0, H)+ x = tl.load(x_ptr)+ y = tl.load(y_ptr)+ z = tl.load(z_ptr)++ out = x + y * z+ tl.store(Residual_out + token_idx * H + tl.arange(0, H), out)++ out_sqr = out * out+ out_norm = tl.sum(out_sqr, axis=0) / H+ out_inv = tl.rsqrt(out_norm + eps)+ out *= out_inv++ if APPLY_ADALN:+ if BROADCAST_ADALN_SEQLEN:+ norm_scale_ptr = Norm_Scale + batch_id * norm_scale_batch_stride + tl.arange(0, H)+ norm_shift_ptr = Norm_Shift + batch_id * norm_shift_batch_stride + tl.arange(0, H)+ else:+ norm_scale_ptr = (+ Norm_Scale+ + batch_id * norm_scale_batch_stride+ + (token_idx % seqlen) * norm_scale_token_stride+ + tl.arange(0, H)+ )+ norm_shift_ptr = (+ Norm_Shift+ + batch_id * norm_shift_batch_stride+ + (token_idx % seqlen) * norm_shift_token_stride+ + tl.arange(0, H)+ )+ norm_scale = tl.load(norm_scale_ptr)+ norm_shift = tl.load(norm_shift_ptr)+ out = out.to(tl.bfloat16)+ out = out * (1.0 + norm_scale) + norm_shift++ tl.store(Normed_out + token_idx * H + tl.arange(0, H), out)+++@triton_op("ltx_kernels::rms_fma", mutates_args=())+def rms_fma(+ x: torch.Tensor,+ y: torch.Tensor,+ gate: torch.Tensor,+ eps: float,+) -> Tuple[torch.Tensor, torch.Tensor]:+ """Apply the gated residual update and normalize the updated value."""+ b, s, h = x.shape+ residual = torch.empty_like(x)+ normed = torch.empty_like(x)+ wrap_triton(_rms_sum_mult_kernel)[(b * s, 1, 1)](+ x,+ y,+ gate,+ None,+ None,+ residual,+ normed,+ seqlen=s,+ z_batch_stride=gate.stride(0),+ z_token_stride=0 if gate.ndim == 2 else gate.stride(1),+ norm_scale_batch_stride=0,+ norm_shift_batch_stride=0,+ norm_scale_token_stride=0,+ norm_shift_token_stride=0,+ eps=eps,+ H=h,+ IS_Z_BROADCAST=gate.ndim == 2 or gate.shape[1] == 1,+ IS_Z_H_BROADCAST=gate.shape[-1] == 1,+ BROADCAST_ADALN_SEQLEN=False,+ APPLY_ADALN=False,+ )+ return residual, normed+++@triton_op("ltx_kernels::rms_fma_adaln", mutates_args=())+def rms_fma_adaln(+ x: torch.Tensor,+ y: torch.Tensor,+ gate: torch.Tensor,+ scale: torch.Tensor,+ shift: torch.Tensor,+ eps: float,+) -> Tuple[torch.Tensor, torch.Tensor]:+ """Apply the gated residual update, RMSNorm, and query modulation."""+ b, s, h = x.shape+ residual = torch.empty_like(x)+ attn_input = torch.empty_like(x)+ wrap_triton(_rms_sum_mult_kernel)[(b * s, 1, 1)](+ x,+ y,+ gate,+ scale,+ shift,+ residual,+ attn_input,+ seqlen=s,+ z_batch_stride=gate.stride(0),+ z_token_stride=0 if gate.ndim == 2 else gate.stride(1),+ norm_scale_batch_stride=scale.stride(0),+ norm_shift_batch_stride=shift.stride(0),+ norm_scale_token_stride=0 if scale.ndim == 2 else scale.stride(1),+ norm_shift_token_stride=0 if shift.ndim == 2 else shift.stride(1),+ eps=eps,+ H=h,+ IS_Z_BROADCAST=gate.ndim == 2 or gate.shape[1] == 1,+ IS_Z_H_BROADCAST=gate.shape[-1] == 1,+ BROADCAST_ADALN_SEQLEN=scale.ndim == 2 or scale.shape[1] == 1,+ APPLY_ADALN=True,+ )+ return residual, attn_inputdiff --git a/packages/ltx-kernels/src/ltx_kernels/ops/rms_norm_split_rope.py b/packages/ltx-kernels/src/ltx_kernels/ops/rms_norm_split_rope.pynew file mode 100644index 0000000..6f28198--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/ops/rms_norm_split_rope.py@@ -0,0 +1,50 @@+"""Fused RMS-norm + split RoPE.+Wraps the CUDA kernel in :mod:`ops_cpp` (built from+``csrc/ops/rms_norm_split_rope*``) as ``torch.library.custom_op`` so it+appears as a single ``call_function`` node under ``torch.compile`` and is+safe to use as a pattern rewrite target.+Mirrors :func:`ltx_core.model.transformer.rope.apply_split_rotary_emb`: the+``cos_freqs`` / ``sin_freqs`` tables are accepted in ``(cos, sin)`` order and+``(B, N, T, D)`` layout (what the eager LTX RoPE precomputation produces).+"""++import torch++[email protected]_op("ltx_kernels::rms_norm_split_rope", mutates_args=())+def rms_norm_split_rope(+ x: torch.Tensor,+ weights: torch.Tensor,+ cos_freqs: torch.Tensor,+ sin_freqs: torch.Tensor,+ eps: float,+) -> torch.Tensor:+ """BF16 fused RMS-norm + split RoPE.+ Args:+ x: ``(B, T, H)`` bf16 input.+ weights: ``(H,)`` bf16 RMSNorm scale.+ cos_freqs: ``(B, N, T, D)`` bf16 cos table; ``N * D == H / 2``.+ sin_freqs: ``(B, N, T, D)`` bf16 sin table; same shape as ``cos_freqs``.+ eps: RMSNorm epsilon.+ Returns:+ ``(B, T, H)`` bf16 output.+ Arg order ``(x, weight, cos, sin)`` mirrors the order Dynamo emits these+ placeholders when capturing the eager PreAttention composite+ (``rms_norm(x, ..., weight, ...)`` first, then RoPE on cos/sin) -- letting+ :class:`SubgraphRewritePass` zip pattern and replacement placeholders by+ position without cross-wiring them.+ """+ import ops_cpp # noqa: PLC0415++ return ops_cpp.rms_norm_split_rope(x, sin_freqs, cos_freqs, weights, eps, False)+++@rms_norm_split_rope.register_fake+def _rms_norm_split_rope_fake(+ x: torch.Tensor,+ weights: torch.Tensor, # noqa: ARG001+ cos_freqs: torch.Tensor, # noqa: ARG001+ sin_freqs: torch.Tensor, # noqa: ARG001+ eps: float, # noqa: ARG001+) -> torch.Tensor:+ return torch.empty_like(x)diff --git a/packages/ltx-kernels/src/ltx_kernels/vae/aot.py b/packages/ltx-kernels/src/ltx_kernels/vae/aot.pynew file mode 100644index 0000000..2784a34--- /dev/null+++ b/packages/ltx-kernels/src/ltx_kernels/vae/aot.py@@ -0,0 +1,293 @@+"""Build and load the production DiffVAE CuTe DSL AOT bundle."""++from __future__ import annotations++import functools+import hashlib+import importlib.resources+import os+from collections.abc import Callable, Hashable+from dataclasses import dataclass+from pathlib import Path+from typing import Any, cast++import cutlass+import cutlass.cute as cute+import torch++CompiledFunction = Callable[..., int | None]+CompileKernel = Callable[..., Any]++_PACKAGED_BUNDLE_DIRECTORY = ("_aot", "sm100a")+_PACKAGED_GPU_ARCH = "sm_100a"+++@dataclass(frozen=True)+class KernelKey:+ """One architecture-specific specialization, used for cache and object identity."""++ compile_kernel: CompileKernel+ gpu_arch: str+ params: tuple[tuple[str, Hashable], ...]++ @classmethod+ def create(+ cls,+ compile_kernel: CompileKernel,+ gpu_arch: str,+ **params: Hashable,+ ) -> "KernelKey":+ for name, value in params.items():+ try:+ hash(value)+ except TypeError as exc:+ raise TypeError(f"compile-time parameter {name!r} must be hashable, got {value!r}") from exc+ return cls(compile_kernel, gpu_arch, tuple(sorted(params.items())))++ @property+ def kind(self) -> str:+ return self.compile_kernel.__module__.rsplit(".", maxsplit=1)[-1].removesuffix("_dsl")++ @property+ def name(self) -> str:+ identity = (+ self.compile_kernel.__module__,+ self.compile_kernel.__qualname__,+ self.gpu_arch,+ self.params,+ )+ digest = hashlib.sha256(repr(identity).encode()).hexdigest()[:16]+ return f"{self.kind}_{self.gpu_arch}_{digest}"++ @property+ def function_prefix(self) -> str:+ return f"ltx_vae_{self.name}"++ @property+ def compile_kwargs(self) -> dict[str, Hashable]:+ return dict(self.params)+++def _device_and_arch(device: torch.device) -> tuple[torch.device, str]:+ if device.type != "cuda":+ raise ValueError(f"VAE DSL kernels need a CUDA device, got {device}")+ device_index = torch.cuda.current_device() if device.index is None else device.index+ target_device = torch.device("cuda", device_index)+ major, minor = torch.cuda.get_device_capability(target_device)+ return target_device, f"sm_{major}{minor}a"+++def fake_dynamic_vector(dtype: type[cutlass.Numeric]) -> cute.Tensor:+ """Match ``from_dlpack(vector).mark_layout_dynamic()`` without storage."""+ return cute.runtime.make_fake_tensor(+ dtype,+ (cute.sym_int32(),),+ (1,),+ )+++def fake_dynamic_matrix(dtype: type[cutlass.Numeric], *, assumed_align: int) -> cute.Tensor:+ """Match the arbitrary row stride accepted by ``_dyn_act``."""+ rows = cute.sym_int32()+ columns = cute.sym_int32()+ row_stride = cute.sym_int64()+ return cute.runtime.make_fake_tensor(+ dtype,+ (rows, columns),+ (row_stride, 1),+ assumed_align=assumed_align,+ )+++def fake_dynamic_weight(dtype: type[cutlass.Numeric], *, columns: int) -> cute.Tensor:+ """Match ``_dyn_w``: compact rows with a dynamically typed K dimension."""+ rows = cute.sym_int32()+ dynamic_columns = cute.sym_int32(divisibility=columns)+ row_stride = cute.sym_int64(divisibility=columns)+ return cute.runtime.make_fake_tensor(+ dtype,+ (rows, dynamic_columns),+ (row_stride, 1),+ assumed_align=32,+ )+++def _bundle_root() -> importlib.resources.abc.Traversable:+ root = importlib.resources.files("ltx_kernels.vae")+ for part in _PACKAGED_BUNDLE_DIRECTORY:+ root = root.joinpath(part)+ return root++[email protected]_cache(maxsize=1)+def _bundle_is_packaged() -> bool:+ return _bundle_root().is_dir()++[email protected]_cache(maxsize=16)+def _load_function(file_name: str, function_prefix: str) -> CompiledFunction:+ resource = _bundle_root().joinpath(file_name)+ if not resource.is_file():+ raise RuntimeError(f"Packaged VAE DSL AOT object is missing: {file_name}")+ try:+ with importlib.resources.as_file(resource) as object_path:+ module = cute.runtime.load_module(os.fspath(object_path))+ return cast(CompiledFunction, getattr(module, function_prefix))+ except Exception as exc:+ raise RuntimeError(f"Failed to load packaged VAE DSL AOT object {file_name}; refusing JIT fallback") from exc++[email protected]_cache(maxsize=8)+def production_kernel_keys(gpu_arch: str) -> tuple[KernelKey, ...]:+ """Return the finite production specialization set for ``gpu_arch``."""+ from ltx_kernels.vae import block_fna_dsl, na_attn_dsl # noqa: PLC0415++ na = na_attn_dsl._compile_kernel+ block = block_fna_dsl._compile_kernel+ return (+ KernelKey.create(+ na,+ gpu_arch,+ kernel_size=(3, 7, 7),+ tile_thw=(2, 8, 8),+ keyframes=False,+ keyframe_queries=False,+ ),+ KernelKey.create(+ na,+ gpu_arch,+ kernel_size=(3, 7, 7),+ tile_thw=(2, 8, 8),+ keyframes=True,+ keyframe_queries=True,+ ),+ KernelKey.create(+ na,+ gpu_arch,+ kernel_size=(3, 5, 5),+ tile_thw=(2, 8, 8),+ keyframes=False,+ keyframe_queries=False,+ ),+ KernelKey.create(+ na,+ gpu_arch,+ kernel_size=(3, 5, 5),+ tile_thw=(2, 8, 8),+ keyframes=True,+ keyframe_queries=True,+ ),+ KernelKey.create(+ block,+ gpu_arch,+ C=256,+ Ctx=512,+ upsample_stride=(2, 2, 2),+ Hidd=1024,+ num_heads=4,+ rope_dim_split=(16, 24, 24),+ kernel_size=(11, 11, 11),+ tile_thw=(4, 4, 8),+ slab_box_max=block_fna_dsl.SLAB_BOX_MAX,+ keyframes=False,+ ),+ KernelKey.create(+ block,+ gpu_arch,+ C=256,+ Ctx=512,+ upsample_stride=(2, 2, 2),+ Hidd=1024,+ num_heads=4,+ rope_dim_split=(16, 24, 24),+ kernel_size=(11, 11, 11),+ tile_thw=(4, 4, 8),+ slab_box_max=block_fna_dsl.SLAB_BOX_MAX,+ keyframes=True,+ ),+ )+++class KernelCache:+ """Compile or load VAE DSL kernels under one canonical key."""++ def __init__(self) -> None:+ self._compiled: dict[KernelKey, CompiledFunction] = {}++ def get(+ self,+ compile_kernel: CompileKernel,+ device: torch.device,+ **params: Hashable,+ ) -> CompiledFunction:+ target_device, gpu_arch = _device_and_arch(device)+ key = KernelKey.create(compile_kernel, gpu_arch, **params)+ if key in self._compiled:+ return self._compiled[key]++ with torch.cuda.device(target_device):+ compiled = self._load_precompiled(key)+ if compiled is None:+ compiled = self.compile(key, options=os.environ.get("CUTE_DSL_OPTS"))+ self._compiled[key] = compiled+ return compiled++ @staticmethod+ def compile(key: KernelKey, options: str | None = None) -> CompiledFunction:+ return cast(+ CompiledFunction,+ key.compile_kernel(+ **key.compile_kwargs,+ **({"options": options} if options else {}),+ ),+ )++ @staticmethod+ def _load_precompiled(key: KernelKey) -> CompiledFunction | None:+ if key.gpu_arch != _PACKAGED_GPU_ARCH:+ return None+ if key not in production_kernel_keys(key.gpu_arch):+ return None+ if not _bundle_is_packaged():+ return None+ return _load_function(f"{key.name}.o", key.function_prefix)++ def count(self, compile_kernel: CompileKernel) -> int:+ return sum(key.compile_kernel is compile_kernel for key in self._compiled)++ def clear(self, compile_kernel: CompileKernel | None = None) -> None:+ if compile_kernel is None:+ self._compiled.clear()+ return+ for key in tuple(self._compiled):+ if key.compile_kernel is compile_kernel:+ del self._compiled[key]+++KERNEL_CACHE = KernelCache()+++def export_production_artifacts(+ output_directory: Path,+ *,+ gpu_arch: str,+ host_target: str,+) -> None:+ """Compile and export every production key into ``output_directory``."""+ if gpu_arch != _PACKAGED_GPU_ARCH:+ raise ValueError(f"Production VAE AOT bundle targets {_PACKAGED_GPU_ARCH}, got {gpu_arch}")+ output_directory.mkdir(parents=True, exist_ok=True)+ options = f"--gpu-arch {gpu_arch}"+ if host_target:+ options = f"{options} --host-target {host_target}"+ if extra_options := os.environ.get("CUTE_DSL_OPTS"):+ options = f"{options} {extra_options}"++ for key in production_kernel_keys(gpu_arch):+ compiled = KERNEL_CACHE.compile(key, options=options)+ compiled.export_to_c(+ file_path=os.fspath(output_directory),+ file_name=key.name,+ function_prefix=key.function_prefix,+ )+ output_directory.joinpath(f"{key.name}.h").unlink()diff --git a/packages/ltx-kernels/src/ltx_kernels/vae/block_fna_dsl.py b/packages/ltx-kernels/src/ltx_kernels/vae/block_fna_dsl.pyindex a6f3b24..7efbc6a 100644--- a/packages/ltx-kernels/src/ltx_kernels/vae/block_fna_dsl.py+++ b/packages/ltx-kernels/src/ltx_kernels/vae/block_fna_dsl.py@@ -41,7 +41,6 @@ parts and why.import dataclassesimport functools-import osfrom typing import Any, NamedTupleimport cutlass@@ -51,6 +50,12 @@ import torchfrom cutlass.cute.nvgpu import cpasync, tcgen05from cutlass.utils import SmemAllocator+from ltx_kernels.vae.aot import (+ KERNEL_CACHE,+ fake_dynamic_matrix,+ fake_dynamic_vector,+ fake_dynamic_weight,+)from ltx_kernels.vae.availability import UNSUPPORTED_MESSAGE, gpu_supports_dsl_kernelsfrom ltx_kernels.vae.fna_attn_core import (_as_rows,@@ -125,8 +130,6 @@ from ltx_kernels.vae.keyframe_slots import (tile_plane_union,)-_COMPILED: "dict[tuple, Any]" = {}-# Channel counts the kernel is compiled and validated for. The shipped DiffVAE only# ever asks for 256 (stage 5); 128 is kept because it is the cheap shape to validate# a pipeline change against -- it compiles in a third of the time.@@ -2226,46 +2229,56 @@ def run_block_fna_dsl(x_.device,)- compiled = _compile(- C=C,- Ctx=Ctx,- upsample_stride=tuple(upsample_stride),- Hidd=Hidd,- num_heads=num_heads,- rope_dim_split=rope_dim_split,- kernel_size=kernel_size,- tile_thw=tile,- keyframes=kf.enabled,- )- compiled(- _dyn_act(_as_rows(x_)),- _dyn_act(_as_rows(ctx_)),- _dyn_act(y_buf),- _dyn_act(kv_cache),- _dyn(norm_cache),- _dyn(barrier),- *kf.operands,- bf(w_ctx),- bf(w_q),- bf(_pack_kv(w_k, w_v, num_heads)),- bf(w_o),- bf(w_gate),- bf(w_up),- bf(w_down),- _dyn(channel_params),- f32(inv_t),- f32(inv_h),- f32(inv_w),- *_runtime_scalars(- volume=(T, H, W),- ctx_volume=(T_lo, H_lo, W_lo),- drop_leading=drop,- n_ctas=n_ctas,- plan=plan,- n_kf=kf.n_kf,- kf_cache_row_stride=kf.cache_row_stride,- ),- )+ with torch.cuda.device(x_.device):+ # ``keyframes`` keys the binary so the no-keyframe kernel keeps exactly the trace, and+ # the register allocation, it had before the keyframe stream existed.+ # Everything else here is structural too, and must stay that way. The per-tile plane+ # union bound used to be in this key; because it moves with the clip length it recompiled+ # the ladder on every new duration, which cost 12+ minutes of in-process MLIR before a+ # 545-frame decode could start. It is now ``SLOTS * TT``, a constant of ``tile_thw``.+ compiled = KERNEL_CACHE.get(+ _compile_kernel,+ x_.device,+ C=C,+ Ctx=Ctx,+ upsample_stride=tuple(upsample_stride),+ Hidd=Hidd,+ num_heads=num_heads,+ rope_dim_split=rope_dim_split,+ kernel_size=kernel_size,+ tile_thw=tile,+ slab_box_max=SLAB_BOX_MAX,+ keyframes=kf.enabled,+ )+ compiled(+ _dyn_act(_as_rows(x_)),+ _dyn_act(_as_rows(ctx_)),+ _dyn_act(y_buf),+ _dyn_act(kv_cache),+ _dyn(norm_cache),+ _dyn(barrier),+ *kf.operands,+ bf(w_ctx),+ bf(w_q),+ bf(_pack_kv(w_k, w_v, num_heads)),+ bf(w_o),+ bf(w_gate),+ bf(w_up),+ bf(w_down),+ _dyn(channel_params),+ f32(inv_t),+ f32(inv_h),+ f32(inv_w),+ *_runtime_scalars(+ volume=(T, H, W),+ ctx_volume=(T_lo, H_lo, W_lo),+ drop_leading=drop,+ n_ctas=n_ctas,+ plan=plan,+ n_kf=kf.n_kf,+ kf_cache_row_stride=kf.cache_row_stride,+ ),+ )video_out = y_buf[: T * H * W].view(T, H, W, C).unsqueeze(0).to(dtype=x.dtype)if not kf.enabled:return video_out@@ -2345,26 +2358,26 @@ def _launch(inv_t,inv_h,inv_w,- T,- H,- W,- T_lo,- H_lo,- W_lo,- drop_leading,- n_ctas,- slab_count,- slab_grid_hw,- slab_grid_w,- slab_tiles_t,- slab_tiles_h,- slab_tiles_w,- max_box_t,- max_box_h,- max_box_w,- cache_row_stride,- n_kf,- kf_cache_row_stride,+ T: cutlass.Int32,+ H: cutlass.Int32,+ W: cutlass.Int32,+ T_lo: cutlass.Int32,+ H_lo: cutlass.Int32,+ W_lo: cutlass.Int32,+ drop_leading: cutlass.Int32,+ n_ctas: cutlass.Int32,+ slab_count: cutlass.Int32,+ slab_grid_hw: cutlass.Int32,+ slab_grid_w: cutlass.Int32,+ slab_tiles_t: cutlass.Int32,+ slab_tiles_h: cutlass.Int32,+ slab_tiles_w: cutlass.Int32,+ max_box_t: cutlass.Int32,+ max_box_h: cutlass.Int32,+ max_box_w: cutlass.Int32,+ cache_row_stride: cutlass.Int32,+ n_kf: cutlass.Int32,+ kf_cache_row_stride: cutlass.Int32,C: cutlass.Constexpr,Ctx: cutlass.Constexpr,SP_T: cutlass.Constexpr,@@ -2519,7 +2532,7 @@ def _launch().launch(grid=[n_ctas, 1, 1], block=[THREADS, 1, 1])-def _compile(+def _compile_kernel(*,C: int,Hidd: int,@@ -2529,30 +2542,12 @@ def _compile(tile_thw: "tuple[int, int, int]",Ctx: int | None = None,upsample_stride: "tuple[int, int, int]" = (1, 1, 1),+ slab_box_max: "tuple[int, int, int]" = SLAB_BOX_MAX,keyframes: bool = False,+ options: str | None = None,):+ """Compile one structural key from storage-free ABI descriptors."""Ctx = C if Ctx is None else Ctx- # ``keyframes`` keys the binary so the no-keyframe kernel keeps exactly the trace, and- # the register allocation, it had before the keyframe stream existed.- # Everything else here is structural too, and must stay that way. The per-tile plane- # union bound used to be in this key; because it moves with the clip length it recompiled- # the ladder on every new duration, which cost 12+ minutes of in-process MLIR before a- # 545-frame decode could start. It is now ``SLOTS * TT``, a constant of ``tile_thw``.- key = (- C,- Ctx,- upsample_stride,- Hidd,- num_heads,- rope_dim_split,- tile_thw,- kernel_size,- MAXP_TOKENS,- SLAB_BOX_MAX,- keyframes,- )- if key in _COMPILED:- return _COMPILED[key]kt, kh, kw = kernel_sizett, th, tw = tile_thwpanel = (tt + kt - 1, th + kh - 1, tw + kw - 1)@@ -2563,53 +2558,51 @@ def _compile(# Halo-box bounds are compile-time, so the rope tables are fixed-size; the box's# actual extents come from ``_choose_slab`` at runtime, which is what keeps T/H/W# dynamic. A one-tile slab is the floor, so the panel itself has to fit.- if any(p > b for p, b in zip(panel, SLAB_BOX_MAX, strict=True)) or panel[0] * panel[1] * panel[2] > MAXP_TOKENS:- raise ValueError(f"halo panel {panel} exceeds the slab box bound {SLAB_BOX_MAX}")- hd = C // num_heads- subpixels = upsample_stride[0] * upsample_stride[1] * upsample_stride[2]- dev = torch.device("cuda")+ if any(p > b for p, b in zip(panel, slab_box_max, strict=True)) or panel[0] * panel[1] * panel[2] > MAXP_TOKENS:+ raise ValueError(f"halo panel {panel} exceeds the slab box bound {slab_box_max}")++ def activation():+ return fake_dynamic_matrix(cutlass.BFloat16, assumed_align=16)- def act(a: int, b: int):- return _dyn_act(torch.zeros(a, b, device=dev, dtype=torch.bfloat16))+ def weight(columns: int):+ return fake_dynamic_weight(cutlass.BFloat16, columns=columns)- def weight(a: int, b: int):- return _dyn_w(torch.zeros(a, b, device=dev, dtype=torch.bfloat16))+ def f32_vector():+ return fake_dynamic_vector(cutlass.Float32)- def vec(n: int):- return _dyn(torch.zeros(n, device=dev, dtype=torch.float32))+ def i32_vector():+ return fake_dynamic_vector(cutlass.Int32)# Shapes here only have to be *typed* right: every extent the kernel reads is a# runtime argument, so the stand-ins can be as small as their layouts allow.trace_plan = _SlabPlan(core=(1, 1, 1), box=(1, 1, 1), grid=(1, 1, 1))- # Pass-through for CuTe DSL compiler flags, e.g. --keep-sass / --ptxas-options=-v.- opts = os.environ.get("CUTE_DSL_OPTS")- _COMPILED[key] = cute.compile(+ return cute.compile(_launch,- act(M, C), # x- act(M, Ctx), # stage4- act(M, C), # y- act(2 * num_heads * M, hd), # kv_cache -- its head stride is a runtime argument- vec(2 * M), # norm_cache- _dyn(torch.zeros(2, device=dev, dtype=torch.int32)), # barrier- act(M, C), # x_kf- act(M, Ctx), # stage4_kf- act(M, C), # y_kf- act(2 * num_heads * M, hd), # kv_cache_kf- vec(2 * M), # norm_cache_kf- vec(1), # kf_times- *(_dyn(torch.zeros(max(n, 1), device=dev, dtype=torch.int32)) for n in (1, 1, 1, 1, 1, 1)),- weight(subpixels * C, Ctx), # w_ctx -- the fused upsample x context_proj- weight(C, C), # w_q- weight(2 * C, C), # w_kv- weight(C, C), # w_o- weight(Hidd, C), # w_gate- weight(Hidd, C), # w_up- weight(C, Hidd), # w_down- vec(_channel_param_offsets(C, hd, subpixels)["total"]), # channel_params- vec(max(rope_dim_split[0] // 2, 1)), # inv_t- vec(max(rope_dim_split[1] // 2, 1)), # inv_h- vec(max(rope_dim_split[2] // 2, 1)), # inv_w+ activation(), # x+ activation(), # stage4+ activation(), # y+ activation(), # kv_cache -- its head stride is a runtime argument+ f32_vector(), # norm_cache+ i32_vector(), # barrier+ activation(), # x_kf+ activation(), # stage4_kf+ activation(), # y_kf+ activation(), # kv_cache_kf+ f32_vector(), # norm_cache_kf+ f32_vector(), # kf_times+ *(i32_vector() for _ in range(6)),+ weight(Ctx), # w_ctx -- the fused upsample x context_proj+ weight(C), # w_q+ weight(C), # w_kv+ weight(C), # w_o+ weight(C), # w_gate+ weight(C), # w_up+ weight(Hidd), # w_down+ f32_vector(), # channel_params+ f32_vector(), # inv_t+ f32_vector(), # inv_h+ f32_vector(), # inv_w*_runtime_scalars(volume=(4, 4, 4), ctx_volume=(4, 4, 4), drop_leading=0, n_ctas=1, plan=trace_plan),*_static_shape(C=C,@@ -2620,11 +2613,11 @@ def _compile(rope_dim_split=rope_dim_split,kernel_size=kernel_size,tile_thw=tile_thw,+ slab_box_max=slab_box_max,keyframes=keyframes,),- **({"options": opts} if opts else {}),+ **({"options": options} if options else {}),)- return _COMPILED[key]def _runtime_scalars(@@ -2667,6 +2660,7 @@ def _static_shape(rope_dim_split: "tuple[int, int, int]",kernel_size: "tuple[int, int, int]",tile_thw: "tuple[int, int, int]",+ slab_box_max: "tuple[int, int, int]",keyframes: bool = False,) -> tuple:"""The kernel's compile-time arguments, in signature order."""@@ -2691,7 +2685,7 @@ def _static_shape(tw,*panel,n_kv,- *SLAB_BOX_MAX,+ *slab_box_max,keyframes,KEYFRAME_CONTEXT_SLOTS,# The stride into ``kf_planes``: a tile's ``TT`` timesteps contribute at mostdiff --git a/packages/ltx-kernels/src/ltx_kernels/vae/na_attn_dsl.py b/packages/ltx-kernels/src/ltx_kernels/vae/na_attn_dsl.pyindex 7ea07fb..6533fd2 100644--- a/packages/ltx-kernels/src/ltx_kernels/vae/na_attn_dsl.py+++ b/packages/ltx-kernels/src/ltx_kernels/vae/na_attn_dsl.py@@ -11,15 +11,14 @@ Q must arrive carrying the attention scale, exactly as ``natten.na3d`` expects iThe one extra thing this kernel needs is the ``k_norm`` weight, from which it builds afixed softmax offset in place of an online row max -- see:mod:`ltx_kernels.vae.softmax_bound`, which is worth reading before calling this.-Compile keys are ``(kernel_size, tile_thw)`` and nothing else -- head count, T, H and-W are all runtime -- so the four deterministic stages share two binaries.+Compile keys are ``(kernel_size, tile_thw)`` per GPU architecture -- head count,+T, H and W are all runtime -- so the four deterministic stages share two binaries."""# NOTE: no `from __future__ import annotations` -- cute.struct needs real types.import functools-import os-from typing import Any, NamedTuple+from typing import NamedTupleimport cutlassimport cutlass.cute as cute@@ -27,6 +26,7 @@ import cutlass.utils.blackwell_helpers as sm100_utilsimport torchfrom cutlass.utils import SmemAllocator+from ltx_kernels.vae.aot import KERNEL_CACHE, fake_dynamic_matrix, fake_dynamic_vectorfrom ltx_kernels.vae.availability import UNSUPPORTED_MESSAGE, gpu_supports_dsl_kernelsfrom ltx_kernels.vae.fna_attn_core import (_as_rows,@@ -76,8 +76,6 @@ from ltx_kernels.vae.fna_types import (from ltx_kernels.vae.keyframe_slots import KEYFRAME_CONTEXT_SLOTS, nearest_video_frames, tile_plane_unionfrom ltx_kernels.vae.softmax_bound import softmax_row_bound-_COMPILED: "dict[tuple, Any]" = {}-# Heads per group. ``HG * HD`` TMEM columns for the attention accumulators plus 256# for the two Q@K accumulators must fit in 512, so 4 is the ceiling; it also has to# be even (the pipeline's buffer parity is ``nh % 2``) and to divide ``NUM_WARPGROUPS`` evenly@@ -451,17 +449,17 @@ def _launch(y_kf,kf_video,kf_video_counts,- T,- H,- W,- NH,- n_hg,- n_tiles,- n_ctas,- grid_hw,- grid_w_,- n_kf,- n_kfq_tiles,+ T: cutlass.Int32,+ H: cutlass.Int32,+ W: cutlass.Int32,+ NH: cutlass.Int32,+ n_hg: cutlass.Int32,+ n_tiles: cutlass.Int32,+ n_ctas: cutlass.Int32,+ grid_hw: cutlass.Int32,+ grid_w_: cutlass.Int32,+ n_kf: cutlass.Int32,+ n_kfq_tiles: cutlass.Int32,kt: cutlass.Constexpr,kh: cutlass.Constexpr,kw: cutlass.Constexpr,@@ -565,25 +563,15 @@ def na_supported(return pt <= T and ph <= H and pw <= W-def _compile(+def _compile_kernel(*,kernel_size: "tuple[int, int, int]",tile_thw: "tuple[int, int, int]",keyframes: bool = False,keyframe_queries: bool = False,+ options: str | None = None,):- # ``keyframes`` is part of the key so the no-keyframe binary keeps the exact trace it- # had before the tail existed -- ``n_kf = 0`` must stay bit-identical, and a runtime- # zero-trip loop would still perturb the codegen around it.- # Everything in this key is *structural*. Nothing derived from the anchor layout may join- # it: the per-tile plane union bound used to, and since it moves with the clip length it- # recompiled the whole stage ladder on every new duration -- 12+ minutes of in-process- # MLIR before a 545-frame decode could start. It is now ``SLOTS * TT``, the true upper- # bound (each of a tile's ``TT`` timesteps contributes at most ``SLOTS`` planes), which is- # a constant of ``tile_thw`` and so already covered here.- key = (kernel_size, tile_thw, keyframes, keyframe_queries)- if key in _COMPILED:- return _COMPILED[key]+ """Compile one structural key from storage-free ABI descriptors."""kt, kh, kw = kernel_sizett, th, tw = tile_thwpt, ph, pw = tt + kt - 1, th + kh - 1, tw + kw - 1@@ -595,32 +583,29 @@ def _compile(# *query* tiles borrow it too, which is what keeps them on one instantiation with the# video tail (see the keyframe query loop in ``_na_kernel``).nkv_kf = (ph * pw + TILE_N - 1) // TILE_N- dev = torch.device("cuda")- def za(a: int, b: int):- return _dyn_act(torch.zeros(a, b, device=dev, dtype=torch.bfloat16))+ def activation():+ return fake_dynamic_matrix(cutlass.BFloat16, assumed_align=16)- def zi(n: int):- return _dyn(torch.zeros(n, device=dev, dtype=torch.int32))+ def i32_vector():+ return fake_dynamic_vector(cutlass.Int32)- # Pass-through for CuTe DSL compiler flags, e.g. --keep-sass / --ptxas-options=-v.- opts = os.environ.get("CUTE_DSL_OPTS")- _COMPILED[key] = cute.compile(+ return cute.compile(_launch,- za(M, HG * HD),- za(M, HD),- za(M, HD),- za(M, HG * HD),- _dyn(torch.zeros(1, device=dev, dtype=torch.float32)),- za(M, HD),- za(M, HD),- zi(KEYFRAME_CONTEXT_SLOTS),- zi(1),- zi(1),- za(M, HG * HD),- za(M, HG * HD),- zi(KEYFRAME_CONTEXT_SLOTS),- zi(1),+ activation(),+ activation(),+ activation(),+ activation(),+ fake_dynamic_vector(cutlass.Float32),+ activation(),+ activation(),+ i32_vector(),+ i32_vector(),+ i32_vector(),+ activation(),+ activation(),+ i32_vector(),+ i32_vector(),4,4,4,@@ -647,9 +632,8 @@ def _compile(KEYFRAME_CONTEXT_SLOTS * tt,nkv_kf,keyframe_queries,- **({"options": opts} if opts else {}),+ **({"options": options} if options else {}),)- return _COMPILED[key]@functools.lru_cache(maxsize=8)@@ -868,39 +852,51 @@ def run_na_attention_bound(kfv = kfv_counts = kf.countsn_kfq_tiles = 0- compiled = _compile(- kernel_size=kernel_size,- tile_thw=(tt, th, tw),- keyframes=kf.enabled,- keyframe_queries=kfq,- )- compiled(- _dyn_act(q_),- _dyn_act(k_),- _dyn_act(v_),- _dyn_act(y_buf),- _dyn(k_bound.detach().reshape(1).float().to(device=q_.device)),- kf.k,- kf.v,- kf.slots,- kf.planes,- kf.counts,- q_kf_,- y_kf_dyn,- kfv,- kfv_counts,- T,- H,- W,- NH,- NH // HG,- n_tiles,- n_ctas,- grid_h * grid_w,- grid_w,- n_kf,- n_kfq_tiles,- )+ with torch.cuda.device(q_.device):+ # ``keyframes`` is part of the key so the no-keyframe binary keeps the exact trace it+ # had before the tail existed -- ``n_kf = 0`` must stay bit-identical, and a runtime+ # zero-trip loop would still perturb the codegen around it.+ # Everything in this key is *structural*. Nothing derived from the anchor layout may join+ # it: the per-tile plane union bound used to, and since it moves with the clip length it+ # recompiled the whole stage ladder on every new duration -- 12+ minutes of in-process+ # MLIR before a 545-frame decode could start. It is now ``SLOTS * TT``, the true upper+ # bound (each of a tile's ``TT`` timesteps contributes at most ``SLOTS`` planes), which is+ # a constant of ``tile_thw`` and so already covered here.+ compiled = KERNEL_CACHE.get(+ _compile_kernel,+ q_.device,+ kernel_size=kernel_size,+ tile_thw=(tt, th, tw),+ keyframes=kf.enabled,+ keyframe_queries=kfq,+ )+ compiled(+ _dyn_act(q_),+ _dyn_act(k_),+ _dyn_act(v_),+ _dyn_act(y_buf),+ _dyn(k_bound.detach().reshape(1).float().to(device=q_.device)),+ kf.k,+ kf.v,+ kf.slots,+ kf.planes,+ kf.counts,+ q_kf_,+ y_kf_dyn,+ kfv,+ kfv_counts,+ T,+ H,+ W,+ NH,+ NH // HG,+ n_tiles,+ n_ctas,+ grid_h * grid_w,+ grid_w,+ n_kf,+ n_kfq_tiles,+ )video_out = y_buf[: T * H * W].view(1, T, H, W, NH * hd).to(dtype=q.dtype)if q_keyframes is None:return video_outdiff --git a/packages/ltx-pipelines/CLAUDE.md b/packages/ltx-pipelines/CLAUDE.mdindex e6b28a0..986f63c 100644--- a/packages/ltx-pipelines/CLAUDE.md+++ b/packages/ltx-pipelines/CLAUDE.md@@ -12,6 +12,16 @@ Run: ls src/ltx_pipelines/*.py to check for new pipeline files.Inference pipelines for LTX-2 audio-video generation. Depends on `ltx-core` for model definitions, diffusion components, and loading. All pipelines live in `packages/ltx-pipelines/src/ltx_pipelines/`.+## Chunk generation (`chunks/`)++Long-video framework: the `Chunk` / `DecodedChunk` wire (`state.py`), `uniform_chunk_layouts` (`layout.py`) and `generate_uniform_chunks` (`planner.py`), chunk operators in `operators.py` (`denoise_chunks`, `spatially_upsample_chunks`, `replace_video_conditionings`, `replace_audio_conditionings`, `decode_chunks`, `replace_chunks_audio`), and stream I/O in `export.py` (`split_decoded_chunks`, `pipeline_output_from_chunks`, `SequentialVideoFrameSource` for overlap-aware IC-LoRA reference decode). `Chunk` carries user-provided `make_video_conditionings` / `make_audio_conditionings` callables that materialize `ConditioningItem` lists at the current latent shape when the chunk reaches denoise, so the same factory survives a spatial upsample between passes. Pipelines assemble those callables from per-item builders in `conditionings.py` (`image_conditionings_for_chunk`, `generated_keyframe_slots_for_chunk`, `reference_video_conditionings_for_chunk`, `audio_reference_conditionings_for_chunk`). Point items (images, generated-keyframe slots) map onto the chunk that owns the stitched `frame_idx` via `ChunkLayout.local_frame_index`. Span items (IC-LoRA reference video, audio-ref) apply to every window and slice to that window inside the factory. Stage-2 swaps a new factory through `replace_video_conditionings` / `replace_audio_conditionings` rather than filtering. `generate_uniform_chunks(audio_latent=)` seeds frozen source audio; `replace_chunks_audio` muxes the original waveform after decode instead of vocoding.++Chunked pipelines hold the same `DiffusionStage` the regular ones do, so every chunk operator wraps a core component through its `__call__`: `denoise_chunks` wraps `DiffusionStage` exactly as `spatially_upsample_chunks` wraps `VideoUpsampler`. `denoise_chunks` calls the stage once per chunk with a `VideoAudio` of `ModalitySpec`s carrying that chunk's own latents and carry-appended conditionings. Continuity across a seam is a `VideoConditionByLatentIndex` / `AudioConditionByLatentIndex` pin of the previous chunk's latent tail at index 0.++Pipelines stay at `ltx_pipelines/<name>.py`. Distilled, TI2Vid two-stage, A2Vid two-stage, Dub-It, and IC-LoRA expose long-video generation via `stream_chunks()`, which composes the chunk operators and returns `(Iterator[DecodedChunk], num_frames, tiling_config)`. `__call__` on those pipelines delegates to `stream_chunks` and wraps the result in `PipelineOutput`; with `chunk_config=None` that is a single full-clip chunk. They also accept `chunk_pixel_frames` / `next_video_carry_frames` on `__call__` via `ChunkConfig`. Each pipeline's `_prepare_run` validates inputs, encodes prompts, and resolves frame count / tiling (plus pipeline-specific prep such as A2Vid source audio) before `stream_chunks` plans windows. DFR is one-shot only; chunked DFR is deferred.++CLI: on `python -m ltx_pipelines.distilled`, `python -m ltx_pipelines.ti2vid_two_stages` (and their MGPU runners), `python -m ltx_pipelines.a2vid_two_stage`, or `python -m ltx_pipelines.dubit`, pass `--chunk-pixel-frames` (default 97) and/or `--chunk-carry-frames` (default 25) via `add_chunk_layout_args` (`utils/args.py`); `--chunk-blend-frames` controls decoded video seam crossfade length (default: full carry, `0` for a hard cut). When any layout flag is set, `chunk_config_from_args` builds a `ChunkConfig` and the CLI/MGPU driver streams `stream_chunks` through `split_decoded_chunks` into `encode_video`; otherwise it encodes `PipelineOutput` from `__call__`. With no chunk flags, `stream_chunks` / `uniform_chunk_layouts` plans one chunk covering the snapped clip.+## Pipeline selection| Pipeline | File | Stages | Model | Sampler | Use case |@@ -22,11 +32,12 @@ Inference pipelines for LTX-2 audio-video generation. Depends on `ltx-core` for| `TI2VidTwoStagesHQPipeline` | `ti2vid_two_stages_hq.py` | 2 | Full + distilled LoRA (both stages) | Res2s | Guided two-stage, res_2s, fewer steps || `A2VidPipelineTwoStage` | `a2vid_two_stage.py` | 2 | Full + distilled LoRA | Euler | Audio-conditioned video || `KeyframeInterpolationPipeline` | `keyframe_interpolation.py` | 2 | Full + distilled LoRA | Euler | Keyframe interpolation |-| `DFRPipeline` | `dfr_pipeline.py` | 2 (+ optional tiled temporal) | Distilled checkpoint + detailing IC-LoRA stage 2 | Euler | Production quality (keyframes + detailing + optional temporal x2) |-| `DistilledPipeline` | `distilled.py` | 2 | Distilled only | Euler (stage 1: ancestral on 2.5+) | Fastest inference |+| `DFRPipeline` | `dfr_pipeline.py` | 2 (+ optional tiled temporal) | Distilled checkpoint + detailing IC-LoRA stage 2 | Euler ancestral (2.5+) | Production quality (keyframes + detailing + optional temporal x2) |+| `DistilledPipeline` | `distilled.py` | 2 | Distilled only | Euler ancestral (2.5+) | Fastest inference || `ICLoraPipeline` | `ic_lora.py` | 2 | Distilled only | Euler | Video-to-video with IC-LoRA control || `DubItPipeline` | `dubit.py` | 2 | Distilled only | Euler | Dub-It with IC-LoRA + audio ref conditioning || `RetakePipeline` | `retake.py` | 1 | Full or distilled | Euler | Video region regeneration |+| `HDRICLoraPipeline` | `hdr_ic_lora.py` | 1 | Distilled + HDR IC-LoRA | Euler | ACEScct SDR-to-HDR; DFR seam keyframes on by default |## Guidance@@ -51,12 +62,13 @@ Inference pipelines for LTX-2 audio-video generation. Depends on `ltx-core` for## Shared building blocks (`utils/blocks.py`)-- `DiffusionStage` -- owns transformer lifecycle; builds model on call, frees on exit via `gpu_model()` context manager (moves params to meta device to release GPU/CPU memory). Accepts optional `stepper` and `loop` overrides. `__init__` takes a pre-built transformer builder; pipelines construct it via the `DiffusionStage.from_checkpoint(checkpoint_path, ..., loras=...)` classmethod, which builds the standard (and, when offloading, streaming) builders. `with_builder` / `with_loras` return a new stage with a swapped builder / LoRA set without re-specifying config.+- `DiffusionStage` -- owns transformer lifecycle; builds model on call, frees on exit via `gpu_model()` context manager (moves params to meta device to release GPU/CPU memory). Accepts an optional `loop` override. `__init__` takes a pre-built transformer builder; pipelines construct it via the `DiffusionStage.from_checkpoint(checkpoint_path, ..., loras=...)` classmethod, which builds the standard (and, when offloading, streaming) builders. `with_builder` / `with_loras` return a new stage with a swapped builder / LoRA set without re-specifying config. ``supports_generated_keyframes`` reads ``use_keyframes_abs_pos_embedding`` from the checkpoint config (no weights loaded). ``__call__`` re-checks slot conditionings via ``_assert_supports_conditionings`` as a backstop for callers that build items directly.+ `__call__` takes `modalities: VideoAudio[ModalitySpec]` and is a latent entry point: each `ModalitySpec` brings the latent to denoise, and that latent is the stage's only source of shape -- pixel dimensions never reach it, and it never sizes a latent itself. A pipeline's *first* stage seeds the latent with `create_initial_video_latent` / `create_initial_audio_latent` / `create_initial_av_latents` (`utils/helpers.py`); every later stage passes the previous stage's output, upscaled or not. So latents are allocated once per run, at the pipeline head. Sizing audio off a playback rate that differs from the video RoPE time base is done by building the audio latent at that rate, not by a stage argument. Returns `VideoAudio`, which unpacks as `(video, audio)`.- `PromptEncoder` -- Gemma text encoder + embeddings processor (video 4096-dim, audio 2048-dim).-- `ImageConditioner` / `AudioConditioner` -- temporary encoder scope; builds encoder, passes to callable, frees. `ImageConditioner` is additionally the single owner of the image-conditioning CRF: `resolve_crf(images)` (called near the top of every pipeline's `__call__`) fills in the H.264 CRF of any `ImageConditioningInput` that left it unset, reading it from the checkpoint's `model_version` (`detect_params`, lazily and cached). So omitting `crf` means "use what matches this model" (33 through LTX-2.3, 18 from 2.4), while an explicit `crf` -- including `0` for no re-compression -- is always honoured.+- `ImageConditioner` / `AudioConditioner` -- temporary encoder scope; builds encoder, passes to callable, frees. `ImageConditioner` is additionally the single owner of the image-conditioning CRF: `resolve_crf(images)` (called near the top of every pipeline's `__call__`) fills in the H.264 CRF of any `ImageConditioningInput` (`utils.types`) that left it unset, reading it from the checkpoint's `model_version` (`detect_params`, lazily and cached). So omitting `crf` means "use what matches this model" (33 through LTX-2.3, 18 from 2.4), while an explicit `crf` -- including `0` for no re-compression -- is always honoured.- `VideoUpsampler` -- 2x spatial upsampling via encoder + upsampler.- `VideoDecoder` / `AudioDecoder` -- latent-to-pixel decoding (iterator for video, `Audio` for audio). `VideoDecoder` takes a single decoder `checkpoint_path` and `diffvae_optimization` (`DiffVAEMode`, default `CHUNKED_EAGER`); pipelines pass `model_paths.video_vae()`, the same file `ImageConditioner` and `VideoUpsampler` build their encoder from -- a video VAE checkpoint carries encoder and decoder together. Decoder kind (conv vs diffusion) is chosen from checkpoint metadata (`is_diffusion_video_vae`); distilled DiffVAE uses fixed 2 Euler steps. CLI: `--video-vae-path` is the video VAE slot in both monolith (optional override; defaults via `ModelPaths.from_monolith`) and split modes; `--diffvae-optimization` (see `docs/optimization.md#diffusion-vae-decoder` for mode meanings and relative compile/runtime/VRAM factors). Multi-GPU pipelines (`*_mgpu.py`) accept the same flags and wrap the loaded decoder in `DistributedVideoDecoder`.-- `DurationPredictor` -- predicts a frame count from `PromptEncoder`'s connector token outputs via `DurationHead` (`ltx_core.duration_head`), snapped to the VAE's temporal grid. Unlike other blocks, it holds the built model directly (`__init__` takes a `DurationHead`, not a builder) since the checkpoint is only a few MB -- no build-on-call/free-on-exit needed. Pipelines construct it via `DurationPredictor.from_checkpoint(checkpoint_path, dtype, device)`, which returns `None` instead of a predictor if the checkpoint has no `duration_head.*` weights (checkpoints predating LTX-2.5 / gemma4). Called with `(video_encoding, audio_encoding, frame_rate=...)` -- either may be `None` but not both. Wired into `TI2VidOneStagePipeline`, `TI2VidTwoStagesPipeline`, `TI2VidTwoStagesHQPipeline`, `DistilledPipeline`, `DFRPipeline`, and `T2AOneStagePipeline` (audio-only: `video_encoding=None`), plus their MGPU runners: when `num_frames` is omitted (`None`), `require_num_frames_source` (called at the top of `__call__`, before any work) raises immediately if no `DurationPredictor` is available, otherwise it's auto-predicted from the caption. The two-stage pipelines (`TI2VidTwoStagesPipeline`, `TI2VidTwoStagesHQPipeline`, `DistilledPipeline`, `DFRPipeline`, `A2VidPipelineTwoStage`) and their MGPU runners return the resolved `num_frames` as a third tuple element from `__call__`, so callers can compute `get_video_chunks_number` for the progress bar without duplicating the auto-duration fallback logic.+- `DurationPredictor` -- predicts a frame count from `PromptEncoder`'s connector token outputs via `DurationHead` (`ltx_core.duration_head`), snapped to the VAE's temporal grid. Unlike other blocks, it holds the built model directly (`__init__` takes a `DurationHead`, not a builder) since the checkpoint is only a few MB -- no build-on-call/free-on-exit needed. Pipelines construct it via `DurationPredictor.from_checkpoint(checkpoint_path, dtype, device)`, which returns `None` instead of a predictor if the checkpoint has no `duration_head.*` weights (checkpoints predating LTX-2.5 / gemma4). Called with `(video_encoding, audio_encoding, frame_rate=...)` -- either may be `None` but not both. Wired into `TI2VidOneStagePipeline`, `TI2VidTwoStagesPipeline`, `TI2VidTwoStagesHQPipeline`, `DistilledPipeline`, `DFRPipeline`, and `T2AOneStagePipeline` (audio-only: `video_encoding=None`), plus their MGPU runners: when `num_frames` is omitted (`None`), `require_num_frames_source` (called at the top of `__call__`, before any work) raises immediately if no `DurationPredictor` is available, otherwise it's auto-predicted from the caption. Auto-duration resolves inside `__call__`; read the final count from ``PipelineOutput.num_frames`` (or the local ``num_frames`` variable before return).### Memory management@@ -70,69 +82,106 @@ Inference pipelines for LTX-2 audio-video generation. Depends on `ltx-core` for- `GuidedDenoiser` -- CFG/STG with static `MultiModalGuider` instances (HQ, A2Vid, Retake non-distilled).- `FactoryGuidedDenoiser` -- per-step guider creation via factory (OneStageTI2Vid, TwoStagesTI2Vid, Keyframe).-All denoisers return a `(video_result, audio_result)` tuple of `DenoisedLatentResult` (defined in `utils/types.py`), either element may be `None` for absent modalities. `DenoisedLatentResult.denoised` is the final blended tensor. Guided denoisers additionally populate per-pass fields (`.cond`, `.uncond`, `.ptb`, `.mod`) on each result; `SimpleDenoiser` leaves these `None`.+All denoisers return `VideoAudio` of `DenoisedLatentResult` (defined in `utils/types.py`). It still unpacks as `(video_result, audio_result)`; either side may be `None` for absent modalities. `DenoisedLatentResult.denoised` is the final blended tensor. Guided denoisers additionally populate per-pass fields (`.cond`, `.uncond`, `.ptb`, `.mod`) on each result; `SimpleDenoiser` leaves these `None`.`GuidedDenoiser` and `FactoryGuidedDenoiser` accept `force_uncond_pass=True` to run the uncond pass even when `cfg_scale=1.0` (required by CFG++ when the guidance scale is 1 but the uncond prediction is still needed for the ODE derivative). Requires `negative_context` to be set on the guider. When enabled, `DenoisedLatentResult.uncond` will be a tensor instead of `None`.Guided denoisers batch all guidance passes into a **single transformer call**: states are repeated along the batch dimension, contexts concatenated, and a `BatchedPerturbationConfig` controls which attention ops are skipped per sample. Pass count is dynamic: B=2 for CFG-only, up to B=4 with CFG+STG+modality isolation. Results are split back and blended by the guider.+## PipelineOutput (`utils/types.py`)++Every video pipeline ``__call__`` returns ``PipelineOutput``: ``video``, ``audio``, ``num_frames``, ``tiling_config``. Prefer attribute access over positional unpack. ``video`` is a lazy decode iterator; ``audio`` is an ``ltx_core.types.Audio``. Slot latents and the final video latent are **not** returned -- keyframe-aware decode is chosen inside the pipeline (``decode_with_keyframes`` on TI2Vid/Distilled, always on DFR). ``result.video`` already reflects that choice.+## Per-pipeline unique features- **HQ**: Res2s second-order sampler for **both** stages, latent-dependent sigma schedule, distilled LoRA on both stages with separate strengths.-- **A2Vid**: Audio frozen in both stages (`frozen=True, noise_scale=0.0`). That zeros `denoise_mask` and forces audio `Modality.sigma=0` (prompt AdaLN / a2v gate). Returns original audio (not VAE-decoded); no `AudioDecoder`. CLI `--num-frames` and `--audio-max-duration` are mutually exclusive: with `--audio-max-duration`, `num_frames` is omitted (`None`) and derived from the decoded clip (capped by remaining audio after `--audio-start-time`); with `--num-frames` or neither, that frame count is used and audio is clipped to match. `__call__` returns `(video, audio, num_frames, tiling_config)` like the other two-stage pipelines.-- **IC-LoRA**: `VideoConditionByReferenceLatent`, `reference_downscale_factor` from LoRA metadata, `skip_stage_2`, attention mask downsampling. Stage 2 is LoRA-free and uses `combined_image_conditionings` (no IC-LoRA conditioning).-- **Dub-It**: Standalone pipeline; IC reference **video** helpers in `iclora_utils.py`, Dub-It-only **audio** patchify/negative positions in `dubit.py`. Appends frozen audio-reference tokens via `AudioConditionByReferenceLatent` (ltx-core), matching video token order (`[target | ref]`) while keeping reference RoPE positions negative (training-compatible). Single IC-LoRA on both stages; full IC-LoRA video conditioning at stage 1 and 2; stage-2 audio is frozen with S1 latent as initial state and uses S1-derived ref. Final audio decoded from stage 1 latent. The Dub-It CLI does not expose `--conditioning-attention-mask`; use `ic_lora.py` if you need spatial IC attention masking.+- **A2Vid**: Audio frozen in both stages (`frozen=True, noise_scale=0.0`). That zeros `denoise_mask` and forces audio `Modality.sigma=0` (prompt AdaLN / a2v gate). Returns original audio (not VAE-decoded); no `AudioDecoder`. Chunked mode seeds each chunk from the encoded source latent (`generate_uniform_chunks(audio_latent=)`) and muxes the original waveform after decode (`replace_chunks_audio`). CLI `--num-frames` and `--audio-max-duration` are mutually exclusive: with `--audio-max-duration`, `num_frames` is omitted (`None`) and derived from the decoded clip (capped by remaining audio after `--audio-start-time`); with `--num-frames` or neither, that frame count is used and audio is clipped to match. Returns ``PipelineOutput`` like the other two-stage pipelines.+- **IC-LoRA**: `VideoConditionByReferenceLatent`, `reference_downscale_factor` / `reference_temporal_scale_factor` from LoRA metadata, `skip_stage_2`, attention mask downsampling. Default stage 2 is LoRA-free (`combined_image_conditionings` only); `apply_ic_lora` / `--stage-2-ic-lora` keeps the reference on a stage. CLI is two stages (`--tile` plus `--tile-height` / `--tile-width` for transformer windows). Longer ladders use `ICLoraPipeline(stages=...)`. Temporal chunking: `stream_chunks()` / `chunk_config` compose the shared chunk operators with per-stage LoRA and `diffusion_stage_with_tiling`; reference video uses `SequentialVideoFrameSource` and chunk-local mask/temporal scaling via `reference_video_conditionings_for_chunk`. CLI `--chunk-pixel-frames` / `--chunk-carry-frames` / `--chunk-blend-frames` stream encode like Distilled/Dub-It.+- **Dub-It**: Standalone pipeline; IC reference **video** helpers and audio-reference patchify (negative RoPE) in `iclora_utils.py`. Appends frozen audio-reference tokens via `AudioConditionByReferenceLatent` (ltx-core), matching video token order (`[target | ref]`) while keeping reference RoPE positions negative (training-compatible). Single IC-LoRA on both stages; full IC-LoRA video conditioning at stage 1 and 2; stage-2 audio is frozen with S1 latent as initial state and uses S1-derived ref. Final audio decoded from stage 1 latent. Chunked mode walks the IC-LoRA reference video once through `SequentialVideoFrameSource` (overlap lookback) and encodes audio-reference tokens in the chunk factories (stage 2 swaps the audio factory to self-reference via `replace_audio_conditionings`). The Dub-It CLI does not expose `--conditioning-attention-mask`; use `ic_lora.py` if you need spatial IC attention masking.- **Keyframe**: Uses `image_conditionings_by_adding_guiding_latent` in both stages (all frames as keyframe guidance, no replacement) -- unlike TI2Vid which uses `combined_image_conditionings` (frame_idx=0 replaces, others guide).- **Retake**: `TemporalRegionMask` for selective time-window regeneration. `regenerate_video`/`regenerate_audio` flags. Conditional distilled/full behavior.-- **Distilled**: Single `self.stage` reused for both stages (not `stage_1`/`stage_2`). Stage 1's sampler is resolved in `__init__` from the checkpoint generation -- `should_use_ancestral_sampler(path)` (`detect_model_version(...) >= (2, 5)`) sets `self.use_ancestral_sampler`, so LTX-2.5+ uses `EulerAncestralDiffusionStep(eta=1.0, s_noise=1.0)` (the reference sampler's own defaults) + `euler_ancestral_denoising_loop` and older checkpoints keep plain Euler. There is no per-call override; assign the attribute before calling to pin a sampler (e.g. to A/B both on one checkpoint). `distilled_mgpu.py` detects per rank from the same checkpoint, so ranks stay symmetric. Stage 2 is always plain Euler -- its 3-step schedule is too short to remove freshly injected noise. The loop's noise seed is offset (`ANCESTRAL_NOISE_SEED_OFFSET`) so its first draw is not bit-identical to the initial `GaussianNoiser` noise.-- **DFR** (Diffusion Fidelity Rendering, `dfr_pipeline.py` + its `dfr_layout.py` sidecar):- operator how-to (resolution, fps, memory) is [Running DFR](docs/pipelines.md#running-dfr).+- **Distilled**: Single `self.stage` reused for both stages (not `stage_1`/`stage_2`). The sampler is resolved in `__init__` from the checkpoint generation -- `should_use_ancestral_sampler(path)` (`detect_model_version(...) >= (2, 5)`) sets `self.use_ancestral_sampler`, so an LTX-2.5+ checkpoint samples every stage with `euler_ancestral_denoising_loop(..., eta=1.0, s_noise=1.0)` (ComfyUI's `sample_euler_ancestral_RF` defaults), and anything older samples with plain Euler. There is no per-call override; assign the attribute before calling to pin a sampler (e.g. to A/B both on one checkpoint). `distilled_mgpu.py` detects per rank from the same checkpoint, so ranks stay symmetric. Each pass has its own noise-seed offset (`ANCESTRAL_NOISE_SEED_OFFSET`, `ANCESTRAL_STAGE_2_NOISE_SEED_OFFSET`), so no two of them inject the same noise and stage 1's first draw is not bit-identical to the initial `GaussianNoiser` noise. Within a pass the seed advances by one on each denoise call, so sequential chunks do not reuse ancestral noise across a seam; a single `DiffusionStage` call is index 0, so one-shot output matches a fixed-seed partial.+- **DFR** (Diffusion Fidelity Rendering, `dfr_pipeline.py` orchestrator + `dfr_stages.py` ++ `dfr_helpers/` sidecar). Adapters import `denoise_stage1`, `denoise_stage2`, `run_one_temporal_round`,+ and `run_spatial_epilogue` from `dfr_stages` (and helpers from `dfr_helpers.ops` /+ `dfr_helpers.layout`) instead of wrapping `DFRPipeline`. Stages must not instantiate Gemma /+ `ModelPaths`. Operator how-to (resolution, fps, memory) is+ [Running DFR](docs/pipelines.md#running-dfr). The pipeline itself:distilled-schedule pipeline on a keyframe-slot-capable **distilled checkpoint**, plus an x2- detailing IC-LoRA (required; ``--detailing-lora``). Stage 1 (half-res) generates video + keyframe slots on an **x8-border segment+ detailing IC-LoRA (required; ``--detailing-lora``). Stage 1, stage 2 and the spatial epilogue take+ their sampler from the same `use_ancestral_sampler` rule as DistilledPipeline (eta=1.0), each with+ its own noise-seed offset; temporal tiles densify with ancestral Euler at eta=0.5 regardless. Stage 1 (half-res) generates video + keyframe slots on an **x8-border segmentgrid**: pad ``(num_frames-1)`` up to a multiple of S (prefer S=32 unless S=24 pads strictly less);- positions ``S, 2S, …, N'-1``. Half-res video is reserved for IC-LoRA; video and slot keyframes are- spatially latent-upsampled. Stage 2 jointly denoises with the distilled weights and the x2+ positions ``S, 2S, …, N'-1``. Half-res video is reserved for IC-LoRA; stage 2 spatially upsamples+ video and slot keyframes before denoising. Stage 2 jointly denoises with the distilled weights and the x2detailing IC-LoRA (``VideoConditionByReferenceLatent`` on thereserved half-res stage-1 video, ``STAGE_2_DISTILLED_SIGMAS``). Shipped audio is **stage 1's**:stage 2 still runs an audio pass (video needs the cross-modal attention) but re-noises audio under- the detailing LoRA. Temporal tiles pass frozen stage-1 audio sliced to the tile's playback+ the detailing LoRA. ``denoise_stage1`` accepts an injectable audio ``ModalitySpec`` (default+ ``ModalitySpec(latent=..., context=audio_context)``); A2V callers must pass ``frozen=True, noise_scale=0.0``+ with ``latent=`` so the supplied audio is not re-noised before freezing. Temporal tiles pass frozen stage-1 audio sliced to the tile's playback*time* window (uncapped fps vs stage-1 duration) and retiled onto the snapped-fps token countfor cross-attention only; they do not refine or ship audio.Optional ``temporal_upscalings`` (0–2): each round temporally x2-upsamples, partitions into- ``2**round`` keyframe-seam tiles with a one-segment lead-in on non-first tiles, invents- mid-segment slots per tile, and densifies with ancestral Euler (η=0.5). Partition/stitch uses- ``dfr_layout.split_canvas_at_seams`` (remainder segments go to the leading tiles; core+ ``2**round`` keyframe-seam tiles; a non-first tile starts on the last keyframe plane before+ its seam with a pinned prefix. Invents mid-segment slots per tile, and densifies with ancestral+ Euler (η=0.5). Partition/stitch uses+ ``dfr_helpers.layout.split_canvas_at_seams`` (remainder segments go to the leading tiles; core``split_at_seams`` uses the same remainder rule). Optional``spatial_upscalings`` (1 or 2, CLI ``--spatial-upscalings``): ``1`` is stage 1 at ``h/2`` andstage 2 at ``h``; ``2`` is stage 1 at ``h/4``, stage 2 at ``h/2``, then a full-res spatialdetailing epilogue at ``h``. Carry keyframes are decoded one plane at a time, Lanczos-stretchedx2 in RGB, and encoded as ``VideoConditionByKeyframeIndex`` (strength 1); only the video latent isspatially upsampled, and the previous-stage video is the IC-LoRA reference. Detailing LoRA- strength is hardcoded to 0.5. The epilogue is a single denoising loop over the full-res canvas,- tiled *inside* the transformer call by ``_TiledModelWrapper`` -- the single-GPU twin of the- multi-GPU ``TiledDataParallelModelWrapper``, sharing ``VideoModalityTilingHelper`` and its blend- masks, installed via ``DiffusionStage.with_model_wrapper``. So every Euler step reconciles the- overlap, and conditionings are filtered per tile at the token level rather than cropped by hand.+ strength is hardcoded to 0.5. The epilogue runs **one denoising pass per temporal window**,+ sequentially, each pass tiled *spatially* inside the transformer call by ``TiledDiffusionModel``+ (``frames=1``) -- the single-GPU twin of the multi-GPU ``TiledDataParallelModelWrapper``, sharing+ ``VideoModalityTilingHelper`` and its blend masks, installed via+ ``DiffusionStage.with_model_wrapper``. The first step runs on a 2x2 grid before any remaining+ steps retile to 4x4; a one-step schedule stays 2x2. Every Euler step reconciles the *spatial*+ overlap, and spatial conditionings are filtered per tile at the token level rather than cropped+ by hand. The+ carried planes are conditioning only -- they are Lanczos upscales, so anchoring the decode on them+ blurs what a keyframe should sharpen; the epilogue attaches a slot a latent frame beside each and+ **ships those full-res planes** instead. Running the temporal windows sequentially rather than per+ step costs the same -- they are seam-cut and never blended into each other -- and is what gives+ each window a finished predecessor to pin its prefix to (``run_spatial_epilogue``). Per window the+ driver rebases image conditionings, filters the keyframe bag and the full-res slots, slices the+ frozen stage-1 audio, and crops the IC-LoRA reference.Wrap the *model*, not the builder: a wrapping builder hides ``StreamingModelBuilder`` from- ``_is_streaming``, so ``--offload`` would skip the streaming teardown. Temporal tiles are cut on the last round's window seams,- which makes their masks rectangular (lead-in denoised for context, then dropped; the earlier tile- keeps the seam cell), so time windows never blend into each other; 2x2 spatial tiles use 12 latent- cells of blended overlap.+ ``_is_streaming``, so ``--offload`` would skip the streaming teardown. Temporal windows are cut on the last round's+ window seams and their lead-in is pinned to the previous window, so time windows never blend into+ each other; spatial tiles blend.``height``/``width`` are always the **final** output; ``2`` requires they divide 128.Three invariants worth knowing before touching the temporal rounds:- - **Stitch handover is exactly at the shared keyframe.** A tile's local latent 0 is an *image*- latent (1 pixel frame) and local latent 1 was denoised against it; neither may be spliced into- the mid-canvas stream. The earlier tile keeps through its trailing seam latent and the later tile- resumes strictly after the KF (``drop_latent_prefix`` covers lead-in + shared seam). Handing over- *before* the KF loses the synchronization point and shows as a jump just before the seam.- - **Conditioning fps snaps to 60 above 30** (``_conditioning_fps``), independently of playback fps.+ - **A non-first tile is a clip, not a slice, and its prefix is pinned.** It begins on the plane at+ the last keyframe position before its seam: cell 0 *is* that plane, cells+ ``1 .. (seam - keyframe)/scale`` are the video between them, and the tile resumes on the cell+ after the seam. The arithmetic closes -- cell ``k`` covers+ ``keyframe + scale*(k-1) + 1 ... keyframe + scale*k`` -- so the last pinned cell ends exactly+ *on* the seam and the seam keyframe needs no conditioning of its own: it is absorbed there.+ This matters because a tile is denoised as its own clip, whose cell 0 the model reads as a+ single pixel frame (causal convention); starting on a mid-canvas 8-frame cell put content and+ shape in disagreement and ran RoPE time 7 frames ahead of the canvas. Starting on a real+ one-frame plane makes the tile look like an i2v clip, which is in distribution.+ The whole prefix is pinned with ``VideoConditionByLatentIndex(strength=1.0)`` -- the plane, then+ the previous tile's *finished output* for those cells -- so ``denoise_mask`` is 0 there and+ ``lerp(clean, noised, mask)`` leaves them equal to it at every step (the mechanism A2Vid uses to+ freeze audio). The tiles are made to agree rather than told about the same frame and expected+ to. Keyframe conditionings before the resume point are dropped: the pinned cells hold this+ stage's content while a plane there holds an earlier stage's, and two contents for one moment is+ worse than none. Because the prefix follows plane positions rather than a cell count,+ ``split_at_seams`` takes **no overlap**: kept runs are disjoint and tile the canvas exactly once+ (``tile_prefix``).+ - **Conditioning fps snaps to 60 above 30** (``conditioning_fps``), independently of playback fps.RoPE time is ``pixel_frame / fps``, so a 48 or 120 fps time base is outside the traineddistribution and the model can no longer lay out the 8 pixel frames inside a latent -- itdecodes as a motion spike at each 8-frame latent border followed by a stall. 24 fps plus onetemporal upsample still ships 48 fps; only the transformer uses 60. Decode/encode use playback fps.- Audio duration is ``frames / fps`` too, so stages 1 and 2 pass ``audio_fps=frame_rate`` -- otherwise- a 48 fps run would ship 121/60 s of sound against a 121/48 s picture.+ Audio duration is ``frames / fps`` too, so stages 1 and 2 size the audio latent with+ ``create_initial_audio_latent(video_latent, fps=frame_rate, video_scale_factors=...)`` -- otherwise a 48 fps run would ship 121/60 s of+ sound against a 121/48 s picture.- **Image conditioning is tile-local.** ``frame_idx`` is a pixel index on the canvas the callerrequested; each temporal round maps it to ``frame_idx * 2**round`` before the window test.After re-basing, ``frame_idx=0`` means the *tile's* first frame, so only images that fall@@ -146,21 +195,19 @@ Guided denoisers batch all guidance passes into a **single transformer call**: s``--temporal-upscalings``, ``--spatial-upscalings``.No ``--num-generated-keyframes``.- Returns ``PipelineOutput`` (same type as the other video pipelines): ``video``, ``audio``,- ``num_frames``, ``tiling_config``, ``keyframes``, ``video_latent``. Prefer attribute access.- ``video`` is decoded with ``decode_video(keyframes=)`` when slots exist. Re-decode needs the- latent and the keyframes together (both optional fields; DFR fills them).- ``keyframes.pixel_frame_indices`` are on the- **final** (post-round) pixel grid, and keyframes landing past the tail trim are dropped rather- than shipped pointing off-canvas. Other pipelines fill ``keyframes`` only when they produced- generated slots already at final output resolution; ``video_latent`` may be ``None`` when the- pipeline does not retain the latent for re-decode.+ Returns ``PipelineOutput``: ``video``, ``audio``, ``num_frames``, ``tiling_config``.+ ``video`` is decoded with ``decode_video(keyframes=)`` using the carry-forward slot planes+ (plain decode only if none survive the final trim).+- **HDR IC-LoRA**: One-stage ACEScct SDR-to-HDR. IC-LoRA `VideoConditionByReferenceLatent` on the VAE-encoded SDR clip; denoise is `DISTILLED_SIGMA_VALUES` (8 Euler steps) with `SimpleDenoiser`. Output is ACEScct `[0, 1]` FHWC plus an EXR sidecar dir (`--exr-colorspace`, default ACEScg). CLI default is `HDRKeyframeConfig` (opt out with `--no-keyframes`); the Python API stays opt-in (`keyframes=None`). A config adds `resolve_canvas` x8 seams, with **every** seam taking both roles: a generated HDR slot and, at the same position, a `VideoConditionByKeyframeIndex` SDR guide (strength 0.95, 1-frame VAE encode), then keyframe-aware DiffVAE decode. A slot per seam matches `dfr_pipeline` (it passes the whole `resolve_canvas` list to `VideoGeneratedKeyframeSlots`); the co-located SDR guide is ours, as DFR's `VideoConditionByKeyframeIndex` guides are round-to-round carry keyframes with fresh slots at segment midpoints. The earlier every-other-seam split is where this pipeline's seam artifacts showed up; pairing the roles costs a full latent frame of tokens per seam instead of per other seam. When using the DiffVAE decode with keyframes the decode VAE must carry a non-zero `decoder.type_emb` (`--video-vae-path .../ltx-2.5-video-vae-bf16.safetensors`); the plain distilled monolith has no such key, the loader synthesizes zeros, and the entire keyframe path then no-ops — clean run, plausible output, keyframes ignored, and nothing checks. Path flags come from the shared `add_model_args`, with the text-encoder, audio-VAE and duration-head components switched off — leaving `--gemma-root` undeclared is what lets a monolith run without a Gemma dir (see `model_paths_from_namespace`).## Image conditioning helpers (`utils/helpers.py`)- `combined_image_conditionings()` -- images with `frame_idx==0` replace latent (`VideoConditionByLatentIndex`), others guide (`VideoConditionByKeyframeIndex`).- `image_conditionings_by_adding_guiding_latent()` -- all images become keyframe guidance regardless of `frame_idx`.- `evenly_spaced_keyframe_positions()` -- evenly spaced **interior** positions (both endpoints excluded).+- `generated_keyframe_conditionings()` / `resolve_generated_keyframes()` -- turn the pipeline-level ``generated_keyframes`` arg into ``VideoGeneratedKeyframeSlots`` or pixel indices.+- `decode_keyframes_from_slots()` -- build ``DecodeKeyframes`` from carried slot latents, dropping planes past a trimmed canvas.+- `assert_generated_keyframes_request()` / `assert_stage_supports_generated_keyframes()` -- preamble validation before any model is built (capability gate + ``decode_with_keyframes`` requires slots).## Generated keyframes@@ -170,27 +217,38 @@ interior frame positions so the model generates extra frames there, relaxing thecompression at those positions. Slots may optionally carry ``initial_keyframes`` latent seeds(written into the appended ``latent`` tokens; ``denoise_mask=1`` still applies).-- **Where**: first stage only, on `TI2VidOneStagePipeline`, `TI2VidTwoStagesPipeline`,+- **Where**: stage 1 on `TI2VidOneStagePipeline`, `TI2VidTwoStagesPipeline`,`TI2VidTwoStagesHQPipeline`, `DistilledPipeline`, `DFRPipeline`, and the three- `*_mgpu` runners. Stage 2 never gets *slots* on TI2Vid/Distilled (effect is baked into the- stage-1 latent). `DFRPipeline` is the exception: stage 2 re-attaches **seeded** slots- (spatially upsampled stage-1 KF latents) and optional tiled temporal rounds attach- mid-segment slots per tile.+ `*_mgpu` runners (`distilled_mgpu`, `ti2vid_two_stages_mgpu`, `ti2vid_two_stages_hq_mgpu`).+ ``decode_with_keyframes`` is supported on the four single-GPU pipelines above except DFR, plus+ those MGPU runners. One-stage runs slots and decode at final resolution (no stage-2 re-attach).+ Chunked two-stage pipelines keep **seeded** slots as conditioning at every stage, upsampling+ stage-1 slot latents with ``self.upsampler`` on the full ``(B, C, K, H, W)`` stack (same as DFR),+ then refining at full res. ``decode_with_keyframes`` controls only whether those final planes+ anchor video decode. `DFRPipeline` always+ re-attaches seeded slots in stage 2 and optional tiled temporal+ rounds attach mid-segment slots per tile; it always keyframe-decodes internally.+ `HDRICLoraPipeline` also supports generated slots (CLI on by default, `--no-keyframes` to disable).- **API**: `generated_keyframes: int | Sequence[int] = 0` on `__call__` for TI2Vid/Distilled(an `int` requests evenly spaced **interior** keyframes; a sequence gives explicit indices).- CLI: `--num-generated-keyframes` via `add_generated_keyframes_arg`. `DFRPipeline` always uses- the x8-border segment grid from `dfr_layout.resolve_canvas` and does **not** expose that arg;- it adds `--detailing-lora` (required),- `--temporal-upsampler-path`, `--temporal-upscalings`.-- **Validation**: `DiffusionStage.supports_generated_keyframes` reads the checkpoint config, and- `__call__` raises if slots are requested without it -- each keyframe costs a full latent frame of- tokens, so silently degrading would waste 16-31% of the token budget.+ CLI: `--num-generated-keyframes` via `add_generated_keyframes_arg`. Pass+ ``decode_with_keyframes=True`` (CLI: ``--decode-with-keyframes`` via ``add_keyframe_decode_arg``)+ to decode through the keyframe-aware DiffVAE path using those slots as anchors.+ `DFRPipeline` derives slot positions from ``dfr_helpers.layout.resolve_canvas``, does **not** expose+ either flag, and calls ``assert_stage_supports_generated_keyframes`` unconditionally; CLI adds+ `--detailing-lora` (required), `--temporal-upsampler-path`, `--temporal-upscalings`.+ `HDRICLoraPipeline` uses `keyframes: HDRKeyframeConfig | None = None` (CLI default on, `--no-keyframes`, `--keyframe-strength`);+ seam indices come from `dfr_seam_roles`, not `--num-generated-keyframes`.+- **Validation**: ``DiffusionStage.supports_generated_keyframes`` reads the checkpoint config.+ Pipelines call ``assert_generated_keyframes_request(decode_with_keyframes, generated_keyframes, stage)``+ (or ``assert_stage_supports_generated_keyframes`` on DFR) in the ``__call__`` preamble, before+ the text encoder loads. ``DiffusionStage.__call__`` re-checks via ``_assert_supports_conditionings``.+ Each keyframe costs a full latent frame of tokens, so silently degrading would waste 16-31% of+ the token budget.- **Cost**: one latent frame of tokens per keyframe, yielding 1 pixel frame instead of 8. At512x768/241f, 5 keyframes is +16% tokens (~1.35x attention); at 1088x1920/121f it is +31% (~1.72x).-- **On ``PipelineOutput``**: ``result.keyframes`` is filled only when those slots already sit at- final output resolution (DFR after upsample/rounds; TI2Vid one-stage when requested). Two-stage- / distilled leave it ``None`` -- stage-1 half-res leftovers are not shipped. ``result.video_latent``- is the tensor passed to the video decoder when retained, otherwise ``None``.+- **On ``PipelineOutput``**: ``video`` already reflects whether the pipeline chose a+ keyframe-aware decode. Slot latents are not shipped on the return type.- **Reading the keyframes back**: `LatentState.generated_keyframes` (`(B, C, K, H, W)`), extracted by`clear_conditioning` using the `generated_keyframe_layout` recorded on the state -- exact, notpositional slicing. From outside a pipeline, substitute `RecordingDiffusionStage` fordiff --git a/packages/ltx-pipelines/docs/conditioning.md b/packages/ltx-pipelines/docs/conditioning.mdindex 7b63d0a..5cb68b2 100644--- a/packages/ltx-pipelines/docs/conditioning.md+++ b/packages/ltx-pipelines/docs/conditioning.md@@ -52,9 +52,11 @@ and invents new ones per tile during temporal rounds.**Usage.** Pass `generated_keyframes` to `__call__`: an `int` requests that many evenly spacedinterior keyframes (both endpoints excluded), a sequence gives explicit frame indices. On the CLI the-flag is `--num-generated-keyframes N` (default `0`, off). It is opt-in per pipeline rather than a-shared flag, so only the CLIs listed above advertise it — `DFRPipeline` derives its own slot-positions and does not accept it.+flag is `--num-generated-keyframes N` (default `0`, off). Pass `decode_with_keyframes=True` (CLI:+`--decode-with-keyframes`) to decode through the keyframe-aware DiffVAE path using those slots as+anchors. It is opt-in per pipeline rather than a shared flag, so only the CLIs listed above+advertise both flags -- `DFRPipeline` derives its own slot positions, always keyframe-decodes, and+does not accept either flag.**Reading the keyframes back.** Generated keyframes land in `LatentState.generated_keyframes` withshape `(B, C, K, H, W)`. Decode each one as a standalone single-frame clip: a K-frame causal decodediff --git a/packages/ltx-pipelines/docs/hdr.md b/packages/ltx-pipelines/docs/hdr.mdindex 810ffc8..a1f3e1c 100644--- a/packages/ltx-pipelines/docs/hdr.md+++ b/packages/ltx-pipelines/docs/hdr.md@@ -2,13 +2,13 @@Native **`--hdr`** support: pass EXR stills / EXR-frame folders into the standard generation and editing pipelines. Decode writes half-float EXR frames plus a BT.2020/HLG master.-For the separate video-to-video HDR IC-LoRA path (LogC3 inverse decode), see [HDRICLoraPipeline](pipelines.md#9-hdriclorapipeline).+For the separate video-to-video HDR IC-LoRA path (ACEScct SDR→HDR, optional DFR-style seam keyframes), see [HDRICLoraPipeline](pipelines.md#9-hdriclorapipeline).## Native HDR (`--hdr`)### Colour spaces-CLI flag: `--hdr {SRGB_LINEAR,ACESCG,ACESCCT}` (enum [`HDRColorSpace`](../src/ltx_pipelines/utils/media_io/color_config.py)).+CLI flag: `--hdr {SRGB_LINEAR,ACESCG,ACESCCT}` (enum [`EXRColorSpace`](../src/ltx_pipelines/utils/media_io/color_config.py)).| Value | Source meaning | Load behaviour || ----- | -------------- | -------------- |@@ -76,16 +76,16 @@ uv run python -m ltx_pipelines.retake \### Python API```python-from ltx_pipelines.utils.media_io import HDRColorSpace, encode_video, resolve_hdr_color_space, vae_dtype_for_hdr+from ltx_pipelines.utils.media_io import EXRColorSpace, encode_video, resolve_hdr_color_space, vae_dtype_for_hdr-hdr = resolve_hdr_color_space(images=images, video_paths=[], hdr=HDRColorSpace.SRGB_LINEAR)+hdr = resolve_hdr_color_space(images=images, video_paths=[], hdr=EXRColorSpace.SRGB_LINEAR)vae_dtype = vae_dtype_for_hdr(hdr, default=torch.bfloat16)# After pipeline decode (iterator of [F,H,W,C] chunks):encode_video(video_chunks, fps, audio, output_path, num_chunks, color_space=hdr)```-Pipelines that accept image / video conditioning expose an optional `color_space: HDRColorSpace | None` on `__call__` (wired from CLI `--hdr`).+Pipelines that accept image / video conditioning expose an optional `color_space: EXRColorSpace | None` on `__call__` (wired from CLI `--hdr`).## Constraints (summary)@@ -94,3 +94,4 @@ Pipelines that accept image / video conditioning expose an optional `color_space- Retake: `--frame-rate` required for EXR folders, forbidden for video files.- Dub-It: no `--hdr`; reference must be an SDR video file (not EXR).- DiffVAE / NATTEN: HDR decode still uses the configured VAE; install the `natten` extra when using a diffusion video VAE (same as SDR).+- Keyframe-aware decode (the IC-LoRA path's default; disable with `--no-keyframes`) needs a VAE whose `decoder.type_emb` is non-zero. A checkpoint without it loads and decodes fine — zeros are synthesized — but the keyframe stream becomes a silent no-op. See [HDRICLoraPipeline](pipelines.md#9-hdriclorapipeline).diff --git a/packages/ltx-pipelines/docs/installation.md b/packages/ltx-pipelines/docs/installation.mdindex 7a3a182..44e1005 100644--- a/packages/ltx-pipelines/docs/installation.md+++ b/packages/ltx-pipelines/docs/installation.md@@ -80,7 +80,7 @@ what pipeline constructors take.- `ltx_pipelines.keyframe_interpolation` - Keyframe interpolation. ([docs](pipelines.md#6-keyframeinterpolationpipeline), [source](../src/ltx_pipelines/keyframe_interpolation.py))- `ltx_pipelines.a2vid_two_stage` - Audio-to-video generation conditioned on an input audio. ([docs](pipelines.md#7-a2vidpipelinetwostage), [source](../src/ltx_pipelines/a2vid_two_stage.py))- `ltx_pipelines.retake` - Regenerate a time region of an existing video. ([docs](pipelines.md#8-retakepipeline), [source](../src/ltx_pipelines/retake.py))-- `ltx_pipelines.hdr_ic_lora` - Video-to-video with HDR output (linear float via LogC3 inverse decode). ([docs](pipelines.md#9-hdriclorapipeline), [source](../src/ltx_pipelines/hdr_ic_lora.py))+- `ltx_pipelines.hdr_ic_lora` - Video-to-video SDR→HDR: writes a BT.2020/HLG master plus an EXR sequence (`--exr-colorspace`, default ACEScg). ([docs](pipelines.md#9-hdriclorapipeline), [source](../src/ltx_pipelines/hdr_ic_lora.py))- `ltx_pipelines.dubit` - Dub-It / re-voicing with IC-LoRA and audio reference conditioning. ([docs](pipelines.md#10-dubitpipeline), [source](../src/ltx_pipelines/dubit.py))Use `--help` with any pipeline module to see all available options and parameters.@@ -101,3 +101,4 @@ These flags are shared across the pipeline CLIs (they come from a common base pa- `--hdr {SRGB_LINEAR,ACESCG,ACESCCT}` - on pipelines that accept image / video conditioning (not Dub-It, HDR IC-LoRA, or T2A): declare the source colour space for EXR stills / EXR-frame folders. Required whenever any EXR input is passed; omit for SDR. With `--hdr` set, encode writes half EXR frames plus a BT.2020/HLG master. See [HDR Support](hdr.md).- `--video-vae-path <path>` - video VAE `.safetensors` (encoder + decoder). Split: the `vae/` component. Monolith: optional override of the VAE bundled in `--checkpoint-path`/`--distilled-checkpoint-path`. When it is a diffusion VAE, decoding builds a `DiffusionVideoDecoder`, which for best performance requires the `natten` extra. See [Optimization Tips](optimization.md#diffusion-vae-decoder).- `--diffvae-optimization {chunked_eager,chunked_compile,combined_compile,blackwell_dsl}` - DiffVAE decode preset (ignored for convolutional VAEs). `blackwell_dsl` is the fast path on datacenter Blackwell.+- `--chunk-pixel-frames` / `--chunk-carry-frames` - on `distilled`, `ti2vid_two_stages` (and their MGPU runners), `a2vid_two_stage`, and `dubit`: pass either flag to generate in windows instead of one full-clip chunk. Defaults are 97 pixel frames and 25-pixel carry when the other is set. Pixel frame counts must be on the causal grid (`8k+1`). Off-grid `--num-frames` is floored to the causal grid.diff --git a/packages/ltx-pipelines/docs/multigpu/sequence-parallel.md b/packages/ltx-pipelines/docs/multigpu/sequence-parallel.mdindex 95f2a5f..4789323 100644--- a/packages/ltx-pipelines/docs/multigpu/sequence-parallel.md+++ b/packages/ltx-pipelines/docs/multigpu/sequence-parallel.md@@ -56,9 +56,9 @@ attn_mgr = AttentionManager()```-Owns the all2all buffers (sized `ceil(max_tokens / world_size)` tokens per rank) and, per step,-`set_seqlen_all2all(...)` updates the per-rank token counts. `num_heads` must be-divisible by `world_size`.+Owns the all2all buffers, sized `ceil(max_tokens / world_size)` tokens per rank. All2All operations+derive their uniform per-rank token counts from the input tensors; callers pad before sharding.+`num_heads` must be divisible by `world_size`.### `SequenceParallelBuilder`diff --git a/packages/ltx-pipelines/docs/optimization.md b/packages/ltx-pipelines/docs/optimization.mdindex 525b6db..c11891c 100644--- a/packages/ltx-pipelines/docs/optimization.md+++ b/packages/ltx-pipelines/docs/optimization.md@@ -312,12 +312,11 @@ Instead of the standard Euler denoising loop, you can use gradient estimation fofrom ltx_pipelines.utils import gradient_estimating_euler_denoising_loop# Use gradient estimation denoising loop-def denoising_loop(sigmas, video_state, audio_state, stepper):+def denoising_loop(sigmas, video_state, audio_state):return gradient_estimating_euler_denoising_loop(sigmas=sigmas,video_state=video_state,audio_state=audio_state,- stepper=stepper,transformer=transformer,denoiser=denoiser,ge_gamma=2.0, # Gradient estimation coefficientdiff --git a/packages/ltx-pipelines/docs/pipeline-selection.md b/packages/ltx-pipelines/docs/pipeline-selection.mdindex 0c8584f..9ccd3b1 100644--- a/packages/ltx-pipelines/docs/pipeline-selection.md+++ b/packages/ltx-pipelines/docs/pipeline-selection.md@@ -13,7 +13,7 @@ Do you need HDR / EXR I/O?├─ YES → Do you have EXR stills or EXR-frame folders for a standard pipeline?│ ├─ YES → Use Distilled / TI2V / Retake / IC-LoRA with `--hdr {SRGB_LINEAR,ACESCG,ACESCCT}`│ │ (see [HDR Support](hdr.md); EXR + BT.2020/HLG output)-│ └─ NO → Use HDRICLoraPipeline (video-to-video with HDR IC-LoRA / LogC3 decode)+│ └─ NO → Use HDRICLoraPipeline (SDR video → ACEScct HDR; HLG master + EXR)│Do you need to condition on existing images/videos?├─ YES → Do you have reference videos for video-to-video?@@ -50,7 +50,7 @@ Do you need to condition on existing images/videos?| [**KeyframeInterpolationPipeline**](pipelines.md#6-keyframeinterpolationpipeline) | 2 | ✅ | ✅ | Keyframes | Animation, interpolation || [**A2VidPipelineTwoStage**](pipelines.md#7-a2vidpipelinetwostage) | 2 | ✅ | ✅ | Audio + Image | Audio-driven video generation || [**RetakePipeline**](pipelines.md#8-retakepipeline) | 1 | ✅ | ❌ | Source Video | Regenerating a time region of a video |-| [**HDRICLoraPipeline**](pipelines.md#9-hdriclorapipeline) | 2 | ❌ | ✅ | Video | HDR IC-LoRA video-to-video (linear float / EXR); see also native [`--hdr`](hdr.md) |+| [**HDRICLoraPipeline**](pipelines.md#9-hdriclorapipeline) | 1 | ❌ | ❌ | Video | SDR-to-HDR with an HDR IC-LoRA (HLG master + EXR via `--exr-colorspace`); see also native [`--hdr`](hdr.md) || [**DubItPipeline**](pipelines.md#10-dubitpipeline) | 2 | ✅ | ✅ | Video + Audio | Dub-It with audio ref conditioning || [**T2AOneStagePipeline**](pipelines.md#11-t2aonestagepipeline) | 1 | Audio only | ❌ | None (text) | Text-to-audio (audio-only output, no video) |diff --git a/packages/ltx-pipelines/docs/pipelines.md b/packages/ltx-pipelines/docs/pipelines.mdindex d6739f4..5ca9213 100644--- a/packages/ltx-pipelines/docs/pipelines.md+++ b/packages/ltx-pipelines/docs/pipelines.md@@ -12,6 +12,8 @@ Full reference for each pipeline. See the [Pipeline Selection Guide](pipeline-seTwo-stage generation: Stage 1 generates low-resolution video with [multimodal guidance](multimodal-guidance.md), Stage 2 upsamples to 2x resolution with distilled LoRA refinement. Supports image conditioning. Slower than DistilledPipeline; for production quality use [`DFRPipeline`](#12-dfrpipeline).+**Extra CLI arguments:** `--chunk-pixel-frames` (default 97) and/or `--chunk-carry-frames` (default 25) enable long-video windowing; `--chunk-blend-frames` controls the decoded seam crossfade (default: full carry, `0` for a hard cut). Also on `ltx_pipelines.ti2vid_two_stages_mgpu`.+**Use when:** You want CFG/STG-guided two-stage text/image-to-video, not the DFR detailing path.---@@ -48,7 +50,9 @@ Single-stage generation (no upsampling) with [multimodal guidance](multimodal-gu**Source**: [`src/ltx_pipelines/distilled.py`](../src/ltx_pipelines/distilled.py)-Two-stage generation with 8 predefined sigmas (8 steps in stage 1, 4 steps in stage 2). No guidance required. Fastest inference among all pipelines. Supports image conditioning. Requires spatial upsampler.+Two-stage generation with 8 predefined sigmas (8 steps in stage 1, 4 steps in stage 2). Each stage samples with Euler ancestral on an LTX-2.5+ checkpoint and with deterministic Euler below that. No guidance required. Fastest inference among all pipelines. Supports image conditioning. Requires spatial upsampler.++**Extra CLI arguments:** `--chunk-pixel-frames` (default 97) and/or `--chunk-carry-frames` (default 25) enable long-video windowing; `--chunk-blend-frames` controls the decoded seam crossfade (default: full carry, `0` for a hard cut). Also on `ltx_pipelines.distilled_mgpu`.**Use when:** Fastest inference is critical, batch processing many videos, or when you have a distilled model checkpoint.@@ -60,9 +64,52 @@ Two-stage generation with 8 predefined sigmas (8 steps in stage 1, 4 steps in st**Source**: [`src/ltx_pipelines/ic_lora.py`](../src/ltx_pipelines/ic_lora.py)-Two-stage generation with IC-LoRA support. Can condition on reference videos (video-to-video) or images at specific frames. CFG guidance in stage 1, upsampling in stage 2. Requires IC-LoRA trained model.+The **CLI is always two stages** on a distilled checkpoint. Stage 1 generates at half of `--height` / `--width` with the IC-LoRA and `--video-conditioning` reference. Stage 2 upsamples 2x and refines. `--skip-stage-2` drops stage 2 for a half-res preview.++Transformer tiling is opt-in and is **not extra stages**. Without `--tile`, 1080-class sizes (for example 1088x1920) stay the untiled recipe even if they are larger than the default tile window. Raising `--height` / `--width` alone does not tile; 4K without `--tile` may OOM (the CLI re-raises that error with `--tile` / tile size and `--offload`).++**`--stage-2-ic-lora`.** Default stage 2 runs the bare checkpoint (the upsampled canvas can recover structure when it is **not** tiled). Pass this flag to keep the IC-LoRA and reference on stage 2 as well. Required when `--tile` makes stage 2 larger than the tile window; each tile is a crop at normalized positions and cannot follow the driving video without the reference.++**`--tile`.** Same two stages, each transformer step evaluated over a fixed window (default `--tile-height 1024` / `--tile-width 1536`, matching stock distilled `--height` / `--width`). An axis smaller than the window is left as one tile, so stage 1 often stays untiled while stage 2 tiles. Override the window with `--tile-height` / `--tile-width` (at least 64, divisible by 32). Those size flags require `--tile`.++**Python.** `ICLoraPipeline(stages=...)` takes a sequence of `ICLoraStageConfig`. Consecutive stages must keep the same `resolution_divisor` or drop by exactly 2x, and the last stage must be divisor 1. That is how you run more than two stages (same-res repeats or `4 -> 2 -> 1`). The CLI does not expose that ladder.++**Note:** Distilled checkpoint only. Pass the IC-LoRA with `--lora`.-**Note:** ICLoraPipeline can only be used with a distilled model.+```bash+# 1080-class, today's two-stage recipe (untiled; stage 2 bare checkpoint)+python -m ltx_pipelines.ic_lora \+ --distilled-checkpoint-path path/to/distilled.safetensors \+ --spatial-upsampler-path path/to/upsampler.safetensors \+ --gemma-root path/to/gemma \+ --lora path/to/ic-lora.safetensors \+ --video-conditioning path/to/guide.mp4 1.0 \+ --prompt "..." \+ --height 1088 --width 1920 \+ --output-path out.mp4++# Same size, keep the guide on stage 2, still untiled+python -m ltx_pipelines.ic_lora \+ ... \+ --height 1088 --width 1920 --stage-2-ic-lora \+ --output-path out.mp4++# 4K: two stages, default 1024x1536 transformer windows+python -m ltx_pipelines.ic_lora \+ ... \+ --height 3840 --width 2176 --tile --stage-2-ic-lora \+ --output-path out.mp4++# 4K with a smaller window+python -m ltx_pipelines.ic_lora \+ ... \+ --height 3840 --width 2176 --tile --tile-height 576 --tile-width 1024 --stage-2-ic-lora \+ --output-path out.mp4+```++**Extra CLI arguments:** `--video-conditioning` (required), `--conditioning-attention-mask`, `--skip-stage-2`, `--stage-2-ic-lora`, `--tile`, `--tile-height`, `--tile-width`, `--chunked` or `--chunk-pixel-frames` / `--chunk-carry-frames` for long clips, and `--chunk-blend-frames` for decoded seam crossfade length (same windowing as Distilled and Dub-It).++**Python.** ``stream_chunks()`` returns ``(Iterator[DecodedChunk], num_frames, tiling_config)``. Pass ``chunk_config`` to ``__call__`` or ``stream_chunks()``; ``chunk_config=None`` is one window over the snapped clip (today's one-shot path). Temporal chunks are the outer loop; each stage still runs per-step spatial tiling when ``--tile`` or ``ICLoraStageConfig.tiling`` is set, so runtime scales roughly with ``temporal_chunks x spatial_tiles x denoising_steps``.**Use when:** Video-to-video transformations, image-to-video with strong control, or when you have reference videos to guide generation.@@ -88,7 +135,7 @@ Two-stage generation with keyframe interpolation. Uses guiding latents (additiveTwo-stage audio-to-video generation. Stage 1 generates video at half resolution with audio conditioning (video-only denoising with the audio frozen), then Stage 2 upsamples by 2x and refines the video while keeping the audio fixed, using a distilled LoRA. The input audio is encoded via the audio VAE and used as the initial audio latent, but the original audio waveform is passed through and returned in the output to preserve fidelity. Supports image conditioning and prompt enhancement.-**Extra CLI arguments:** `--audio-path` (required), `--audio-start-time`, `--audio-max-duration`. `--num-frames` and `--audio-max-duration` are mutually exclusive. With `--audio-max-duration`, video length is derived from the effective clip (`min(--audio-max-duration, remaining audio after --audio-start-time)`) at `--frame-rate`, snapped to the VAE temporal grid (`8k+1`). With `--num-frames` (or neither), audio is clipped to `--num-frames / --frame-rate`.+**Extra CLI arguments:** `--audio-path` (required), `--audio-start-time`, `--audio-max-duration`, `--chunk-pixel-frames` / `--chunk-carry-frames`, and `--chunk-blend-frames`. `--num-frames` and `--audio-max-duration` are mutually exclusive. With `--audio-max-duration`, video length is derived from the effective clip (`min(--audio-max-duration, remaining audio after --audio-start-time)`) at `--frame-rate`, snapped to the VAE temporal grid (`8k+1`). With `--num-frames` (or neither), audio is clipped to `--num-frames / --frame-rate`.**Use when:** You have an audio clip and want to generate a matching video, audio-reactive video generation, or music visualization.@@ -116,13 +163,17 @@ Single-stage generation that encodes the source video and audio into latents, ap**Source**: [`src/ltx_pipelines/hdr_ic_lora.py`](../src/ltx_pipelines/hdr_ic_lora.py)-Two-stage video-to-video on the distilled model with an HDR IC-LoRA. Decoded latents pass through an HDR inverse transform (ARRI LogC3) to produce a **linear HDR float** tensor `[f, h, w, c]`. Video-only (audio skipped). Text embeddings are pre-computed externally and loaded from a `.safetensors` file. Tonemapping and EXR saving are the caller's responsibility. LoRA and embeddings: [`Lightricks/LTX-2.3-22b-IC-LoRA-HDR`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-HDR).+One-stage ACEScct SDR-to-HDR on a distilled model with an HDR IC-LoRA. The source is converted to ACEScct (`--input-colorspace`), VAE-encoded, and used as the IC-LoRA reference. Denoising is the distilled 8-step Euler schedule over the whole clip. Text embeddings are loaded from a `.safetensors` file. Output is a 10-bit BT.2020/HLG master plus an EXR sequence beside it (`--exr-colorspace`, default ACEScg).-This path is separate from native EXR/`--hdr` support on the other pipelines (see [HDR Support](hdr.md)). Prefer `--hdr` + distilled / retake / TI2V when you already have EXR plates and want first-class EXR+HLG I/O without an HDR IC-LoRA.+Seam keyframes are on by default. Pass `--no-keyframes` for plain IC-LoRA. When keyframes are on, pass `--video-vae-path` to a keyframe-trained video VAE.-**Extra CLI arguments:** `--input` (mp4 or directory, required), `--output-dir` (required), `--hdr-lora` (required), `--text-embeddings` (pre-computed `.safetensors`, required), `--num-frames`, `--spatial-tile` (tiled VAE decode tile size; reduce on lower-VRAM GPUs), `--skip-mp4` (EXR only, no H.264 preview), `--exr-half` (float16 EXR), `--high-quality` (generates 2x frames internally for smoother output, ~2x slower), `--offload {none,cpu,disk}` (weight offloading; disables FP8 quantization when not `none`).+Native EXR `--hdr` conditioning on the other pipelines is a separate path; see [HDR Support](hdr.md).-**Use when:** You need linear HDR float output for EXR export, color grading, or custom tonemapping workflows.+**Extra CLI arguments:** `--input` (required), `--output-path` (required), `--exr-colorspace` (`acescg` / `acescct` / `srgb_linear`; default `acescg`), `--hdr-lora` (required), `--text-embeddings` (required), `--distilled-checkpoint-path` or `--transformer-path`, `--video-vae-path` (needed with keyframes, the default), `--input-colorspace`, `--frame-rate` (EXR directories only), `--seed`, `--high-quality`, `--offload`, `--no-quantization`, `--diffvae-optimization`, `--no-keyframes`, `--keyframe-strength`.++**Constraints:** Source frame count must be 8k+1. `--frame-rate` is required for EXR folders and must not be set for MP4/MOV.++**Use when:** You need ACEScct HDR from an SDR video (or linear Rec.709 / ACEScg / ACEScct EXR folder) for HLG masters and EXR grading.---@@ -134,6 +185,8 @@ This path is separate from native EXR/`--hdr` support on the other pipelines (seUses IC-LoRA on a **distilled** checkpoint with a **single** Dub-It IC-LoRA applied in **both** stages. The reference clip provides video and audio reference tokens whose VAE latents are appended to the target audio sequence as frozen reference tokens. The frame count and frame rate are derived from the reference video (frame count is silently snapped to the nearest `8k+1`), so the CLI does not accept `--num-frames` or `--frame-rate`. Required: `--reference-video`. Optional: `--reference-strength`. LoRA: [`Lightricks/LTX-2.3-22b-IC-LoRA-DubIt`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-DubIt).+**Extra CLI arguments:** `--chunk-pixel-frames` / `--chunk-carry-frames` and `--chunk-blend-frames`. Frame count still comes from the reference video.+**Note:** Requires a distilled model checkpoint and one Dub-It IC-LoRA (`--lora` exactly once).**Use when:** Dubbing, rephrasing with matched lips and speaker identity.@@ -158,15 +211,15 @@ Single-stage, **audio-only** generation: the video branch is absent (`video=None**Best for:** Production-quality text/image-to-video — generating at half resolution with extra generated keyframes, then re-rendering at full resolution with a spatial detailing LoRA, optionally densifying time by 2x or 4x.-**Source**: [`src/ltx_pipelines/dfr_pipeline.py`](../src/ltx_pipelines/dfr_pipeline.py)+**Source**: [`src/ltx_pipelines/dfr_pipeline.py`](../src/ltx_pipelines/dfr_pipeline.py). Stage functions live in [`dfr_stages.py`](../src/ltx_pipelines/dfr_stages.py) (`denoise_stage1`, `denoise_stage2`, `run_one_temporal_round`, `run_spatial_epilogue`); layout and pure helpers live under [`dfr_helpers/`](../src/ltx_pipelines/dfr_helpers/). Other adapters import the stage functions instead of wrapping `DFRPipeline`.-Diffusion Fidelity Rendering runs the distilled sigma schedule on a **distilled checkpoint** (the same transformer as DistilledPipeline). Stage 1 generates video **and [generated keyframe slots](conditioning.md#generated-keyframe-slots)** at half resolution, placing slots on an 8-frame-border segment grid; the half-resolution result is kept as a reference while video and keyframes are upsampled in latent space. Stage 2 re-denoises at full resolution with a 2x spatial detailing IC-LoRA, conditioned on the stage-1 reference.+Diffusion Fidelity Rendering runs the distilled sigma schedule on a **distilled checkpoint** (the same transformer as DistilledPipeline). Stage 1 generates video **and [generated keyframe slots](conditioning.md#generated-keyframe-slots)** at half resolution, placing slots on an 8-frame-border segment grid; the half-resolution result is kept as a reference while video and keyframes are upsampled in latent space. Stage 2 re-denoises at full resolution with a 2x spatial detailing IC-LoRA, conditioned on the stage-1 reference. Both stages and the spatial epilogue sample with Euler ancestral on an LTX-2.5+ checkpoint and with deterministic Euler below that.Audio comes from **stage 1**. Stage 2 still runs an audio pass, because the video branch needs the cross-modal attention, but nothing refines audio after stage 1.-**Temporal refinement (optional, default `0`).** `--temporal-upscalings {0,1,2}` adds rounds that each double the **playback** frame rate: the canvas is upsampled temporally, split into `2**round` tiles that meet at shared keyframes, given fresh mid-segment slots, and densified with ancestral Euler. Whatever padding the canvas needs internally, you always get `(num_frames - 1) * 2**rounds + 1` frames back. `--temporal-upsampler-path` is required when the count is greater than 0.+**Temporal refinement (optional, default `0`).** `--temporal-upscalings {0,1,2}` adds rounds that each double the **playback** frame rate: the canvas is upsampled temporally, split into `2**round` tiles, given fresh mid-segment slots, and densified with ancestral Euler. A non-first tile starts on the last keyframe plane before its seam; that prefix is pinned to the previous tile's output. Whatever padding the canvas needs internally, you always get `(num_frames - 1) * 2**rounds + 1` frames back. `--temporal-upsampler-path` is required when the count is greater than 0.-**Spatial epilogue (`--spatial-upscalings 2`).** Default `--spatial-upscalings` is `1`: stage 1 at `h/2`, stage 2 at the final `h×w`. With `2`, stage 1 is at `h/4` and stage 2 at `h/2`. The epilogue decodes each carry keyframe as its own latent, Lanczos-stretches the RGB x2, and encodes it again. Only the video latent is spatially upsampled. Time windows are seam-cut and 2x2-tiled (12 latent cells of overlap); the 3-step detailing schedule runs with those keyframes as strength-1 conditions, the previous-stage video as the IC-LoRA reference, and frozen stage-1 audio so video-audio cross-attention still has a stream. The pipeline still ships the original stage-1 audio. Spatial tiles blend after every Euler step. Detailing LoRA strength is fixed at 0.5. The same encoded keyframes are used for keyframe-aware DiffVAE decode.+**Spatial epilogue (`--spatial-upscalings 2`).** Default `--spatial-upscalings` is `1`: stage 1 at `h/2`, stage 2 at the final `h×w`. With `2`, stage 1 is at `h/4` and stage 2 at `h/2`. The epilogue decodes each carry keyframe as its own latent, Lanczos-stretches the RGB x2, and encodes it again. Only the video latent is spatially upsampled. Time windows run sequentially (pinned prefix handover) and are 4×4-tiled spatially (10 latent cells of overlap); the 3-step detailing schedule runs with those keyframes as strength-1 conditions, the previous-stage video as the IC-LoRA reference, and frozen stage-1 audio so video-audio cross-attention still has a stream. The pipeline still ships the original stage-1 audio. Spatial tiles blend after every Euler step. Detailing LoRA strength is fixed at 0.5. The same encoded keyframes are used for keyframe-aware DiffVAE decode.**Extra CLI arguments:** `--detailing-lora PATH [STRENGTH]` (required; strength is ignored and hardcoded to 0.5), `--spatial-upscalings {1,2}` (default `1`), `--temporal-upsampler-path` (required when `--temporal-upscalings` > 0), `--temporal-upscalings {0,1,2}` (default `0`). Unlike the other keyframe-capable pipelines, DFR does **not** take `--num-generated-keyframes` — it derives slot positions from its own segment grid. There is no `--distilled-lora`; the distilled weights are the checkpoint.diff --git a/packages/ltx-pipelines/pyproject.toml b/packages/ltx-pipelines/pyproject.tomlindex d9e2f75..39f67c3 100644--- a/packages/ltx-pipelines/pyproject.toml+++ b/packages/ltx-pipelines/pyproject.toml@@ -1,6 +1,6 @@[project]name = "ltx-pipelines"-version = "1.3.0"+version = "1.4.0"description = "Pipelines implementation for Lightricks' LTX-2 model"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/ltx-pipelines/src/ltx_pipelines/a2vid_two_stage.py b/packages/ltx-pipelines/src/ltx_pipelines/a2vid_two_stage.pyindex 1f5e995..4c88181 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/a2vid_two_stage.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/a2vid_two_stage.py@@ -1,5 +1,7 @@import argparseimport logging+from collections.abc import Iterator, Sequence+from dataclasses import dataclassimport torch@@ -7,6 +9,7 @@ from ltx_core.allocator_trim_strategy import AllocatorTrimStrategyfrom ltx_core.components.guiders import MultiModalGuider, MultiModalGuiderParamsfrom ltx_core.components.noisers import GaussianNoiserfrom ltx_core.components.schedulers import LTX2Scheduler+from ltx_core.conditioning import ConditioningItemfrom ltx_core.loader import LoraPathStrengthAndSDOpsfrom ltx_core.loader.registry import Registryfrom ltx_core.model.audio_vae import encode_audio as vae_encode_audio@@ -15,8 +18,29 @@ from ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, get_from ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicyfrom ltx_core.types import Audio, AudioLatentShape, VideoPixelShape+from ltx_pipelines.chunks import (+ Chunk,+ ChunkConfig,+ DecodedChunk,+ MakeVideoConditionings,+ decode_chunks,+ denoise_chunks,+ generate_uniform_chunks,+ pipeline_output_from_chunks,+ replace_chunks_audio,+ spatially_upsample_chunks,+ split_decoded_chunks,+)+from ltx_pipelines.chunks.conditionings import (+ assert_image_frames_in_clip,+ image_conditionings_for_chunk,+ images_for_chunk,+)from ltx_pipelines.utils.args import (- ImageConditioningInput,+ add_chunk_layout_args,+ add_generated_keyframes_arg,+ add_keyframe_decode_arg,+ chunk_config_from_args,default_2_stage_arg_parser,resolve_cli_params,)@@ -32,29 +56,52 @@ from ltx_pipelines.utils.constants import (STAGE_2_DISTILLED_SIGMAS,PipelineParams,)-from ltx_pipelines.utils.denoisers import GuidedDenoiser, SimpleDenoiser+from ltx_pipelines.utils.denoisers import GuidedDenoiserfrom ltx_pipelines.utils.helpers import (+ assert_generated_keyframes_request,assert_resolution,audio_duration_seconds,- combined_image_conditionings,ensure_tiling_config,get_device,num_frames_from_audio_duration,+ snap_frames_to_grid,tiling_scale_factors_for_vae,)from ltx_pipelines.utils.media_io import (- HDRColorSpace,+ EXRColorSpace,decode_audio_from_file,encode_video,resolve_hdr_color_space,vae_dtype_for_hdr,)from ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, PipelineOutput+from ltx_pipelines.utils.types import ImageConditioningInput, OffloadMode, PipelineOutput, VideoAudiologger = logging.getLogger(__name__)+@dataclass(frozen=True)+class _A2VidRunContext:+ """Setup snapshot for :meth:`A2VidPipelineTwoStage.stream_chunks`.+ Built by :meth:`A2VidPipelineTwoStage._prepare_run`.+ """++ generator: torch.Generator+ noiser: GaussianNoiser+ dtype: torch.dtype+ vae_dtype: torch.dtype+ images: list[ImageConditioningInput]+ v_context_p: torch.Tensor+ a_context_p: torch.Tensor+ v_context_n: torch.Tensor+ num_frames: int+ tiling_config: TilingConfig+ stage_1_width: int+ stage_1_height: int+ encoded_audio_latent: torch.Tensor+ source_audio: Audio++class A2VidPipelineTwoStage:"""Two-stage audio to video generation pipeline.@@ -148,8 +195,9 @@ class A2VidPipelineTwoStage:diffvae_optimization=diffvae_optimization,)- def __call__( # noqa: PLR0913+ def _prepare_run( # noqa: PLR0913self,+ *,prompt: str,negative_prompt: str,seed: int,@@ -157,29 +205,26 @@ class A2VidPipelineTwoStage:width: int,num_frames: int | None,frame_rate: float,- num_inference_steps: int,- video_guider_params: MultiModalGuiderParams,images: list[ImageConditioningInput],audio_path: str,- audio_start_time: float = 0.0,- audio_max_duration: float | None = None,- vae_dtype: torch.dtype | None = None,- tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,- enhance_prompt: bool = False,- enhance_static_cache: bool = False,- max_batch_size: int = 1,- stage_1_sigmas: torch.Tensor | None = None,- stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,- color_space: HDRColorSpace | None = None,- ) -> PipelineOutput:+ audio_start_time: float,+ audio_max_duration: float | None,+ vae_dtype: torch.dtype | None,+ tiling_config: TilingConfig | AutoTiling | None,+ enhance_prompt: bool,+ enhance_static_cache: bool,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ ) -> _A2VidRunContext:+ """Validate inputs, decode/encode audio, and resolve frame count / tiling before chunk planning."""images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=True)+ assert_generated_keyframes_request(decode_with_keyframes, generated_keyframes, self.stage_1)generator = torch.Generator(device=self.device).manual_seed(seed)noiser = GaussianNoiser(generator=generator)dtype = torch.bfloat16- if vae_dtype is None:- vae_dtype = dtype+ resolved_vae_dtype = dtype if vae_dtype is None else vae_dtype# Decode audio first so the frame count can follow the effective clip length# (``audio_max_duration`` capped by remaining audio after ``audio_start_time``).@@ -194,6 +239,7 @@ class A2VidPipelineTwoStage:audio_duration_seconds(decoded_audio),frame_rate,)+ num_frames = snap_frames_to_grid(num_frames)ctx_p, ctx_n = self.prompt_encoder([prompt, negative_prompt],@@ -205,127 +251,240 @@ class A2VidPipelineTwoStage:v_context_n, _ = ctx_n.video_encoding, ctx_n.audio_encodingscale_factors = tiling_scale_factors_for_vae(self.video_decoder.checkpoint_path)- tiling_config = ensure_tiling_config(+ resolved_tiling_config = ensure_tiling_config(tiling_config,scale_factors=scale_factors,vae_checkpoint_path=self.video_decoder.checkpoint_path,video_shape=VideoPixelShape(batch=1, frames=num_frames, height=height, width=width, fps=frame_rate),diffvae_optimization=self.video_decoder.diffvae_optimization,device=self.device,+ keyframes=decode_with_keyframes,)encoded_audio_latent = self.audio_conditioner(lambda enc: vae_encode_audio(decoded_audio, enc, None))audio_shape = AudioLatentShape.from_duration(batch=1, duration=num_frames / frame_rate, channels=8, mel_bins=16)encoded_audio_latent = encoded_audio_latent[:, :, : audio_shape.frames]+ source_audio = Audio(+ waveform=decoded_audio.waveform.squeeze(0),+ sampling_rate=decoded_audio.sampling_rate,+ )- # Stage 1: encode image conditionings with the VAE encoder, then denoise- # video-only (audio frozen).- stage_1_output_shape = VideoPixelShape(- batch=1,- frames=num_frames,- width=width // 2,- height=height // 2,- fps=frame_rate,+ return _A2VidRunContext(+ generator=generator,+ noiser=noiser,+ dtype=dtype,+ vae_dtype=resolved_vae_dtype,+ images=images,+ v_context_p=v_context_p,+ a_context_p=a_context_p,+ v_context_n=v_context_n,+ num_frames=num_frames,+ tiling_config=resolved_tiling_config,+ stage_1_width=width // 2,+ stage_1_height=height // 2,+ encoded_audio_latent=encoded_audio_latent,+ source_audio=source_audio,)- stage_1_conditionings = self.image_conditioner(- lambda enc: combined_image_conditionings(- images=images,- height=stage_1_output_shape.height,- width=stage_1_output_shape.width,- video_encoder=enc,- dtype=dtype,- device=self.device,- color_space=color_space,++ def _video_conditionings(+ self,+ images: list[ImageConditioningInput],+ num_frames: int,+ color_space: EXRColorSpace | None,+ ) -> MakeVideoConditionings:+ assert_image_frames_in_clip(images, num_frames)++ def make(chunk: Chunk) -> list[ConditioningItem]:+ if chunk.video is None or not images_for_chunk(chunk, images):+ return []+ return self.image_conditioner(+ lambda enc: image_conditionings_for_chunk(+ chunk,+ images=images,+ video_encoder=enc,+ color_space=color_space,+ ))++ return make++ def __call__( # noqa: PLR0913+ self,+ prompt: str,+ negative_prompt: str,+ seed: int,+ height: int,+ width: int,+ num_frames: int | None,+ frame_rate: float,+ num_inference_steps: int,+ video_guider_params: MultiModalGuiderParams,+ images: list[ImageConditioningInput],+ audio_path: str,+ audio_start_time: float = 0.0,+ audio_max_duration: float | None = None,+ vae_dtype: torch.dtype | None = None,+ tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,+ enhance_prompt: bool = False,+ enhance_static_cache: bool = False,+ max_batch_size: int = 1,+ stage_1_sigmas: torch.Tensor | None = None,+ stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,+ color_space: EXRColorSpace | None = None,+ chunk_config: ChunkConfig | None = None,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ ) -> PipelineOutput:+ chunks, num_frames, tiling_config = self.stream_chunks(+ prompt=prompt,+ negative_prompt=negative_prompt,+ seed=seed,+ height=height,+ width=width,+ num_frames=num_frames,+ frame_rate=frame_rate,+ num_inference_steps=num_inference_steps,+ video_guider_params=video_guider_params,+ images=images,+ audio_path=audio_path,+ audio_start_time=audio_start_time,+ audio_max_duration=audio_max_duration,+ vae_dtype=vae_dtype,+ tiling_config=tiling_config,+ enhance_prompt=enhance_prompt,+ enhance_static_cache=enhance_static_cache,+ max_batch_size=max_batch_size,+ stage_1_sigmas=stage_1_sigmas,+ stage_2_sigmas=stage_2_sigmas,+ color_space=color_space,+ chunk_config=chunk_config,+ generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,)+ return pipeline_output_from_chunks(chunks, num_frames=num_frames, tiling_config=tiling_config)++ def stream_chunks( # noqa: PLR0913+ self,+ prompt: str,+ negative_prompt: str,+ seed: int,+ height: int,+ width: int,+ num_frames: int | None,+ frame_rate: float,+ num_inference_steps: int,+ video_guider_params: MultiModalGuiderParams,+ images: list[ImageConditioningInput],+ audio_path: str,+ audio_start_time: float = 0.0,+ audio_max_duration: float | None = None,+ vae_dtype: torch.dtype | None = None,+ tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,+ enhance_prompt: bool = False,+ enhance_static_cache: bool = False,+ max_batch_size: int = 1,+ stage_1_sigmas: torch.Tensor | None = None,+ stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,+ color_space: EXRColorSpace | None = None,+ chunk_config: ChunkConfig | None = None,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ ) -> tuple[Iterator[DecodedChunk], int, TilingConfig]:+ """Generate a video as a stream of decoded chunks.+ ``chunk_config=None`` plans a single chunk covering the snapped clip.+ Audio is the frozen source latent both stages; decoded output is the original waveform.+ """+ ctx = self._prepare_run(+ prompt=prompt,+ negative_prompt=negative_prompt,+ seed=seed,+ height=height,+ width=width,+ num_frames=num_frames,+ frame_rate=frame_rate,+ images=images,+ audio_path=audio_path,+ audio_start_time=audio_start_time,+ audio_max_duration=audio_max_duration,+ vae_dtype=vae_dtype,+ tiling_config=tiling_config,+ enhance_prompt=enhance_prompt,+ enhance_static_cache=enhance_static_cache,+ generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,+ )+ if chunk_config is None:+ chunk_config = ChunkConfig(chunk_pixel_frames=ctx.num_frames, next_video_carry_frames=0)sigmas = (stage_1_sigmas if stage_1_sigmas is not None else self._scheduler.execute(steps=num_inference_steps)).to(dtype=torch.float32, device=self.device)+ stage_2_sigmas = stage_2_sigmas.to(dtype=torch.float32, device=self.device)- video_state, _ = self.stage_1(- denoiser=GuidedDenoiser(- v_context=v_context_p,- a_context=a_context_p,+ target = VideoPixelShape(+ batch=1,+ frames=ctx.num_frames,+ height=ctx.stage_1_height,+ width=ctx.stage_1_width,+ fps=frame_rate,+ )++ def make_denoiser(chunk: Chunk) -> GuidedDenoiser:+ return GuidedDenoiser(+ v_context=chunk.video_context,+ a_context=chunk.audio_context,video_guider=MultiModalGuider(params=video_guider_params,- negative_context=v_context_n,- ),- audio_guider=MultiModalGuider(- params=MultiModalGuiderParams(),+ negative_context=ctx.v_context_n,),- ),+ audio_guider=MultiModalGuider(params=MultiModalGuiderParams()),+ )++ chunks = generate_uniform_chunks(+ target=target,+ context=VideoAudio(video=ctx.v_context_p, audio=ctx.a_context_p),+ device=self.device,+ dtype=ctx.dtype,+ config=chunk_config,+ video_scale_factors=self.stage_1.video_scale_factors,+ audio_latent=ctx.encoded_audio_latent,+ make_video_conditionings=self._video_conditionings(ctx.images, ctx.num_frames, color_space),+ generated_keyframes=generated_keyframes,+ )+ base = denoise_chunks(+ chunks,+ self.stage_1,sigmas=sigmas,- noiser=noiser,- width=stage_1_output_shape.width,- height=stage_1_output_shape.height,- frames=num_frames,+ noiser=ctx.noiser,fps=frame_rate,- video=ModalitySpec(- context=v_context_p,- conditionings=stage_1_conditionings,- ),- audio=ModalitySpec(- context=a_context_p,- frozen=True,- noise_scale=0.0,- initial_latent=encoded_audio_latent,- ),max_batch_size=max_batch_size,+ make_denoiser=make_denoiser,+ freeze_audio=True,)-- # Stage 2: Upsample and refine the video at higher resolution with distilled LoRA.- upscaled_video_latent = self.upsampler(video_state.latent[:1])-- stage_2_sigmas = stage_2_sigmas.to(dtype=torch.float32, device=self.device)- stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)- stage_2_conditionings = self.image_conditioner(- lambda enc: combined_image_conditionings(- images=images,- height=stage_2_output_shape.height,- width=stage_2_output_shape.width,- video_encoder=enc,- dtype=dtype,- device=self.device,- color_space=color_space,- )- )-- video_state, _ = self.stage_2(- denoiser=SimpleDenoiser(v_context_p, a_context_p),+ upscaled = spatially_upsample_chunks(base, self.upsampler)+ refined = denoise_chunks(+ upscaled,+ self.stage_2,sigmas=stage_2_sigmas,- noiser=noiser,- width=width,- height=height,- frames=num_frames,+ noiser=ctx.noiser,fps=frame_rate,- video=ModalitySpec(- context=v_context_p,- conditionings=stage_2_conditionings,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=upscaled_video_latent,- ),- audio=ModalitySpec(- context=a_context_p,- frozen=True,- noise_scale=0.0,- initial_latent=encoded_audio_latent,- ),+ freeze_audio=True,)-- decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)-- # Return the original input audio instead of VAE-decoded audio to preserve fidelity.- # decode_audio_from_file already returns normalised [-1, 1] float values.- # Trim to the snapped video duration so a slightly longer clip cannot freeze- # the last frames. Floor so a half-sample leftover cannot outlast the video.- video_samples = max(1, int((num_frames / frame_rate) * decoded_audio.sampling_rate))- original_audio = Audio(- waveform=decoded_audio.waveform.squeeze(0)[..., :video_samples],- sampling_rate=decoded_audio.sampling_rate,+ decoded = decode_chunks(+ refined,+ self.video_decoder,+ audio_decoder=None,+ fps=frame_rate,+ tiling_config=ctx.tiling_config,+ generator=ctx.generator,+ dtype=ctx.vae_dtype,+ keyframes=decode_with_keyframes,+ )+ return (+ replace_chunks_audio(decoded, ctx.source_audio, frame_rate),+ ctx.num_frames,+ ctx.tiling_config,)-- return PipelineOutput(decoded_video, original_audio, num_frames, tiling_config, None, video_state.latent)def resolve_a2vid_cli_duration(@@ -418,7 +577,7 @@ def resolve_a2vid_duration_or_exit(def main() -> None:logging.basicConfig(level=logging.INFO)params = resolve_cli_params()- parser = build_a2vid_arg_parser(params)+ parser = add_chunk_layout_args(add_keyframe_decode_arg(add_generated_keyframes_arg(build_a2vid_arg_parser(params))))args = parser.parse_args()num_frames, audio_max_duration = resolve_a2vid_duration_or_exit(parser, args, default_num_frames=params.num_frames)pipeline = A2VidPipelineTwoStage(@@ -434,7 +593,16 @@ def main() -> None:)hdr = resolve_hdr_color_space(images=args.images, hdr=args.hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- result = pipeline(+ chunk_config = chunk_config_from_args(args)+ video_guider_params = MultiModalGuiderParams(+ cfg_scale=args.video_cfg_guidance_scale,+ stg_scale=args.video_stg_guidance_scale,+ rescale_scale=args.video_rescale_scale,+ modality_scale=args.a2v_guidance_scale,+ skip_step=args.video_skip_step,+ stg_blocks=args.video_stg_blocks,+ )+ chunks, num_frames_out, tiling_config = pipeline.stream_chunks(prompt=args.prompt,negative_prompt=args.negative_prompt,seed=args.seed,@@ -443,14 +611,7 @@ def main() -> None:num_frames=num_frames,frame_rate=args.frame_rate,num_inference_steps=args.num_inference_steps,- video_guider_params=MultiModalGuiderParams(- cfg_scale=args.video_cfg_guidance_scale,- stg_scale=args.video_stg_guidance_scale,- rescale_scale=args.video_rescale_scale,- modality_scale=args.a2v_guidance_scale,- skip_step=args.video_skip_step,- stg_blocks=args.video_stg_blocks,- ),+ video_guider_params=video_guider_params,images=args.images,vae_dtype=vae_dtype,color_space=hdr,@@ -461,14 +622,29 @@ def main() -> None:audio_start_time=args.audio_start_time,audio_max_duration=audio_max_duration,max_batch_size=args.max_batch_size,+ chunk_config=chunk_config,+ generated_keyframes=args.num_generated_keyframes,+ decode_with_keyframes=args.decode_with_keyframes,)+ if chunk_config is not None:+ video, audio, audio_sampling_rate = split_decoded_chunks(chunks)+ video_chunks_number = 1+ else:+ result = pipeline_output_from_chunks(+ chunks,+ num_frames=num_frames_out,+ tiling_config=tiling_config,+ )+ video, audio, audio_sampling_rate = result.video, result.audio, None+ video_chunks_number = get_video_chunks_number(result.num_frames, result.tiling_config)encode_video(- video=result.video,+ video=video,fps=args.frame_rate,- audio=result.audio,+ audio=audio,output_path=args.output_path,- video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),+ video_chunks_number=video_chunks_number,color_space=hdr,+ audio_sampling_rate=audio_sampling_rate,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/chunks/__init__.py b/packages/ltx-pipelines/src/ltx_pipelines/chunks/__init__.pynew file mode 100644index 0000000..0fc5f89--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/chunks/__init__.py@@ -0,0 +1,57 @@+"""Long-video chunk generation: Chunk wire, conditioning factories, and chunk operators."""++from ltx_pipelines.chunks.audio import deferred_stitch_audio, stitch_audio+from ltx_pipelines.chunks.export import (+ SequentialVideoFrameSource,+ pipeline_output_from_chunks,+ split_decoded_chunks,+)+from ltx_pipelines.chunks.layout import (+ ChunkConfig,+ ChunkLayout,+ audio_latent_for_layout,+ uniform_chunk_layouts,+)+from ltx_pipelines.chunks.operators import (+ decode_chunks,+ denoise_chunks,+ replace_audio_conditionings,+ replace_chunks_audio,+ replace_video_conditionings,+ spatially_upsample_chunks,+)+from ltx_pipelines.chunks.planner import generate_uniform_chunks, plan_chunk_keyframes+from ltx_pipelines.chunks.state import (+ Chunk,+ DecodedChunk,+ GeneratedKeyframes,+ MakeAudioConditionings,+ MakeVideoConditionings,+ VideoConditioningsWithGeneratedKeyframes,+)++__all__ = [+ "Chunk",+ "ChunkConfig",+ "ChunkLayout",+ "DecodedChunk",+ "GeneratedKeyframes",+ "MakeAudioConditionings",+ "MakeVideoConditionings",+ "SequentialVideoFrameSource",+ "VideoConditioningsWithGeneratedKeyframes",+ "audio_latent_for_layout",+ "decode_chunks",+ "deferred_stitch_audio",+ "denoise_chunks",+ "generate_uniform_chunks",+ "pipeline_output_from_chunks",+ "plan_chunk_keyframes",+ "replace_audio_conditionings",+ "replace_chunks_audio",+ "replace_video_conditionings",+ "spatially_upsample_chunks",+ "split_decoded_chunks",+ "stitch_audio",+ "uniform_chunk_layouts",+]diff --git a/packages/ltx-pipelines/src/ltx_pipelines/chunks/audio.py b/packages/ltx-pipelines/src/ltx_pipelines/chunks/audio.pynew file mode 100644index 0000000..8015c53--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/chunks/audio.py@@ -0,0 +1,36 @@+"""Concatenate chunk audio parts after the video iterator has been drained."""++from __future__ import annotations++from collections.abc import Iterator++import torch++from ltx_core.color.audio_mux import normalize_audio_waveform+from ltx_core.types import Audio+++def stitch_audio(parts: list[Audio]) -> Audio | None:+ """Concatenate chunk parts into one ``Audio``, or ``None`` when empty.+ Parts must already be valid stereo. Call only after every part is available+ (e.g. after the video iterator has been consumed).+ """+ if not parts:+ return None+ sample_rate = parts[0].sampling_rate+ tensors: list[torch.Tensor] = []+ for audio in parts:+ if audio.sampling_rate != sample_rate:+ raise ValueError(f"chunk audio sampling rate {audio.sampling_rate} does not match expected {sample_rate}")+ tensors.append(normalize_audio_waveform(audio.waveform).cpu())+ return Audio(waveform=torch.cat(tensors, dim=0), sampling_rate=sample_rate)+++def deferred_stitch_audio(parts: list[Audio]) -> Iterator[Audio]:+ """Lazy iterator that stitches ``parts`` after video drain.+ ``split_decoded_chunks`` appends to ``parts`` while video is consumed; pull+ this iterator only once every part is present.+ """+ stitched = stitch_audio(parts)+ if stitched is not None:+ yield stitcheddiff --git a/packages/ltx-pipelines/src/ltx_pipelines/chunks/conditionings.py b/packages/ltx-pipelines/src/ltx_pipelines/chunks/conditionings.pynew file mode 100644index 0000000..883be7d--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/chunks/conditionings.py@@ -0,0 +1,186 @@+"""Per-item builders that turn a Chunk's window into ConditioningItem lists.+The chunk operators do not import this module. Each function produces one item+type. Pipelines close over ImageConditioner, color space, and clip-level inputs,+and compose the builders they need into ``make_video_conditionings`` /+``make_audio_conditionings``. Point items map through+:meth:`ChunkLayout.local_frame_index`; span items apply to every window.+"""++from __future__ import annotations++from collections.abc import Mapping, Sequence++import torch++from ltx_core.conditioning import (+ AudioConditionByReferenceLatent,+ ConditioningItem,+ VideoGeneratedKeyframeSlots,+)+from ltx_core.model.video_vae import TilingConfig, VideoEncoder+from ltx_core.types import VIDEO_SCALE_FACTORS+from ltx_pipelines.chunks.export import SequentialVideoFrameSource+from ltx_pipelines.chunks.layout import audio_latent_for_layout+from ltx_pipelines.chunks.state import Chunk+from ltx_pipelines.iclora_utils import (+ append_ic_lora_reference_video_conditionings,+ patchify_audio_reference_latent,+)+from ltx_pipelines.utils.helpers import combined_image_conditionings+from ltx_pipelines.utils.media_io import is_exr_dir+from ltx_pipelines.utils.media_io.color_config import EXRColorSpace+from ltx_pipelines.utils.types import ImageConditioningInput+++def assert_image_frames_in_clip(images: Sequence[ImageConditioningInput], num_frames: int) -> None:+ """Raise if any image ``frame_idx`` lies outside the planned stitched clip."""+ for image in images:+ if image.frame_idx < 0 or image.frame_idx >= num_frames:+ raise ValueError(f"frame_idx={image.frame_idx} is outside the planned stitched range [0, {num_frames})")+++def images_for_chunk(chunk: Chunk, images: Sequence[ImageConditioningInput]) -> list[ImageConditioningInput]:+ """Remap clip-level image inputs onto ``chunk``'s stitched kept window."""+ return [+ image._replace(frame_idx=local)+ for image in images+ if (local := chunk.layout.local_frame_index(image.frame_idx)) is not None+ ]+++def image_conditionings_for_chunk(+ chunk: Chunk,+ *,+ images: Sequence[ImageConditioningInput],+ video_encoder: VideoEncoder,+ color_space: EXRColorSpace | None = None,+) -> list[ConditioningItem]:+ """Encode image conditionings that land in ``chunk``, at its current latent spatial size."""+ local = images_for_chunk(chunk, images)+ if not local or chunk.video is None:+ return []+ height, width = _pixel_hw(chunk)+ return combined_image_conditionings(+ images=local,+ height=height,+ width=width,+ video_encoder=video_encoder,+ dtype=chunk.video.dtype,+ device=chunk.video.device,+ color_space=color_space,+ )+++def generated_keyframe_slots_for_chunk(+ chunk: Chunk,+ *,+ keyframe_indices: Sequence[int],+) -> list[ConditioningItem]:+ """Build generated-keyframe slots whose clip-level indices land in ``chunk``."""+ local = [local for idx in keyframe_indices if (local := chunk.layout.local_frame_index(idx)) is not None]+ if not local:+ return []+ return [+ VideoGeneratedKeyframeSlots(+ pixel_frame_indices=local,+ initial_keyframes=None if chunk.generated_keyframes is None else chunk.generated_keyframes.latent,+ )+ ]+++def reference_video_conditionings_for_chunk(+ chunk: Chunk,+ *,+ video_conditioning: Sequence[tuple[str, float]],+ video_encoder: VideoEncoder,+ frame_sources: Mapping[str, SequentialVideoFrameSource],+ downscale_factor: int = 1,+ reference_temporal_scale_factor: int = 1,+ conditioning_attention_strength: float = 1.0,+ conditioning_attention_mask: torch.Tensor | None = None,+ encode_tiling: TilingConfig | None = None,+ color_space: EXRColorSpace | None = None,+) -> list[ConditioningItem]:+ """Encode reference video(s) sliced to ``chunk``'s pixel window, one item per pair.+ ``frame_sources`` must hold one :class:`~ltx_pipelines.chunks.export.SequentialVideoFrameSource`+ per reference path so multi-chunk runs decode each file once in order.+ ``encode_tiling``: pass ``None`` for a single-pass untiled encode or a concrete+ config for tiled encode.+ """+ if chunk.video is None or not video_conditioning:+ return []+ height, width = _pixel_hw(chunk)+ items: list[ConditioningItem] = []+ mask_slice = (+ _slice_conditioning_attention_mask_for_chunk(conditioning_attention_mask, chunk)+ if conditioning_attention_mask is not None+ else None+ )+ start = chunk.layout.start_pixel_frame+ count = chunk.layout.pixel_frames+ for path, strength in video_conditioning:+ if is_exr_dir(path):+ frames = None+ else:+ if path not in frame_sources:+ raise KeyError(f"frame_sources missing SequentialVideoFrameSource for reference path {path!r}")+ frames = frame_sources[path].take(start, count)+ append_ic_lora_reference_video_conditionings(+ items,+ [(path, strength)],+ height=height,+ width=width,+ num_frames=count,+ starting_frame=start,+ video_encoder=video_encoder,+ dtype=chunk.video.dtype,+ device=chunk.video.device,+ reference_downscale_factor=downscale_factor,+ reference_temporal_scale_factor=reference_temporal_scale_factor,+ conditioning_attention_strength=conditioning_attention_strength,+ conditioning_attention_mask=mask_slice,+ tiling_config=encode_tiling,+ color_space=color_space,+ frames=frames,+ reference_prefix_frames=chunk.layout.prev_video_carry_frames,+ )+ return items+++def audio_reference_conditionings_for_chunk(+ chunk: Chunk,+ *,+ latent: torch.Tensor | None,+ fps: float,+ strength: float = 1.0,+ negative_positions: bool = True,+) -> list[ConditioningItem]:+ """Build audio-reference tokens for ``chunk``, sliced to its layout window.+ ``latent`` is the full-clip VAE latent. ``latent is None`` means use the chunk's own+ audio latent (stage-2 self-reference).+ """+ source = chunk.audio if latent is None else audio_latent_for_layout(latent, chunk.layout, fps)+ if source is None:+ raise ValueError("audio reference with latent=None requires chunk.audio")+ ref_patch, ref_pos = patchify_audio_reference_latent(+ source,+ negative_positions=negative_positions,+ device=source.device,+ )+ return [AudioConditionByReferenceLatent(ref_patch, ref_pos, strength=strength)]+++def _pixel_hw(chunk: Chunk) -> tuple[int, int]:+ assert chunk.video is not None+ return chunk.video.shape[-2] * VIDEO_SCALE_FACTORS.height, chunk.video.shape[-1] * VIDEO_SCALE_FACTORS.width+++def _slice_conditioning_attention_mask_for_chunk(+ mask: torch.Tensor,+ chunk: Chunk,+) -> torch.Tensor:+ start = chunk.layout.start_pixel_frame+ end = start + chunk.layout.pixel_frames+ if mask.shape[2] < end:+ raise ValueError(f"conditioning_attention_mask has {mask.shape[2]} frames but chunk needs [{start}, {end})")+ return mask[:, :, start:end, :, :]diff --git a/packages/ltx-pipelines/src/ltx_pipelines/chunks/export.py b/packages/ltx-pipelines/src/ltx_pipelines/chunks/export.pynew file mode 100644index 0000000..d83b9c5--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/chunks/export.py@@ -0,0 +1,128 @@+"""Chunk stream I/O: overlap-aware reference decode, lazy stitch, and ``PipelineOutput`` packing."""++from __future__ import annotations++import logging+from collections import deque+from collections.abc import Generator, Iterator+from itertools import chain++import torch+from torch._prims_common import DeviceLikeType++from ltx_core.color.audio_mux import validate_audio_waveform+from ltx_core.model.video_vae import TilingConfig+from ltx_core.types import Audio+from ltx_pipelines.chunks.audio import deferred_stitch_audio, stitch_audio+from ltx_pipelines.chunks.state import DecodedChunk+from ltx_pipelines.utils.media_io import decode_video_by_frame+from ltx_pipelines.utils.types import PipelineOutput++logger = logging.getLogger(__name__)+++class SequentialVideoFrameSource:+ """Decode a video once, in order, reusing overlap frames already yielded.+ ``take(start, count)`` yields frames ``[start, start+count)``. Later windows may+ overlap; kept frames stay until a later ``take`` starts past them. Asking for a+ frame that has already been dropped raises.+ """++ def __init__(self, path: str, device: DeviceLikeType) -> None:+ self._path = path+ self._device = device+ self._gen: Generator[torch.Tensor, None, None] | None = None+ self._next = 0+ self._kept_start = 0+ self._kept: deque[torch.Tensor] = deque()++ def take(self, start: int, count: int) -> Iterator[torch.Tensor]:+ if start < 0 or count < 0:+ raise ValueError(f"start and count must be >= 0, got start={start} count={count}")+ end = start + count+ if start < self._kept_start:+ raise ValueError(f"cannot take frames [{start}:{end}); lookback starts at {self._kept_start}")+ if start > self._next:+ raise ValueError(f"cannot skip from frame {self._next} to {start}; take windows in order")+ while self._kept_start < start:+ self._kept.popleft()+ self._kept_start += 1+ if end > self._next:+ if self._gen is None:+ self._gen = decode_video_by_frame(self._path, self._device, starting_frame=self._next)+ while self._next < end:+ try:+ self._kept.append(next(self._gen))+ except StopIteration:+ break+ self._next += 1+ return iter(list(self._kept)[:count])++ def close(self) -> None:+ if self._gen is not None:+ self._gen.close()+ self._gen = None+++def split_decoded_chunks(+ chunks: Iterator[DecodedChunk],+) -> tuple[Iterator[torch.Tensor], Iterator[Audio] | None, int | None]:+ """Split decoded chunks into a video iterator, stitched audio, and sample rate.+ Drain ``video`` before iterating ``audio``; audio is filled as video is+ consumed. Both audio fields are ``None`` when the stream is video-only.+ """+ first = next(chunks, None)+ if first is None:+ raise ValueError("split_decoded_chunks received no chunks")++ height, width = first.video.shape[-3], first.video.shape[-2]+ has_audio = first.audio is not None+ sample_rate = first.audio.sampling_rate if has_audio else None+ audio_chunks: list[Audio] = []++ def validate_and_collect(chunk: DecodedChunk) -> None:+ if (chunk.audio is not None) != has_audio:+ raise ValueError("audio presence must be the same for every chunk")+ if chunk.video.shape[0] == 0:+ raise ValueError("chunk had no video frames")+ chunk_h, chunk_w = chunk.video.shape[-3], chunk.video.shape[-2]+ if (chunk_h, chunk_w) != (height, width):+ raise ValueError(f"chunk video size {chunk_w}x{chunk_h} does not match expected {width}x{height}")+ if chunk.audio is not None:+ validate_audio_waveform(chunk.audio)+ audio_chunks.append(chunk.audio)++ def video() -> Iterator[torch.Tensor]:+ for chunk in chain((first,), chunks):+ validate_and_collect(chunk)+ yield chunk.video++ audio = None if sample_rate is None else deferred_stitch_audio(audio_chunks)+ return video(), audio, sample_rate+++def pipeline_output_from_chunks(+ chunks: Iterator[DecodedChunk],+ *,+ num_frames: int,+ tiling_config: TilingConfig | None,+) -> PipelineOutput:+ """Pack decoded chunks into :class:`PipelineOutput` for ``__call__``.+ One chunk keeps that chunk's video/audio identity. Several chunks yield+ each video tensor in order and one concatenated audio track.+ """+ decoded = list(chunks)+ if not decoded:+ raise ValueError("expected a decoded chunk")+ audios: list[Audio] = []+ for chunk in decoded:+ if chunk.audio is None:+ raise ValueError("expected decoded audio")+ validate_audio_waveform(chunk.audio)+ audios.append(chunk.audio)+ if len(decoded) == 1:+ only = decoded[0]+ return PipelineOutput(iter((only.video,)), audios[0], num_frames, tiling_config)+ stitched = stitch_audio(audios)+ assert stitched is not None+ return PipelineOutput((chunk.video for chunk in decoded), stitched, num_frames, tiling_config)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/chunks/layout.py b/packages/ltx-pipelines/src/ltx_pipelines/chunks/layout.pynew file mode 100644index 0000000..cf8308b--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/chunks/layout.py@@ -0,0 +1,231 @@+"""Chunk window layout: sizing, carry, and temporal windows."""++from __future__ import annotations++import logging+from dataclasses import dataclass++import torch++from ltx_core.types import VIDEO_SCALE_FACTORS, AudioLatentShape, VideoPixelShape+from ltx_pipelines.utils.helpers import snap_frames_to_grid++logger = logging.getLogger(__name__)+++@dataclass(frozen=True)+class ChunkConfig:+ """Window size, carry, and decoded overlap blending for uniform chunk planning."""++ chunk_pixel_frames: int = 97+ next_video_carry_frames: int = 25+ overlap_blend_frames: int | None = None++ def __post_init__(self) -> None:+ blend = self.next_video_carry_frames if self.overlap_blend_frames is None else self.overlap_blend_frames+ object.__setattr__(self, "overlap_blend_frames", blend)+ if blend < 0:+ raise ValueError(f"overlap_blend_frames ({blend}) must be >= 0")+ if blend > self.next_video_carry_frames:+ raise ValueError(+ f"overlap_blend_frames ({blend}) must be <= next_video_carry_frames ({self.next_video_carry_frames})"+ )+++@dataclass(frozen=True)+class ChunkLayout:+ """Temporal window for one chunk on the stitched **video pixel** timeline.+ All ``*_frames`` counts are pixel frames on the stitched video timeline.+ Attributes:+ pixel_frames: Full generation window for this chunk, previous carry included.+ start_pixel_frame: Global pixel-frame index where this window begins (previous+ carry included). Kept decoded output starts at+ ``start_pixel_frame + prev_video_carry_frames``.+ prev_video_carry_frames: Leading pixel frames this chunk re-renders in overlap+ with the previous chunk. These frames are dropped after decode because the+ prior chunk already emitted them (0 on chunk 0).+ next_video_carry_frames: Pixel duration this chunk passes to the next chunk (0 on+ the last chunk). After denoise, the matching tail is sliced from the end of+ the video (and audio) latent and pinned at index 0 for continuity.+ next_video_blend_frames: Number of decoded tail frames to retain and crossfade+ with the next chunk's overlap (0 on the last chunk).+ """++ pixel_frames: int+ start_pixel_frame: int+ prev_video_carry_frames: int+ next_video_carry_frames: int+ next_video_blend_frames: int = 0++ def __post_init__(self) -> None:+ t = VIDEO_SCALE_FACTORS.time+ if self.pixel_frames != 0 and (self.pixel_frames - 1) % t != 0:+ raise ValueError(+ f"pixel_frames ({self.pixel_frames}) must be on the causal grid ((n - 1) % {t} == 0, e.g. 97), or 0"+ )+ if self.prev_video_carry_frames != 0 and (self.prev_video_carry_frames - 1) % t != 0:+ raise ValueError(+ f"prev_video_carry_frames ({self.prev_video_carry_frames}) must be on the causal grid "+ f"((n - 1) % {t} == 0, e.g. 97), or 0"+ )+ if self.next_video_carry_frames != 0 and (self.next_video_carry_frames - 1) % t != 0:+ raise ValueError(+ f"next_video_carry_frames ({self.next_video_carry_frames}) must be on the causal grid "+ f"((n - 1) % {t} == 0, e.g. 97), or 0"+ )+ if self.prev_video_carry_frames < 0:+ raise ValueError(f"prev_video_carry_frames ({self.prev_video_carry_frames}) must be >= 0")+ if self.next_video_carry_frames < 0:+ raise ValueError(f"next_video_carry_frames ({self.next_video_carry_frames}) must be >= 0")+ if self.prev_video_carry_frames >= self.pixel_frames:+ raise ValueError(+ f"prev_video_carry_frames ({self.prev_video_carry_frames}) must be < pixel_frames ({self.pixel_frames})"+ )+ if self.next_video_carry_frames >= self.pixel_frames:+ raise ValueError(+ f"next_video_carry_frames ({self.next_video_carry_frames}) must be < pixel_frames ({self.pixel_frames})"+ )+ if not 0 <= self.next_video_blend_frames <= self.next_video_carry_frames:+ raise ValueError(+ f"next_video_blend_frames ({self.next_video_blend_frames}) must be between 0 and "+ f"next_video_carry_frames ({self.next_video_carry_frames})"+ )+ kept_frames = self.pixel_frames - self.prev_video_carry_frames+ if self.next_video_blend_frames >= kept_frames:+ raise ValueError(+ f"next_video_blend_frames ({self.next_video_blend_frames}) must be < kept pixel frames ({kept_frames})"+ )++ def local_frame_index(self, global_idx: int) -> int | None:+ """Map a stitched-timeline pixel index onto this chunk, or ``None`` if another chunk owns it.+ The owning window is the kept range after dropping the previous chunk's carry+ (``start_pixel_frame + prev_video_carry_frames`` … ``start_pixel_frame + pixel_frames``).+ The local index is ``global_idx - start_pixel_frame``, which places a seam frame at the carry.+ """+ kept_start = self.start_pixel_frame + self.prev_video_carry_frames+ kept_end = self.start_pixel_frame + self.pixel_frames+ if kept_start <= global_idx < kept_end:+ return global_idx - self.start_pixel_frame+ return None++ @property+ def owned_pixel_range(self) -> tuple[int, int]:+ """Half-open stitched-timeline range owned after the pinned incoming carry."""+ start = self.start_pixel_frame + self.prev_video_carry_frames+ end = self.start_pixel_frame + self.pixel_frames+ return start, end+++def _split_target_pixel_frames_into_chunk_lengths(+ target_pixel_frames: int, chunk_pixel_frames: int, next_video_carry_frames: int+) -> list[int]:+ """Per-chunk pixel lengths; stitched output floors ``target_pixel_frames`` to the causal grid."""+ t = VIDEO_SCALE_FACTORS.time+ if chunk_pixel_frames != 0 and (chunk_pixel_frames - 1) % t != 0:+ raise ValueError(+ f"chunk_pixel_frames ({chunk_pixel_frames}) must be on the causal grid ((n - 1) % {t} == 0, e.g. 97), or 0"+ )+ if next_video_carry_frames != 0 and (next_video_carry_frames - 1) % t != 0:+ raise ValueError(+ f"next_video_carry_frames ({next_video_carry_frames}) must be on the causal grid "+ f"((n - 1) % {t} == 0, e.g. 97), or 0"+ )++ chunk_latent_frames = (chunk_pixel_frames - 1) // t + 1+ target_latent_frames = (target_pixel_frames - 1) // t + 1+ if target_latent_frames <= chunk_latent_frames:+ return [(target_latent_frames - 1) * t + 1]++ carry_latent_frames = (next_video_carry_frames - 1) // t + 1 if next_video_carry_frames != 0 else 0+ if carry_latent_frames < 3:+ raise ValueError(+ f"next_video_carry_frames ({next_video_carry_frames}) must be >= "+ f"{(3 - 1) * t + 1} on the causal grid when chunking"+ )+ if carry_latent_frames >= chunk_latent_frames:+ raise ValueError(+ f"next_video_carry_frames ({next_video_carry_frames}) must be < chunk pixel frames ({chunk_pixel_frames})"+ )++ new_latent_frames = chunk_latent_frames - carry_latent_frames+ extra_full, remainder = divmod(target_latent_frames - chunk_latent_frames, new_latent_frames)+ sizes = [chunk_pixel_frames] * (1 + extra_full)+ if remainder:+ sizes.append((carry_latent_frames + remainder - 1) * t + 1)+ return sizes+++def uniform_chunk_layouts(+ *,+ target_pixel_shape: VideoPixelShape,+ config: ChunkConfig,+) -> list[ChunkLayout]:+ """Uniform fixed-size chunking plan for the target pixel shape.+ The stitched clip length floors ``target_pixel_shape.frames`` to the causal grid+ (``(frames - 1) % 8 == 0``), matching single-shot ``VideoLatentShape.from_pixel_shape``.+ When ``chunk_pixel_frames`` covers the snapped clip, the plan is a single chunk with no+ carry.+ """+ target_frames = target_pixel_shape.frames+ snapped_frames = snap_frames_to_grid(target_frames)+ if snapped_frames != target_frames:+ logger.info(+ "Target %d pixel frames floors to %d on the causal grid",+ target_frames,+ snapped_frames,+ )+ chunk_lengths = _split_target_pixel_frames_into_chunk_lengths(+ target_frames, config.chunk_pixel_frames, config.next_video_carry_frames+ )++ stitched_start = 0+ layouts: list[ChunkLayout] = []+ last = len(chunk_lengths) - 1+ for i, size in enumerate(chunk_lengths):+ prev_carry = 0 if i == 0 else layouts[i - 1].next_video_carry_frames+ next_carry = 0 if i == last else config.next_video_carry_frames+ layouts.append(+ ChunkLayout(+ pixel_frames=size,+ start_pixel_frame=stitched_start - prev_carry,+ prev_video_carry_frames=prev_carry,+ next_video_carry_frames=next_carry,+ next_video_blend_frames=0 if i == last else config.overlap_blend_frames,+ )+ )+ stitched_start += size - prev_carry+ return layouts+++def audio_latent_for_layout(+ full: torch.Tensor,+ layout: ChunkLayout,+ fps: float,+) -> torch.Tensor:+ """Audio latent covering ``layout``'s pixel window at ``fps``.+ A source shorter than the window is zero-padded on the right so the slice always+ matches the chunk's audio latent length (same as one-shot A2Vid feeding a short+ frozen latent into a longer video).+ """+ if fps <= 0:+ raise ValueError(f"fps must be > 0, got {fps}")+ start = AudioLatentShape.from_duration(batch=full.shape[0], duration=float(layout.start_pixel_frame) / fps).frames+ window = VideoPixelShape(+ batch=full.shape[0],+ frames=layout.pixel_frames,+ height=1,+ width=1,+ fps=fps,+ )+ n_frames = AudioLatentShape.from_video_pixel_shape(window).frames+ end = start + n_frames+ if start < 0:+ raise ValueError(+ f"audio latent slice [{start}:{end}] starts before the source "+ f"for start_pixel_frame={layout.start_pixel_frame} pixel_frames={layout.pixel_frames} fps={fps}"+ )+ available = full[:, :, start:end]+ if available.shape[2] == n_frames:+ return available+ pad = n_frames - available.shape[2]+ return torch.nn.functional.pad(available, (0, 0, 0, pad))diff --git a/packages/ltx-pipelines/src/ltx_pipelines/chunks/operators.py b/packages/ltx-pipelines/src/ltx_pipelines/chunks/operators.pynew file mode 100644index 0000000..cd3cdcc--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/chunks/operators.py@@ -0,0 +1,568 @@+"""Chunk operators: stream ``Chunk`` / ``DecodedChunk`` through denoise, upsample, and decode."""++from __future__ import annotations++from collections.abc import Callable, Iterator+from dataclasses import replace++import torch++from ltx_core.conditioning import ConditioningItem, VideoConditionByKeyframeIndex, VideoGeneratedKeyframeSlots+from ltx_core.conditioning.types.latent_cond import AudioConditionByLatentIndex, VideoConditionByLatentIndex+from ltx_core.model.video_vae.keyframes import DecodeKeyframes+from ltx_core.types import VIDEO_SCALE_FACTORS, Audio, AudioLatentShape+from ltx_pipelines.chunks.layout import ChunkLayout+from ltx_pipelines.chunks.state import (+ Chunk,+ DecodedChunk,+ GeneratedKeyframes,+ MakeAudioConditionings,+ MakeVideoConditionings,+ VideoConditioningsWithGeneratedKeyframes,+)+from ltx_pipelines.utils import SimpleDenoiser, assert_stage_supports_generated_keyframes+from ltx_pipelines.utils.blocks import (+ AudioDecoder,+ DenoisingLoop,+ DiffusionStage,+ Noiser,+ VideoDecoder,+ VideoUpsampler,+)+from ltx_pipelines.utils.helpers import decode_keyframes_from_slots+from ltx_pipelines.utils.types import Denoiser, ModalitySpec, VideoAudio++MakeDenoiser = Callable[[Chunk], Denoiser]++# Longer than the vocoder receptive field so independently decoded seams can+# overlap-add without exposing either chunk's boundary transient.+AUDIO_SEAM_CROSSFADE_MS = 40.0+++def denoise_chunks( # noqa: PLR0913+ chunks: Iterator[Chunk],+ stage: DiffusionStage,+ sigmas: torch.Tensor,+ noiser: Noiser,+ fps: float,+ *,+ noise_scale: float | None = None,+ audio_noise_scale: float | None = None,+ loop: DenoisingLoop | None = None,+ max_batch_size: int = 1,+ make_denoiser: MakeDenoiser | None = None,+ freeze_video: bool = False,+ freeze_audio: bool = False,+) -> Iterator[Chunk]:+ """Denoise each ``Chunk`` through ``stage``, materializing conditionings and threading carry."""+ scale = sigmas[0].item() if noise_scale is None else noise_scale+ audio_scale = scale if audio_noise_scale is None else audio_noise_scale+ carry_video: torch.Tensor | None = None+ carry_audio: torch.Tensor | None = None+ # Each denoise pass owns a separate carry at that stage's spatial resolution.+ stage_carry_keyframes: GeneratedKeyframes | None = None+ for chunk in chunks:+ denoiser = (+ make_denoiser(chunk)+ if make_denoiser is not None+ else SimpleDenoiser(chunk.video_context, chunk.audio_context)+ )+ incoming_keyframes = stage_carry_keyframes if stage_carry_keyframes is not None else chunk.incoming_keyframes+ video_cond = _append_incoming_keyframes(list(chunk.make_video_conditionings(chunk)), incoming_keyframes)+ audio_cond = list(chunk.make_audio_conditionings(chunk))+ if any(isinstance(item, VideoGeneratedKeyframeSlots) for item in video_cond):+ assert_stage_supports_generated_keyframes(stage)++ # A frozen modality is pinned to ``noise_scale=0.0``, matching every other freeze site in+ # the package. ``_build_state`` noises before it zeroes the denoise mask, so a frozen spec+ # carrying the schedule's scale would hand the transformer a latent that is mostly Gaussian+ # noise while ``sigma=0`` labels it clean conditioning.+ video = (+ ModalitySpec(+ latent=chunk.video,+ conditioning_fps=fps,+ conditionings=_append_carry(video_cond, carry_video, VideoConditionByLatentIndex),+ noise_scale=0.0 if freeze_video else scale,+ frozen=freeze_video,+ )+ if chunk.video is not None+ else None+ )+ audio = (+ ModalitySpec(+ latent=chunk.audio,+ conditioning_fps=fps,+ conditionings=_append_carry(audio_cond, carry_audio, AudioConditionByLatentIndex),+ noise_scale=0.0 if freeze_audio else audio_scale,+ frozen=freeze_audio,+ )+ if chunk.audio is not None+ else None+ )++ video_state, audio_state = stage(+ denoiser=denoiser,+ sigmas=sigmas,+ noiser=noiser,+ modalities=VideoAudio(video=video, audio=audio),+ loop=loop,+ max_batch_size=max_batch_size,+ )+ video_latent = video_state.latent if video_state is not None else None+ audio_latent = audio_state.latent if audio_state is not None else None+ # A frozen modality is conditioning, not output: keep the latent that went in rather+ # than the loop's copy of it. ``euler_denoising_loop`` steps frozen states too, and+ # ``to_velocity`` rounds to the latent dtype on every step, so what comes back has+ # drifted a few bf16 ulps from what was frozen -- inaudible in a latent, but the+ # vocoder turns it into a visibly different waveform.+ if freeze_video:+ video_latent = chunk.video+ if freeze_audio:+ audio_latent = chunk.audio+ sidecar = None+ if video_state is not None and video_state.generated_keyframes is not None:+ layout = video_state.generated_keyframe_layout+ positions = layout.pixel_frame_indices if layout is not None else ()+ sidecar = GeneratedKeyframes(latent=video_state.generated_keyframes, pixel_frame_indices=positions)+ carry_video_frames = 0+ carry_audio_frames = 0+ if chunk.layout.next_video_carry_frames != 0:+ t = VIDEO_SCALE_FACTORS.time+ carry_video_frames = (chunk.layout.next_video_carry_frames - 1) // t + 1+ carry_audio_frames = max(+ 1,+ AudioLatentShape.from_duration(+ batch=1,+ duration=float(chunk.layout.next_video_carry_frames) / fps,+ ).frames,+ )+ carry_video = _slice_latent_tail(video_latent, carry_video_frames)+ carry_audio = _slice_latent_tail(audio_latent, carry_audio_frames)+ stage_carry_keyframes = _keyframes_for_next_chunk(sidecar, chunk.layout)+ yield replace(+ chunk,+ video=video_latent,+ audio=audio_latent,+ generated_keyframes=sidecar,+ incoming_keyframes=incoming_keyframes,+ )+++def spatially_upsample_chunks(chunks: Iterator[Chunk], upsampler: VideoUpsampler) -> Iterator[Chunk]:+ """Spatially upsample each chunk's video latent and generated-keyframe slots; audio and factories pass through."""+ for chunk in chunks:+ if chunk.video is None:+ yield chunk+ continue+ video = upsampler(chunk.video[:1])+ sidecar = chunk.generated_keyframes+ if sidecar is not None:+ sidecar = replace(sidecar, latent=upsampler(sidecar.latent[:1]))+ incoming = chunk.incoming_keyframes+ if incoming is not None:+ incoming = replace(incoming, latent=upsampler(incoming.latent[:1]))+ yield replace(chunk, video=video, generated_keyframes=sidecar, incoming_keyframes=incoming)+++def replace_video_conditionings(+ chunks: Iterator[Chunk],+ make_video_conditionings: MakeVideoConditionings,+ *,+ preserve_generated_keyframes: bool = True,+) -> Iterator[Chunk]:+ """Replace pipeline-owned video conditionings, preserving planned keyframes by default."""+ for chunk in chunks:+ current = chunk.make_video_conditionings+ replacement = (+ current.replace_inner(make_video_conditionings)+ if preserve_generated_keyframes and isinstance(current, VideoConditioningsWithGeneratedKeyframes)+ else make_video_conditionings+ )+ yield replace(chunk, make_video_conditionings=replacement)+++def replace_audio_conditionings(+ chunks: Iterator[Chunk],+ make_audio_conditionings: MakeAudioConditionings,+) -> Iterator[Chunk]:+ """Overwrite each chunk's audio conditioning factory; the video factory is unchanged."""+ for chunk in chunks:+ yield replace(chunk, make_audio_conditionings=make_audio_conditionings)+++def decode_chunks(+ chunks: Iterator[Chunk],+ video_decoder: VideoDecoder,+ audio_decoder: AudioDecoder | None,+ fps: float,+ *,+ tiling_config: object | None = None,+ generator: torch.Generator | None = None,+ dtype: torch.dtype | None = None,+ keyframes: bool = False,+) -> Iterator[DecodedChunk]:+ """Decode chunks and join their carried overlap.+ Each body streams immediately, while its outgoing video tail waits to blend+ with the next chunk's carried prefix. Audio retains matching seam samples+ and equal-power crossfades them across the same boundary.+ With ``keyframes=True``, incoming carried keyframes and the chunk's newly+ generated keyframes anchor its decode; their local indices are rebased to+ the global timeline. Empty decoder output is skipped. Without an+ ``audio_decoder``, chunks are video-only.+ """+ pending_tail: DecodedChunk | None = None+ for chunk in chunks:+ if chunk.video is None:+ raise ValueError("decode_chunks requires chunk.video")+ layout = chunk.layout+ decoded_frames = _decode_chunk_video(+ chunk,+ video_decoder,+ tiling_config,+ generator,+ dtype=dtype,+ keyframes=keyframes,+ )+ if decoded_frames is None:+ continue++ frames = _drop_video_overlap(decoded_frames, layout.prev_video_carry_frames)+ audio, seam_fade_samples = _vocoded_chunk_audio(+ chunk,+ frames,+ audio_decoder,+ fps=fps,+ pending_tail=pending_tail,+ )+ pending_tail, audio = _apply_pending_audio_crossfade(pending_tail, audio, seam_fade_samples)++ if pending_tail is not None:+ yield _blend_pending_video_tail(pending_tail, decoded_frames, layout.prev_video_carry_frames)+ pending_tail = None++ body, pending_tail = _body_and_pending_tail(+ DecodedChunk(video=frames, audio=audio),+ layout=layout,+ fps=fps,+ )+ yield body+ if pending_tail is not None:+ yield pending_tail+++def _decode_chunk_video(+ chunk: Chunk,+ video_decoder: VideoDecoder,+ tiling_config: object | None,+ generator: torch.Generator | None,+ *,+ dtype: torch.dtype | None,+ keyframes: bool,+) -> torch.Tensor | None:+ decode_kwargs: dict[str, object] = {+ "dtype": dtype,+ "device_fn": lambda _batch, device=chunk.video.device: device,+ }+ if keyframes:+ decode_kf = _decode_generated_keyframes(chunk)+ if decode_kf is not None:+ decode_kwargs["keyframes"] = decode_kf+ decoded_batches = list(video_decoder(chunk.video, tiling_config, generator, **decode_kwargs))+ if not decoded_batches:+ return None+ return torch.cat(decoded_batches, dim=0)+++def _vocoded_chunk_audio(+ chunk: Chunk,+ frames: torch.Tensor,+ audio_decoder: AudioDecoder | None,+ *,+ fps: float,+ pending_tail: DecodedChunk | None,+) -> tuple[Audio | None, int]:+ """Vocode this chunk's audio aligned to ``frames``, plus extra prefix samples for seam crossfade."""+ if audio_decoder is None or chunk.audio is None:+ return None, 0+ decoded_audio = audio_decoder(chunk.audio)+ fade_samples = _audio_seam_crossfade_samples(decoded_audio.sampling_rate)+ pending_audio_samples = (+ 0 if pending_tail is None or pending_tail.audio is None else pending_tail.audio.waveform.shape[-1]+ )+ extra_samples = min(fade_samples, pending_audio_samples)+ base_samples = min(+ decoded_audio.waveform.shape[-1],+ round(frames.shape[0] / fps * decoded_audio.sampling_rate),+ )+ waveform, kept_samples = _keep_vocoded_audio_tail(+ decoded_audio.waveform,+ kept_video_frames=frames.shape[0],+ fps=fps,+ sampling_rate=decoded_audio.sampling_rate,+ extra_samples=extra_samples,+ )+ audio = Audio(waveform=waveform, sampling_rate=decoded_audio.sampling_rate)+ seam_fade_samples = max(0, kept_samples - base_samples)+ return audio, seam_fade_samples+++def _apply_pending_audio_crossfade(+ pending_tail: DecodedChunk | None,+ audio: Audio | None,+ seam_fade_samples: int,+) -> tuple[DecodedChunk | None, Audio | None]:+ if pending_tail is None or pending_tail.audio is None or audio is None:+ return pending_tail, audio+ pending_audio, audio = _crossfade_audio_seam(pending_tail.audio, audio, seam_fade_samples)+ return replace(pending_tail, audio=pending_audio), audio+++def _blend_pending_video_tail(+ pending_tail: DecodedChunk,+ decoded_frames: torch.Tensor,+ prev_video_carry_frames: int,+) -> DecodedChunk:+ overlap_end = prev_video_carry_frames+ blend_start = overlap_end - pending_tail.video.shape[0]+ if blend_start < 0:+ raise ValueError(+ f"pending blend tail ({pending_tail.video.shape[0]} frames) exceeds current overlap ({overlap_end} frames)"+ )+ overlap = decoded_frames[blend_start:overlap_end]+ return replace(+ pending_tail,+ video=_crossfade_video_overlap(pending_tail.video, overlap),+ )+++def _body_and_pending_tail(+ decoded: DecodedChunk,+ *,+ layout: ChunkLayout,+ fps: float,+) -> tuple[DecodedChunk, DecodedChunk | None]:+ blend_frames = layout.next_video_blend_frames+ if blend_frames == 0:+ return decoded, None+ prefix_audio_samples = 0+ if decoded.audio is not None:+ tail_audio_samples = round(blend_frames / fps * decoded.audio.sampling_rate)+ prefix_audio_samples = max(0, decoded.audio.waveform.shape[-1] - tail_audio_samples)+ return _split_decoded_tail(+ decoded,+ tail_frames=blend_frames,+ prefix_audio_samples=prefix_audio_samples,+ )+++def replace_chunks_audio(+ chunks: Iterator[DecodedChunk],+ source: Audio,+ fps: float,+) -> Iterator[DecodedChunk]:+ """Replace each chunk's audio with the equivalent slice of ``source``.+ Each chunk takes the next unused samples so the stitched waveform stays contiguous.+ A source shorter than the video emits what remains, then empty. Slices stay on+ ``source.waveform``'s device. Run after :func:`decode_chunks` once overlap frames+ are already dropped.+ """+ stitched_pixel_frames = 0+ emitted_audio_samples = 0+ sampling_rate = source.sampling_rate+ waveform = source.waveform+ for chunk in chunks:+ stitched_pixel_frames += chunk.video.shape[0]+ end_audio_sample = round(stitched_pixel_frames / fps * sampling_rate)+ remaining = waveform.shape[-1] - emitted_audio_samples+ chunk_audio_samples = max(0, min(remaining, end_audio_sample - emitted_audio_samples))+ sliced = waveform[..., emitted_audio_samples : emitted_audio_samples + chunk_audio_samples]+ emitted_audio_samples += chunk_audio_samples+ yield replace(chunk, audio=Audio(waveform=sliced, sampling_rate=sampling_rate))+++def _decode_generated_keyframes(chunk: Chunk) -> DecodeKeyframes | None:+ """Build ``DecodeKeyframes`` from incoming shared anchors and this chunk's slots."""+ sidecars = [sidecar for sidecar in (chunk.incoming_keyframes, chunk.generated_keyframes) if sidecar is not None]+ if not sidecars:+ return None+ latent = torch.cat([sidecar.latent for sidecar in sidecars], dim=2)+ positions = tuple(position for sidecar in sidecars for position in sidecar.pixel_frame_indices)+ kf = decode_keyframes_from_slots(+ latent,+ positions,+ chunk.layout.pixel_frames,+ )+ if kf is None:+ return None+ start_pixel_frame = chunk.layout.start_pixel_frame+ if start_pixel_frame == 0:+ return kf+ return replace(+ kf,+ pixel_frame_indices=kf.pixel_frame_indices + start_pixel_frame,+ clip_start_frame=start_pixel_frame,+ )+++def _append_carry(+ conditionings: list[ConditioningItem],+ carry: torch.Tensor | None,+ carry_condition_cls: type[VideoConditionByLatentIndex] | type[AudioConditionByLatentIndex],+) -> list[ConditioningItem]:+ if carry is None:+ return conditionings+ return [*conditionings, carry_condition_cls(latent=carry, strength=1.0, latent_idx=0)]+++def _append_incoming_keyframes(+ conditionings: list[ConditioningItem],+ incoming: GeneratedKeyframes | None,+) -> list[ConditioningItem]:+ """Append prior overlap planes as fixed one-frame keyframe conditioning."""+ if incoming is None:+ return conditionings+ incoming_items = [+ VideoConditionByKeyframeIndex(+ keyframes=incoming.latent[:, :, index : index + 1],+ frame_idx=position,+ strength=1.0,+ num_pixel_frames=1,+ )+ for index, position in enumerate(incoming.pixel_frame_indices)+ ]+ return [*conditionings, *incoming_items]+++def _keyframes_for_next_chunk(+ sidecar: GeneratedKeyframes | None,+ layout: ChunkLayout,+) -> GeneratedKeyframes | None:+ """Keep only generated planes in the outgoing overlap and rebase them for the next chunk."""+ next_carry = layout.next_video_carry_frames+ if sidecar is None or next_carry <= 0:+ return None+ next_chunk_start = layout.pixel_frames - next_carry+ keep = [+ (index, position)+ for index, position in enumerate(sidecar.pixel_frame_indices)+ if next_chunk_start <= position < layout.pixel_frames+ ]+ if not keep:+ return None+ return GeneratedKeyframes(+ latent=torch.cat([sidecar.latent[:, :, index : index + 1] for index, _ in keep], dim=2),+ pixel_frame_indices=tuple(position - next_chunk_start for _, position in keep),+ )+++def _slice_latent_tail(latent: torch.Tensor | None, frames: int) -> torch.Tensor | None:+ """Last ``frames`` along time (dim 2), cloned. ``None`` if missing or ``frames <= 0``."""+ if latent is None or frames <= 0:+ return None+ return latent[:, :, -frames:].clone()+++def _drop_video_overlap(frames: torch.Tensor, prev_video_carry_frames: int) -> torch.Tensor:+ """Drop leading ``prev_video_carry_frames`` decoded video frames (already emitted by the prior chunk)."""+ if prev_video_carry_frames <= 0:+ return frames+ if prev_video_carry_frames >= frames.shape[0]:+ raise ValueError(+ f"prev_video_carry_frames ({prev_video_carry_frames}) must be < decoded frame count ({frames.shape[0]})"+ )+ return frames[prev_video_carry_frames:]+++def _split_decoded_tail(+ chunk: DecodedChunk,+ *,+ tail_frames: int,+ prefix_audio_samples: int,+) -> tuple[DecodedChunk, DecodedChunk]:+ """Split a decoded chunk, cloning only the retained tail so it releases the full frame storage."""+ body_audio = None+ tail_audio = None+ if chunk.audio is not None:+ body_audio = replace(chunk.audio, waveform=chunk.audio.waveform[..., :prefix_audio_samples])+ tail_audio = replace(chunk.audio, waveform=chunk.audio.waveform[..., prefix_audio_samples:].clone())+ return (+ DecodedChunk(video=chunk.video[:-tail_frames], audio=body_audio),+ DecodedChunk(video=chunk.video[-tail_frames:].clone(), audio=tail_audio),+ )+++def _crossfade_video_overlap(previous: torch.Tensor, overlap: torch.Tensor) -> torch.Tensor:+ """Replace the matching tail of ``previous`` with a linear crossfade into ``overlap``."""+ count = min(previous.shape[0], overlap.shape[0])+ if count == 0:+ return previous+ weights = torch.arange(1, count + 1, device=previous.device, dtype=previous.dtype) / (count + 1)+ weights = weights.reshape(count, *([1] * (previous.ndim - 1)))+ blended = torch.lerp(previous[-count:], overlap[-count:], weights)+ return torch.cat([previous[:-count], blended], dim=0)+++def _crossfade_audio_seam(left: Audio, right: Audio, fade: int) -> tuple[Audio, Audio]:+ """Equal-power crossfade ``right``'s leading overlap into ``left``'s tail."""+ if left.sampling_rate != right.sampling_rate:+ raise ValueError(+ f"chunk audio sampling rate {right.sampling_rate} does not match expected {left.sampling_rate}"+ )+ if left.waveform.shape[:-1] != right.waveform.shape[:-1]:+ raise ValueError(+ f"chunk audio shape {tuple(right.waveform.shape)} does not match pending tail "+ f"shape {tuple(left.waveform.shape)}"+ )+ fade = min(fade, left.waveform.shape[-1], right.waveform.shape[-1])+ if fade <= 0:+ return left, right+ t = torch.linspace(0, 1, fade, device=left.waveform.device, dtype=left.waveform.dtype)+ weight_shape = (*([1] * (left.waveform.ndim - 1)), fade)+ weight_out = torch.cos(t * (torch.pi / 2)).reshape(weight_shape)+ weight_in = torch.sin(t * (torch.pi / 2)).reshape(weight_shape)+ mixed = left.waveform[..., -fade:] * weight_out + right.waveform[..., :fade] * weight_in+ left_waveform = torch.cat([left.waveform[..., :-fade], mixed], dim=-1)+ right_waveform = right.waveform[..., fade:]+ return replace(left, waveform=left_waveform), replace(right, waveform=right_waveform)+++def _audio_seam_crossfade_samples(sampling_rate: int) -> int:+ """Sample count for :data:`AUDIO_SEAM_CROSSFADE_MS`."""+ if sampling_rate <= 0:+ raise ValueError(f"sampling_rate must be > 0, got {sampling_rate}")+ return max(1, round(AUDIO_SEAM_CROSSFADE_MS / 1000.0 * sampling_rate))+++def _keep_vocoded_audio_tail(+ waveform: torch.Tensor,+ *,+ kept_video_frames: int,+ fps: float,+ sampling_rate: int,+ extra_samples: int = 0,+) -> tuple[torch.Tensor, int]:+ """Keep this chunk's video-aligned audio tail plus optional seam overlap."""+ keep = round(kept_video_frames / fps * sampling_rate) + extra_samples+ keep = max(0, min(waveform.shape[-1], keep))+ if keep == 0:+ return waveform[..., :0], 0+ return waveform[..., -keep:], keep+++def _keep_audio_tail_to_match_video(+ waveform: torch.Tensor,+ *,+ fps: float,+ stitched_pixel_frames: int,+ emitted_audio_samples: int,+ sampling_rate: int,+) -> tuple[torch.Tensor, int]:+ """Keep the waveform tail so cumulative samples match cumulative kept video.+ Causal VAE decoding and chunk overlap live at the front of each decode; the tail+ is what aligns stitched audio duration with stitched video.+ """+ end_audio_sample = round(stitched_pixel_frames / fps * sampling_rate)+ chunk_audio_samples = max(0, min(waveform.shape[-1], end_audio_sample - emitted_audio_samples))+ if chunk_audio_samples == 0:+ return waveform[..., :0], 0+ return waveform[..., -chunk_audio_samples:], chunk_audio_samplesdiff --git a/packages/ltx-pipelines/src/ltx_pipelines/chunks/planner.py b/packages/ltx-pipelines/src/ltx_pipelines/chunks/planner.pynew file mode 100644index 0000000..96eacd7--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/chunks/planner.py@@ -0,0 +1,140 @@+"""Plan chunk keyframes and emit zero-latent Chunks with injected contexts and factories."""++from __future__ import annotations++import logging+from collections.abc import Iterator, Sequence++import torch++from ltx_core.conditioning import ConditioningItem+from ltx_core.types import SpatioTemporalScaleFactors, VideoPixelShape+from ltx_pipelines.chunks.conditionings import generated_keyframe_slots_for_chunk+from ltx_pipelines.chunks.layout import ChunkConfig, ChunkLayout, audio_latent_for_layout, uniform_chunk_layouts+from ltx_pipelines.chunks.state import (+ Chunk,+ MakeAudioConditionings,+ MakeVideoConditionings,+ VideoConditioningsWithGeneratedKeyframes,+ _empty_conditionings,+)+from ltx_pipelines.utils.helpers import (+ create_initial_av_latents,+ evenly_spaced_keyframe_positions,+ has_generated_keyframes,+ resolve_generated_keyframes,+)+from ltx_pipelines.utils.types import VideoAudio++logger = logging.getLogger(__name__)+++def plan_chunk_keyframes(+ generated_keyframes: int | Sequence[int],+ *,+ num_frames: int,+ layouts: Sequence[ChunkLayout],+) -> tuple[int, ...]:+ """Resolve ``generated_keyframes`` to global pixel indices for overlapping chunks.+ An integer is a per-chunk budget. Non-final chunks reserve one slot at their seam+ and spread the rest through their new pixel range; final chunks spread every slot.+ A sequence is an exact list of global positions, assigned to chunks by layout ownership.+ """+ if not has_generated_keyframes(generated_keyframes):+ return ()+ if len(layouts) <= 1 or not isinstance(generated_keyframes, int):+ return tuple(resolve_generated_keyframes(generated_keyframes, num_frames))++ last = len(layouts) - 1+ positions = {+ position+ for index, layout in enumerate(layouts)+ for position in _budget_positions_for_layout(generated_keyframes, layout, is_final=index == last)+ }+ return tuple(sorted(positions))+++def _budget_positions_for_layout(budget: int, layout: ChunkLayout, *, is_final: bool) -> tuple[int, ...]:+ start, end = layout.owned_pixel_range+ if end <= start:+ return ()+ interior_count = budget if is_final else budget - 1+ try:+ positions = tuple(+ start + position for position in evenly_spaced_keyframe_positions(interior_count, end - start)+ )+ except ValueError as error:+ raise ValueError(+ f"generated_keyframes={budget} does not fit in chunk owned pixel range [{start}, {end})"+ ) from error+ if is_final:+ return positions+ return (*positions, end - 1)+++def generate_uniform_chunks(+ *,+ target: VideoPixelShape,+ context: VideoAudio[torch.Tensor],+ device: torch.device,+ dtype: torch.dtype,+ config: ChunkConfig,+ video_scale_factors: SpatioTemporalScaleFactors,+ make_video_conditionings: MakeVideoConditionings = _empty_conditionings,+ make_audio_conditionings: MakeAudioConditionings = _empty_conditionings,+ audio_latent: torch.Tensor | None = None,+ generated_keyframes: int | Sequence[int] = 0,+) -> Iterator[Chunk]:+ """Yield zero-latent ``Chunk``s from :func:`uniform_chunk_layouts`, with contexts and factories.+ ``config`` sets the window size and carry. When ``chunk_pixel_frames`` covers the snapped+ clip, the plan is a single chunk.+ When ``audio_latent`` is set, each chunk's audio is the matching slice rather than zeros.+ ``generated_keyframes`` is planned against these layouts and appended after the+ pipeline-owned video conditionings. The same resulting callables are stamped on+ every chunk; each factory sees that chunk's layout and latents when denoise materializes.+ """+ layouts = uniform_chunk_layouts(target_pixel_shape=target, config=config)+ keyframe_indices = plan_chunk_keyframes(+ generated_keyframes,+ num_frames=target.frames,+ layouts=layouts,+ )+ if keyframe_indices:++ def make_generated_keyframes(chunk: Chunk) -> list[ConditioningItem]:+ return generated_keyframe_slots_for_chunk(chunk, keyframe_indices=keyframe_indices)++ make_video_conditionings = VideoConditioningsWithGeneratedKeyframes(+ inner=make_video_conditionings,+ generated_keyframes=make_generated_keyframes,+ )+ logger.info("Plan: %d chunks", len(layouts))++ def _chunks() -> Iterator[Chunk]:+ for layout in layouts:+ pixel_shape = target._replace(frames=layout.pixel_frames)+ video, initial_audio = create_initial_av_latents(+ width=pixel_shape.width,+ height=pixel_shape.height,+ frames=pixel_shape.frames,+ fps=pixel_shape.fps,+ device=device,+ dtype=dtype,+ video_scale_factors=video_scale_factors,+ )+ audio = (+ audio_latent_for_layout(audio_latent, layout, target.fps).to(device=device, dtype=dtype)+ if audio_latent is not None+ else initial_audio+ )+ yield Chunk(+ layout=layout,+ video=video,+ audio=audio,+ video_context=context.video,+ audio_context=context.audio,+ make_video_conditionings=make_video_conditionings,+ make_audio_conditionings=make_audio_conditionings,+ )++ return _chunks()diff --git a/packages/ltx-pipelines/src/ltx_pipelines/chunks/state.py b/packages/ltx-pipelines/src/ltx_pipelines/chunks/state.pynew file mode 100644index 0000000..818f51f--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/chunks/state.py@@ -0,0 +1,91 @@+"""The chunk wire: layout, latents, contexts, and conditioning factories."""++from __future__ import annotations++from collections.abc import Callable+from dataclasses import dataclass++import torch++from ltx_core.conditioning import ConditioningItem+from ltx_core.types import Audio+from ltx_pipelines.chunks.layout import ChunkLayout+++def _empty_conditionings(_chunk: Chunk) -> list[ConditioningItem]:+ return []+++MakeVideoConditionings = Callable[["Chunk"], list[ConditioningItem]]+MakeAudioConditionings = Callable[["Chunk"], list[ConditioningItem]]+++@dataclass(frozen=True)+class VideoConditioningsWithGeneratedKeyframes:+ """Append planned generated-keyframe slots after pipeline-owned conditionings."""++ inner: MakeVideoConditionings+ generated_keyframes: MakeVideoConditionings++ def __call__(self, chunk: Chunk) -> list[ConditioningItem]:+ return [*self.inner(chunk), *self.generated_keyframes(chunk)]++ def replace_inner(self, inner: MakeVideoConditionings) -> VideoConditioningsWithGeneratedKeyframes:+ return VideoConditioningsWithGeneratedKeyframes(inner=inner, generated_keyframes=self.generated_keyframes)+++@dataclass(frozen=True)+class GeneratedKeyframes:+ """Extracted slot planes after denoise, with their chunk-local pixel indices.+ Attributes:+ latent: Unpatchified ``(B, C, K, H, W)`` slot latent (same sidecar as+ ``LatentState.generated_keyframes``).+ pixel_frame_indices: Chunk-local pixel-frame index of each plane, parallel to K.+ """++ latent: torch.Tensor+ pixel_frame_indices: tuple[int, ...]+++@dataclass(frozen=True)+class Chunk:+ """One chunk in transit between chunk operators.+ Attributes:+ layout: Temporal window this chunk covers on the stitched pixel timeline.+ video: Raw (never patchified) video latent, or ``None`` if this stream is unused.+ audio: Raw audio latent, or ``None`` if this stream is unused.+ video_context: Prompt embeddings for the video denoiser.+ audio_context: Prompt embeddings for the audio denoiser.+ make_video_conditionings: Factory that materializes video+ :class:`~ltx_core.conditioning.ConditioningItem` lists at the current latent+ shape when the chunk reaches denoise. The same callable survives a spatial+ upsample.+ make_audio_conditionings: Same as ``make_video_conditionings`` for audio.+ generated_keyframes: Slot planes extracted after denoise, or ``None`` if this+ chunk did not produce them.+ incoming_keyframes: Planes received from the previous chunk's outgoing overlap,+ rebased onto this chunk's local timeline for fixed conditioning and decode.+ """++ layout: ChunkLayout+ video: torch.Tensor | None+ audio: torch.Tensor | None+ video_context: torch.Tensor | None = None+ audio_context: torch.Tensor | None = None+ make_video_conditionings: MakeVideoConditionings = _empty_conditionings+ make_audio_conditionings: MakeAudioConditionings = _empty_conditionings+ generated_keyframes: GeneratedKeyframes | None = None+ incoming_keyframes: GeneratedKeyframes | None = None+++@dataclass(frozen=True)+class DecodedChunk:+ """Contiguous decoded output segment for progressive encode.+ Attributes:+ video: Pixel frames after dropping or blending stitch overlap. One input chunk+ may produce separate body and blended-tail segments to keep buffering bounded.+ audio: Vocoded (or muxed source) audio matching this video segment, or ``None``.+ """++ video: torch.Tensor+ audio: Audio | None = Nonediff --git a/packages/ltx-pipelines/src/ltx_pipelines/dfr_helpers/__init__.py b/packages/ltx-pipelines/src/ltx_pipelines/dfr_helpers/__init__.pynew file mode 100644index 0000000..dc1e91a--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/dfr_helpers/__init__.py@@ -0,0 +1,5 @@+"""DFR layout and pure helpers used by ``dfr_stages`` and ``dfr_pipeline``.+Public modules:+- ``layout`` -- canvas segment grid and temporal tile partitioning+- ``ops`` -- audio tiling, keyframe bags, Lanczos, canvas trim+"""diff --git a/packages/ltx-pipelines/src/ltx_pipelines/dfr_layout.py b/packages/ltx-pipelines/src/ltx_pipelines/dfr_helpers/layout.pysimilarity index 80%rename from packages/ltx-pipelines/src/ltx_pipelines/dfr_layout.pyrename to packages/ltx-pipelines/src/ltx_pipelines/dfr_helpers/layout.pyindex c0b33c7..8dea7e5 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/dfr_layout.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/dfr_helpers/layout.py@@ -95,20 +95,27 @@ class TemporalTilePlan:temporal_scale: int = VIDEO_SCALE_FACTORS.time,) -> None:"""Partition the canvas with :func:`split_canvas_at_seams` and attach per-window anchors/slots.- Overlap is one canvas segment in latent cells plus the shared seam cell, matching the old- lead-in + ``drop_latent_prefix += 1`` handover. Remainder segments go to the leading tiles.+ Remainder segments go to the leading tiles.+ Slots are one per canvas segment midpoint, derived globally and then handed to whichever+ window contains them.+ The split takes **no overlap**: a tile's kept cells are exactly the segments it owns. The+ pinned prefix a non-first tile denoises before them is not a cell count at all -- it starts+ at the last keyframe before the seam, so the caller derives it from the plane positions+ (:func:`~ltx_pipelines.dfr_helpers.ops.tile_prefix`) rather than from a configured overlap."""seams = [0, *(pixel_to_latent_index(position, temporal_scale) for position in seam_positions)]latent_len = (num_frames - 1) // temporal_scale + 1- overlap = (seams[1] - seams[0]) + 1 if len(seams) > 1 else 0- intervals = split_canvas_at_seams(seams, num_tiles, overlap, latent_len)+ intervals = split_canvas_at_seams(seams, num_tiles, 0, latent_len)+ # Midpoints of the *canvas* segments, not of each window's own marks. A window's first mark+ # is its own start, so per-window midpoints land wherever that falls -- including off the x8+ # latent border, which a plane may not do: a tile starts on one (see ``tile_prefix``).+ global_slots = [(left + right) // 2 for left, right in itertools.pairwise([0, *seam_positions])]tiles: list[TemporalTile] = []for interval in intervals:pixel_start = interval.start * temporal_scalepixel_end = (interval.end - 1) * temporal_scaleanchors = tuple(position for position in seam_positions if pixel_start <= position <= pixel_end)- marks = [pixel_start, *[position for position in seam_positions if pixel_start < position <= pixel_end]]- slots = tuple((left + right) // 2 for left, right in itertools.pairwise(marks))+ slots = tuple(position for position in global_slots if pixel_start <= position <= pixel_end)tiles.append(TemporalTile(interval, pixel_start, pixel_end, anchors, slots))self.tiles = tuple(tiles)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/dfr_helpers/ops.py b/packages/ltx-pipelines/src/ltx_pipelines/dfr_helpers/ops.pynew file mode 100644index 0000000..cdc9fca--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/dfr_helpers/ops.py@@ -0,0 +1,330 @@+"""Pure DFR helpers: fps snap, Lanczos, audio tiling, keyframe bags, canvas trim.+No ``DiffusionStage`` / Gemma / ``ModelPaths``. Imported by ``dfr_stages`` and ``dfr_pipeline``.+"""++from __future__ import annotations++import logging+from collections.abc import Iterable, Sequence+from dataclasses import dataclass, replace++import numpy as np+import torch+from PIL import Image++from ltx_core.conditioning import ConditioningItem, VideoConditionByKeyframeIndex, VideoConditionByLatentIndex+from ltx_core.tiling import DimensionTilingConfig, TileCountConfig+from ltx_core.types import Audio, AudioLatentShape, VideoPixelShape+from ltx_pipelines.utils.types import ImageConditioningInput++logger = logging.getLogger(__name__)++# Anchor keyframes carried between temporal rounds are ours, pinned just short of fully clean so a+# tile can still settle its seam frame.+ANCHOR_KEYFRAME_STRENGTH = 0.95+TEMPORAL_ANCESTRAL_ETA = 0.5+# Transformer fps is independent of playback fps. RoPE time is ``pixel_frame / fps``, so rates the+# model never saw (48, 50, 120, ...) cannot lay out the 8 pixel frames inside one latent token --+# they decode as a motion spike at each latent border followed by a stall. Anything above 30 snaps+# to 60; playback fps is used for decoding only.+MAX_CONDITIONING_FPS = 60.0+SNAP_CONDITIONING_FPS_ABOVE = 30.0+++def conditioning_fps(playback_fps: float) -> float:+ """RoPE/token fps for the transformer. Values above 30 snap to 60; playback fps is unchanged."""+ return MAX_CONDITIONING_FPS if playback_fps > SNAP_CONDITIONING_FPS_ABOVE else playback_fps+++# HDR stage-2 spatial overlap. Temporal windows are sequential and pinned; spatial tiles inside+# a time window blend after every Euler step; time windows are not blended. The first detailing+# step is 2x2; remaining steps retile to 4x4. A two-value schedule stays 2x2.+EPILOGUE_SPATIAL_OVERLAP = 10+EPILOGUE_SPATIAL_COARSE_TILES = 2+EPILOGUE_SPATIAL_TILES = 4+EPILOGUE_KEYFRAME_STRENGTH = 1.0+DETAILING_LORA_STRENGTH = 0.5+++def lanczos_x2_fhwc(frames: torch.Tensor) -> torch.Tensor:+ """Stretch each RGB frame 2x with Lanczos. ``frames`` is ``(F, H, W, C)`` in ``[0, 1]``."""+ if frames.ndim != 4:+ raise ValueError(f"Expected (F, H, W, C) RGB, got shape {tuple(frames.shape)}")+ if frames.shape[0] < 1:+ raise ValueError("Need at least one frame to Lanczos-upsample")+ out: list[torch.Tensor] = []+ for frame in frames:+ height, width, channels = frame.shape+ array = (frame.detach().float().clamp(0, 1).cpu().numpy() * 255.0).round().astype(np.uint8)+ if channels == 1:+ image = Image.fromarray(array[..., 0], mode="L")+ elif channels == 3:+ image = Image.fromarray(array, mode="RGB")+ else:+ raise ValueError(f"Lanczos x2 expects 1 or 3 channels, got {channels}")+ image = image.resize((width * 2, height * 2), resample=Image.Resampling.LANCZOS)+ resized = torch.from_numpy(np.asarray(image, dtype=np.float32) / 255.0)+ if resized.ndim == 2:+ resized = resized.unsqueeze(-1)+ out.append(resized)+ return torch.stack(out, dim=0)+++def clamp_dim_tiling(cfg: DimensionTilingConfig, dim_size: int, axis: str) -> DimensionTilingConfig:+ """Clamp a single dim's tile count and overlap to the latent's extent.+ ``split_by_count`` requires ``overlap < tile_size``; with+ ``tile_size = (dim_size + overlap*(n-1)) // n`` this reduces to+ ``overlap <= dim_size - n``. When the configured overlap exceeds this+ bound it is clamped; if the latent is too small to hold ``n`` tiles+ at all, tiling falls back to a single tile on this axis.+ """+ n = cfg.num_tiles+ if n <= 1:+ return cfg+ if dim_size < n:+ logger.warning(+ "%s tiling: dim_size=%d < num_tiles=%d; falling back to 1 tile on this axis.",+ axis,+ dim_size,+ n,+ )+ return DimensionTilingConfig(1, 0)+ max_overlap = dim_size - n+ if cfg.overlap <= max_overlap:+ return cfg+ logger.warning(+ "%s tiling: overlap=%d exceeds latent bound (%d); clamping to %d.",+ axis,+ cfg.overlap,+ max_overlap,+ max_overlap,+ )+ return DimensionTilingConfig(n, max_overlap)+++def clamp_tile_to_latent(tiling: TileCountConfig, latent_shape: tuple[int, int, int]) -> TileCountConfig:+ """Clamp frame, height, and width tilings to the latent's extents.+ ``latent_shape`` is ``(F, H, W)`` in latent units.+ """+ frames, height, width = latent_shape+ return replace(+ tiling,+ frames=clamp_dim_tiling(tiling.frames, frames, "Frame"),+ height=clamp_dim_tiling(tiling.height, height, "Height"),+ width=clamp_dim_tiling(tiling.width, width, "Width"),+ )+++def resample_audio_time(+ audio_latent: torch.Tensor,+ src_start: float,+ src_end: float,+ out_frames: int,+) -> torch.Tensor:+ """Linearly sample ``audio_latent`` along T over ``[src_start, src_end)`` latent cells."""+ if out_frames < 1:+ raise ValueError(f"out_frames must be >= 1, got {out_frames}")+ full_t = audio_latent.shape[2]+ if full_t < 1:+ raise ValueError("Cannot resample an empty audio latent")+ span = src_end - src_start+ if span <= 0:+ raise ValueError(f"Audio window is empty: [{src_start}, {src_end})")+ step = span / out_frames+ positions = src_start + step * torch.arange(out_frames, device=audio_latent.device, dtype=torch.float32)+ positions = positions.clamp(0, full_t - 1)+ lo = positions.floor().long()+ hi = (lo + 1).clamp(max=full_t - 1)+ weight = (positions - lo.to(torch.float32)).to(dtype=audio_latent.dtype).view(1, 1, -1, 1)+ return audio_latent[:, :, lo] * (1 - weight) + audio_latent[:, :, hi] * weight+++def audio_latent_for_tile(+ audio_latent: torch.Tensor,+ *,+ pixel_start: int,+ local_frames: int,+ playback_fps: float,+ source_duration: float,+ cond_fps: float,+) -> torch.Tensor:+ """Stage-1 audio for one temporal tile: playback window, resampled to the stage's token count.+ Source bounds are wall-clock: ``pixel_start / playback_fps`` through+ ``(pixel_start + local_frames) / playback_fps``, as a fraction of ``source_duration`` (stage 1's+ ``N / fps``). Temporal upsample uses ``N -> 2(N-1)+1`` while fps doubles, so the new canvas is+ slightly shorter than ``2x``; a fraction of *canvas frames* would therefore pull audio from past+ the tile's playback. ``cond_fps`` sizes only the *output* token count DiffusionStage allocates.+ """+ if local_frames <= 0:+ raise ValueError(f"local_frames must be >= 1, got {local_frames}")+ if playback_fps <= 0:+ raise ValueError(f"playback_fps must be > 0, got {playback_fps}")+ if source_duration <= 0:+ raise ValueError(f"source_duration must be > 0, got {source_duration}")+ full_t = audio_latent.shape[2]+ if full_t <= 0:+ raise ValueError("Cannot slice audio for a tile with an empty audio latent")+ src_start = pixel_start / playback_fps / source_duration * full_t+ src_end = (pixel_start + local_frames) / playback_fps / source_duration * full_t+ target_frames = AudioLatentShape.from_video_pixel_shape(+ VideoPixelShape(batch=1, frames=local_frames, height=1, width=1, fps=cond_fps)+ ).frames+ return resample_audio_time(audio_latent, src_start, src_end, target_frames)+++def keyframe_conditionings_from_latents(+ keyframes: torch.Tensor,+ positions: Sequence[int],+ strength: float,+) -> list[ConditioningItem]:+ """Build ``VideoConditionByKeyframeIndex`` guides from already-encoded keyframe latents."""+ if keyframes.ndim != 5:+ raise ValueError(f"Expected keyframes (B, C, K, H, W), got {tuple(keyframes.shape)}")+ if keyframes.shape[2] != len(positions):+ raise ValueError(f"Expected {len(positions)} keyframe latents, got K={keyframes.shape[2]}")+ return [+ VideoConditionByKeyframeIndex(+ keyframes=keyframes[:, :, index : index + 1],+ frame_idx=int(frame_idx),+ strength=strength,+ )+ for index, frame_idx in enumerate(positions)+ ]+++def slot_initials_from_video(+ video_latent: torch.Tensor,+ positions: Sequence[int],+ temporal_scale: int,+) -> torch.Tensor:+ """Stack the nearest video latent frames as ``(B, C, K, H, W)`` slot seeds."""+ frames = []+ for position in positions:+ index = min(max(round(int(position) / temporal_scale), 0), video_latent.shape[2] - 1)+ frames.append(video_latent[:, :, index : index + 1])+ return torch.cat(frames, dim=2)+++@dataclass(frozen=True)+class TilePrefix:+ """Where a non-first tile starts, and how much of it is handed over rather than denoised.+ A tile used to begin on a mid-canvas 8-frame cell while being denoised as its own clip, whose+ cell 0 the model reads as a *single* pixel frame (causal convention). Content and shape+ disagreed there, which is why the lead-in had to be thrown away and why RoPE time inside a tile+ ran 7 frames ahead of the canvas.+ So a tile now begins on a real one-frame latent: the keyframe plane at the last plane position+ before the seam. Cell 0 is that plane, cells ``1 .. (seam - keyframe) / scale`` are the video+ between it and the seam, and the tile resumes on the cell after the seam. The frame accounting+ closes exactly -- cell ``k`` covers ``keyframe + scale*(k-1) + 1 ... keyframe + scale*k``, so the+ last pinned cell ends *on* the seam and the seam keyframe needs no conditioning of its own: it is+ absorbed into that cell. The tile then looks like an i2v clip, which is in distribution.+ Attributes:+ keyframe_position: pixel frame of the plane that becomes cell 0.+ video_start_cell: first canvas cell of the pinned video run (right after the plane).+ cells: pinned latent cells, the plane included.+ resume_pixel: first pixel frame this tile actually denoises.+ """++ keyframe_position: int+ video_start_cell: int+ cells: int+ resume_pixel: int+++def tile_prefix(seam_pixel: int, plane_positions: Iterable[int], temporal_scale: int) -> TilePrefix:+ """Resolve a non-first tile's pinned prefix from the planes available before its seam."""+ before = [position for position in plane_positions if position < seam_pixel]+ if not before:+ raise RuntimeError(f"no keyframe plane before seam {seam_pixel} to start the tile on")+ keyframe = max(before)+ if keyframe % temporal_scale or seam_pixel % temporal_scale:+ raise RuntimeError(f"keyframe {keyframe} and seam {seam_pixel} must both sit on the x{temporal_scale} border")+ return TilePrefix(+ keyframe_position=keyframe,+ video_start_cell=keyframe // temporal_scale + 1,+ cells=1 + (seam_pixel - keyframe) // temporal_scale,+ resume_pixel=seam_pixel + 1,+ )+++def lead_in_carryover(+ previous: tuple[int, torch.Tensor],+ prefix: TilePrefix,+ plane: torch.Tensor,+) -> ConditioningItem:+ """Pin a tile's prefix: its cell-0 plane, then the video between that plane and the seam.+ The video half used to be re-denoised from the upsampled input with the shared keyframe at the+ seam left to make the two tiles agree. This makes them agree instead: strength 1 sets+ ``denoise_mask = 0``, and ``GaussianNoiser`` does ``lerp(clean, noised, mask)``, so those cells+ *are* the previous tile's result at every step -- the mechanism A2Vid uses to freeze audio.+ ``previous`` is ``(canvas cell the previous tile's cell 0 stands for, its output)``. The lookup+ has to go through the canvas because the two tiles start in different places: a prefixed tile's+ cell 0 is its *plane*, so its cell ``k`` is canvas cell ``base + k``, while the first tile of a+ round starts on the canvas itself. Passing the video-run start for both and adding one is how+ this got the first hand-over wrong -- tile 0 has no plane to skip.+ """+ base_cell, previous_latent = previous+ video_cells = prefix.cells - 1+ offset = prefix.video_start_cell - base_cell+ if offset < 0 or offset + video_cells > previous_latent.shape[2]:+ raise RuntimeError(+ f"pinned canvas cells [{prefix.video_start_cell}, {prefix.video_start_cell + video_cells}) fall "+ f"outside the previous tile, whose cell 0 is canvas cell {base_cell} and which is "+ f"{previous_latent.shape[2]} cells long"+ )+ carried = torch.cat([plane, previous_latent[:, :, offset : offset + video_cells]], dim=2)+ if carried.shape[2] != prefix.cells:+ raise RuntimeError(f"pinned prefix is {carried.shape[2]} cells, expected {prefix.cells}")+ return VideoConditionByLatentIndex(latent=carried, strength=1.0, latent_idx=0)+++def rebase_image_conditionings(+ images: Sequence[ImageConditioningInput],+ *,+ pixel_scale: int,+ pixel_start: int = 0,+ pixel_end: int | None = None,+) -> list[ImageConditioningInput]:+ """Map user ``frame_idx`` values from the requested canvas onto a temporally-upsampled grid.+ After ``r`` temporal rounds the same moment sits at ``frame_idx * 2**r``. When ``pixel_end`` is+ set, only images inside ``[pixel_start, pixel_end]`` are kept and indices become tile-local.+ """+ rebased: list[ImageConditioningInput] = []+ for image in images:+ scaled = image.frame_idx * pixel_scale+ if pixel_end is not None and not (pixel_start <= scaled <= pixel_end):+ continue+ rebased.append(ImageConditioningInput(image.path, scaled - pixel_start, image.strength, image.crf))+ return rebased+++def trim_video_to_requested_frames(+ latent: torch.Tensor,+ *,+ canvas_frames: int,+ requested_frames: int,+ temporal_upscalings: int,+ temporal_scale: int,+) -> tuple[torch.Tensor, int]:+ """Drop canvas tail padding so the caller gets ``(requested - 1) * 2**rounds + 1`` frames."""+ target_frames = (requested_frames - 1) * 2**temporal_upscalings + 1+ if target_frames > canvas_frames:+ raise RuntimeError(f"Target {target_frames} frames exceeds the generated canvas {canvas_frames}")+ if target_frames == canvas_frames:+ return latent, canvas_frames+ keep_latents = (target_frames - 1) // temporal_scale + 1+ return latent[:, :, :keep_latents], target_frames+++def trim_audio_to_video_duration(+ decoded_audio: Audio,+ *,+ num_frames: int,+ playback_fps: float,+) -> Audio:+ """Cut decoded audio to the shipped video duration so the muxed container does not outlast it."""+ video_seconds = num_frames / playback_fps+ audio_samples = min(decoded_audio.waveform.shape[-1], round(video_seconds * decoded_audio.sampling_rate))+ if audio_samples != decoded_audio.waveform.shape[-1]:+ return replace(decoded_audio, waveform=decoded_audio.waveform[..., :audio_samples])+ return decoded_audiodiff --git a/packages/ltx-pipelines/src/ltx_pipelines/dfr_mgpu.py b/packages/ltx-pipelines/src/ltx_pipelines/dfr_mgpu.pyindex 198669c..785041d 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/dfr_mgpu.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/dfr_mgpu.py@@ -271,6 +271,7 @@ class DFRRunner(MGPURunner):enhance_static_cache=enhance_static_cache,temporal_upscalings=temporal_upscalings,spatial_upscalings=spatial_upscalings,+ decode_device_fn=lambda _: self._pipeline.device,)if dist.get_rank() != _DRIVER_RANK:yield None # workers: nothing to encodediff --git a/packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py b/packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.pyindex 6bd066d..146b3c8 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/dfr_pipeline.py@@ -4,49 +4,47 @@ from __future__ import annotationsimport argparseimport logging-from collections.abc import Sequence+from collections.abc import Callablefrom dataclasses import replace-from functools import partial-from typing import TYPE_CHECKING+from typing import Any-import numpy as npimport torch-from PIL import Imagefrom ltx_core.allocator_trim_strategy import AllocatorTrimStrategy-from ltx_core.components.diffusion_steps import EulerAncestralDiffusionStepfrom ltx_core.components.noisers import GaussianNoiser-from ltx_core.conditioning import (- ConditioningItem,- VideoConditionByKeyframeIndex,- VideoConditionByReferenceLatent,- VideoGeneratedKeyframeSlots,-)from ltx_core.loader import LoraPathStrengthAndSDOpsfrom ltx_core.loader.registry import Registry-from ltx_core.modality_tiling import VideoModalityTilingHelperfrom ltx_core.model.transformer.compiling import CompilationConfig-from ltx_core.model.transformer.modality import Modalityfrom ltx_core.model.video_vae import (AUTO_TILING,AutoTiling,TilingConfig,- VideoEncoder,get_video_chunks_number,)from ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy-from ltx_core.tiling import DimensionTilingConfig, Tile, TileCountConfig-from ltx_core.tools import LatentTools, VideoLatentTools-from ltx_core.types import VIDEO_SCALE_FACTORS, AudioLatentShape, LatentState, VideoPixelShape-from ltx_pipelines.dfr_layout import (- TemporalTilePlan,- pixel_to_latent_index,- resolve_canvas,+from ltx_core.types import VIDEO_SCALE_FACTORS, VideoPixelShape+from ltx_pipelines.dfr_helpers.layout import resolve_canvas+from ltx_pipelines.dfr_helpers.ops import (+ DETAILING_LORA_STRENGTH,+ trim_audio_to_video_duration,+ trim_video_to_requested_frames,+)+from ltx_pipelines.dfr_stages import (+ KeyframeCarry,+ denoise_stage1,+ denoise_stage2,+ run_one_temporal_round,+ run_spatial_epilogue,+)+from ltx_pipelines.distilled import (+ ANCESTRAL_NOISE_SEED_OFFSET,+ ANCESTRAL_STAGE_2_NOISE_SEED_OFFSET,+ ancestral_sampler_kwargs,+ should_use_ancestral_sampler,)from ltx_pipelines.iclora_utils import read_lora_reference_downscale_factorfrom ltx_pipelines.utils.args import (- ImageConditioningInput,LoraAction,default_2_stage_distilled_arg_parser,resolve_cli_params,@@ -64,340 +62,52 @@ from ltx_pipelines.utils.blocks import (resolve_num_frames,)from ltx_pipelines.utils.constants import DISTILLED_SIGMAS, STAGE_2_DISTILLED_SIGMAS-from ltx_pipelines.utils.denoisers import SimpleDenoiserfrom ltx_pipelines.utils.helpers import (assert_resolution,- combined_image_conditionings,+ assert_stage_supports_generated_keyframes,decode_keyframes_from_slots,ensure_tiling_config,get_device,tiling_scale_factors_for_vae,)-from ltx_pipelines.utils.media_io import encode_video, to_vae_range+from ltx_pipelines.utils.media_io import encode_videofrom ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.samplers import euler_ancestral_denoising_loop-from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode, PipelineOutput--if TYPE_CHECKING:- from ltx_core.guidance.perturbations import BatchedPerturbationConfig--logger = logging.getLogger(__name__)--# Anchor keyframes carried between temporal rounds are ours, pinned just short of fully clean so a-# tile can still settle its seam frame.-_ANCHOR_KEYFRAME_STRENGTH = 0.95-_TEMPORAL_ANCESTRAL_ETA = 0.5-# Transformer fps is independent of playback fps. RoPE time is ``pixel_frame / fps``, so rates the-# model never saw (48, 50, 120, ...) cannot lay out the 8 pixel frames inside one latent token ---# they decode as a motion spike at each latent border followed by a stall. Anything above 30 snaps-# to 60; playback fps is used for decoding only.-_MAX_CONDITIONING_FPS = 60.0-_SNAP_CONDITIONING_FPS_ABOVE = 30.0---def _conditioning_fps(playback_fps: float) -> float:- """RoPE/token fps for the transformer. Values above 30 snap to 60; playback fps is unchanged."""- return _MAX_CONDITIONING_FPS if playback_fps > _SNAP_CONDITIONING_FPS_ABOVE else playback_fps---# HDR stage-2 spatial overlap. Temporal epilogue tiles cut on the last t-round's window-# seams (same lead-in dropout; the earlier tile keeps the seam cell). Spatial tiles inside-# a time window blend and retile after every Euler step; time windows are not blended.-_EPILOGUE_SPATIAL_OVERLAP = 12-_EPILOGUE_KEYFRAME_STRENGTH = 1.0-_DETAILING_LORA_STRENGTH = 0.5---def _lanczos_x2_fhwc(frames: torch.Tensor) -> torch.Tensor:- """Stretch each RGB frame 2x with Lanczos. ``frames`` is ``(F, H, W, C)`` in ``[0, 1]``."""- if frames.ndim != 4:- raise ValueError(f"Expected (F, H, W, C) RGB, got shape {tuple(frames.shape)}")- if frames.shape[0] < 1:- raise ValueError("Need at least one frame to Lanczos-upsample")- out: list[torch.Tensor] = []- for frame in frames:- height, width, channels = frame.shape- array = (frame.detach().float().clamp(0, 1).cpu().numpy() * 255.0).round().astype(np.uint8)- if channels == 1:- image = Image.fromarray(array[..., 0], mode="L")- elif channels == 3:- image = Image.fromarray(array, mode="RGB")- else:- raise ValueError(f"Lanczos x2 expects 1 or 3 channels, got {channels}")- image = image.resize((width * 2, height * 2), resample=Image.Resampling.LANCZOS)- resized = torch.from_numpy(np.asarray(image, dtype=np.float32) / 255.0)- if resized.ndim == 2:- resized = resized.unsqueeze(-1)- out.append(resized)- return torch.stack(out, dim=0)---def _clamp_dim_tiling(cfg: DimensionTilingConfig, dim_size: int, axis: str) -> DimensionTilingConfig:- """Clamp a single dim's tile count and overlap to the latent's extent.- ``split_by_count`` requires ``overlap < tile_size``; with- ``tile_size = (dim_size + overlap*(n-1)) // n`` this reduces to- ``overlap <= dim_size - n``. When the configured overlap exceeds this- bound it is clamped; if the latent is too small to hold ``n`` tiles- at all, tiling falls back to a single tile on this axis.- """- n = cfg.num_tiles- if n <= 1:- return cfg- if dim_size < n:- logger.warning(- "%s tiling: dim_size=%d < num_tiles=%d; falling back to 1 tile on this axis.",- axis,- dim_size,- n,- )- return DimensionTilingConfig(1, 0)- max_overlap = dim_size - n- if cfg.overlap <= max_overlap:- return cfg- logger.warning(- "%s tiling: overlap=%d exceeds latent bound (%d); clamping to %d.",- axis,- cfg.overlap,- max_overlap,- max_overlap,- )- return DimensionTilingConfig(n, max_overlap)---def _clamp_tile_to_latent(tiling: TileCountConfig, latent_shape: tuple[int, int, int]) -> TileCountConfig:- """Clamp frame, height, and width tilings to the latent's extents.- ``latent_shape`` is ``(F, H, W)`` in latent units.- """- frames, height, width = latent_shape- return replace(- tiling,- frames=_clamp_dim_tiling(tiling.frames, frames, "Frame"),- height=_clamp_dim_tiling(tiling.height, height, "Height"),- width=_clamp_dim_tiling(tiling.width, width, "Width"),- )---class _TiledModelWrapper(torch.nn.Module):- """Runs the transformer once per latent tile and blends the tiles into one prediction.- The single-GPU counterpart of- :class:`~ltx_core.multigpu.transformer.tiled_data_parallel.TiledDataParallelModelWrapper`:- same :class:`VideoModalityTilingHelper`, same trapezoidal blend masks, same- conditioning-token filtering. Two differences: every tile runs here rather than round-robin- across ranks, so the ranks' ``all_reduce`` is just the accumulator; and this wraps the- ``X0Model`` instead of the bare velocity model, so it blends x0 predictions rather than- velocities. ``to_denoised`` is affine in the velocity and every tile sees the same- per-token timesteps, so with blend weights summing to 1 the two are the same value.- Tiling inside the model call is what makes the overlap agree at *every* denoising step: the- sampler above still sees one full-canvas latent and takes one Euler step on it.- """-- def __init__(- self,- model: torch.nn.Module,- *,- video_tools: VideoLatentTools,- tiling: TileCountConfig,- seams: Sequence[int] = (),- normalize_positions: bool = True,- ) -> None:- super().__init__()- self.model = model- self._normalize_positions = normalize_positions- self._helper = VideoModalityTilingHelper(tiling, video_tools, seams=seams)-- @property- def num_blocks(self) -> int:- return self.model.num_blocks-- @property- def tiles(self) -> list[Tile]:- """The tiles every forward pass walks, in blend order."""- return self._helper.tiles-- def forward(- self,- video: Modality | None,- audio: Modality | None,- perturbations: BatchedPerturbationConfig | None,- ) -> tuple[torch.Tensor | None, torch.Tensor | None]:- if video is None:- return self.model(video, audio, perturbations)-- denoised_video: torch.Tensor | None = None- denoised_audio: torch.Tensor | None = None- for tile in self._helper.tiles:- tiled_video, ctx = self._helper.tile_modality(video, tile, normalize_positions=self._normalize_positions)- tile_out, audio_out = self.model(tiled_video, audio, perturbations)- denoised_video = self._helper.blend(tile_out, tile, ctx, denoised_video)- if audio_out is not None:- denoised_audio = audio_out if denoised_audio is None else denoised_audio + audio_out-- assert denoised_video is not None- if denoised_audio is not None:- # Every tile saw the whole audio but a different video context; average as TDP does.- denoised_audio = denoised_audio / len(self._helper.tiles)- return denoised_video, denoised_audio---def _resample_audio_time(- audio_latent: torch.Tensor,- src_start: float,- src_end: float,- out_frames: int,-) -> torch.Tensor:- """Linearly sample ``audio_latent`` along T over ``[src_start, src_end)`` latent cells."""- if out_frames < 1:- raise ValueError(f"out_frames must be >= 1, got {out_frames}")- full_t = audio_latent.shape[2]- if full_t < 1:- raise ValueError("Cannot resample an empty audio latent")- span = src_end - src_start- if span <= 0:- raise ValueError(f"Audio window is empty: [{src_start}, {src_end})")- step = span / out_frames- positions = src_start + step * torch.arange(out_frames, device=audio_latent.device, dtype=torch.float32)- positions = positions.clamp(0, full_t - 1)- lo = positions.floor().long()- hi = (lo + 1).clamp(max=full_t - 1)- weight = (positions - lo.to(torch.float32)).to(dtype=audio_latent.dtype).view(1, 1, -1, 1)- return audio_latent[:, :, lo] * (1 - weight) + audio_latent[:, :, hi] * weight---def _audio_latent_for_tile(- audio_latent: torch.Tensor,- *,- pixel_start: int,- local_frames: int,- playback_fps: float,- source_duration: float,- cond_fps: float,-) -> torch.Tensor:- """Stage-1 audio for one temporal tile: playback window, resampled to the stage's token count.- Source bounds are wall-clock: ``pixel_start / playback_fps`` through- ``(pixel_start + local_frames) / playback_fps``, as a fraction of ``source_duration`` (stage 1's- ``N / fps``). Temporal upsample uses ``N -> 2(N-1)+1`` while fps doubles, so the new canvas is- slightly shorter than ``2x``; a fraction of *canvas frames* would therefore pull audio from past- the tile's playback. ``cond_fps`` sizes only the *output* token count DiffusionStage allocates.- """- if local_frames <= 0:- raise ValueError(f"local_frames must be >= 1, got {local_frames}")- if playback_fps <= 0:- raise ValueError(f"playback_fps must be > 0, got {playback_fps}")- if source_duration <= 0:- raise ValueError(f"source_duration must be > 0, got {source_duration}")- full_t = audio_latent.shape[2]- if full_t <= 0:- raise ValueError("Cannot slice audio for a tile with an empty audio latent")- src_start = pixel_start / playback_fps / source_duration * full_t- src_end = (pixel_start + local_frames) / playback_fps / source_duration * full_t- target_frames = AudioLatentShape.from_video_pixel_shape(- VideoPixelShape(batch=1, frames=local_frames, height=1, width=1, fps=cond_fps)- ).frames- return _resample_audio_time(audio_latent, src_start, src_end, target_frames)---def _keyframe_conditionings_from_latents(- keyframes: torch.Tensor,- positions: Sequence[int],- strength: float,-) -> list[ConditioningItem]:- """Build ``VideoConditionByKeyframeIndex`` guides from already-encoded keyframe latents."""- if keyframes.ndim != 5:- raise ValueError(f"Expected keyframes (B, C, K, H, W), got {tuple(keyframes.shape)}")- if keyframes.shape[2] != len(positions):- raise ValueError(f"Expected {len(positions)} keyframe latents, got K={keyframes.shape[2]}")- return [- VideoConditionByKeyframeIndex(- keyframes=keyframes[:, :, index : index + 1],- frame_idx=int(frame_idx),- strength=strength,- )- for index, frame_idx in enumerate(positions)- ]---def _slot_initials_from_video(- video_latent: torch.Tensor,- positions: Sequence[int],- temporal_scale: int,-) -> torch.Tensor:- """Stack the nearest video latent frames as ``(B, C, K, H, W)`` slot seeds."""- frames = []- for position in positions:- index = min(max(round(int(position) / temporal_scale), 0), video_latent.shape[2] - 1)- frames.append(video_latent[:, :, index : index + 1])- return torch.cat(frames, dim=2)---def _merge_carry_forward_keyframes(- anchor_positions: Sequence[int],- anchor_latents: torch.Tensor | None,- slot_positions: Sequence[int],- slot_latents: torch.Tensor | None,-) -> tuple[list[int], torch.Tensor]:- """Build the next round's anchor bag: carried keyframe stills plus this round's denoised slots.- Positions must already be on the current round's pixel grid; callers remap (x2) for the next round.- """- by_position: dict[int, torch.Tensor] = {}- for positions, latents, label in (- (anchor_positions, anchor_latents, "anchor"),- (slot_positions, slot_latents, "slot"),- ):- if not positions:- continue- if latents is None:- raise RuntimeError(f"Missing {label} keyframe latents for carry-forward merge")- if latents.shape[2] != len(positions):- raise ValueError(f"{label} latents K={latents.shape[2]} != {len(positions)} positions")- for index, position in enumerate(positions):- by_position[int(position)] = latents[:, :, index : index + 1]- if not by_position:- raise RuntimeError("Carry-forward keyframe bag is empty")- ordered = sorted(by_position)- return ordered, torch.cat([by_position[position] for position in ordered], dim=2)-+from ltx_pipelines.utils.types import (+ DEFAULT_AUTO_DURATION,+ AutoDuration,+ ImageConditioningInput,+ OffloadMode,+ PipelineOutput,+)-def _rebase_image_conditionings(- images: Sequence[ImageConditioningInput],- *,- pixel_scale: int,- pixel_start: int = 0,- pixel_end: int | None = None,-) -> list[ImageConditioningInput]:- """Map user ``frame_idx`` values from the requested canvas onto a temporally-upsampled grid.- After ``r`` temporal rounds the same moment sits at ``frame_idx * 2**r``. When ``pixel_end`` is- set, only images inside ``[pixel_start, pixel_end]`` are kept and indices become tile-local.- """- rebased: list[ImageConditioningInput] = []- for image in images:- scaled = image.frame_idx * pixel_scale- if pixel_end is not None and not (pixel_start <= scaled <= pixel_end):- continue- rebased.append(ImageConditioningInput(image.path, scaled - pixel_start, image.strength, image.crf))- return rebased+_EPILOGUE_ANCESTRAL_NOISE_SEED_OFFSET = 30000class DFRPipeline:"""DFR pipeline on a keyframe-slot-capable distilled checkpoint.Stage 1 (half-res) generates video and keyframe slots on an x8-border segment grid; the half-res- video is reserved as the IC-LoRA reference while video and slots are spatially latent-upsampled.- Stage 2 re-denoises at full resolution with an x2 detailing- IC-LoRA. Shipped audio comes from stage 1: stage 2 still runs an audio pass because video needs+ video is reserved as the IC-LoRA reference; stage 2 spatially upsamples video and slots before denoising.+ Stage 2 re-denoises at full resolution with an x2 detailing IC-LoRA. Both stages and the spatial+ epilogue sample according to ``self.use_ancestral_sampler`` (see+ :func:`~ltx_pipelines.distilled.should_use_ancestral_sampler`). Shipped audio comes from stage 1:+ stage 2 still runs an audio pass because video needsthe cross-modal attention, but it re-noises audio under the detailing LoRA. Temporal tiles passfrozen stage-1 audio sliced to the tile's playback window (retiled onto the snapped-fps tokencount) for cross-attention only; they do not refine or ship audio.Optional ``temporal_upscalings`` (0-2): each round temporally x2-upsamples, splits the canvasinto ``2**round`` keyframe-seam tiles, invents mid-segment slots per tile, densifies with ancestral- Euler, and stitches. Optional ``spatial_upscalings`` (1 or 2): ``1`` is stage 1 at ``h/2`` and+ Euler, and stitches. A non-first tile starts on the last keyframe plane before its seam with a+ pinned prefix. Optional ``spatial_upscalings`` (1 or 2): ``1`` is stage 1 at ``h/2`` andstage 2 at ``h``; ``2`` is stage 1 at ``h/4``, stage 2 at ``h/2``, then a full-res spatialdetailing epilogue at ``h``. Carry keyframes are decoded one plane at a time, Lanczos-stretchedx2 in RGB, and encoded again; only the video latent is spatially upsampled. The epilogue runs- the 3-step detailing schedule with those keyframes as strength-1 conditions and the previous-stage- video as the IC-LoRA reference. Temporal tiles are seam-cut (lead-in dropped, earlier tile- keeps the seam). Spatial tiles inside a time window blend and retile after every Euler- step; time windows are not blended into each other. The caller always- gets ``(num_frames - 1) * 2**rounds + 1`` frames even when the canvas padded its tail.+ one 3-step detailing pass per temporal window with those keyframes as strength-1 conditions and+ the previous-stage video as the IC-LoRA reference. Spatial tiles inside a time window blend and+ retile after every Euler step; time windows are sequential and not blended into each other. The+ caller always gets ``(num_frames - 1) * 2**rounds + 1`` frames even when the canvas padded its tail.+ Diffusion work lives in ``dfr_stages`` so other adapters can import the same functions without+ constructing this class or a prompt encoder."""def __init__( # noqa: PLR0913@@ -422,7 +132,7 @@ class DFRPipeline:if not detailing_lora:raise ValueError("detailing_lora is required")self._detailing_lora = tuple(- LoraPathStrengthAndSDOps(item.path, _DETAILING_LORA_STRENGTH, item.sd_ops) for item in detailing_lora+ LoraPathStrengthAndSDOps(item.path, DETAILING_LORA_STRENGTH, item.sd_ops) for item in detailing_lora)self._detailing_downscale = read_lora_reference_downscale_factor(self._detailing_lora[0].path)@@ -495,14 +205,20 @@ class DFRPipeline:self.dtype,self.device,)+ self.use_ancestral_sampler = should_use_ancestral_sampler(model_paths.transformer())++ def _sampler_kwargs(self, seed: int, noise_seed_offset: int) -> dict[str, Any]:+ """Ancestral overrides, or an empty dict to leave ``DiffusionStage`` on its Euler defaults."""+ if not self.use_ancestral_sampler:+ return {}+ return ancestral_sampler_kwargs(seed, self.dtype, noise_seed_offset)def _emit_stage(self,name: str,*,latent: torch.Tensor,- keyframes: torch.Tensor | None,- positions: Sequence[int],+ keyframes: KeyframeCarry,height: int,width: int,num_frames: int,@@ -512,10 +228,12 @@ class DFRPipeline:sink = getattr(self, "_stage_latent_sink", None)if sink is None:return+ positions = list(keyframes)+ stacked_keyframes = torch.cat(list(keyframes.values()), dim=2) if keyframes else Nonesink(name,latent=latent,- keyframes=keyframes,+ keyframes=stacked_keyframes,positions=positions,height=height,width=width,@@ -523,7 +241,7 @@ class DFRPipeline:fps=fps,)- def __call__( # noqa: PLR0912, PLR0913, PLR0915+ def __call__( # noqa: PLR0913, PLR0915self,prompt: str,seed: int,@@ -535,6 +253,7 @@ class DFRPipeline:temporal_upscalings: int = 0,spatial_upscalings: int = 1,tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,+ decode_device_fn: Callable[[int], str | torch.device] | None = None,enhance_prompt: bool = False,enhance_static_cache: bool = False,stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS,@@ -579,343 +298,139 @@ class DFRPipeline:requested_frames = num_framesnum_frames, _, positions = resolve_canvas(num_frames)stage_1_frames = num_frames- stage_1_duration = stage_1_frames / frame_rate- self.stage.assert_generated_keyframes_supported()+ source_duration = stage_1_frames / frame_rate+ assert_stage_supports_generated_keyframes(self.stage)spatial_div = 2**spatial_upscalingsstage_1_w, stage_1_h = width // spatial_div, height // spatial_divstage_2_w, stage_2_h = width // (spatial_div // 2), height // (spatial_div // 2)# --- Stage 1: half-res (or quarter-res) base + keyframe slots -------------------- stage_1_sigmas = stage_1_sigmas.to(dtype=torch.float32, device=self.device)- stage_1_conditionings = self.image_conditioner(- lambda enc: combined_image_conditionings(- images=images,- height=stage_1_h,- width=stage_1_w,- video_encoder=enc,- dtype=dtype,- device=self.device,- )- )- stage_1_conditionings.append(VideoGeneratedKeyframeSlots(pixel_frame_indices=positions))-- video_state, audio_state = self.stage(- denoiser=SimpleDenoiser(video_context, audio_context),+ stage_1 = denoise_stage1(+ stage=self.stage,+ image_conditioner=self.image_conditioner,+ images=images,+ video_shape=VideoPixelShape(batch=1, frames=num_frames, height=stage_1_h, width=stage_1_w, fps=frame_rate),+ positions=positions,+ video_context=video_context,+ audio_context=audio_context,sigmas=stage_1_sigmas,noiser=noiser,- width=stage_1_w,- height=stage_1_h,- frames=num_frames,- fps=_conditioning_fps(frame_rate),- # Shipped audio is stage 1's, so it must be as long as the clip plays. The snapped- # transformer fps would otherwise size it from ``num_frames / 60``.- audio_fps=frame_rate,- video=ModalitySpec(context=video_context, conditionings=stage_1_conditionings),- audio=ModalitySpec(context=audio_context),+ device=self.device,+ dtype=dtype,+ **self._sampler_kwargs(seed, ANCESTRAL_NOISE_SEED_OFFSET),)-- reserved_half_res_video = video_state.latent[:1].detach().clone()- stage_1_audio_latent = audio_state.latent.detach().clone() if audio_state is not None else None- if video_state.generated_keyframes is None:- raise RuntimeError("Stage 1 did not return generated_keyframes despite requesting slots")- upsampled_slot_keyframes = self.upsampler(video_state.generated_keyframes)- upscaled_video_latent = self.upsampler(reserved_half_res_video)+ audio_latent = stage_1.audio_state.latent.detach().clone()# --- Stage 2: spatial detailing ------------------------------------------------- stage_2_sigmas = stage_2_sigmas.to(dtype=torch.float32, device=self.device)- stage_2_conditionings = self.image_conditioner(- lambda enc: combined_image_conditionings(- images=images,- height=stage_2_h,- width=stage_2_w,- video_encoder=enc,- dtype=dtype,- device=self.device,- )- )- stage_2_conditionings.append(- VideoGeneratedKeyframeSlots(pixel_frame_indices=positions, initial_keyframes=upsampled_slot_keyframes)- )- stage_2_conditionings.append(- VideoConditionByReferenceLatent(- latent=reserved_half_res_video,- downscale_factor=self._detailing_downscale,- strength=1.0,- )- )-- video_state, audio_state = self.stage_detailing(- denoiser=SimpleDenoiser(video_context, audio_context),+ video_shape = VideoPixelShape(batch=1, frames=num_frames, height=stage_2_h, width=stage_2_w, fps=frame_rate)+ stage_2 = denoise_stage2(+ stage=self.stage_detailing,+ image_conditioner=self.image_conditioner,+ upsampler=self.upsampler,+ images=images,+ video_shape=video_shape,+ keyframes=stage_1.keyframes,+ half_res_reference=stage_1.video_state.latent[:1].detach().clone(),+ downscale_factor=self._detailing_downscale,+ audio_latent=audio_latent,+ video_context=video_context,+ audio_context=audio_context,sigmas=stage_2_sigmas,noiser=noiser,- width=stage_2_w,- height=stage_2_h,- frames=num_frames,- fps=_conditioning_fps(frame_rate),- # Same basis as stage 1: this pass re-noises stage 1's audio latent.- audio_fps=frame_rate,- video=ModalitySpec(- context=video_context,- conditionings=stage_2_conditionings,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=upscaled_video_latent,- ),- audio=ModalitySpec(- context=audio_context,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=audio_state.latent,- ),+ device=self.device,+ dtype=dtype,+ **self._sampler_kwargs(seed, ANCESTRAL_STAGE_2_NOISE_SEED_OFFSET),)-- # Stage 2's slots become the next round's anchors.- carry_positions = list(positions)- carry_keyframes = video_state.generated_keyframes- current_fps = frame_rate- temporal_sigmas = DISTILLED_SIGMAS[4:].to(dtype=torch.float32, device=self.device)- last_window_seams: list[int] = []+ video_state = stage_2.video_state+ keyframes = stage_2.keyframesself._emit_stage("s2",latent=video_state.latent,- keyframes=carry_keyframes,- positions=carry_positions,- height=stage_2_h,- width=stage_2_w,- num_frames=num_frames,- fps=current_fps,+ keyframes=keyframes,+ height=video_shape.height,+ width=video_shape.width,+ num_frames=video_shape.frames,+ fps=video_shape.fps,)+ last_window_seams: list[int] = []for round_idx in range(1, temporal_upscalings + 1):assert self.temporal_upsampler is not None- if carry_keyframes is None or not carry_positions:+ if not keyframes:raise RuntimeError(f"Temporal round {round_idx}: missing carry-forward keyframes")-- video_latent = self.temporal_upsampler(video_state.latent[:1])- num_frames = 2 * (num_frames - 1) + 1- current_fps = 2 * current_fps- # Carried keyframes are single-frame latents, so only their positions scale with the round.- seam_positions = [2 * position for position in carry_positions]- anchor_keyframes = carry_keyframes- seam_to_index = {seam: index for index, seam in enumerate(seam_positions)}- cond_fps = _conditioning_fps(current_fps)- windows = TemporalTilePlan(seam_positions, num_frames, 2**round_idx, temporal_scale)- last_window_seams = list(seam_positions)-- tile_latents: list[torch.Tensor] = []- slot_positions: list[int] = []- slot_latent_slices: list[torch.Tensor] = []- if stage_1_audio_latent is None:- raise RuntimeError("DFR temporal tiles need the frozen stage-1 audio latent")-- for tile_index, (interval, pixel_start, pixel_end, anchor_global, slot_global) in enumerate(windows):- local_frames = (interval.end - interval.start - 1) * temporal_scale + 1- tile_video = video_latent[:, :, interval.start : interval.end]-- # Image conditioning is tile-local: ``frame_idx`` is on the requested canvas, so- # scale onto this round's grid (``* 2**round``) before the window test and re-base.- # ``frame_idx=0`` still means this tile's first frame after re-basing, so only- # images that actually fall inside the window are re-attached.- tile_images = _rebase_image_conditionings(- images,- pixel_scale=2**round_idx,- pixel_start=pixel_start,- pixel_end=pixel_end,- )- round_conditionings = (- self.image_conditioner(- lambda enc, _images=tile_images: combined_image_conditionings(- images=_images,- height=stage_2_h,- width=stage_2_w,- video_encoder=enc,- dtype=dtype,- device=self.device,- )- )- if tile_images- else []- )-- # Every seam in the window is a hard keyframe, including the one at local frame 0.- if anchor_global:- missing = [position for position in anchor_global if position not in seam_to_index]- if missing:- raise RuntimeError(f"Anchor seams {missing} missing from the carry-forward bag")- anchor_latents = torch.cat(- [anchor_keyframes[:, :, seam_to_index[p] : seam_to_index[p] + 1] for p in anchor_global], dim=2- )- round_conditionings.extend(- _keyframe_conditionings_from_latents(- anchor_latents,- [int(position) - pixel_start for position in anchor_global],- strength=_ANCHOR_KEYFRAME_STRENGTH,- )- )-- if slot_global:- slot_local = [int(position) - pixel_start for position in slot_global]- round_conditionings.append(- VideoGeneratedKeyframeSlots(- pixel_frame_indices=slot_local,- initial_keyframes=_slot_initials_from_video(tile_video, slot_local, temporal_scale),- )- )-- tile_state, _ = self.stage(- denoiser=SimpleDenoiser(video_context, audio_context),- sigmas=temporal_sigmas,- noiser=noiser,- width=stage_2_w,- height=stage_2_h,- frames=local_frames,- fps=cond_fps,- video=ModalitySpec(- context=video_context,- conditionings=round_conditionings,- noise_scale=temporal_sigmas[0].item(),- initial_latent=tile_video,- ),- audio=ModalitySpec(- context=audio_context,- frozen=True,- noise_scale=0.0,- initial_latent=_audio_latent_for_tile(- stage_1_audio_latent,- pixel_start=pixel_start,- local_frames=local_frames,- playback_fps=current_fps,- source_duration=stage_1_duration,- cond_fps=cond_fps,- ),- ),- stepper=EulerAncestralDiffusionStep(eta=_TEMPORAL_ANCESTRAL_ETA),- # Tiles are positionally identical, so a shared ancestral seed would inject- # byte-identical noise into every one of them.- loop=partial(euler_ancestral_denoising_loop, noise_seed=seed + 1000 * round_idx + tile_index),- )- tile_latents.append(tile_state.latent[:1, :, interval.left_ramp :])-- if slot_global:- if tile_state.generated_keyframes is None:- raise RuntimeError(f"Temporal round {round_idx}: tile produced no keyframe slots")- slot_positions.extend(slot_global)- slot_latent_slices.append(tile_state.generated_keyframes)-- stitched = torch.cat(tile_latents, dim=2)- expected_t = (num_frames - 1) // temporal_scale + 1- if stitched.shape[2] != expected_t:- raise RuntimeError(f"Stitched latent T={stitched.shape[2]} != expected {expected_t}")- if not isinstance(video_state, LatentState):- raise TypeError(f"Expected LatentState, got {type(video_state)}")- video_state = replace(video_state, latent=stitched, generated_keyframes=None)-- slot_latents = torch.cat(slot_latent_slices, dim=2) if slot_latent_slices else None- if slot_positions and slot_latents is not None:- # Lead-in segments repeat the previous tile's slots; the earlier tile's version wins.- first_index: dict[int, int] = {}- for index, position in enumerate(slot_positions):- first_index.setdefault(position, index)- slot_positions = sorted(first_index)- slot_latents = torch.cat(- [slot_latents[:, :, first_index[p] : first_index[p] + 1] for p in slot_positions], dim=2- )-- carry_positions, carry_keyframes = _merge_carry_forward_keyframes(- seam_positions, anchor_keyframes, slot_positions, slot_latents+ video_shape = video_shape._replace(frames=2 * (video_shape.frames - 1) + 1, fps=2 * video_shape.fps)+ video_state, keyframes, last_window_seams = run_one_temporal_round(+ round_idx=round_idx,+ stage=self.stage,+ temporal_upsampler=self.temporal_upsampler,+ image_conditioner=self.image_conditioner,+ video_state=video_state,+ keyframes=keyframes,+ video_shape=video_shape,+ images=images,+ video_context=video_context,+ audio_context=audio_context,+ audio_latent=audio_latent,+ source_duration=source_duration,+ seed=seed,+ noiser=noiser,+ sigmas=DISTILLED_SIGMAS[4:].to(dtype=torch.float32, device=self.device),+ device=self.device,+ dtype=dtype,+ temporal_scale=temporal_scale,)self._emit_stage(f"t{round_idx}",latent=video_state.latent,- keyframes=carry_keyframes,- positions=carry_positions,- height=stage_2_h,- width=stage_2_w,- num_frames=num_frames,- fps=current_fps,+ keyframes=keyframes,+ height=video_shape.height,+ width=video_shape.width,+ num_frames=video_shape.frames,+ fps=video_shape.fps,)+ num_frames = video_shape.frames+ current_fps = video_shape.fps# --- Spatial epilogue (spatial_upscalings == 2): s2 is h/2; this pass is final H x W ---if spatial_upscalings == 2:- if carry_keyframes is None or not carry_positions:- raise RuntimeError("Spatial epilogue: missing carry-forward keyframes")- guide = video_state.latent[:1]- pixel_keyframes = self._decode_lanczos_carry_keyframes(carry_keyframes, seed)- upscaled_video = self.upsampler(guide)-- def _encode_epilogue_keyframes(enc: VideoEncoder) -> tuple[list[ConditioningItem], torch.Tensor]:- image_conds = combined_image_conditionings(- images=_rebase_image_conditionings(images, pixel_scale=2**temporal_upscalings),- height=height,- width=width,- video_encoder=enc,- dtype=dtype,- device=self.device,- )- planes = []- for rgb in pixel_keyframes:- sample = to_vae_range(rgb.to(device=self.device, dtype=torch.float32))- sample = sample.permute(3, 0, 1, 2).unsqueeze(0).contiguous().to(dtype=dtype)- planes.append(enc(sample))- return image_conds, torch.cat(planes, dim=2)-- epi_conditionings, encoded_kfs = self.image_conditioner(_encode_epilogue_keyframes)- epi_conditionings.extend(- _keyframe_conditionings_from_latents(encoded_kfs, carry_positions, strength=_EPILOGUE_KEYFRAME_STRENGTH)- )- epi_conditionings.append(- VideoConditionByReferenceLatent(- latent=guide,- downscale_factor=self._detailing_downscale,- strength=1.0,- )- )- n_time_tiles = max(1, 2**temporal_upscalings)- epi_seams = [pixel_to_latent_index(position, temporal_scale) for position in last_window_seams]- temporal_overlap = (epi_seams[0] + 1) if n_time_tiles > 1 and epi_seams else 0- epi_tiling = TileCountConfig(- frames=DimensionTilingConfig(n_time_tiles, overlap=temporal_overlap),- height=DimensionTilingConfig(2, _EPILOGUE_SPATIAL_OVERLAP),- width=DimensionTilingConfig(2, _EPILOGUE_SPATIAL_OVERLAP),- )- if stage_1_audio_latent is None:- raise RuntimeError("Spatial epilogue: missing stage-1 audio latent")- cond_fps = _conditioning_fps(current_fps)- epi_pixel_frames = (upscaled_video.shape[2] - 1) * temporal_scale + 1- epi_latent = self._run_spatial_epilogue(- latent=upscaled_video,- conditionings=epi_conditionings,- tiling=epi_tiling,+ epi = run_spatial_epilogue(+ stage=self.stage_detailing,+ upsampler=self.upsampler,+ image_conditioner=self.image_conditioner,+ video_decoder=self.video_decoder,+ video_state=video_state,+ keyframes=keyframes,+ images=images,+ video_shape=VideoPixelShape(batch=1, frames=num_frames, height=height, width=width, fps=current_fps),+ temporal_upscalings=temporal_upscalings,+ last_window_seams=last_window_seams,+ video_context=video_context,+ audio_context=audio_context,+ audio_latent=audio_latent,+ source_duration=source_duration,sigmas=stage_2_sigmas,- v_ctx=video_context,- a_ctx=audio_context,- audio_latent=_audio_latent_for_tile(- stage_1_audio_latent,- pixel_start=0,- local_frames=epi_pixel_frames,- playback_fps=current_fps,- source_duration=stage_1_duration,- cond_fps=cond_fps,- ),- fps=cond_fps,+ downscale_factor=self._detailing_downscale,seed=seed,- seams=epi_seams,+ device=self.device,+ dtype=dtype,+ temporal_scale=temporal_scale,+ **self._sampler_kwargs(seed, _EPILOGUE_ANCESTRAL_NOISE_SEED_OFFSET),)- video_state = replace(video_state, latent=epi_latent, generated_keyframes=None)- carry_keyframes = encoded_kfs-- # The canvas may have padded its tail, and each round maps N -> 2(N-1)+1, so the caller's- # contract is ``(requested - 1) * 2**rounds + 1``. ``requested - 1`` is a multiple of the VAE- # temporal scale, so the trim always lands on a latent boundary.- target_frames = (requested_frames - 1) * 2**temporal_upscalings + 1- if target_frames > num_frames:- raise RuntimeError(f"Target {target_frames} frames exceeds the generated canvas {num_frames}")- if target_frames != num_frames:- keep_latents = (target_frames - 1) // temporal_scale + 1- video_state = replace(video_state, latent=video_state.latent[:, :, :keep_latents])- num_frames = target_frames- # After the trim, so keyframes past the caller's last frame are dropped rather than- # shipped pointing off-canvas.- final_keyframes = decode_keyframes_from_slots(carry_keyframes, carry_positions, num_frames)+ video_state = epi.video_state+ keyframes = epi.keyframes++ trimmed_latent, num_frames = trim_video_to_requested_frames(+ video_state.latent,+ canvas_frames=num_frames,+ requested_frames=requested_frames,+ temporal_upscalings=temporal_upscalings,+ temporal_scale=temporal_scale,+ )+ video_state = replace(video_state, latent=trimmed_latent)+ keyframe_positions = list(keyframes)+ stacked_keyframes = torch.cat(list(keyframes.values()), dim=2)+ final_keyframes = decode_keyframes_from_slots(stacked_keyframes, keyframe_positions, num_frames)playback_fps = frame_rate * 2**temporal_upscalingstiling_config = ensure_tiling_config(@@ -927,111 +442,19 @@ class DFRPipeline:device=self.device,keyframes=final_keyframes is not None,)- decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, keyframes=final_keyframes)- if stage_1_audio_latent is None:- raise RuntimeError("Stage 1 produced no audio latent to ship")- decoded_audio = self.audio_decoder(stage_1_audio_latent)- # Audio was generated for the padded canvas, so cut it to the video's duration or the muxed- # container outlasts the picture.- video_seconds = num_frames / playback_fps- audio_samples = min(decoded_audio.waveform.shape[-1], round(video_seconds * decoded_audio.sampling_rate))- if audio_samples != decoded_audio.waveform.shape[-1]:- decoded_audio = replace(decoded_audio, waveform=decoded_audio.waveform[..., :audio_samples])- return PipelineOutput(- decoded_video, decoded_audio, num_frames, tiling_config, final_keyframes, video_state.latent- )-- def _decode_lanczos_carry_keyframes(self, keyframe_latents: torch.Tensor, seed: int) -> list[torch.Tensor]:- """Decode each carry keyframe as its own 1-frame clip, then Lanczos-x2 the RGB.- The VAE is causal, so a stacked encode/decode would bleed neighbouring planes. Each- plane is a standalone one-pixel-frame latent, matching ``DecodeKeyframes``. Dist- ``decode_single_frames`` is a local SGPU passthrough, so every rank gets pixels- instead of the empty worker yield from ``decode_video``.- """- if keyframe_latents.ndim != 5:- raise ValueError(f"Expected carry keyframes (B, C, K, H, W), got {tuple(keyframe_latents.shape)}")- n_planes = keyframe_latents.shape[2]- logger.info("Epilogue: decoding %d carry keyframes separately, then Lanczos x2", n_planes)- planes = [keyframe_latents[:, :, index : index + 1] for index in range(n_planes)]- generators = [torch.Generator(device=self.device).manual_seed(seed + 4000 + index) for index in range(n_planes)]- rgb_planes: list[torch.Tensor] = []- for index, rgb in enumerate(self.video_decoder.decode_single_frames(planes, generators)):- if rgb.shape[0] < 1:- raise RuntimeError(f"Decoder returned no pixels for carry keyframe {index}")- rgb_planes.append(_lanczos_x2_fhwc(rgb.detach().cpu()))- if len(rgb_planes) != n_planes:- raise RuntimeError(f"Expected {n_planes} decoded carry keyframes, got {len(rgb_planes)}")- return rgb_planes-- def _run_spatial_epilogue(- self,- *,- latent: torch.Tensor,- conditionings: list[ConditioningItem],- tiling: TileCountConfig,- sigmas: torch.Tensor,- v_ctx: torch.Tensor,- a_ctx: torch.Tensor,- audio_latent: torch.Tensor,- fps: float,- seed: int,- seams: Sequence[int] = (),- ) -> torch.Tensor:- """Full-res spatial detailing: one denoising loop over a canvas tiled inside the model.- :class:`_TiledModelWrapper` tiles each transformer call and blends the per-tile- predictions, so the sampler steps a single full-resolution canvas and the spatial overlap- is reconciled at every Euler step rather than once at the end. Temporal tiles are cut on- ``seams``, which makes their blend masks rectangular: the lead-in is denoised for context- and then discarded, and the earlier tile keeps the seam cell. Conditionings are filtered- per tile at the token level, so they are passed here on the full canvas.- Audio is the frozen stage-1 latent, resampled onto this canvas, so video-audio cross- attention still sees it. The returned audio state is discarded; the pipeline ships the- original stage-1 audio.- """- tiling = _clamp_tile_to_latent(tiling, tuple(latent.shape[2:5]))- _, _, n_frames, n_height, n_width = latent.shape- scale_factors = self.stage_detailing.video_scale_factors- pixel_frames = (n_frames - 1) * scale_factors.time + 1-- def _tile(model: torch.nn.Module, tools: LatentTools | None) -> torch.nn.Module:- if not isinstance(tools, VideoLatentTools):- raise TypeError(f"Spatial epilogue needs video tools to tile, got {type(tools).__name__}")- return _TiledModelWrapper(model, video_tools=tools, tiling=tiling, seams=seams)-- stage = self.stage_detailing.with_model_wrapper(_tile)- logger.info(- "Spatial epilogue: %d step(s) over %s tiles (frames=%s height=%s width=%s, seams=%s)",- sigmas.numel() - 1,- tiling.frames.num_tiles * tiling.height.num_tiles * tiling.width.num_tiles,- tiling.frames,- tiling.height,- tiling.width,- list(seams),+ decoded_video = self.video_decoder(+ video_state.latent,+ tiling_config,+ generator,+ keyframes=final_keyframes,+ device_fn=decode_device_fn,)- video_state, _ = stage(- denoiser=SimpleDenoiser(v_ctx, a_ctx),- sigmas=sigmas.to(dtype=torch.float32, device=self.device),- noiser=GaussianNoiser(generator=torch.Generator(device=self.device).manual_seed(seed + 2000)),- width=n_width * scale_factors.width,- height=n_height * scale_factors.height,- frames=pixel_frames,- fps=fps,- video=ModalitySpec(- context=v_ctx,- conditionings=conditionings,- noise_scale=float(sigmas[0].item()),- initial_latent=latent.to(device=self.device, dtype=self.dtype),- ),- audio=ModalitySpec(- context=a_ctx,- frozen=True,- noise_scale=0.0,- initial_latent=audio_latent,- ),+ decoded_audio = trim_audio_to_video_duration(+ self.audio_decoder(audio_latent),+ num_frames=num_frames,+ playback_fps=playback_fps,)- if video_state is None:- raise RuntimeError("Spatial epilogue produced no video state")- return video_state.latent+ return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config)def add_dfr_cli_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:diff --git a/packages/ltx-pipelines/src/ltx_pipelines/dfr_stages.py b/packages/ltx-pipelines/src/ltx_pipelines/dfr_stages.pynew file mode 100644index 0000000..f6aa71e--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/dfr_stages.py@@ -0,0 +1,1304 @@+"""DFR diffusion stages: caller-built ``DiffusionStage`` / VAE blocks, no Gemma.+``DFRPipeline`` and other adapters construct their own stages -- including+sequence-parallel wrappers and resident weights -- and pass them in. These functions must not+instantiate ``ModelPaths`` or a prompt encoder.+Public stage functions: ``denoise_stage1``, ``denoise_stage2``, ``run_one_temporal_round``,+``run_spatial_epilogue``.+Each public stage function prepares modality specs internally (upsample, conditionings,+``ModalitySpec`` assembly) and calls ``DiffusionStage``. Adapters call only the public+entry points.+"""++from __future__ import annotations++import logging+from collections.abc import Callable, Iterable, Sequence+from dataclasses import replace+from functools import partial+from typing import NamedTuple++import torch++from ltx_core.components.noisers import GaussianNoiser, Noiser+from ltx_core.conditioning import ConditioningItem, VideoConditionByReferenceLatent, VideoGeneratedKeyframeSlots+from ltx_core.model.video_vae import VideoEncoder+from ltx_core.tiling import DimensionTilingConfig, TileCountConfig+from ltx_core.tools import LatentTools, VideoLatentTools+from ltx_core.types import VIDEO_SCALE_FACTORS, LatentState, SpatioTemporalScaleFactors, VideoPixelShape+from ltx_pipelines.dfr_helpers.layout import TemporalTile, TemporalTilePlan+from ltx_pipelines.dfr_helpers.ops import (+ ANCHOR_KEYFRAME_STRENGTH,+ EPILOGUE_KEYFRAME_STRENGTH,+ EPILOGUE_SPATIAL_COARSE_TILES,+ EPILOGUE_SPATIAL_OVERLAP,+ EPILOGUE_SPATIAL_TILES,+ TEMPORAL_ANCESTRAL_ETA,+ TilePrefix,+ audio_latent_for_tile,+ clamp_tile_to_latent,+ conditioning_fps,+ keyframe_conditionings_from_latents,+ lanczos_x2_fhwc,+ lead_in_carryover,+ rebase_image_conditionings,+ slot_initials_from_video,+ tile_prefix,+)+from ltx_pipelines.utils.blocks import DiffusionStage, ImageConditioner, VideoDecoder, VideoUpsampler+from ltx_pipelines.utils.denoisers import SimpleDenoiser+from ltx_pipelines.utils.helpers import (+ combined_image_conditionings,+ create_initial_audio_latent,+ create_initial_video_latent,+)+from ltx_pipelines.utils.media_io import to_vae_range+from ltx_pipelines.utils.samplers import euler_ancestral_denoising_loop+from ltx_pipelines.utils.tiled_diffusion import TiledDiffusionModel+from ltx_pipelines.utils.types import ImageConditioningInput, ModalitySpec, VideoAudio++logger = logging.getLogger(__name__)++KeyframeCarry = dict[int, torch.Tensor]+++class DenoiseStage1Result(NamedTuple):+ """Half-res stage-1 outputs consumed by stage 2 and later passes.+ ``video_state`` / ``audio_state`` are the denoise outputs as produced. An orchestrator+ that reuses ``.latent`` (IC-LoRA, upsample, shipped audio) should take a detached clone+ of the positive batch. ``keyframes`` maps pixel indices on the stage-1 canvas to generated+ slot planes. Stage 2 spatially upsamples video and slots before denoising.+ """++ video_state: LatentState+ audio_state: LatentState+ keyframes: KeyframeCarry+++class DenoiseStage2Result(NamedTuple):+ """Full-res (or half-res) detailing pass. Shipped audio is still stage 1's clone."""++ video_state: LatentState+ audio_state: LatentState | None+ keyframes: KeyframeCarry+++class SpatialEpilogueResult(NamedTuple):+ """Full-res detailing canvas. Carry bag is Lanczos-rebuilt encoded keyframe planes."""++ video_state: LatentState+ keyframes: KeyframeCarry+++class TemporalTileResult(NamedTuple):+ """One ancestral temporal tile: owned latent slice plus bookkeeping for the next tile."""++ owned_latent: torch.Tensor+ previous_tile: tuple[int, torch.Tensor]+ new_planes: dict[int, torch.Tensor]+++class TemporalTileVideo(NamedTuple):+ """Latent slice and pixel window one temporal tile denoises."""++ tile_video: torch.Tensor+ pixel_start: int+ pixel_end: int+ resume_pixel: int+ pinned_cells: int++ def local_frames(self, temporal_scale: int) -> int:+ return (self.tile_video.shape[2] - 1) * temporal_scale + 1+++class _PreparedDenoise(NamedTuple):+ """Video/audio modality specs and canvas shape for one ``DiffusionStage`` call."""++ video: ModalitySpec+ audio: ModalitySpec+ canvas: VideoPixelShape+++class _PreparedTemporalTile(NamedTuple):+ """Prepared specs plus tile geometry for one ancestral temporal tile."""++ denoise: _PreparedDenoise+ tile_video: TemporalTileVideo+++class _PreparedEpilogueWindow(NamedTuple):+ """Prepared specs plus bookkeeping for one spatial-epilogue temporal window."""++ window_latent: torch.Tensor+ denoise: _PreparedDenoise+ pinned_cells: int+ prefix: TilePrefix | None+ interval_start: int+++def _keyframes_from_stacked(positions: Sequence[int], planes: torch.Tensor) -> KeyframeCarry:+ """Associate a stacked keyframe tensor with pixel indices on the current canvas."""+ if planes.shape[2] != len(positions):+ raise ValueError(f"Keyframe planes K={planes.shape[2]} != {len(positions)} positions")+ return {int(position): planes[:, :, index : index + 1] for index, position in enumerate(positions)}+++def _stack_keyframes(keyframes: KeyframeCarry) -> tuple[list[int], torch.Tensor]:+ """Adapt keyframe carry to APIs that require parallel positions and a stacked tensor."""+ if not keyframes:+ raise RuntimeError("Keyframe carry is empty")+ positions = list(keyframes)+ return positions, torch.cat(list(keyframes.values()), dim=2)+++def _image_conditionings(+ image_conditioner: ImageConditioner,+ images: Sequence[ImageConditioningInput],+ *,+ height: int,+ width: int,+ dtype: torch.dtype,+ device: torch.device,+) -> list[ConditioningItem]:+ return image_conditioner(+ lambda enc: combined_image_conditionings(+ images=list(images),+ height=height,+ width=width,+ video_encoder=enc,+ dtype=dtype,+ device=device,+ )+ )+++def _prepare_stage1_specs(+ *,+ image_conditioner: ImageConditioner,+ images: list[ImageConditioningInput],+ video_shape: VideoPixelShape,+ positions: Sequence[int],+ video_context: torch.Tensor,+ audio_context: torch.Tensor,+ audio_spec: ModalitySpec | None,+ device: torch.device,+ dtype: torch.dtype,+ scale_factors: SpatioTemporalScaleFactors,+) -> _PreparedDenoise:+ video_fps = conditioning_fps(video_shape.fps)+ video_latent = create_initial_video_latent(+ width=video_shape.width,+ height=video_shape.height,+ frames=video_shape.frames,+ fps=video_fps,+ device=device,+ dtype=dtype,+ scale_factors=scale_factors,+ )+ if audio_spec is None:+ audio_spec = ModalitySpec(+ latent=create_initial_audio_latent(+ video_latent,+ fps=video_shape.fps,+ video_scale_factors=scale_factors,+ ),+ conditioning_fps=video_shape.fps,+ context=audio_context,+ )+ conditionings = _image_conditionings(+ image_conditioner,+ images,+ height=video_shape.height,+ width=video_shape.width,+ dtype=dtype,+ device=device,+ )+ conditionings.append(VideoGeneratedKeyframeSlots(pixel_frame_indices=list(positions)))+ return _PreparedDenoise(+ video=ModalitySpec(+ latent=video_latent,+ conditioning_fps=video_fps,+ context=video_context,+ conditionings=conditionings,+ ),+ audio=audio_spec,+ canvas=video_shape,+ )+++def _prepare_stage2_specs( # noqa: PLR0913+ *,+ upsampler: VideoUpsampler,+ image_conditioner: ImageConditioner,+ images: list[ImageConditioningInput],+ video_shape: VideoPixelShape,+ keyframes: KeyframeCarry,+ half_res_reference: torch.Tensor,+ downscale_factor: int,+ audio_latent: torch.Tensor,+ video_context: torch.Tensor,+ audio_context: torch.Tensor,+ sigmas: torch.Tensor,+ device: torch.device,+ dtype: torch.dtype,+) -> _PreparedDenoise:+ upscaled_video_latent = upsampler(half_res_reference)+ positions, stacked_keyframes = _stack_keyframes(keyframes)+ upscaled_keyframes = upsampler(stacked_keyframes)+ conditionings = _image_conditionings(+ image_conditioner,+ images,+ height=video_shape.height,+ width=video_shape.width,+ dtype=dtype,+ device=device,+ )+ conditionings.append(+ VideoGeneratedKeyframeSlots(+ pixel_frame_indices=positions,+ initial_keyframes=upscaled_keyframes,+ )+ )+ conditionings.append(+ VideoConditionByReferenceLatent(+ latent=half_res_reference,+ downscale_factor=downscale_factor,+ strength=1.0,+ )+ )+ return _PreparedDenoise(+ video=ModalitySpec(+ latent=upscaled_video_latent,+ conditioning_fps=conditioning_fps(video_shape.fps),+ context=video_context,+ conditionings=conditionings,+ noise_scale=sigmas[0].item(),+ ),+ audio=ModalitySpec(+ latent=audio_latent,+ conditioning_fps=video_shape.fps,+ context=audio_context,+ noise_scale=sigmas[0].item(),+ ),+ canvas=video_shape,+ )+++def denoise_stage1( # noqa: PLR0913+ *,+ stage: DiffusionStage,+ image_conditioner: ImageConditioner,+ images: list[ImageConditioningInput],+ video_shape: VideoPixelShape,+ positions: Sequence[int],+ video_context: torch.Tensor,+ audio_context: torch.Tensor,+ sigmas: torch.Tensor,+ noiser: Noiser,+ device: torch.device,+ dtype: torch.dtype,+ audio_spec: ModalitySpec | None = None,+ loop: Callable[..., tuple[LatentState | None, LatentState | None]] | None = None,+) -> DenoiseStage1Result:+ """Stage 1: generate half-res video + keyframe slots; reserve video latent for IC-LoRA.+ ``audio_spec`` defaults to a generated soundtrack. For A2V pass+ ``ModalitySpec(latent=..., context=audio_context, frozen=True, noise_scale=0.0)`` so the+ supplied latent stays frozen without re-noising (``ModalitySpec`` defaults ``noise_scale`` to+ ``1.0``, which would noise the latent before freezing it).+ Transformer fps snaps above 30; audio duration stays at playback ``video_shape.fps``.+ """+ sigmas = sigmas.to(dtype=torch.float32, device=device)+ prepared = _prepare_stage1_specs(+ image_conditioner=image_conditioner,+ images=images,+ video_shape=video_shape,+ positions=positions,+ video_context=video_context,+ audio_context=audio_context,+ audio_spec=audio_spec,+ device=device,+ dtype=dtype,+ scale_factors=stage.video_scale_factors,+ )+ video_state, audio_state = stage(+ denoiser=SimpleDenoiser(video_context, audio_context),+ sigmas=sigmas,+ noiser=noiser,+ modalities=VideoAudio(video=prepared.video, audio=prepared.audio),+ loop=loop,+ )+ if video_state is None:+ raise RuntimeError("Stage 1 produced no video state")+ if audio_state is None:+ raise RuntimeError("Stage 1 produced no audio state")+ if video_state.generated_keyframes is None:+ raise RuntimeError("Stage 1 did not return generated_keyframes despite requesting slots")+ return DenoiseStage1Result(+ video_state=video_state,+ audio_state=audio_state,+ keyframes=_keyframes_from_stacked(positions, video_state.generated_keyframes),+ )+++def denoise_stage2( # noqa: PLR0913+ *,+ stage: DiffusionStage,+ image_conditioner: ImageConditioner,+ upsampler: VideoUpsampler,+ images: list[ImageConditioningInput],+ video_shape: VideoPixelShape,+ keyframes: KeyframeCarry,+ half_res_reference: torch.Tensor,+ downscale_factor: int,+ audio_latent: torch.Tensor,+ video_context: torch.Tensor,+ audio_context: torch.Tensor,+ sigmas: torch.Tensor,+ noiser: Noiser,+ device: torch.device,+ dtype: torch.dtype,+ loop: Callable[..., tuple[LatentState | None, LatentState | None]] | None = None,+) -> DenoiseStage2Result:+ """Stage 2: spatial upsample, then detailing IC-LoRA + seeded slots.+ Upsamples ``half_res_reference`` and ``keyframes`` as its first step, matching temporal+ rounds and the epilogue. Audio is re-noised for cross-modal attention only.+ """+ sigmas = sigmas.to(dtype=torch.float32, device=device)+ prepared = _prepare_stage2_specs(+ upsampler=upsampler,+ image_conditioner=image_conditioner,+ images=images,+ video_shape=video_shape,+ keyframes=keyframes,+ half_res_reference=half_res_reference,+ downscale_factor=downscale_factor,+ audio_latent=audio_latent,+ video_context=video_context,+ audio_context=audio_context,+ sigmas=sigmas,+ device=device,+ dtype=dtype,+ )+ video_state, audio_state = stage(+ denoiser=SimpleDenoiser(video_context, audio_context),+ sigmas=sigmas,+ noiser=noiser,+ modalities=VideoAudio(video=prepared.video, audio=prepared.audio),+ loop=loop,+ )+ if video_state is None:+ raise RuntimeError("Stage 2 produced no video state")+ if video_state.generated_keyframes is None:+ raise RuntimeError("Stage 2 did not return generated_keyframes despite requesting slots")+ return DenoiseStage2Result(+ video_state=video_state,+ audio_state=audio_state,+ keyframes=_keyframes_from_stacked(list(keyframes), video_state.generated_keyframes),+ )+++def _temporal_tile_video_input(+ *,+ video_latent: torch.Tensor,+ tile: TemporalTile,+ prefix: TilePrefix | None,+ plane_at: dict[int, torch.Tensor],+ temporal_scale: int,+) -> TemporalTileVideo:+ """Build the latent slice and pixel window one temporal tile denoises."""+ interval = tile.interval+ if prefix is None:+ tile_video = video_latent[:, :, interval.start : interval.end]+ return TemporalTileVideo(tile_video, 0, (tile_video.shape[2] - 1) * temporal_scale, 0, 0)++ tile_video = torch.cat(+ [+ plane_at[prefix.keyframe_position].to(dtype=video_latent.dtype),+ video_latent[:, :, prefix.video_start_cell : interval.end],+ ],+ dim=2,+ )+ local_frames = (tile_video.shape[2] - 1) * temporal_scale + 1+ pixel_start = prefix.keyframe_position+ return TemporalTileVideo(tile_video, pixel_start, pixel_start + local_frames - 1, prefix.resume_pixel, prefix.cells)+++def _temporal_tile_conditionings( # noqa: PLR0913+ *,+ image_conditioner: ImageConditioner,+ images: list[ImageConditioningInput],+ canvas: VideoPixelShape,+ tile_video: TemporalTileVideo,+ tile: TemporalTile,+ prefix: TilePrefix | None,+ previous_tile: tuple[int, torch.Tensor] | None,+ keyframes: KeyframeCarry,+ pixel_scale: int,+ temporal_scale: int,+ round_idx: int,+ tile_index: int,+ device: torch.device,+ dtype: torch.dtype,+) -> list[ConditioningItem]:+ """Assemble image, anchor, slot, and lead-in conditionings for one temporal tile."""+ tile_images = rebase_image_conditionings(+ images,+ pixel_scale=pixel_scale,+ pixel_start=tile_video.pixel_start,+ pixel_end=tile_video.pixel_end,+ )+ conditionings = (+ _image_conditionings(+ image_conditioner,+ tile_images,+ height=canvas.height,+ width=canvas.width,+ dtype=dtype,+ device=device,+ )+ if tile_images+ else []+ )++ kept_anchors = tuple(position for position in tile.anchors if position >= tile_video.resume_pixel)+ if kept_anchors:+ missing = [position for position in kept_anchors if position not in keyframes]+ if missing:+ raise RuntimeError(f"Anchor seams {missing} missing from the carry-forward bag")+ anchor_latents = torch.cat([keyframes[position] for position in kept_anchors], dim=2)+ conditionings.extend(+ keyframe_conditionings_from_latents(+ anchor_latents,+ [int(position) - tile_video.pixel_start for position in kept_anchors],+ strength=ANCHOR_KEYFRAME_STRENGTH,+ )+ )++ if tile.slots:+ slot_local = [int(position) - tile_video.pixel_start for position in tile.slots]+ conditionings.append(+ VideoGeneratedKeyframeSlots(+ pixel_frame_indices=slot_local,+ initial_keyframes=slot_initials_from_video(tile_video.tile_video, slot_local, temporal_scale),+ )+ )++ if prefix is not None and previous_tile is not None:+ conditionings.append(lead_in_carryover(previous_tile, prefix, tile_video.tile_video[:, :, :1]))+ logger.info(+ "Temporal round %d tile %d: starts on the plane at %d, %d cell(s) pinned, denoises from %d",+ round_idx,+ tile_index,+ prefix.keyframe_position,+ prefix.cells,+ tile_video.resume_pixel,+ )++ return conditionings+++def _prepare_temporal_tile_specs( # noqa: PLR0913+ *,+ image_conditioner: ImageConditioner,+ images: list[ImageConditioningInput],+ canvas: VideoPixelShape,+ video_latent: torch.Tensor,+ tile_index: int,+ tile: TemporalTile,+ prefix: TilePrefix | None,+ previous_tile: tuple[int, torch.Tensor] | None,+ plane_at: dict[int, torch.Tensor],+ keyframes: KeyframeCarry,+ round_idx: int,+ pixel_scale: int,+ temporal_scale: int,+ audio_latent: torch.Tensor,+ source_duration: float,+ video_context: torch.Tensor,+ audio_context: torch.Tensor,+ sigmas: torch.Tensor,+ device: torch.device,+ dtype: torch.dtype,+) -> _PreparedTemporalTile:+ """Upsample is done at round scope; build tile slice, conditionings, and modality specs."""+ tile_video = _temporal_tile_video_input(+ video_latent=video_latent,+ tile=tile,+ prefix=prefix,+ plane_at=plane_at,+ temporal_scale=temporal_scale,+ )+ local_frames = tile_video.local_frames(temporal_scale)+ cond_fps = conditioning_fps(canvas.fps)+ conditionings = _temporal_tile_conditionings(+ image_conditioner=image_conditioner,+ images=images,+ canvas=canvas,+ tile_video=tile_video,+ tile=tile,+ prefix=prefix,+ previous_tile=previous_tile,+ keyframes=keyframes,+ pixel_scale=pixel_scale,+ temporal_scale=temporal_scale,+ round_idx=round_idx,+ tile_index=tile_index,+ device=device,+ dtype=dtype,+ )+ tile_canvas = canvas._replace(frames=local_frames)+ return _PreparedTemporalTile(+ denoise=_PreparedDenoise(+ video=ModalitySpec(+ latent=tile_video.tile_video,+ conditioning_fps=cond_fps,+ context=video_context,+ conditionings=conditionings,+ noise_scale=sigmas[0].item(),+ ),+ audio=ModalitySpec(+ latent=audio_latent_for_tile(+ audio_latent,+ pixel_start=tile_video.pixel_start,+ local_frames=local_frames,+ playback_fps=canvas.fps,+ source_duration=source_duration,+ cond_fps=cond_fps,+ ),+ conditioning_fps=cond_fps,+ context=audio_context,+ frozen=True,+ noise_scale=0.0,+ ),+ canvas=tile_canvas,+ ),+ tile_video=tile_video,+ )+++def _collect_temporal_tile_result(+ *,+ tile_state: LatentState,+ tile: TemporalTile,+ tile_video: TemporalTileVideo,+ prefix: TilePrefix | None,+ round_idx: int,+) -> TemporalTileResult:+ interval = tile.interval+ next_previous = (+ prefix.video_start_cell - 1 if prefix else interval.start,+ tile_state.latent[:1].detach(),+ )+ owned_latent = tile_state.latent[:1, :, tile_video.pinned_cells :]++ if not tile.slots:+ return TemporalTileResult(owned_latent, next_previous, {})++ if tile_state.generated_keyframes is None:+ raise RuntimeError(f"Temporal round {round_idx}: tile produced no keyframe slots")+ new_planes = {+ int(position): tile_state.generated_keyframes[:, :, slot_index : slot_index + 1]+ for slot_index, position in enumerate(tile.slots)+ }+ return TemporalTileResult(owned_latent, next_previous, new_planes)+++def _denoise_temporal_tile( # noqa: PLR0913+ *,+ stage: DiffusionStage,+ image_conditioner: ImageConditioner,+ images: list[ImageConditioningInput],+ canvas: VideoPixelShape,+ video_latent: torch.Tensor,+ tile_index: int,+ tile: TemporalTile,+ prefix: TilePrefix | None,+ previous_tile: tuple[int, torch.Tensor] | None,+ plane_at: dict[int, torch.Tensor],+ keyframes: KeyframeCarry,+ round_idx: int,+ pixel_scale: int,+ temporal_scale: int,+ audio_latent: torch.Tensor,+ source_duration: float,+ video_context: torch.Tensor,+ audio_context: torch.Tensor,+ sigmas: torch.Tensor,+ noiser: Noiser,+ seed: int,+ device: torch.device,+ dtype: torch.dtype,+) -> TemporalTileResult:+ """Ancestral-densify one temporal tile. Returns owned latent and any new slot planes."""+ prepared = _prepare_temporal_tile_specs(+ image_conditioner=image_conditioner,+ images=images,+ canvas=canvas,+ video_latent=video_latent,+ tile_index=tile_index,+ tile=tile,+ prefix=prefix,+ previous_tile=previous_tile,+ plane_at=plane_at,+ keyframes=keyframes,+ round_idx=round_idx,+ pixel_scale=pixel_scale,+ temporal_scale=temporal_scale,+ audio_latent=audio_latent,+ source_duration=source_duration,+ video_context=video_context,+ audio_context=audio_context,+ sigmas=sigmas,+ device=device,+ dtype=dtype,+ )+ denoise = prepared.denoise+ tile_state, _ = stage(+ denoiser=SimpleDenoiser(video_context, audio_context),+ sigmas=sigmas,+ noiser=noiser,+ modalities=VideoAudio(video=denoise.video, audio=denoise.audio),+ loop=partial(+ euler_ancestral_denoising_loop,+ noise_seed=seed + 1000 * round_idx + tile_index,+ eta=TEMPORAL_ANCESTRAL_ETA,+ ),+ )+ if tile_state is None:+ raise RuntimeError(f"Temporal round {round_idx}: tile produced no video state")+ return _collect_temporal_tile_result(+ tile_state=tile_state,+ tile=tile,+ tile_video=prepared.tile_video,+ prefix=prefix,+ round_idx=round_idx,+ )+++def run_one_temporal_round( # noqa: PLR0913+ *,+ round_idx: int,+ stage: DiffusionStage,+ temporal_upsampler: VideoUpsampler,+ image_conditioner: ImageConditioner,+ video_state: LatentState,+ keyframes: KeyframeCarry,+ video_shape: VideoPixelShape,+ images: list[ImageConditioningInput],+ video_context: torch.Tensor,+ audio_context: torch.Tensor,+ audio_latent: torch.Tensor,+ source_duration: float,+ seed: int,+ noiser: Noiser,+ sigmas: torch.Tensor,+ device: torch.device,+ dtype: torch.dtype,+ temporal_scale: int,+) -> tuple[LatentState, KeyframeCarry, list[int]]:+ """Upsample once, ancestral-densify all tiles, stitch, and rebuild the carry-forward bag.+ ``video_shape`` is the desired canvas *after* this round (x2 frames and fps vs the previous+ stage), matching how stage 1 / stage 2 take their target ``VideoPixelShape``.+ """+ video_latent = temporal_upsampler(video_state.latent[:1])+ scaled_keyframes = {2 * position: plane for position, plane in keyframes.items()}+ seam_positions = list(scaled_keyframes)+ windows = TemporalTilePlan(seam_positions, video_shape.frames, 2**round_idx, temporal_scale)+ tile_latents: list[torch.Tensor] = []+ previous_tile: tuple[int, torch.Tensor] | None = None+ plane_at = dict(scaled_keyframes)++ for tile_index, tile in enumerate(windows):+ prefix = (+ None+ if tile_index == 0+ else tile_prefix((tile.interval.start - 1) * temporal_scale, plane_at, temporal_scale)+ )+ tile_result = _denoise_temporal_tile(+ stage=stage,+ image_conditioner=image_conditioner,+ images=images,+ canvas=video_shape,+ video_latent=video_latent,+ tile_index=tile_index,+ tile=tile,+ prefix=prefix,+ previous_tile=previous_tile,+ plane_at=plane_at,+ keyframes=scaled_keyframes,+ round_idx=round_idx,+ pixel_scale=2**round_idx,+ temporal_scale=temporal_scale,+ audio_latent=audio_latent,+ source_duration=source_duration,+ video_context=video_context,+ audio_context=audio_context,+ sigmas=sigmas,+ noiser=noiser,+ seed=seed,+ device=device,+ dtype=dtype,+ )+ previous_tile = tile_result.previous_tile+ tile_latents.append(tile_result.owned_latent)+ for position, plane in tile_result.new_planes.items():+ plane_at.setdefault(position, plane)++ stitched = torch.cat(tile_latents, dim=2)+ expected_t = (video_shape.frames - 1) // temporal_scale + 1+ if stitched.shape[2] != expected_t:+ raise RuntimeError(f"Stitched latent T={stitched.shape[2]} != expected {expected_t}")+ next_video_state = replace(video_state, latent=stitched, generated_keyframes=None)+ return next_video_state, dict(sorted(plane_at.items())), seam_positions+++def _decode_carry_keyframes(+ video_decoder: VideoDecoder,+ keyframes: KeyframeCarry,+ *,+ seed: int,+ device: torch.device,+) -> dict[int, torch.Tensor]:+ """Decode each carry keyframe as its own 1-frame RGB clip.+ The VAE is causal, so a stacked encode/decode would bleed neighbouring planes. Each+ plane is a standalone one-pixel-frame latent, matching ``DecodeKeyframes``. Dist+ ``decode_single_frames`` splits the planes across the ranks and gathers them back, so+ every rank gets every plane instead of the empty worker yield from ``decode_video``.+ Generators are per plane, which keeps the pixels independent of the world size.+ """+ for position, plane in keyframes.items():+ if plane.ndim != 5 or plane.shape[2] != 1:+ raise ValueError(f"Expected one keyframe plane at {position}, got {tuple(plane.shape)}")+ n_planes = len(keyframes)+ logger.info("Epilogue: decoding %d carry keyframes separately", n_planes)+ planes = list(keyframes.values())+ generators = [torch.Generator(device=device).manual_seed(seed + 4000 + index) for index in range(n_planes)]+ rgb_planes: list[torch.Tensor] = []+ for index, rgb in enumerate(video_decoder.decode_single_frames(planes, generators)):+ if rgb.shape[0] < 1:+ raise RuntimeError(f"Decoder returned no pixels for carry keyframe {index}")+ rgb_planes.append(rgb.detach().cpu())+ if len(rgb_planes) != n_planes:+ raise RuntimeError(f"Expected {n_planes} decoded carry keyframes, got {len(rgb_planes)}")+ return dict(zip(keyframes, rgb_planes, strict=True))+++def _encode_keyframe_pixels(+ enc: VideoEncoder,+ pixel_keyframes: dict[int, torch.Tensor],+ *,+ dtype: torch.dtype,+ device: torch.device,+) -> KeyframeCarry:+ """Encode each Lanczos RGB clip as a one-frame latent plane."""++ def encode(rgb: torch.Tensor) -> torch.Tensor:+ sample = to_vae_range(rgb.to(device=device, dtype=torch.float32))+ return enc(sample.permute(3, 0, 1, 2).unsqueeze(0).contiguous().to(dtype=dtype))++ return {position: encode(rgb) for position, rgb in pixel_keyframes.items()}+++def _rebuild_epilogue_keyframes(+ *,+ video_decoder: VideoDecoder,+ image_conditioner: ImageConditioner,+ keyframes: KeyframeCarry,+ video_state: LatentState,+ images: Sequence[ImageConditioningInput],+ temporal_upscalings: int,+ seed: int,+ device: torch.device,+ dtype: torch.dtype,+) -> tuple[KeyframeCarry, torch.Tensor | None]:+ """Decode carry planes, Lanczos-x2, and encode. Opening plane if no frame-0 image.+ Decoder is freed before the encoder is built: decode completes, then+ ``image_conditioner`` loads the encoder for the RGB planes only.+ """+ opening_position = -1+ to_decode = dict(keyframes)+ epi_images = rebase_image_conditionings(images, pixel_scale=2**temporal_upscalings)+ if not any(image.frame_idx == 0 for image in epi_images):+ to_decode[opening_position] = video_state.latent[:1, :, :1]+ pixel_keyframes = _decode_carry_keyframes(video_decoder, to_decode, seed=seed, device=device)+ pixel_keyframes = {position: lanczos_x2_fhwc(rgb) for position, rgb in pixel_keyframes.items()}+ encoded = image_conditioner(lambda enc: _encode_keyframe_pixels(enc, pixel_keyframes, dtype=dtype, device=device))+ opening = encoded.pop(opening_position, None)+ return encoded, opening+++def _prepare_tiled_spatial_denoise_specs(+ *,+ latent: torch.Tensor,+ conditionings: list[ConditioningItem],+ video_context: torch.Tensor,+ audio_context: torch.Tensor,+ audio_latent: torch.Tensor,+ fps: float,+ scale_factors: SpatioTemporalScaleFactors,+ device: torch.device,+ dtype: torch.dtype,+ noise_scale: float,+) -> _PreparedDenoise:+ _, _, n_frames, n_height, n_width = latent.shape+ pixel_frames = (n_frames - 1) * scale_factors.time + 1+ return _PreparedDenoise(+ video=ModalitySpec(+ latent=latent.to(device=device, dtype=dtype),+ conditioning_fps=fps,+ context=video_context,+ conditionings=conditionings,+ noise_scale=noise_scale,+ ),+ audio=ModalitySpec(+ latent=audio_latent,+ conditioning_fps=fps,+ context=audio_context,+ frozen=True,+ noise_scale=0.0,+ ),+ canvas=VideoPixelShape(+ batch=1,+ frames=pixel_frames,+ height=n_height * scale_factors.height,+ width=n_width * scale_factors.width,+ fps=fps,+ ),+ )+++def _prepare_epilogue_window_specs( # noqa: PLR0913+ *,+ index: int,+ num_windows: int,+ window: TemporalTile,+ prefix: TilePrefix | None,+ latent: torch.Tensor,+ guide: torch.Tensor,+ plane_at: dict[int, torch.Tensor],+ window_images: list[ConditioningItem],+ keyframes: KeyframeCarry,+ opening_plane: torch.Tensor | None,+ previous: tuple[int, torch.Tensor] | None,+ downscale_factor: int,+ canvas: VideoPixelShape,+ audio_latent: torch.Tensor,+ source_duration: float,+ video_context: torch.Tensor,+ audio_context: torch.Tensor,+ noise_scale: float,+ temporal_scale: int,+ scale_factors: SpatioTemporalScaleFactors,+ device: torch.device,+ dtype: torch.dtype,+) -> _PreparedEpilogueWindow:+ interval = window.interval+ if prefix is None:+ window_latent_in = latent[:, :, interval.start : interval.end]+ reference = guide[:, :, interval.start : interval.end]+ origin, resume_pixel, pinned_cells = window.pixel_start, 0, 0+ else:+ window_latent_in = torch.cat(+ [+ plane_at[prefix.keyframe_position].to(dtype=latent.dtype),+ latent[:, :, prefix.video_start_cell : interval.end],+ ],+ dim=2,+ )+ reference = guide[:, :, prefix.video_start_cell - 1 : interval.end]+ origin, resume_pixel, pinned_cells = (+ prefix.keyframe_position,+ prefix.resume_pixel,+ prefix.cells,+ )+ local_frames = (window_latent_in.shape[2] - 1) * temporal_scale + 1+ conditionings: list[ConditioningItem] = list(window_images)++ for position, plane in keyframes.items():+ if origin <= position <= window.pixel_end and position >= resume_pixel:+ conditionings.extend(+ keyframe_conditionings_from_latents(+ plane,+ [int(position) - origin],+ strength=EPILOGUE_KEYFRAME_STRENGTH,+ )+ )+ if opening_plane is not None and prefix is None:+ conditionings.extend(+ keyframe_conditionings_from_latents(opening_plane, [0], strength=EPILOGUE_KEYFRAME_STRENGTH)+ )+ conditionings.append(+ VideoConditionByReferenceLatent(+ latent=reference,+ downscale_factor=downscale_factor,+ strength=1.0,+ )+ )+ if prefix is not None and previous is not None:+ conditionings.append(lead_in_carryover(previous, prefix, window_latent_in[:, :, :1]))+ logger.info(+ "Epilogue window %d/%d: starts at px %d, %d cell(s) pinned, denoises from %d",+ index + 1,+ num_windows,+ origin,+ pinned_cells,+ resume_pixel,+ )++ cond_fps = conditioning_fps(canvas.fps)+ return _PreparedEpilogueWindow(+ window_latent=window_latent_in,+ denoise=_prepare_tiled_spatial_denoise_specs(+ latent=window_latent_in,+ conditionings=conditionings,+ video_context=video_context,+ audio_context=audio_context,+ audio_latent=audio_latent_for_tile(+ audio_latent,+ pixel_start=origin,+ local_frames=local_frames,+ playback_fps=canvas.fps,+ source_duration=source_duration,+ cond_fps=cond_fps,+ ),+ fps=cond_fps,+ scale_factors=scale_factors,+ device=device,+ dtype=dtype,+ noise_scale=noise_scale,+ ),+ pinned_cells=pinned_cells,+ prefix=prefix,+ interval_start=interval.start,+ )+++def _execute_tiled_spatial_denoise(+ stage: DiffusionStage,+ *,+ prepared: _PreparedDenoise,+ latent: torch.Tensor,+ tiling: TileCountConfig,+ sigmas: torch.Tensor,+ video_context: torch.Tensor,+ audio_context: torch.Tensor,+ seed: int,+ device: torch.device,+ loop: Callable[..., tuple[LatentState | None, LatentState | None]] | None = None,+) -> torch.Tensor:+ """Run one spatially tiled denoising pass from prepared modality specs."""+ tiling = clamp_tile_to_latent(tiling, tuple(latent.shape[2:5]))++ def _tile(model: torch.nn.Module, tools: LatentTools | None) -> torch.nn.Module:+ if not isinstance(tools, VideoLatentTools):+ raise TypeError(f"Spatial epilogue needs video tools to tile, got {type(tools).__name__}")+ return TiledDiffusionModel(model, video_tools=tools, tiling=tiling)++ tiled_stage = stage.with_model_wrapper(_tile)+ logger.info(+ "Spatial epilogue: %d step(s) over %s tiles (frames=%s height=%s width=%s)",+ sigmas.numel() - 1,+ tiling.frames.num_tiles * tiling.height.num_tiles * tiling.width.num_tiles,+ tiling.frames,+ tiling.height,+ tiling.width,+ )+ video_state, _ = tiled_stage(+ denoiser=SimpleDenoiser(video_context, audio_context),+ sigmas=sigmas.to(dtype=torch.float32, device=device),+ noiser=GaussianNoiser(generator=torch.Generator(device=device).manual_seed(seed + 2000)),+ modalities=VideoAudio(video=prepared.video, audio=prepared.audio),+ loop=loop,+ )+ if video_state is None:+ raise RuntimeError("Spatial epilogue produced no video state")+ return video_state.latent+++def _epilogue_sigma_phases(sigmas: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor | None]:+ """Split a detailing schedule into one coarse step and any remaining fine steps."""+ if sigmas.ndim != 1 or sigmas.numel() < 2:+ raise ValueError(f"Epilogue schedule needs at least one step (2 sigma values), got shape {tuple(sigmas.shape)}")+ if sigmas.numel() == 2:+ return sigmas, None+ return sigmas[:2], sigmas[1:]+++def _run_epilogue_windows( # noqa: PLR0913+ *,+ stage: DiffusionStage,+ latent: torch.Tensor,+ guide: torch.Tensor,+ windows: TemporalTilePlan,+ prefixes: Sequence[TilePrefix | None],+ window_images: Sequence[list[ConditioningItem]],+ keyframes: KeyframeCarry,+ opening_plane: torch.Tensor | None,+ sigmas: torch.Tensor,+ video_context: torch.Tensor,+ audio_context: torch.Tensor,+ audio_latent: torch.Tensor,+ source_duration: float,+ canvas: VideoPixelShape,+ seed: int,+ device: torch.device,+ dtype: torch.dtype,+ downscale_factor: int,+ temporal_scale: int,+ loop: Callable[..., tuple[LatentState | None, LatentState | None]] | None = None,+) -> torch.Tensor:+ """Detail each temporal window with one coarse-grid step, then any remaining steps on the fine grid."""+ stitched: list[torch.Tensor] = []+ previous: tuple[int, torch.Tensor] | None = None+ coarse_sigmas, fine_sigmas = _epilogue_sigma_phases(sigmas)+ coarse_tiling = TileCountConfig(+ frames=DimensionTilingConfig(1, overlap=0),+ height=DimensionTilingConfig(EPILOGUE_SPATIAL_COARSE_TILES, EPILOGUE_SPATIAL_OVERLAP),+ width=DimensionTilingConfig(EPILOGUE_SPATIAL_COARSE_TILES, EPILOGUE_SPATIAL_OVERLAP),+ )+ scale_factors = stage.video_scale_factors+ for index, window in enumerate(windows):+ prepared_window = _prepare_epilogue_window_specs(+ index=index,+ num_windows=len(windows),+ window=window,+ prefix=prefixes[index],+ latent=latent,+ guide=guide,+ plane_at=keyframes,+ window_images=window_images[index],+ keyframes=keyframes,+ opening_plane=opening_plane,+ previous=previous,+ downscale_factor=downscale_factor,+ canvas=canvas,+ audio_latent=audio_latent,+ source_duration=source_duration,+ video_context=video_context,+ audio_context=audio_context,+ noise_scale=float(coarse_sigmas[0].item()),+ temporal_scale=temporal_scale,+ scale_factors=scale_factors,+ device=device,+ dtype=dtype,+ )+ window_latent = _execute_tiled_spatial_denoise(+ stage,+ prepared=prepared_window.denoise,+ latent=prepared_window.window_latent,+ tiling=coarse_tiling,+ sigmas=coarse_sigmas,+ video_context=video_context,+ audio_context=audio_context,+ seed=seed + 100 * index,+ device=device,+ loop=loop,+ )+ if fine_sigmas is not None:+ fine_tiling = TileCountConfig(+ frames=DimensionTilingConfig(1, overlap=0),+ height=DimensionTilingConfig(EPILOGUE_SPATIAL_TILES, EPILOGUE_SPATIAL_OVERLAP),+ width=DimensionTilingConfig(EPILOGUE_SPATIAL_TILES, EPILOGUE_SPATIAL_OVERLAP),+ )+ audio_latent_in = prepared_window.denoise.audio.latent+ if audio_latent_in is None:+ raise RuntimeError("Epilogue window prepared no audio latent")+ fine_prepared = _prepare_tiled_spatial_denoise_specs(+ latent=window_latent,+ conditionings=list(prepared_window.denoise.video.conditionings),+ video_context=video_context,+ audio_context=audio_context,+ audio_latent=audio_latent_in,+ fps=prepared_window.denoise.canvas.fps,+ scale_factors=scale_factors,+ device=device,+ dtype=dtype,+ noise_scale=0.0,+ )+ window_latent = _execute_tiled_spatial_denoise(+ stage,+ prepared=fine_prepared,+ latent=window_latent,+ tiling=fine_tiling,+ sigmas=fine_sigmas,+ video_context=video_context,+ audio_context=audio_context,+ seed=seed + 100 * index,+ device=device,+ loop=loop,+ )+ prefix = prepared_window.prefix+ previous = (+ prefix.video_start_cell - 1 if prefix else prepared_window.interval_start,+ window_latent.detach(),+ )+ stitched.append(window_latent[:, :, prepared_window.pinned_cells :])+ return torch.cat(stitched, dim=2)+++def _plan_epilogue_windows(+ *,+ n_latent_frames: int,+ last_window_seams: Sequence[int],+ keyframe_positions: Iterable[int],+ temporal_upscalings: int,+ temporal_scale: int,+) -> tuple[TemporalTilePlan, tuple[TilePrefix | None, ...]]:+ """Cut the upscaled canvas into temporal tiles and pin each non-first tile on a carry keyframe."""+ pixel_frames = (n_latent_frames - 1) * temporal_scale + 1+ windows = TemporalTilePlan(+ last_window_seams,+ pixel_frames,+ max(1, 2**temporal_upscalings),+ temporal_scale,+ )+ prefixes = tuple(+ None+ if index == 0+ else tile_prefix((window.interval.start - 1) * temporal_scale, keyframe_positions, temporal_scale)+ for index, window in enumerate(windows)+ )+ return windows, prefixes+++def _encode_epilogue_window_images(+ enc: VideoEncoder,+ *,+ windows: TemporalTilePlan,+ prefixes: Sequence[TilePrefix | None],+ images: Sequence[ImageConditioningInput],+ temporal_upscalings: int,+ video_shape: VideoPixelShape,+ dtype: torch.dtype,+ device: torch.device,+) -> list[list[ConditioningItem]]:+ """Encode user image conditionings that fall inside each epilogue window."""+ per_window: list[list[ConditioningItem]] = []+ for index, window in enumerate(windows):+ prefix = prefixes[index]+ origin = window.pixel_start if prefix is None else prefix.keyframe_position+ resume = 0 if prefix is None else prefix.resume_pixel+ inside = [+ image+ for image in rebase_image_conditionings(+ images,+ pixel_scale=2**temporal_upscalings,+ pixel_start=origin,+ pixel_end=window.pixel_end,+ )+ if image.frame_idx + origin >= resume+ ]+ per_window.append(+ combined_image_conditionings(+ images=inside,+ height=video_shape.height,+ width=video_shape.width,+ video_encoder=enc,+ dtype=dtype,+ device=device,+ )+ if inside+ else []+ )+ return per_window+++def run_spatial_epilogue( # noqa: PLR0913+ *,+ stage: DiffusionStage,+ upsampler: VideoUpsampler,+ image_conditioner: ImageConditioner,+ video_decoder: VideoDecoder,+ video_state: LatentState,+ keyframes: KeyframeCarry,+ images: Sequence[ImageConditioningInput],+ video_shape: VideoPixelShape,+ temporal_upscalings: int,+ last_window_seams: Sequence[int],+ video_context: torch.Tensor,+ audio_context: torch.Tensor,+ audio_latent: torch.Tensor | None,+ source_duration: float,+ sigmas: torch.Tensor,+ downscale_factor: int,+ seed: int,+ device: torch.device,+ dtype: torch.dtype,+ temporal_scale: int = VIDEO_SCALE_FACTORS.time,+ loop: Callable[..., tuple[LatentState | None, LatentState | None]] | None = None,+) -> SpatialEpilogueResult:+ """Full-res spatial detailing: Lanczos KF rebuild, x2 video upsample, per-window tiled passes.+ ``video_shape`` is the epilogue canvas (final output height, width, frame count, fps).+ Temporal tiles cut on+ ``last_window_seams`` from the last t-round (empty when ``temporal_upscalings == 0``).+ Conditioning fps snaps to 60 above 30. Carry keyframes are decoded one plane at a time,+ Lanczos-stretched x2, and encoded as strength-1 conditions; only the video latent is+ spatially upsampled. Frozen stage-1 audio is resampled onto each window for+ cross-attention; the caller still ships the original stage-1 audio. Image ``frame_idx`` is+ scaled by ``2**temporal_upscalings`` onto the final canvas. Trim stays with the caller.+ """+ if not keyframes:+ raise RuntimeError("Spatial epilogue: missing carry-forward keyframes")+ if audio_latent is None:+ raise RuntimeError("Spatial epilogue: missing stage-1 audio latent")+ encoded_keyframes, encoded_opening = _rebuild_epilogue_keyframes(+ video_decoder=video_decoder,+ image_conditioner=image_conditioner,+ keyframes=keyframes,+ video_state=video_state,+ images=images,+ temporal_upscalings=temporal_upscalings,+ seed=seed,+ device=device,+ dtype=dtype,+ )+ guide = video_state.latent[:1]+ upscaled = upsampler(guide)+ windows, prefixes = _plan_epilogue_windows(+ n_latent_frames=upscaled.shape[2],+ last_window_seams=last_window_seams,+ keyframe_positions=keyframes,+ temporal_upscalings=temporal_upscalings,+ temporal_scale=temporal_scale,+ )+ window_images = image_conditioner(+ lambda enc: _encode_epilogue_window_images(+ enc,+ windows=windows,+ prefixes=prefixes,+ images=images,+ temporal_upscalings=temporal_upscalings,+ video_shape=video_shape,+ dtype=dtype,+ device=device,+ )+ )+ if encoded_opening is not None:+ logger.info("Spatial epilogue: anchoring frame 0 on the generated opening frame (not shipped)")+ epi_latent = _run_epilogue_windows(+ stage=stage,+ latent=upscaled,+ guide=guide,+ windows=windows,+ prefixes=prefixes,+ window_images=window_images,+ keyframes=encoded_keyframes,+ opening_plane=encoded_opening,+ sigmas=sigmas,+ video_context=video_context,+ audio_context=audio_context,+ audio_latent=audio_latent,+ source_duration=source_duration,+ canvas=video_shape,+ seed=seed,+ device=device,+ dtype=dtype,+ downscale_factor=downscale_factor,+ temporal_scale=temporal_scale,+ loop=loop,+ )+ if epi_latent.shape[2] != upscaled.shape[2]:+ raise RuntimeError(f"Epilogue stitched T={epi_latent.shape[2]} != expected {upscaled.shape[2]}")+ return SpatialEpilogueResult(+ video_state=replace(video_state, latent=epi_latent, generated_keyframes=None),+ keyframes=encoded_keyframes,+ )diff --git a/packages/ltx-pipelines/src/ltx_pipelines/distilled.py b/packages/ltx-pipelines/src/ltx_pipelines/distilled.pyindex 58e3c12..3ec33f4 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/distilled.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/distilled.py@@ -1,23 +1,43 @@import logging-from collections.abc import Sequence-from functools import partial+from collections.abc import Iterator, Sequence+from dataclasses import dataclassfrom typing import Anyimport torchfrom ltx_core.allocator_trim_strategy import AllocatorTrimStrategy-from ltx_core.components.diffusion_steps import EulerAncestralDiffusionStepfrom ltx_core.components.noisers import GaussianNoiser+from ltx_core.conditioning import ConditioningItemfrom ltx_core.loader import LoraPathStrengthAndSDOpsfrom ltx_core.loader.registry import Registry+from ltx_core.model.transformer import X0Modelfrom ltx_core.model.transformer.compiling import CompilationConfigfrom ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, get_video_chunks_numberfrom ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy-from ltx_core.types import VideoPixelShape+from ltx_core.types import LatentState, VideoPixelShape+from ltx_pipelines.chunks import (+ Chunk,+ ChunkConfig,+ DecodedChunk,+ MakeVideoConditionings,+ decode_chunks,+ denoise_chunks,+ generate_uniform_chunks,+ pipeline_output_from_chunks,+ spatially_upsample_chunks,+ split_decoded_chunks,+)+from ltx_pipelines.chunks.conditionings import (+ assert_image_frames_in_clip,+ image_conditionings_for_chunk,+ images_for_chunk,+)from ltx_pipelines.utils.args import (- ImageConditioningInput,+ add_chunk_layout_args,add_generated_keyframes_arg,+ add_keyframe_decode_arg,+ chunk_config_from_args,default_2_stage_distilled_arg_parser,resolve_cli_params,)@@ -32,33 +52,30 @@ from ltx_pipelines.utils.blocks import (require_num_frames_source,resolve_num_frames,)-from ltx_pipelines.utils.constants import (- DISTILLED_SIGMAS,- STAGE_2_DISTILLED_SIGMAS,- detect_model_version,-)-from ltx_pipelines.utils.denoisers import SimpleDenoiser+from ltx_pipelines.utils.constants import DISTILLED_SIGMAS, STAGE_2_DISTILLED_SIGMAS, detect_model_versionfrom ltx_pipelines.utils.helpers import (+ assert_generated_keyframes_request,assert_resolution,- combined_image_conditionings,ensure_tiling_config,- generated_keyframe_conditionings,get_device,- has_generated_keyframes,+ snap_frames_to_grid,tiling_scale_factors_for_vae,)-from ltx_pipelines.utils.media_io import (- HDRColorSpace,- encode_video,- resolve_hdr_color_space,- vae_dtype_for_hdr,-)+from ltx_pipelines.utils.media_io import EXRColorSpace, encode_video, resolve_hdr_color_space, vae_dtype_for_hdrfrom ltx_pipelines.utils.model_paths import ModelPathsfrom ltx_pipelines.utils.samplers import euler_ancestral_denoising_loop-from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode, PipelineOutput+from ltx_pipelines.utils.types import (+ DEFAULT_AUTO_DURATION,+ AutoDuration,+ Denoiser,+ ImageConditioningInput,+ OffloadMode,+ PipelineOutput,+ VideoAudio,+)-# Generation from which stage 1 is sampled with the ancestral (SDE) Euler sampler instead of the-# deterministic one.+# Generation from which a denoising pass uses the ancestral (SDE) Euler sampler rather than the+# deterministic one. ``DFRPipeline`` reuses this rule and the helpers below.ANCESTRAL_SAMPLER_SINCE_VERSION = (2, 5)# Fully ancestral noise injection: eta=0 is a plain Euler step, eta=1 injects the full@@ -71,19 +88,73 @@ ANCESTRAL_S_NOISE = 1.0# loop's ``_get_plain_noise`` both draw ``torch.randn`` at the same shape, dtype, and device from a# freshly seeded generator. Mirrors the substep-seed offset in ``res2s_audio_video_denoising_loop``.ANCESTRAL_NOISE_SEED_OFFSET = 10000+# Every pass draws from its own offset, so no two of them inject the same noise.+ANCESTRAL_STAGE_2_NOISE_SEED_OFFSET = 20000+++def ancestral_sampler_kwargs(seed: int, dtype: torch.dtype, noise_seed_offset: int) -> dict[str, Any]:+ """``loop`` override that samples a :class:`DiffusionStage` with ancestral Euler.+ The loop increments ``noise_seed`` on each denoise call (sequential chunks) so overlapping+ windows do not reuse ancestral noise. A single ``DiffusionStage`` call uses index 0,+ matching a fixed-seed partial.+ """+ call_index = 0+ base_seed = seed + noise_seed_offset++ def ancestral_loop(+ sigmas: torch.Tensor,+ video_state: LatentState | None,+ audio_state: LatentState | None,+ transformer: X0Model,+ denoiser: Denoiser,+ ) -> VideoAudio[LatentState]:+ nonlocal call_index+ result = euler_ancestral_denoising_loop(+ sigmas,+ video_state,+ audio_state,+ transformer,+ denoiser,+ noise_seed=base_seed + call_index,+ model_dtype=dtype,+ eta=ANCESTRAL_ETA,+ s_noise=ANCESTRAL_S_NOISE,+ )+ call_index += 1+ return result++ return {"loop": ancestral_loop}def should_use_ancestral_sampler(transformer_path: str) -> bool:- """Whether a checkpoint's generation calls for the ancestral stage-1 sampler.+ """Whether a checkpoint's generation calls for the ancestral sampler.Takes the transformer checkpoint (``ModelPaths.transformer()``) since that is the componentcarrying ``model_version`` in both the monolith and split layouts.- This is what :class:`DistilledPipeline` resolves at construction into- ``self.use_ancestral_sampler``; a named function rather than an inline comparison so the rule- can be tested, and reused, without loading a checkpoint's weights.+ This is what the pipelines resolve at construction into ``self.use_ancestral_sampler``; a named+ function rather than an inline comparison so the rule can be tested, and reused, without+ loading a checkpoint's weights."""return detect_model_version(transformer_path) >= ANCESTRAL_SAMPLER_SINCE_VERSION+@dataclass(frozen=True)+class _DistilledRunContext:+ """Setup snapshot for :meth:`DistilledPipeline.stream_chunks`, built by :meth:`DistilledPipeline._prepare_run`."""++ generator: torch.Generator+ noiser: GaussianNoiser+ dtype: torch.dtype+ vae_dtype: torch.dtype+ #: ``images`` with every unset CRF filled in, so callers do not re-resolve it.+ images: list[ImageConditioningInput]+ video_context: torch.Tensor+ audio_context: torch.Tensor+ num_frames: int+ tiling_config: TilingConfig+ stage_1_width: int+ stage_1_height: int++class DistilledPipeline:"""Two-stage distilled video generation pipeline.@@ -167,52 +238,28 @@ class DistilledPipeline:)self.use_ancestral_sampler = should_use_ancestral_sampler(model_paths.transformer())- def _stage_1_sampler_kwargs(self, seed: int) -> dict[str, Any]:- """Resolve stage 1's ``stepper`` / ``loop`` overrides for :class:`DiffusionStage`.- Returns an empty dict for the deterministic sampler, letting ``DiffusionStage`` apply its- own ``EulerDiffusionStep`` + ``euler_denoising_loop`` defaults rather than restating them.- """- if not self.use_ancestral_sampler:- return {}-- return {- "stepper": EulerAncestralDiffusionStep(eta=ANCESTRAL_ETA, s_noise=ANCESTRAL_S_NOISE),- "loop": partial(- euler_ancestral_denoising_loop,- noise_seed=seed + ANCESTRAL_NOISE_SEED_OFFSET,- model_dtype=self.dtype,- ),- }-- def __call__( # noqa: PLR0913+ def _prepare_run( # noqa: PLR0913self,+ *,prompt: str,seed: int,height: int,width: int,frame_rate: float,images: list[ImageConditioningInput],- num_frames: int | AutoDuration = DEFAULT_AUTO_DURATION,- vae_dtype: torch.dtype | None = None,- tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,- enhance_prompt: bool = False,- enhance_static_cache: bool = False,- stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS,- stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,- color_space: HDRColorSpace | None = None,- generated_keyframes: int | Sequence[int] = 0,- ) -> PipelineOutput:- """Generate a video.- Stage 1 samples with the ancestral (SDE) Euler sampler or the deterministic one according- to ``self.use_ancestral_sampler``, detected from the checkpoint generation. Stage 2 is- always deterministic -- its 3-step refinement schedule is too short to remove freshly- injected noise.- """+ num_frames: int | AutoDuration,+ vae_dtype: torch.dtype | None,+ tiling_config: TilingConfig | AutoTiling | None,+ enhance_prompt: bool,+ enhance_static_cache: bool,+ generated_keyframes: int | Sequence[int],+ decode_with_keyframes: bool,+ ) -> _DistilledRunContext:+ """Validate inputs, encode prompts, and resolve frame count / tiling before chunk planning."""require_num_frames_source(num_frames, self.duration_predictor)images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=True)- if has_generated_keyframes(generated_keyframes):- self.stage.assert_generated_keyframes_supported()+ assert_generated_keyframes_request(decode_with_keyframes, generated_keyframes, self.stage)generator = torch.Generator(device=self.device).manual_seed(seed)noiser = GaussianNoiser(generator=generator)@@ -228,101 +275,235 @@ class DistilledPipeline:)video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding- num_frames = resolve_num_frames(- num_frames,- self.duration_predictor,- video_encoding=video_context,- audio_encoding=audio_context,- frame_rate=frame_rate,+ resolved_num_frames = snap_frames_to_grid(+ resolve_num_frames(+ num_frames,+ self.duration_predictor,+ video_encoding=video_context,+ audio_encoding=audio_context,+ frame_rate=frame_rate,+ ))scale_factors = tiling_scale_factors_for_vae(self.video_decoder.checkpoint_path)- tiling_config = ensure_tiling_config(+ resolved_tiling_config = ensure_tiling_config(tiling_config,scale_factors=scale_factors,vae_checkpoint_path=self.video_decoder.checkpoint_path,- video_shape=VideoPixelShape(batch=1, frames=num_frames, height=height, width=width, fps=frame_rate),+ video_shape=VideoPixelShape(+ batch=1, frames=resolved_num_frames, height=height, width=width, fps=frame_rate+ ),diffvae_optimization=self.video_decoder.diffvae_optimization,device=self.device,+ keyframes=decode_with_keyframes,)- # Stage 1: Initial low resolution video generation.- stage_1_sigmas = stage_1_sigmas.to(dtype=torch.float32, device=self.device)- stage_1_w, stage_1_h = width // 2, height // 2- stage_1_conditionings = self.image_conditioner(- lambda enc: combined_image_conditionings(- images=images,- height=stage_1_h,- width=stage_1_w,- video_encoder=enc,- dtype=dtype,- device=self.device,- color_space=color_space,- )+ return _DistilledRunContext(+ generator=generator,+ noiser=noiser,+ dtype=dtype,+ vae_dtype=vae_dtype,+ images=images,+ video_context=video_context,+ audio_context=audio_context,+ num_frames=resolved_num_frames,+ tiling_config=resolved_tiling_config,+ stage_1_width=width // 2,+ stage_1_height=height // 2,)- stage_1_conditionings.extend(generated_keyframe_conditionings(generated_keyframes, num_frames))- video_state, audio_state = self.stage(- denoiser=SimpleDenoiser(video_context, audio_context),- sigmas=stage_1_sigmas,- noiser=noiser,- width=stage_1_w,- height=stage_1_h,- frames=num_frames,- fps=frame_rate,- video=ModalitySpec(context=video_context, conditionings=stage_1_conditionings),- audio=ModalitySpec(context=audio_context),- **self._stage_1_sampler_kwargs(seed),+ def _sampler_kwargs(self, seed: int, noise_seed_offset: int) -> dict[str, Any]:+ """Ancestral overrides, or an empty dict to leave the caller on its Euler defaults.+ The overrides are consumed by :class:`DiffusionStage` and by ``denoise_chunks``; the+ latter reuses one dict across a chunk sequence, which is what advances the ancestral+ noise seed per chunk.+ """+ if not self.use_ancestral_sampler:+ return {}+ return ancestral_sampler_kwargs(seed, self.dtype, noise_seed_offset)++ def _video_conditionings(+ self,+ images: list[ImageConditioningInput],+ num_frames: int,+ color_space: EXRColorSpace | None,+ ) -> MakeVideoConditionings:+ assert_image_frames_in_clip(images, num_frames)++ def make(chunk: Chunk) -> list[ConditioningItem]:+ if chunk.video is None or not images_for_chunk(chunk, images):+ return []+ return self.image_conditioner(+ lambda enc: image_conditionings_for_chunk(+ chunk,+ images=images,+ video_encoder=enc,+ color_space=color_space,+ )+ )++ return make++ def __call__( # noqa: PLR0913+ self,+ prompt: str,+ seed: int,+ height: int,+ width: int,+ frame_rate: float,+ images: list[ImageConditioningInput],+ num_frames: int | AutoDuration = DEFAULT_AUTO_DURATION,+ vae_dtype: torch.dtype | None = None,+ tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,+ enhance_prompt: bool = False,+ enhance_static_cache: bool = False,+ stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS,+ stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,+ color_space: EXRColorSpace | None = None,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ chunk_config: ChunkConfig | None = None,+ ) -> PipelineOutput:+ """Generate a video.+ Each stage samples according to ``self.use_ancestral_sampler``: the ancestral (SDE) Euler+ sampler on an LTX-2.5+ checkpoint, the deterministic one below that.+ ``chunk_config=None`` plans a single chunk covering the snapped clip.+ """+ chunks, num_frames, tiling_config = self.stream_chunks(+ prompt=prompt,+ seed=seed,+ height=height,+ width=width,+ frame_rate=frame_rate,+ images=images,+ num_frames=num_frames,+ vae_dtype=vae_dtype,+ tiling_config=tiling_config,+ enhance_prompt=enhance_prompt,+ enhance_static_cache=enhance_static_cache,+ stage_1_sigmas=stage_1_sigmas,+ stage_2_sigmas=stage_2_sigmas,+ color_space=color_space,+ generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,+ chunk_config=chunk_config,)+ return pipeline_output_from_chunks(chunks, num_frames=num_frames, tiling_config=tiling_config)- # Stage 2: Upsample and refine the video at higher resolution with distilled LORA.- upscaled_video_latent = self.upsampler(video_state.latent[:1])+ def stream_chunks( # noqa: PLR0913+ self,+ prompt: str,+ seed: int,+ height: int,+ width: int,+ frame_rate: float,+ images: list[ImageConditioningInput],+ num_frames: int | AutoDuration = DEFAULT_AUTO_DURATION,+ vae_dtype: torch.dtype | None = None,+ tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,+ enhance_prompt: bool = False,+ enhance_static_cache: bool = False,+ stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS,+ stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,+ color_space: EXRColorSpace | None = None,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ chunk_config: ChunkConfig | None = None,+ ) -> tuple[Iterator[DecodedChunk], int, TilingConfig]:+ """Generate a video as a stream of decoded chunks for long clips.+ Each stage samples according to ``self.use_ancestral_sampler``, with its own noise-seed+ offset, exactly as in :meth:`__call__`. Within a stage the ancestral seed advances per+ chunk, so overlapping windows do not reuse noise across a seam. With+ ``decode_with_keyframes=True``, stage-2 keeps generated-keyframe slots through denoise and each+ chunk decodes through the keyframe-aware DiffVAE path.+ ``chunk_config=None`` plans a single chunk covering the snapped clip, which is+ how :meth:`__call__` runs. The returned frame count is the stitched length the chunks+ actually decode to, which floors ``num_frames`` to the causal grid the same way the+ plan does.+ """+ ctx = self._prepare_run(+ prompt=prompt,+ seed=seed,+ height=height,+ width=width,+ frame_rate=frame_rate,+ images=images,+ num_frames=num_frames,+ vae_dtype=vae_dtype,+ tiling_config=tiling_config,+ enhance_prompt=enhance_prompt,+ enhance_static_cache=enhance_static_cache,+ generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,+ )+ if chunk_config is None:+ chunk_config = ChunkConfig(chunk_pixel_frames=ctx.num_frames, next_video_carry_frames=0)+ stage_1_sigmas = stage_1_sigmas.to(dtype=torch.float32, device=self.device)stage_2_sigmas = stage_2_sigmas.to(dtype=torch.float32, device=self.device)- stage_2_conditionings = self.image_conditioner(- lambda enc: combined_image_conditionings(- images=images,- height=height,- width=width,- video_encoder=enc,- dtype=dtype,- device=self.device,- color_space=color_space,- )++ target = VideoPixelShape(+ batch=1,+ frames=ctx.num_frames,+ height=ctx.stage_1_height,+ width=ctx.stage_1_width,+ fps=frame_rate,+ )+ chunks = generate_uniform_chunks(+ target=target,+ context=VideoAudio(video=ctx.video_context, audio=ctx.audio_context),+ device=self.device,+ dtype=ctx.dtype,+ config=chunk_config,+ video_scale_factors=self.stage.video_scale_factors,+ make_video_conditionings=self._video_conditionings(ctx.images, ctx.num_frames, color_space),+ generated_keyframes=generated_keyframes,)- video_state, audio_state = self.stage(- denoiser=SimpleDenoiser(video_context, audio_context),+ base = denoise_chunks(+ chunks,+ self.stage,+ sigmas=stage_1_sigmas,+ noiser=ctx.noiser,+ fps=frame_rate,+ noise_scale=1.0,+ **self._sampler_kwargs(seed, ANCESTRAL_NOISE_SEED_OFFSET),+ )+ upscaled = spatially_upsample_chunks(base, self.upsampler)+ refined = denoise_chunks(+ upscaled,+ self.stage,sigmas=stage_2_sigmas,- noiser=noiser,- width=width,- height=height,- frames=num_frames,+ noiser=ctx.noiser,fps=frame_rate,- video=ModalitySpec(- context=video_context,- conditionings=stage_2_conditionings,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=upscaled_video_latent,- ),- audio=ModalitySpec(- context=audio_context,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=audio_state.latent,+ **self._sampler_kwargs(seed, ANCESTRAL_STAGE_2_NOISE_SEED_OFFSET),+ )+ return (+ decode_chunks(+ refined,+ self.video_decoder,+ self.audio_decoder,+ fps=frame_rate,+ tiling_config=ctx.tiling_config,+ generator=ctx.generator,+ dtype=ctx.vae_dtype,+ keyframes=decode_with_keyframes,),+ ctx.num_frames,+ ctx.tiling_config,)- decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)- decoded_audio = self.audio_decoder(audio_state.latent)- return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)-@torch.inference_mode()def main() -> None:logging.basicConfig(level=logging.INFO)params = resolve_cli_params(distilled=True)- parser = add_generated_keyframes_arg(- default_2_stage_distilled_arg_parser(params=params, supports_auto_duration=True)+ parser = add_chunk_layout_args(+ add_keyframe_decode_arg(+ add_generated_keyframes_arg(+ default_2_stage_distilled_arg_parser(params=params, supports_auto_duration=True)+ )+ ))args = parser.parse_args()pipeline = DistilledPipeline(@@ -337,7 +518,8 @@ def main() -> None:)hdr = resolve_hdr_color_space(images=args.images, hdr=args.hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- result = pipeline(+ chunk_config = chunk_config_from_args(args)+ chunks, num_frames, tiling_config = pipeline.stream_chunks(prompt=args.prompt,seed=args.seed,height=args.height,@@ -351,15 +533,28 @@ def main() -> None:enhance_static_cache=args.enhance_static_cache,tiling_config=AUTO_TILING,generated_keyframes=args.num_generated_keyframes,+ decode_with_keyframes=args.decode_with_keyframes,+ chunk_config=chunk_config,)-+ if chunk_config is not None:+ video, audio, audio_sampling_rate = split_decoded_chunks(chunks)+ video_chunks_number = 1+ else:+ result = pipeline_output_from_chunks(+ chunks,+ num_frames=num_frames,+ tiling_config=tiling_config,+ )+ video, audio, audio_sampling_rate = result.video, result.audio, None+ video_chunks_number = get_video_chunks_number(result.num_frames, result.tiling_config)encode_video(- video=result.video,+ video=video,fps=args.frame_rate,- audio=result.audio,+ audio=audio,output_path=args.output_path,- video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),+ video_chunks_number=video_chunks_number,color_space=hdr,+ audio_sampling_rate=audio_sampling_rate,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/distilled_mgpu.py b/packages/ltx-pipelines/src/ltx_pipelines/distilled_mgpu.pyindex 24efee6..fad2d63 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/distilled_mgpu.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/distilled_mgpu.py@@ -21,12 +21,12 @@ import torch.distributed as distfrom ltx_core.allocator_trim_strategy import AllocatorTrimStrategyfrom ltx_core.loader.registry import ModelRegistryfrom ltx_core.model.transformer.compiling import CompilationConfig-from ltx_core.model.video_vae import get_video_chunks_numberfrom ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.multigpu.transformer.attention import AttentionManagerfrom ltx_core.quantization import QuantizationPolicyfrom ltx_core.quantization.fp8_cast import build_policy as _build_fp8_cast_policyfrom ltx_core.tiling import DimensionTilingConfig, TileCountConfig, balanced_tile_split+from ltx_pipelines.chunks import ChunkConfig, split_decoded_chunksfrom ltx_pipelines.distilled import DistilledPipelinefrom ltx_pipelines.multigpu.controller import MGPUControllerfrom ltx_pipelines.multigpu.gemma_builders import AccelerateGemmaBuilder@@ -34,7 +34,7 @@ from ltx_pipelines.multigpu.runner import MGPURunnerfrom ltx_pipelines.multigpu.sp_builder import SequenceParallelBuilderfrom ltx_pipelines.multigpu.vae_builders import DistributedDecoderBuilderfrom ltx_pipelines.multigpu.weight_tracker import TransformerWeightTracker-from ltx_pipelines.utils.media_io import HDRColorSpace, encode_video, resolve_hdr_color_space, vae_dtype_for_hdr+from ltx_pipelines.utils.media_io import EXRColorSpace, encode_video, resolve_hdr_color_space, vae_dtype_for_hdrfrom ltx_pipelines.utils.model_paths import ModelPathsfrom ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration@@ -153,53 +153,68 @@ class DistilledRunner(MGPURunner):images: list[Any] | None = None,enhance_prompt: bool = False,enhance_static_cache: bool = False,- hdr: HDRColorSpace | None = None,+ hdr: EXRColorSpace | None = None,generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ chunk_config: ChunkConfig | None = None,) -> Iterator[str | None]:# The pipeline raises ValueError on invalid input (symmetric across ranks); the controller# catches that and turns it into a recoverable RunnerError. Anything else is fatal.hdr = resolve_hdr_color_space(images=images or [], hdr=hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- result = self._pipeline(+ chunks, _, _ = self._pipeline.stream_chunks(prompt=prompt,seed=seed,height=height,width=width,- num_frames=num_frames,frame_rate=frame_rate,images=images or [],+ num_frames=num_frames,vae_dtype=vae_dtype,- color_space=hdr,tiling_config=None,enhance_prompt=enhance_prompt,enhance_static_cache=enhance_static_cache,+ color_space=hdr,generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,+ chunk_config=chunk_config,)if dist.get_rank() != _DRIVER_RANK:- yield None # workers: nothing to encode+ for _ in chunks:+ pass+ yield Nonereturn+ video, audio, audio_sampling_rate = split_decoded_chunks(chunks)encode_video(- video=result.video,+ video=video,fps=frame_rate,- audio=result.audio,+ audio=audio,output_path=output_path,- video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),+ video_chunks_number=1,color_space=hdr,+ audio_sampling_rate=audio_sampling_rate,)yield output_pathif __name__ == "__main__":from ltx_pipelines.utils.args import (+ add_chunk_layout_args,add_generated_keyframes_arg,+ add_keyframe_decode_arg,+ chunk_config_from_args,default_2_stage_distilled_arg_parser,resolve_cli_params,)logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")params = resolve_cli_params(distilled=True)- parser = add_generated_keyframes_arg(- default_2_stage_distilled_arg_parser(params=params, supports_auto_duration=True)+ parser = add_chunk_layout_args(+ add_keyframe_decode_arg(+ add_generated_keyframes_arg(+ default_2_stage_distilled_arg_parser(params=params, supports_auto_duration=True)+ )+ ))args = parser.parse_args()@@ -227,6 +242,8 @@ if __name__ == "__main__":enhance_static_cache=args.enhance_static_cache,hdr=args.hdr,generated_keyframes=args.num_generated_keyframes,+ decode_with_keyframes=args.decode_with_keyframes,+ chunk_config=chunk_config_from_args(args),):pass # drive the job to completion; the runner writes the file as a side effectfinally:diff --git a/packages/ltx-pipelines/src/ltx_pipelines/dubit.py b/packages/ltx-pipelines/src/ltx_pipelines/dubit.pyindex 3316fc0..b42609e 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/dubit.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/dubit.py@@ -3,13 +3,14 @@from __future__ import annotationsimport logging+from collections.abc import Iterator, Sequence+from dataclasses import dataclassimport torchfrom ltx_core.allocator_trim_strategy import AllocatorTrimStrategyfrom ltx_core.components.noisers import GaussianNoiser-from ltx_core.components.patchifiers import AudioPatchifier-from ltx_core.conditioning import AudioConditionByReferenceLatent+from ltx_core.conditioning import ConditioningItemfrom ltx_core.loader import LoraPathStrengthAndSDOpsfrom ltx_core.loader.registry import Registryfrom ltx_core.model.audio_vae import encode_audio as vae_encode_audio@@ -24,13 +25,37 @@ from ltx_core.model.video_vae import ()from ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy-from ltx_core.types import AudioLatentShape, VideoPixelShape+from ltx_core.types import VideoPixelShape+from ltx_pipelines.chunks import (+ Chunk,+ ChunkConfig,+ DecodedChunk,+ MakeAudioConditionings,+ MakeVideoConditionings,+ SequentialVideoFrameSource,+ decode_chunks,+ denoise_chunks,+ generate_uniform_chunks,+ pipeline_output_from_chunks,+ replace_audio_conditionings,+ spatially_upsample_chunks,+ split_decoded_chunks,+)+from ltx_pipelines.chunks.conditionings import (+ assert_image_frames_in_clip,+ audio_reference_conditionings_for_chunk,+ image_conditionings_for_chunk,+ reference_video_conditionings_for_chunk,+)from ltx_pipelines.iclora_utils import (- append_ic_lora_reference_video_conditionings,+ patchify_audio_reference_latent,read_lora_reference_downscale_factor,)from ltx_pipelines.utils.args import (- ImageConditioningInput,+ add_chunk_layout_args,+ add_generated_keyframes_arg,+ add_keyframe_decode_arg,+ chunk_config_from_args,dubit_arg_parser,resolve_cli_params,)@@ -44,23 +69,42 @@ from ltx_pipelines.utils.blocks import (VideoUpsampler,)from ltx_pipelines.utils.constants import DISTILLED_SIGMAS, STAGE_2_DISTILLED_SIGMAS-from ltx_pipelines.utils.denoisers import SimpleDenoiserfrom ltx_pipelines.utils.helpers import (+ assert_generated_keyframes_request,assert_resolution,- combined_image_conditionings,ensure_tiling_config,get_device,snap_frames_to_grid,tiling_scale_factors_for_vae,)-from ltx_pipelines.utils.media_io import (- HDRColorSpace,- decode_audio_from_file,- encode_video,- get_videostream_metadata,-)+from ltx_pipelines.utils.media_io import EXRColorSpace, decode_audio_from_file, encode_video, get_videostream_metadatafrom ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, PipelineOutput+from ltx_pipelines.utils.types import ImageConditioningInput, OffloadMode, PipelineOutput, VideoAudio++__all__ = ["DubItPipeline", "main", "patchify_dubit_audio_reference_latent"]++patchify_dubit_audio_reference_latent = patchify_audio_reference_latent+++@dataclass(frozen=True)+class _DubItRunContext:+ """Setup snapshot for :meth:`DubItPipeline.stream_chunks`, built by :meth:`DubItPipeline._prepare_run`."""++ generator: torch.Generator+ noiser: GaussianNoiser+ dtype: torch.dtype+ vae_dtype: torch.dtype+ images: list[ImageConditioningInput]+ video_context: torch.Tensor+ audio_context: torch.Tensor+ num_frames: int+ frame_rate: float+ tiling_config: TilingConfig+ stage_1_width: int+ stage_1_height: int+ ref_audio_latent: torch.Tensor+ reference_video_path: str+ reference_strength: floatclass DubItPipeline:@@ -144,44 +188,6 @@ class DubItPipeline:)self.reference_downscale_factor = read_lora_reference_downscale_factor(ic_lora.path)- def _create_stage_conditionings(- self,- images: list[ImageConditioningInput],- reference_video_path: str,- reference_strength: float,- height: int,- width: int,- num_frames: int,- video_encoder: VideoEncoder,- encode_tiling: TilingConfig | None,- color_space: HDRColorSpace | None = None,- ) -> list:- conditionings = combined_image_conditionings(- images=images,- height=height,- width=width,- video_encoder=video_encoder,- dtype=self.dtype,- device=self.device,- color_space=color_space,- )- append_ic_lora_reference_video_conditionings(- conditionings,- [(reference_video_path, reference_strength)],- height=height,- width=width,- num_frames=num_frames,- video_encoder=video_encoder,- dtype=self.dtype,- device=self.device,- reference_downscale_factor=self.reference_downscale_factor,- conditioning_attention_strength=1.0,- conditioning_attention_mask=None,- tiling_config=encode_tiling,- color_space=color_space,- )- return conditionings-def _encode_reference_audio_vae_latent(self, video_path: str) -> torch.Tensor:audio = decode_audio_from_file(video_path, self.device)if audio is None:@@ -189,26 +195,27 @@ class DubItPipeline:raise ValueError(msg)return self.audio_conditioner(lambda enc: vae_encode_audio(audio, enc, None))- @torch.inference_mode()- def __call__( # noqa: PLR0913+ def _prepare_run( # noqa: PLR0913self,+ *,prompt: str,seed: int,height: int,width: int,images: list[ImageConditioningInput],reference_video_path: str,- reference_strength: float = 1.0,- enhance_prompt: bool = False,- enhance_static_cache: bool = False,- vae_dtype: torch.dtype | None = None,- tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,- stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS,- stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,- color_space: HDRColorSpace | None = None,- ) -> PipelineOutput:+ reference_strength: float,+ enhance_prompt: bool,+ enhance_static_cache: bool,+ vae_dtype: torch.dtype | None,+ tiling_config: TilingConfig | AutoTiling | None,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ ) -> _DubItRunContext:+ """Validate inputs, encode prompts/reference, and resolve frame count / tiling before chunk planning."""images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=True)+ assert_generated_keyframes_request(decode_with_keyframes, generated_keyframes, self.stage)meta = get_videostream_metadata(reference_video_path)num_frames = snap_frames_to_grid(meta.frames)@@ -216,8 +223,7 @@ class DubItPipeline:generator = torch.Generator(device=self.device).manual_seed(seed)noiser = GaussianNoiser(generator=generator)- if vae_dtype is None:- vae_dtype = self.dtype+ resolved_vae_dtype = self.dtype if vae_dtype is None else vae_dtype(ctx_p,) = self.prompt_encoder([prompt],@@ -228,135 +234,236 @@ class DubItPipeline:video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encodingscale_factors = tiling_scale_factors_for_vae(self.video_decoder.checkpoint_path)- tiling_config = ensure_tiling_config(+ resolved_tiling_config = ensure_tiling_config(tiling_config,scale_factors=scale_factors,vae_checkpoint_path=self.video_decoder.checkpoint_path,video_shape=VideoPixelShape(batch=1, frames=num_frames, height=height, width=width, fps=frame_rate),diffvae_optimization=self.video_decoder.diffvae_optimization,device=self.device,+ keyframes=decode_with_keyframes,)-- stage_1_output_shape = VideoPixelShape(- batch=1,- frames=num_frames,- width=width // 2,- height=height // 2,- fps=frame_rate,+ ref_audio_latent = self._encode_reference_audio_vae_latent(reference_video_path)+ return _DubItRunContext(+ generator=generator,+ noiser=noiser,+ dtype=self.dtype,+ vae_dtype=resolved_vae_dtype,+ images=images,+ video_context=video_context,+ audio_context=audio_context,+ num_frames=num_frames,+ frame_rate=frame_rate,+ tiling_config=resolved_tiling_config,+ stage_1_width=width // 2,+ stage_1_height=height // 2,+ ref_audio_latent=ref_audio_latent,+ reference_video_path=reference_video_path,+ reference_strength=reference_strength,)- encode_tiling = TileSizeConfig.default()-- def build_image_conditionings(output_shape: VideoPixelShape) -> list:- return self.image_conditioner(- lambda enc: self._create_stage_conditionings(- images=images,- reference_video_path=reference_video_path,- reference_strength=reference_strength,- height=output_shape.height,- width=output_shape.width,- num_frames=num_frames,- video_encoder=enc,- encode_tiling=encode_tiling,- color_space=color_space,- )- )-- def build_audio_ref_conditioning(audio_latent: torch.Tensor) -> AudioConditionByReferenceLatent:- ref_patch, ref_pos = patchify_dubit_audio_reference_latent(- audio_latent,- negative_positions=True,- device=self.device,- )- return AudioConditionByReferenceLatent(ref_patch, ref_pos, strength=1.0)-- stage_1_conditionings = build_image_conditionings(stage_1_output_shape)- ref_vae = self._encode_reference_audio_vae_latent(reference_video_path)- audio_conditionings = [build_audio_ref_conditioning(ref_vae)]+ def _video_conditionings(+ self,+ images: list[ImageConditioningInput],+ num_frames: int,+ reference_video_path: str,+ reference_strength: float,+ color_space: EXRColorSpace | None,+ frame_source: SequentialVideoFrameSource,+ ) -> MakeVideoConditionings:+ assert_image_frames_in_clip(images, num_frames)++ def make(chunk: Chunk) -> list[ConditioningItem]:+ if chunk.video is None:+ return []++ def encode(enc: VideoEncoder) -> list[ConditioningItem]:+ items = [+ *image_conditionings_for_chunk(chunk, images=images, video_encoder=enc, color_space=color_space),+ *reference_video_conditionings_for_chunk(+ chunk,+ video_conditioning=[(reference_video_path, reference_strength)],+ video_encoder=enc,+ downscale_factor=self.reference_downscale_factor,+ encode_tiling=TileSizeConfig.default(),+ color_space=color_space,+ frame_sources={reference_video_path: frame_source},+ ),+ ]+ return items++ return self.image_conditioner(encode)++ return make++ def _audio_conditionings(self, *, latent: torch.Tensor | None, fps: float) -> MakeAudioConditionings:+ def make(chunk: Chunk) -> list[ConditioningItem]:+ return audio_reference_conditionings_for_chunk(chunk, latent=latent, fps=fps)++ return make- stage_1_sigmas_tensor = stage_1_sigmas.to(dtype=torch.float32, device=self.device)- video_state, audio_state = self.stage(- denoiser=SimpleDenoiser(video_context, audio_context),- sigmas=stage_1_sigmas_tensor,- noiser=noiser,- width=stage_1_output_shape.width,- height=stage_1_output_shape.height,- frames=num_frames,- fps=frame_rate,- video=ModalitySpec(- context=video_context,- conditionings=stage_1_conditionings,- ),- audio=ModalitySpec(- context=audio_context,- conditionings=audio_conditionings,- ),+ @torch.inference_mode()+ def __call__( # noqa: PLR0913+ self,+ prompt: str,+ seed: int,+ height: int,+ width: int,+ images: list[ImageConditioningInput],+ reference_video_path: str,+ reference_strength: float = 1.0,+ enhance_prompt: bool = False,+ enhance_static_cache: bool = False,+ vae_dtype: torch.dtype | None = None,+ tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,+ stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS,+ stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,+ color_space: EXRColorSpace | None = None,+ chunk_config: ChunkConfig | None = None,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ ) -> PipelineOutput:+ chunks, num_frames, tiling_config = self.stream_chunks(+ prompt=prompt,+ seed=seed,+ height=height,+ width=width,+ images=images,+ reference_video_path=reference_video_path,+ reference_strength=reference_strength,+ enhance_prompt=enhance_prompt,+ enhance_static_cache=enhance_static_cache,+ vae_dtype=vae_dtype,+ tiling_config=tiling_config,+ stage_1_sigmas=stage_1_sigmas,+ stage_2_sigmas=stage_2_sigmas,+ color_space=color_space,+ chunk_config=chunk_config,+ generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,)+ return pipeline_output_from_chunks(chunks, num_frames=num_frames, tiling_config=tiling_config)- s1_audio_latent = audio_state.latent.clone()-- upscaled_video_latent = self.upsampler(video_state.latent[:1])- stage_2_sigmas_tensor = stage_2_sigmas.to(dtype=torch.float32, device=self.device)- stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)- stage_2_conditionings = build_image_conditionings(stage_2_output_shape)+ def stream_chunks( # noqa: PLR0913+ self,+ prompt: str,+ seed: int,+ height: int,+ width: int,+ images: list[ImageConditioningInput],+ reference_video_path: str,+ reference_strength: float = 1.0,+ enhance_prompt: bool = False,+ enhance_static_cache: bool = False,+ vae_dtype: torch.dtype | None = None,+ tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,+ stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS,+ stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,+ color_space: EXRColorSpace | None = None,+ chunk_config: ChunkConfig | None = None,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ ) -> tuple[Iterator[DecodedChunk], int, TilingConfig]:+ """Generate a dubbed clip as a stream of decoded chunks.+ ``chunk_config=None`` plans a single chunk covering the snapped clip.+ Stage 2 freezes stage-1 audio and uses it as the audio-reference tokens.+ """+ ctx = self._prepare_run(+ prompt=prompt,+ seed=seed,+ height=height,+ width=width,+ images=images,+ reference_video_path=reference_video_path,+ reference_strength=reference_strength,+ enhance_prompt=enhance_prompt,+ enhance_static_cache=enhance_static_cache,+ vae_dtype=vae_dtype,+ tiling_config=tiling_config,+ generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,+ )+ if chunk_config is None:+ chunk_config = ChunkConfig(chunk_pixel_frames=ctx.num_frames, next_video_carry_frames=0)- stage_2_audio_conditionings = [build_audio_ref_conditioning(s1_audio_latent)]+ stage_1_sigmas = stage_1_sigmas.to(dtype=torch.float32, device=self.device)+ stage_2_sigmas = stage_2_sigmas.to(dtype=torch.float32, device=self.device)- video_state, _audio_unused = self.stage(- denoiser=SimpleDenoiser(video_context, audio_context),- sigmas=stage_2_sigmas_tensor,- noiser=noiser,- width=width,- height=height,- frames=num_frames,- fps=frame_rate,- video=ModalitySpec(- context=video_context,- conditionings=stage_2_conditionings,- noise_scale=stage_2_sigmas_tensor[0].item(),- initial_latent=upscaled_video_latent,- ),- audio=ModalitySpec(- context=audio_context,- conditionings=stage_2_audio_conditionings,- frozen=True,- noise_scale=0.0,- initial_latent=s1_audio_latent,- ),+ target = VideoPixelShape(+ batch=1,+ frames=ctx.num_frames,+ height=ctx.stage_1_height,+ width=ctx.stage_1_width,+ fps=ctx.frame_rate,+ )+ # Lazy stage-1 → upsample → stage-2 pulls one chunk through both resolutions before+ # the next, so lookback still holds the window for the full-res encode.+ frame_source = SequentialVideoFrameSource(ctx.reference_video_path, self.device)+ make_video = self._video_conditionings(+ ctx.images,+ ctx.num_frames,+ ctx.reference_video_path,+ ctx.reference_strength,+ color_space,+ frame_source=frame_source,+ )+ chunks = generate_uniform_chunks(+ target=target,+ context=VideoAudio(video=ctx.video_context, audio=ctx.audio_context),+ device=self.device,+ dtype=ctx.dtype,+ config=chunk_config,+ video_scale_factors=self.stage.video_scale_factors,+ make_video_conditionings=make_video,+ make_audio_conditionings=self._audio_conditionings(latent=ctx.ref_audio_latent, fps=ctx.frame_rate),+ generated_keyframes=generated_keyframes,+ )+ base = denoise_chunks(+ chunks,+ self.stage,+ sigmas=stage_1_sigmas,+ noiser=ctx.noiser,+ fps=ctx.frame_rate,+ )+ upscaled = spatially_upsample_chunks(base, self.upsampler)+ stage_2_input = replace_audio_conditionings(+ upscaled,+ self._audio_conditionings(latent=None, fps=ctx.frame_rate),+ )+ refined = denoise_chunks(+ stage_2_input,+ self.stage,+ sigmas=stage_2_sigmas,+ noiser=ctx.noiser,+ fps=ctx.frame_rate,+ freeze_audio=True,)- decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)- decoded_audio = self.audio_decoder(s1_audio_latent)- return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)---def patchify_dubit_audio_reference_latent(- vae_latents: torch.Tensor,- *,- negative_positions: bool,- device: torch.device,-) -> tuple[torch.Tensor, torch.Tensor]:- """Patchify audio VAE latents and build RoPE positions (optional negative shift for reference)."""- patchifier = AudioPatchifier(patch_size=1)- patchified = patchifier.patchify(vae_latents)- b, c, _t, mel_bins = vae_latents.shape- seq_len = patchified.shape[1]- latent_coords = patchifier.get_patch_grid_bounds(- output_shape=AudioLatentShape(batch=b, channels=c, frames=seq_len, mel_bins=mel_bins),- device=device,- )- positions = latent_coords.to(dtype=torch.float32)- if negative_positions:- aud_dur = positions[:, :, -1, 1].max().item()- positions = positions - aud_dur - 0.04- return patchified, positions+ def decoded() -> Iterator[DecodedChunk]:+ try:+ yield from decode_chunks(+ refined,+ self.video_decoder,+ self.audio_decoder,+ fps=ctx.frame_rate,+ tiling_config=ctx.tiling_config,+ generator=ctx.generator,+ dtype=ctx.vae_dtype,+ keyframes=decode_with_keyframes,+ )+ finally:+ frame_source.close()++ return (decoded(), ctx.num_frames, ctx.tiling_config)@torch.inference_mode()def main() -> None:logging.basicConfig(level=logging.INFO)params = resolve_cli_params(distilled=True)- parser = dubit_arg_parser(params=params)+ parser = add_chunk_layout_args(+ add_keyframe_decode_arg(add_generated_keyframes_arg(dubit_arg_parser(params=params)))+ )args = parser.parse_args()if not args.lora or len(args.lora) != 1:@@ -373,8 +480,8 @@ def main() -> None:diffvae_optimization=args.diffvae_optimization,)src = get_videostream_metadata(args.reference_video)- # Dub-It is SDR-only (no ``--hdr``); EXR references are rejected in arg validation.- result = pipeline(+ chunk_config = chunk_config_from_args(args)+ chunks, num_frames, tiling_config = pipeline.stream_chunks(prompt=args.prompt,seed=args.seed,height=args.height,@@ -385,13 +492,29 @@ def main() -> None:tiling_config=AUTO_TILING,enhance_prompt=args.enhance_prompt,enhance_static_cache=args.enhance_static_cache,+ chunk_config=chunk_config,+ generated_keyframes=args.num_generated_keyframes,+ decode_with_keyframes=args.decode_with_keyframes,)+ if chunk_config is not None:+ video, audio, audio_sampling_rate = split_decoded_chunks(chunks)+ video_chunks_number = 1+ else:+ result = pipeline_output_from_chunks(+ chunks,+ num_frames=num_frames,+ tiling_config=tiling_config,+ )+ video, audio, audio_sampling_rate = result.video, result.audio, None+ video_chunks_number = get_video_chunks_number(result.num_frames, result.tiling_config)encode_video(- video=result.video,- fps=int(src.fps),- audio=result.audio,+ video=video,+ fps=src.fps,+ audio=audio,output_path=args.output_path,- video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),+ video_chunks_number=video_chunks_number,+ color_space=None,+ audio_sampling_rate=audio_sampling_rate,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/hdr_ic_lora.py b/packages/ltx-pipelines/src/ltx_pipelines/hdr_ic_lora.pyindex e1fe319..764af40 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/hdr_ic_lora.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/hdr_ic_lora.py@@ -1,986 +1,561 @@-"""HDR IC-LoRA pipeline: two-stage video generation with HDR output.-Extends the standard IC-LoRA pipeline with HDR decode via LogC3 inverse-transform. ``__call__`` returns a **linear HDR float** tensor-``[f, h, w, c]``; tonemapping and EXR saving are the caller's-responsibility.-Text embeddings must be pre-computed externally (e.g. using-``PromptEncoder`` from ``ltx_pipelines.utils.blocks`` with a Gemma text-encoder) and saved as a ``.safetensors`` file with ``video_context``-and ``audio_context`` tensors (via ``safetensors.torch.save_file``).-The path is passed via ``text_embeddings_path``.-Run as a script for batch inference::- python -m ltx_pipelines.hdr_ic_lora \\- --input ./videos/ \\- --output-dir ./hdr-output \\- --distilled-checkpoint-path /models/ltx-2.3-22b-distilled.safetensors \\- --spatial-upsampler-path /models/ltx-2.3-spatial-upscaler-x2-1.0.safetensors \\- --hdr-lora /path/to/hdr_lora.safetensors \\- --text-embeddings /path/to/hdr_scene_emb.safetensors \\- --num-frames 161-Supports resolutions up to 4K (3840x2160 @ 121 frames on 80 GB,-49 frames on 48 GB). The caller is responsible for choosing a resolution-and frame count that fits in GPU memory. See ``--help`` for a reference-table, or use ``ltx_pipelines.utils.vram_budget.max_frames_for_resolution``-to query your specific configuration.-"""--import dataclasses+"""Single-GPU IC-LoRA from SDR video or EXR frames to HDR (HLG MP4 and EXR sequence)."""++from __future__ import annotations+import logging-from dataclasses import replace+from collections.abc import Sequencefrom pathlib import Pathimport torch-from einops import rearrangefrom safetensors import safe_openfrom ltx_core.allocator_trim_strategy import AllocatorTrimStrategyfrom ltx_core.components.noisers import GaussianNoiser-from ltx_core.components.patchifiers import VideoLatentPatchifierfrom ltx_core.conditioning import (ConditioningItem,+ VideoConditionByKeyframeIndex,VideoConditionByReferenceLatent,)-from ltx_core.devices import empty_device_cache-from ltx_core.hdr import HDRTransfer, to_hdr_linearfrom ltx_core.loader import LoraPathStrengthAndSDOps-from ltx_core.loader.registry import ModelRegistry, Registry+from ltx_core.loader.registry import Registryfrom ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP-from ltx_core.modality_tiling import VideoModalityTilingHelperfrom ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, VideoEncoder+from ltx_core.model.video_vae.keyframes import DecodeKeyframesfrom ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy-from ltx_core.tiling import DimensionSizeConfig, DimensionTilingConfig, TileCountConfig, TileSizeConfig-from ltx_core.tools import VideoLatentTools-from ltx_core.types import VideoLatentShape, VideoPixelShape-from ltx_pipelines.utils.blocks import (- DiffusionStage,- ImageConditioner,- VideoDecoder,- VideoUpsampler,-)-from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES+from ltx_core.types import LatentState, SpatioTemporalScaleFactors, VideoPixelShape+from ltx_pipelines.dfr_helpers.layout import resolve_canvas+from ltx_pipelines.utils.args import hdr_ic_lora_arg_parser+from ltx_pipelines.utils.blocks import DiffusionStage, ImageConditioner, VideoDecoder+from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUESfrom ltx_pipelines.utils.denoisers import SimpleDenoiserfrom ltx_pipelines.utils.helpers import (+ assert_stage_supports_generated_keyframes,+ decode_keyframes_from_slots,ensure_tiling_config,+ generated_keyframe_conditionings,get_device,- modality_from_latent_state,tiling_scale_factors_for_vae,)-from ltx_pipelines.utils.media_io import ResizeMode, align_resolution, load_video_conditioning_hdr+from ltx_pipelines.utils.media_io import (+ EXRVideoInput,+ ResizeMode,+ VideoInput,+ align_resolution,+ encode_video,+ get_videostream_metadata,+ load_exr_as_hdr_conditioning,+ load_video_as_hdr_conditioning,+)from ltx_pipelines.utils.model_paths import ModelPathsfrom ltx_pipelines.utils.quantization_factory import QuantizationKind-from ltx_pipelines.utils.types import ModalitySpec, OffloadMode+from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, VideoAudiologger = logging.getLogger(__name__)-# ----------------------------------------------------------------------------# Constants-# -----------------------------------------------------------------------------DEFAULT_NUM_FRAMES = 161-MIN_RESOLUTION = 64-ALIGNMENT_DIVISOR = 64+MIN_RESOLUTION = 32+ALIGNMENT_DIVISOR = 32-# Conditioning videos whose spatial resolution (H x W) exceeds this value are-# encoded with the tiled encoder. The default (512 x 768) is suitable for-# H100-80GB. On lower-VRAM GPUs pass tiled_vae_encode_pixel_threshold=256*256-# to the pipeline constructor.+# Spatial area (H x W) above which conditioning encode uses ``tiled_encode``.+# Empirical VRAM gate (~80 GB / H100): below this, a single full-frame encode is+# assumed safe; above it, tile. Not derived from VAE scale factors or AUTO_TILING.+# On lower-VRAM GPUs pass a smaller value (e.g. ``256 * 256``) to the constructor.TILED_VAE_ENCODE_PIXEL_THRESHOLD = 512 * 768+# Full distilled schedule (8 Euler steps, 9 sigma values including 1.0 and 0.0).+DEFAULT_DENOISE_SIGMAS = list(DISTILLED_SIGMA_VALUES)_DEFAULT_QUANTIZATION = QuantizationKind.FP8_CAST+# Same pin as ``dfr_pipeline._ANCHOR_KEYFRAME_STRENGTH``.+DEFAULT_KEYFRAME_STRENGTH = 0.95+_SNAP_CONDITIONING_FPS_ABOVE = 30.0+_HIGH_FPS_CONDITIONING_FPS = 30.0-# Default stage-2 configuration: one refinement phase with modest 2-way tiling-# in every dimension and a short 2-step distilled sigma schedule.-_S2 = STAGE_2_DISTILLED_SIGMA_VALUES-_TILED_2F2H2W_OV8_6 = TileCountConfig(- frames=DimensionTilingConfig(2, 8),- height=DimensionTilingConfig(2, 6),- width=DimensionTilingConfig(2, 6),-)--STAGE2_TILINGS = [_TILED_2F2H2W_OV8_6]-STAGE2_SIGMAS = [[_S2[0], _S2[1], 0.0]]-STAGE2_USE_IC_LORA = [True]---def _encode_tiling_config(tiling_config: TilingConfig) -> TilingConfig:- if not isinstance(tiling_config, TileSizeConfig):- return tiling_config- if not tiling_config.height.is_tiled() and not tiling_config.width.is_tiled():- return tiling_config- long = max(tiling_config.height.tile_size, tiling_config.width.tile_size)- overlap = tiling_config.height.overlap if tiling_config.height.is_tiled() else tiling_config.width.overlap- return TileSizeConfig(- frames=tiling_config.frames,- height=DimensionSizeConfig(tile_size=long, overlap=overlap),- width=DimensionSizeConfig(tile_size=long, overlap=overlap),- )+def _conditioning_fps(playback_fps: float) -> float:+ """RoPE fps for this pipeline."""+ if playback_fps > _SNAP_CONDITIONING_FPS_ABOVE:+ return _HIGH_FPS_CONDITIONING_FPS+ return playback_fps-def _clamp_dim_tiling(cfg: DimensionTilingConfig, dim_size: int, axis: str) -> DimensionTilingConfig:- """Clamp a single dim's tile count and overlap to the latent's extent.- ``split_by_count`` requires ``overlap < tile_size``; with- ``tile_size = (dim_size + overlap*(n-1)) // n`` this reduces to- ``overlap <= dim_size - n``. When the configured overlap exceeds this- bound it is clamped; if the latent is too small to hold ``n`` tiles- at all, tiling falls back to a single tile on this axis.+def _dfr_seam_pixel_positions(num_frames: int, *, high_quality_hdr: bool) -> list[int]:+ """DFR x8-border segment seams from :func:`resolve_canvas`, clipped to the real clip.+ A 1-frame source is a valid 8k+1 clip with no interior seams, so this returns ``[]``+ rather than calling :func:`resolve_canvas`, which rejects ``num_frames < 2``."""- n = cfg.num_tiles- if n <= 1:- return cfg- if dim_size < n:- logger.warning(- "%s tiling: dim_size=%d < num_tiles=%d; falling back to 1 tile on this axis.",- axis,- dim_size,- n,- )- return DimensionTilingConfig(1, 0)- max_overlap = dim_size - n- if cfg.overlap <= max_overlap:- return cfg- logger.warning(- "%s tiling: overlap=%d exceeds latent bound (%d); clamping to %d.",- axis,- cfg.overlap,- max_overlap,- max_overlap,- )- return DimensionTilingConfig(n, max_overlap)---def _clamp_tile_to_latent(tiling: TileCountConfig, latent_shape: tuple[int, int, int]) -> TileCountConfig:- """Clamp frame, height, and width tilings to the latent's extents.- ``latent_shape`` is ``(F, H, W)`` in latent units.- """- f, h, w = latent_shape- return replace(- tiling,- frames=_clamp_dim_tiling(tiling.frames, f, "Frame"),- height=_clamp_dim_tiling(tiling.height, h, "Height"),- width=_clamp_dim_tiling(tiling.width, w, "Width"),- )---# Default tiling config (spatial tile 1280 px, overlap 256 px; temporal 32-# frames, overlap 16). On GPUs with < 80 GB VRAM you may need to shrink-# the spatial tile size (e.g. 768) to avoid OOM during VAE decode.-DEFAULT_SPATIAL_TILE = 1280-DEFAULT_SPATIAL_OVERLAP = 256-DEFAULT_TEMPORAL_TILE = 32-DEFAULT_TEMPORAL_OVERLAP = 16--# ----------------------------------------------------------------------------# HDR LoRA config-# -----------------------------------------------------------------------------[email protected](frozen=True)-class HdrLoraConfig:- """Explicit HDR LoRA parameters.- Read from LoRA safetensors metadata by :func:`read_hdr_lora_config`, or- constructed manually for testing.- """-- hdr_transform: HDRTransfer = HDRTransfer.LOGC3- reference_downscale_factor: int = 1---def read_hdr_lora_config(lora_path: str) -> HdrLoraConfig | None:- """Read HDR config from LoRA safetensors metadata.- Returns ``None`` when the LoRA has no HDR metadata.+ if num_frames < 2:+ return []+ _canvas, _segment, positions = resolve_canvas(num_frames)+ positions = [int(p) for p in positions if int(p) < num_frames]+ if high_quality_hdr:+ positions = [2 * p for p in positions]+ return positions+++def _seam_roles(positions: list[int]) -> tuple[list[int], list[int]]:+ """Assign canvas seams to generated HDR slots and SDR keyframe conditions.+ Every seam takes **both** roles: it gets a generated HDR slot and, at the same+ position, a 1-frame SDR guide. ``S=24``: generated ``[24, 48, 72, …]``, SDR kf+ ``[24, 48, 72, …]``."""- try:- with safe_open(lora_path, framework="pt") as f:- metadata = f.metadata() or {}- except (OSError, ValueError) as e:- logger.warning("Failed to read metadata from LoRA file '%s': %s", lora_path, e)- return None-- raw_transform = metadata.get("hdr_transform", "")- has_hdr = bool(raw_transform or metadata.get("use_hdr_transform"))- if not has_hdr:- return None-- # Metadata may store a bare flag ("true") or a transfer name ("logc3").- transfer = HDRTransfer(raw_transform) if raw_transform and raw_transform != "true" else HDRTransfer.LOGC3- scale = int(metadata.get("reference_downscale_factor", 1))- return HdrLoraConfig(hdr_transform=transfer, reference_downscale_factor=scale)+ return list(positions), list(positions)+++def dfr_seam_roles(num_frames: int, *, high_quality_hdr: bool) -> tuple[list[int], list[int]]:+ """Generated HDR slot indices and SDR guide indices for an HDR DFR run."""+ return _seam_roles(_dfr_seam_pixel_positions(num_frames, high_quality_hdr=high_quality_hdr))+++def _keyframe_conditionings_from_pixel_frames(+ video_encoder: VideoEncoder,+ pixel_video: torch.Tensor,+ positions: list[int],+ strength: float,+ *,+ gen_h: int,+ gen_w: int,+ tiling_config: TilingConfig | None,+ tiled_threshold: int,+ dtype: torch.dtype | None = None,+) -> list[ConditioningItem]:+ """VAE-encode each seam SDR frame as a true 1-frame (L0-style) keyframe latent."""+ if pixel_video.ndim != 5:+ raise ValueError(f"Expected pixel video (B, C, T, H, W), got {tuple(pixel_video.shape)}")+ num_frames = pixel_video.shape[2]+ use_tiled = tiling_config is not None and gen_h * gen_w > tiled_threshold+ conditionings: list[ConditioningItem] = []+ for frame_idx in positions:+ idx = int(frame_idx)+ if idx < 0 or idx >= num_frames:+ raise ValueError(f"Seam frame_idx={idx} out of range for pixel video T={num_frames}")+ frame = pixel_video[:, :, idx : idx + 1]+ encoded = video_encoder.tiled_encode(frame, tiling_config) if use_tiled else video_encoder(frame)+ if dtype is not None:+ encoded = encoded.to(dtype=dtype)+ conditionings.append(+ VideoConditionByKeyframeIndex(+ keyframes=encoded,+ frame_idx=idx,+ strength=strength,+ num_pixel_frames=1,+ )+ )+ return conditionings-# ----------------------------------------------------------------------------# Pipeline-# ---------------------------------------------------------------------------+def _load_video_context(path: str | Path, device: torch.device) -> torch.Tensor:+ """Load ``video_context`` (or trainer ``video_prompt_embeds``) from ``.safetensors``."""+ emb_path = Path(path)+ if not emb_path.is_file():+ raise FileNotFoundError(f"Text embeddings not found: {emb_path}")+ with safe_open(emb_path, framework="pt", device=str(device)) as f:+ keys = list(f.keys())+ for name in ("video_context", "video_prompt_embeds"):+ if name in keys:+ return f.get_tensor(name)+ raise KeyError(f"video_context/video_prompt_embeds not found in {emb_path} (keys={keys})")class HDRICLoraPipeline:- """Two-stage IC-LoRA pipeline with HDR support.- Same two-stage architecture as ICLoraPipeline (half-res generation + 2x- upscale refinement), with HDR decode via LogC3 inverse.- ``__call__`` returns a **linear HDR float** tensor ``[f, h, w, c]``.- Tonemapping and EXR saving are the caller's responsibility.+ """Single-GPU IC-LoRA from SDR to HDR in one denoise stage.+ The model works in ACEScct; export is an HLG MP4 plus an EXR sequence.+ Pass ``keyframe_strength`` to ``__call__`` for DFR-style seam keyframes+ (generated HDR slots + 1-frame SDR guides + keyframe-aware DiffVAE decode).+ ``None`` is plain IC-LoRA."""- def __init__( # noqa: PLR0913+ def __init__(self,model_paths: ModelPaths,- spatial_upsampler_path: str,hdr_lora: str | Path,text_embeddings_path: str | Path,device: torch.device | None = None,quantization: QuantizationPolicy | QuantizationKind | None = _DEFAULT_QUANTIZATION,registry: Registry | None = None,- hdr_lora_config: HdrLoraConfig | None = None,tiled_vae_encode_pixel_threshold: int = TILED_VAE_ENCODE_PIXEL_THRESHOLD,offload_mode: OffloadMode = OffloadMode.NONE,alloc_trim_strategy: AllocatorTrimStrategy = AllocatorTrimStrategy.TRIM,diffvae_optimization: DiffVAEMode = DiffVAEMode.CHUNKED_EAGER,- ):- """- Args:- model_paths: Resolved component paths (diffusion + video VAE at minimum).- spatial_upsampler_path: Path to the spatial upsampler checkpoint.- hdr_lora: Path to the HDR IC-LoRA ``.safetensors`` file.- text_embeddings_path: Path to pre-computed text embeddings- (``.safetensors`` file with ``video_context`` and- ``audio_context`` tensors).- device: Target device. Auto-detected when ``None``.- quantization: Quantization policy. Defaults to ``fp8_cast``.- registry: Optional registry for non-diffusion blocks (VAE encode/decode,- upsampler). Diffusion stages always use a dedicated full- :class:`ModelRegistry` that is cleared before decode so- transformer weights do not pin VRAM.- hdr_lora_config: Explicit HDR LoRA config override. When ``None``,- auto-detected from LoRA safetensors metadata.- tiled_vae_encode_pixel_threshold: Conditioning videos whose spatial- area (H x W) exceeds this value are encoded with the tiled- encoder. Default ``512 * 768`` is suitable for 80 GB GPUs.- Use ``256 * 256`` on GPUs with less VRAM.- offload_mode: Weight offloading strategy for diffusion stages.- """+ ) -> None:self.device = device or get_device()self._tiled_vae_encode_threshold = tiled_vae_encode_pixel_thresholdif isinstance(quantization, QuantizationKind):quantization = quantization.to_policy(checkpoint_path=model_paths.transformer())if offload_mode != OffloadMode.NONE and quantization is not None:- logger.info("Offload mode enabled — disabling quantization (not supported with layer streaming).")+ logger.info("Offload mode enabled — disabling quantization.")quantization = None+self.dtype = torch.bfloat16+ self.vae_dtype = torch.float32lora_path = str(Path(hdr_lora).resolve())loras = (LoraPathStrengthAndSDOps(lora_path, 1.0, LTXV_LORA_COMFY_RENAMING_MAP),)- # Load pre-computed text embeddings from safetensors.- emb_path = Path(text_embeddings_path)- logger.info("Loading text embeddings from %s", emb_path)- with safe_open(emb_path, framework="pt", device=str(self.device)) as f:- self.text_embeddings: tuple[torch.Tensor, torch.Tensor] = (- f.get_tensor("video_context"),- f.get_tensor("audio_context"),- )+ logger.info("Loading text embeddings from %s", text_embeddings_path)+ self.video_context = _load_video_context(text_embeddings_path, self.device)+ vae_ckpt = model_paths.video_vae()self.image_conditioner = ImageConditioner(- model_paths.video_vae(),- self.dtype,+ vae_ckpt,+ self.vae_dtype,self.device,registry=registry,alloc_trim_strategy=alloc_trim_strategy,)- # Full cache for diffusion only: cheap per-tile stage_2 rebuilds. Cleared- # before decode so transformer SDs are not still pinning VRAM.- self._diffusion_registry = ModelRegistry()- self.stage_1 = DiffusionStage.from_checkpoint(- model_paths.transformer(),- self.dtype,- self.device,- loras=loras,- quantization=quantization,- registry=self._diffusion_registry,- offload_mode=offload_mode,- alloc_trim_strategy=alloc_trim_strategy,- )- self.stage_2 = DiffusionStage.from_checkpoint(+ self.stage = DiffusionStage.from_checkpoint(model_paths.transformer(),self.dtype,self.device,loras=loras,quantization=quantization,- registry=self._diffusion_registry,- offload_mode=offload_mode,- alloc_trim_strategy=alloc_trim_strategy,- )- self.upsampler = VideoUpsampler(- model_paths.video_vae(),- spatial_upsampler_path,- self.dtype,- self.device,registry=registry,+ offload_mode=offload_mode,alloc_trim_strategy=alloc_trim_strategy,)self.video_decoder = VideoDecoder(- model_paths.video_vae(),- self.dtype,+ vae_ckpt,+ self.vae_dtype,self.device,registry=registry,alloc_trim_strategy=alloc_trim_strategy,diffvae_optimization=diffvae_optimization,)- # HDR config: explicit override, or auto-detect from LoRA metadata.- if hdr_lora_config is not None:- self._hdr_config: HdrLoraConfig | None = hdr_lora_config- else:- self._hdr_config = read_hdr_lora_config(lora_path)-- if self._hdr_config is not None:- logger.info(- "[HDR IC-LoRA] HDR mode enabled (%s decode)",- self._hdr_config.hdr_transform.value,- )-- @property- def hdr_transform(self) -> HDRTransfer:- """Active HDR working-space transfer (defaults to LogC3)."""- return self._hdr_config.hdr_transform if self._hdr_config is not None else HDRTransfer.LOGC3+ logger.info("[HDR IC-LoRA] ACEScct ready (vae_dtype=%s)", self.vae_dtype)- @property- def reference_downscale_factor(self) -> int:- """Reference video downscale factor from HDR LoRA config."""- return self._hdr_config.reference_downscale_factor if self._hdr_config is not None else 1-- def __call__( # noqa: PLR0913+ def __call__(self,+ video: VideoInput | EXRVideoInput,seed: int,- height: int,- width: int,- num_frames: int,- frame_rate: float,- video_conditioning: list[tuple[str, float]],+ *,tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,+ denoise_sigmas: list[float] | None = None,+ conditioning_strength: float = 1.0,high_quality_hdr: bool = False,- stage2_tilings: list[TileCountConfig] | None = None,- stage2_sigmas: list[list[float]] | None = None,- stage2_use_ic_lora: list[bool] | None = None,- ) -> torch.Tensor:- """Generate video with IC-LoRA conditioning and HDR output.- Returns a linear HDR float tensor ``[f, h, w, c]``.+ keyframe_strength: float | None = None,+ ) -> tuple[torch.Tensor, float]:+ """Generate ACEScct HDR from an MP4/MOV or EXR-frame folder.Args:- seed: Random seed for reproducibility.- height: Desired output video height in pixels. Aligned internally- to the nearest multiple of 64 (rounded up). Decoded output is- cropped back to this size.- width: Desired output video width in pixels. Same alignment rules- as *height*.- num_frames: Number of frames to generate.- frame_rate: Output video frame rate.- video_conditioning: List of (path, strength) tuples for IC-LoRA video conditioning.- high_quality_hdr: High-quality HDR mode. Duplicates each conditioning- frame and generates at 2x frame count, then keeps every other- output frame. Reduces temporal artifacts at the cost of ~2x- generation time.+ video: :class:`VideoInput` (MP4/MOV) or :class:`EXRVideoInput` (EXR folder).+ seed: RNG seed.+ tiling_config: ``AUTO_TILING`` (default), a concrete config, or ``None`` (untiled).+ denoise_sigmas: Override default ``DEFAULT_DENOISE_SIGMAS``.+ conditioning_strength: IC-LoRA reference strength (default 1.0).+ high_quality_hdr: Duplicate each conditioning frame and generate at+ ``2N-1`` frames, then keep every other output frame. Reduces+ temporal artifacts at ~2x generation cost.+ keyframe_strength: ``None`` for plain IC-LoRA. A float puts a generated slot+ and a 1-frame SDR guide on every ``resolve_canvas`` seam at that strength.Returns:- Linear HDR float tensor ``[f, h, w, c]``.+ ``(acescct_hdr, fps)`` where ``acescct_hdr`` is float ``[F, H, W, C]`` in+ ``[0, 1]`` (FHWC for export) and ``fps`` is the source frame rate."""- # In high-quality HDR mode, generate 2*N - 1 frames internally- # (satisfies (n-1)%8==0 when N itself does), then keep every other frame.- if high_quality_hdr:- gen_num_frames = 2 * num_frames - 1- logger.info("[HDR IC-LoRA] High-quality HDR: %d -> %d internal frames", num_frames, gen_num_frames)- else:- gen_num_frames = num_frames+ match video:+ case EXRVideoInput(dir=video_path, frame_rate=fps):+ video_path = Path(video_path)+ case VideoInput(path=video_path):+ video_path = Path(video_path)+ fps = None+ meta = get_videostream_metadata(str(video_path), fps=fps)++ # Assert 8k+1 frame count.+ video_scale = SpatioTemporalScaleFactors.default()+ if (meta.frames - 1) % video_scale.time != 0:+ snapped = ((meta.frames - 1) // video_scale.time) * video_scale.time + 1+ raise ValueError(+ f"Video frame count must satisfy 8k+1 (e.g. 97, 193). "+ f"Got {meta.frames}; use a video with {snapped} frames."+ )++ # Pad W/H up to a multiple of 32, croped back after decode.gen_w, gen_h, crop_w, crop_h = align_resolution(- width, height, ResizeMode.REFLECT_PAD, divisor=ALIGNMENT_DIVISOR+ meta.width, meta.height, ResizeMode.REFLECT_PAD, divisor=ALIGNMENT_DIVISOR)if gen_h < MIN_RESOLUTION or gen_w < MIN_RESOLUTION:raise ValueError(- f"Resolution ({width}x{height}) is too small after alignment "- f"(got {gen_w}x{gen_h}, need at least {MIN_RESOLUTION}x{MIN_RESOLUTION})."- )- needs_crop = crop_w != gen_w or crop_h != gen_h- if needs_crop:- logger.info(- "[HDR IC-LoRA] Aligned %dx%d -> %dx%d, will crop to %dx%d",- width,- height,- gen_w,- gen_h,- crop_w,- crop_h,+ f"Resolution ({meta.width}x{meta.height}) too small after alignment "+ f"(got {gen_w}x{gen_h}, need >= {MIN_RESOLUTION}).")+ # Generate 2N-1 frames for high-quality HDR, N frames otherwise.+ num_frames = meta.frames+ gen_frames = 2 * num_frames - 1 if high_quality_hdr else num_frames++ generated_kf: list[int] = []+ guides_kf: list[int] = []+ if keyframe_strength is not None:+ generated_kf, guides_kf = dfr_seam_roles(num_frames, high_quality_hdr=high_quality_hdr)+ assert_stage_supports_generated_keyframes(self.stage)+ if not generated_kf and not guides_kf:+ logger.warning(+ "[HDR IC-LoRA] keyframe_strength=%.2f but this %d-frame clip has no DFR seams "+ "after clipping the canvas; running plain IC-LoRA.",+ keyframe_strength,+ num_frames,+ )+ else:+ logger.info(+ "[HDR IC-LoRA] DFR seams @ strength=%.2f → generated %s | SDR kf %s",+ keyframe_strength,+ generated_kf,+ guides_kf,+ )+scale_factors = tiling_scale_factors_for_vae(self.video_decoder.checkpoint_path)tiling_config = ensure_tiling_config(tiling_config,scale_factors=scale_factors,vae_checkpoint_path=self.video_decoder.checkpoint_path,- video_shape=VideoPixelShape(batch=1, frames=gen_num_frames, height=gen_h, width=gen_w, fps=frame_rate),+ video_shape=VideoPixelShape(+ batch=1,+ frames=gen_frames,+ height=gen_h,+ width=gen_w,+ fps=meta.fps,+ ),diffvae_optimization=self.video_decoder.diffvae_optimization,device=self.device,+ keyframes=bool(generated_kf),)+ acescct_sdr = self._load_acescct_conditioning(video, gen_h, gen_w, num_frames)+ if high_quality_hdr:+ # BCTHW: duplicate each frame, trim to gen_frames (2N-1).+ logger.info("[HDR IC-LoRA] High-quality HDR: %d -> %d internal frames", num_frames, gen_frames)+ acescct_sdr = acescct_sdr.repeat_interleave(2, dim=2)[:, :, :gen_frames]++ logger.info(+ "%s (%dx%d → gen %dx%d, %df%s, colorspace=%s)",+ video_path,+ meta.width,+ meta.height,+ gen_w,+ gen_h,+ num_frames,+ f", hq_internal={gen_frames}" if high_quality_hdr else "",+ video.color_space.value+ if isinstance(video, EXRVideoInput)+ else ("srgb_gamma" if video.gamma_encoded else "srgb"),+ )generator = torch.Generator(device=self.device).manual_seed(seed)- noiser = GaussianNoiser(generator=generator)-- video_context, _ = self.text_embeddings-- # Stage 1: Initial low resolution video generation.- s1_w, s1_h = gen_w // 2, gen_h // 2-- stage_1_conditionings = self.image_conditioner(- lambda enc: self._create_conditionings(- video_conditioning=video_conditioning,- height=s1_h,- width=s1_w,- video_encoder=enc,- num_frames=gen_num_frames,+ sigmas = list(denoise_sigmas) if denoise_sigmas is not None else list(DEFAULT_DENOISE_SIGMAS)+ sigma_t = torch.tensor(sigmas, dtype=torch.float32, device=self.device)++ conditionings = self.image_conditioner(+ lambda enc: self._create_reference_conditionings(+ enc,+ video_conditioning=acescct_sdr,+ conditioning_strength=conditioning_strength,+ gen_h=gen_h,+ gen_w=gen_w,tiling_config=tiling_config,- high_quality_hdr=high_quality_hdr,+ guides_kf=guides_kf,+ keyframe_strength=keyframe_strength,))+ video_state = self._run_diffusion_stage(+ conditionings=conditionings,+ sigmas=sigma_t,+ video_context=self.video_context,+ frames=gen_frames,+ frame_rate=meta.fps,+ seed=seed,+ generated_kf=generated_kf,+ )- stage_1_sigmas = torch.Tensor(DISTILLED_SIGMA_VALUES).to(self.device)-- try:- # HDR is video-only: skip the audio stream to avoid denoising 5B audio params.- video_state, _ = self.stage_1(- denoiser=SimpleDenoiser(video_context, None),- sigmas=stage_1_sigmas,- noiser=noiser,- width=s1_w,- height=s1_h,- frames=gen_num_frames,- fps=frame_rate,- video=ModalitySpec(- context=video_context,- conditionings=stage_1_conditionings,- ),- )-- if stage2_tilings is None:- stage2_tilings = list(STAGE2_TILINGS)- if stage2_sigmas is None:- stage2_sigmas = [list(s) for s in STAGE2_SIGMAS]- if stage2_use_ic_lora is None:- stage2_use_ic_lora = list(STAGE2_USE_IC_LORA)- if not (len(stage2_tilings) == len(stage2_sigmas) == len(stage2_use_ic_lora)):- raise ValueError("stage2_tilings, stage2_sigmas, and stage2_use_ic_lora must have equal length")-- # Stage 2: Upsample and refine at full resolution.- upscaled_video_latent = self.upsampler(video_state.latent[:1])-- stage_2_conditionings = self.image_conditioner(- lambda enc: self._create_conditionings(- video_conditioning=video_conditioning,- height=gen_h,- width=gen_w,- video_encoder=enc,- num_frames=gen_num_frames,- tiling_config=tiling_config,- high_quality_hdr=high_quality_hdr,- )- )- # Per-tile stage_2(...) rebuilds are cheap with shell caching.- phase_latent = upscaled_video_latent- for phase_idx, (tiling, sigmas_list, use_ic) in enumerate(- zip(stage2_tilings, stage2_sigmas, stage2_use_ic_lora, strict=True)- ):- diffusion_tiling = _clamp_tile_to_latent(tiling, tuple(phase_latent.shape[2:5]))- conditionings = stage_2_conditionings if use_ic else []- sigma_t = torch.tensor(sigmas_list, dtype=torch.float32, device=self.device)- logger.info(- "[Stage 2 / phase %d] sigmas=%s ic_lora=%s tiling_h=%s tiling_w=%s",- phase_idx,- sigmas_list,- use_ic,- diffusion_tiling.height,- diffusion_tiling.width,- )- phase_latent = self._run_stage2_phase(- latent=phase_latent,- conditionings=conditionings,- tiling=diffusion_tiling,- sigmas=sigma_t,- v_ctx=video_context,- frame_rate=frame_rate,- seed=seed,- )- final_video_latent = phase_latent- finally:- # Drop cached transformer shells/weights so decode (or failure cleanup) can claim VRAM.- self._diffusion_registry.clear()-- crop_size = (crop_w, crop_h) if needs_crop else None- return self._decode_video(- final_video_latent,+ acescct_hdr = self._decode_video(+ video_state,tiling_config,generator,- crop_size,+ crop_w=crop_w,+ crop_h=crop_h,+ generated_kf=generated_kf,+ gen_frames=gen_frames,high_quality_hdr=high_quality_hdr,)+ return acescct_hdr, meta.fps- def _run_stage2_phase(+ def _load_acescct_conditioning(+ self,+ video: VideoInput | EXRVideoInput,+ height: int,+ width: int,+ num_frames: int,+ ) -> torch.Tensor:+ """Load the IC-LoRA reference as ACEScct BCTHW on CPU."""+ match video:+ case EXRVideoInput(dir=path, color_space=color_space):+ frames = load_exr_as_hdr_conditioning(+ path,+ height,+ width,+ torch.float32,+ torch.device("cpu"),+ frame_cap=num_frames,+ color_space=color_space,+ resize_mode=ResizeMode.REFLECT_PAD,+ )+ case VideoInput(path=path, gamma_encoded=gamma_encoded):+ frames = load_video_as_hdr_conditioning(+ path,+ height,+ width,+ num_frames,+ torch.float32,+ torch.device("cpu"),+ gamma_encoded=gamma_encoded,+ resize_mode=ResizeMode.REFLECT_PAD,+ )+ chunks = list(frames)+ if not chunks:+ raise ValueError(f"No frames loaded from {path}")+ return torch.cat(chunks, dim=2)++ def _create_reference_conditionings(+ self,+ video_encoder: VideoEncoder,+ video_conditioning: torch.Tensor,+ conditioning_strength: float,+ gen_h: int,+ gen_w: int,+ tiling_config: TilingConfig | None,+ *,+ guides_kf: Sequence[int] = (),+ keyframe_strength: float | None = None,+ ) -> list[ConditioningItem]:+ """VAE-encode the IC-LoRA reference, plus optional 1-frame SDR seam guides."""+ video = video_conditioning.to(device=self.device, dtype=self.vae_dtype)+ if tiling_config is not None and gen_h * gen_w > self._tiled_vae_encode_threshold:+ encoded = video_encoder.tiled_encode(video, tiling_config)+ else:+ encoded = video_encoder(video)+ encoded = encoded.to(device=self.device, dtype=self.dtype)+ conditionings: list[ConditioningItem] = [+ VideoConditionByReferenceLatent(+ latent=encoded,+ downscale_factor=1,+ strength=conditioning_strength,+ )+ ]+ if not guides_kf:+ return conditionings+ if keyframe_strength is None:+ raise ValueError("SDR seam guides require keyframe_strength")+ guide_items = _keyframe_conditionings_from_pixel_frames(+ video_encoder,+ video,+ list(guides_kf),+ keyframe_strength,+ gen_h=gen_h,+ gen_w=gen_w,+ tiling_config=tiling_config,+ tiled_threshold=self._tiled_vae_encode_threshold,+ dtype=self.dtype,+ )+ return [*conditionings, *guide_items]++ def _run_diffusion_stage(self,- latent: torch.Tensor,conditionings: list[ConditioningItem],- tiling: TileCountConfig,sigmas: torch.Tensor,- v_ctx: torch.Tensor,+ video_context: torch.Tensor,+ frames: int,frame_rate: float,seed: int,- ) -> torch.Tensor:- """Run one stage-2 denoising phase with optional IC-LoRA conditioning.- Each tile calls ``stage_2(...)`` (build→denoise→dispose) with a tile-sized- ``ModalitySpec`` for video only (audio is omitted entirely for HDR).- IC-LoRA conditionings are sliced spatially to match each tile's extent.- """- batch, n_channels, n_frames, n_height, n_width = latent.shape- full_shape = VideoLatentShape(batch=batch, channels=n_channels, frames=n_frames, height=n_height, width=n_width)- full_tools = VideoLatentTools(- VideoLatentPatchifier(patch_size=1),- full_shape,- frame_rate,- scale_factors=self.stage_2.video_scale_factors,- )- helper = VideoModalityTilingHelper(tiling, full_tools)-- ref_initial = full_tools.create_initial_state(device=self.device, dtype=self.dtype)- ref_modality = modality_from_latent_state(ref_initial, v_ctx, sigmas[0])- n_gen = full_tools.target_shape.token_count()- blend_output = torch.zeros(batch, n_gen, n_channels, device=self.device, dtype=self.dtype)- patchifier = VideoLatentPatchifier(patch_size=1)- df = self.reference_downscale_factor-- for tile_idx, tile in enumerate(helper.tiles):- _, ctx = helper.tile_modality(ref_modality, tile, normalize_positions=True)- frame_s, height_s, width_s = tile.in_coords- tile_h = height_s.stop - height_s.start- tile_w = width_s.stop - width_s.start- tile_f = frame_s.stop - frame_s.start-- tile_conditionings = [- VideoConditionByReferenceLatent(- latent=cond.latent[- :,- :,- frame_s,- slice(height_s.start // df, height_s.stop // df),- slice(width_s.start // df, width_s.stop // df),- ].to(device=self.device, dtype=self.dtype),- downscale_factor=cond.downscale_factor,- strength=cond.strength,- )- for cond in conditionings- ]-- sf = self.stage_2.video_scale_factors- tile_video_state, _ = self.stage_2(- denoiser=SimpleDenoiser(v_ctx, None),- sigmas=sigmas,- noiser=GaussianNoiser(generator=torch.Generator(device=self.device).manual_seed(seed + tile_idx)),- width=tile_w * sf.width,- height=tile_h * sf.height,- frames=(tile_f - 1) * sf.time + 1,- fps=frame_rate,+ generated_kf: Sequence[int] = (),+ ) -> LatentState:+ video_context = video_context.to(device=self.device, dtype=self.dtype)+ source_conditioning = next((c for c in conditionings if isinstance(c, VideoConditionByReferenceLatent)), None)+ if source_conditioning is None:+ raise RuntimeError("Diffusion stage requires a VideoConditionByReferenceLatent IC-LoRA source conditioning")+ phase_conditionings = list(conditionings)+ phase_conditionings.extend(generated_keyframe_conditionings(generated_kf, frames))+ video_state, _ = self.stage(+ denoiser=SimpleDenoiser(video_context, None),+ sigmas=sigmas,+ noiser=GaussianNoiser(generator=torch.Generator(device=self.device).manual_seed(seed)),+ modalities=VideoAudio(video=ModalitySpec(- context=v_ctx,- conditionings=tile_conditionings,- noise_scale=sigmas[0].item(),- initial_latent=latent[:, :, frame_s, height_s, width_s].to(device=self.device, dtype=self.dtype),+ latent=source_conditioning.latent,+ conditioning_fps=_conditioning_fps(frame_rate),+ context=video_context,+ conditionings=phase_conditionings,+ noise_scale=float(sigmas[0].item()),),- )-- tile_tokens = patchifier.patchify(tile_video_state.latent)- blend_output = helper.blend(tile_tokens, tile, ctx, blend_output)-- return full_tools.unpatchify(replace(ref_initial, latent=blend_output)).latent+ ),+ )+ return video_statedef _decode_video(self,- latent: torch.Tensor,+ video_state: LatentState,tiling_config: TilingConfig | None,generator: torch.Generator,- crop_size: tuple[int, int] | None = None,*,+ crop_w: int,+ crop_h: int,+ generated_kf: Sequence[int],+ gen_frames: int,high_quality_hdr: bool = False,) -> torch.Tensor:- """Decode latent to HDR video, optionally cropping to target size.- Args:- crop_size: ``(width, height)`` to crop decoded frames to, or- ``None`` to skip cropping.- high_quality_hdr: When True, keep only every other frame (undoes the- 2x generation applied during high-quality HDR mode).- Returns:- Linear HDR float tensor ``[f, h, w, c]``.+ """VAE-decode latent chunks to FHWC ``[0, 1]`` (decoder already clamps); optional pad crop.+ When ``high_quality_hdr`` is set, keep every other frame (undoes the ``2N-1``+ generation applied during high-quality mode)."""- # Always-HDR path: float32 weights + latent so compute/output/tiling stay fp32.- # to_hdr_linear expects float32 [0, 1] working-space codes.- latent = latent.to(dtype=torch.float32)- decoded = torch.cat(- list(self.video_decoder(latent, tiling_config, generator, dtype=torch.float32)),- dim=0,+ decode_kf = decode_keyframes_from_slots(video_state.generated_keyframes, generated_kf, gen_frames)+ if decode_kf is not None:+ decode_kf = DecodeKeyframes(+ latents=decode_kf.latents.to(device=video_state.latent.device, dtype=self.vae_dtype),+ pixel_frame_indices=decode_kf.pixel_frame_indices,+ clip_start_frame=decode_kf.clip_start_frame,+ )+ chunks = self.video_decoder(+ video_state.latent,+ tiling_config,+ generator,+ dtype=self.vae_dtype,+ keyframes=decode_kf,)- decoded = rearrange(decoded, "f h w c -> 1 c f h w")- hdr = to_hdr_linear(decoded, transfer=self.hdr_transform)- del decoded- out = rearrange(hdr[0], "c f h w -> f h w c")- if crop_size is not None:- out = out[:, : crop_size[1], : crop_size[0], :]+ decoded = torch.cat(list(chunks), dim=0)+ decoded = decoded[:, :crop_h, :crop_w, :]if high_quality_hdr:- out = out[::2]- return out-- def _create_conditionings(- self,- video_conditioning: list[tuple[str, float]],- height: int,- width: int,- num_frames: int,- video_encoder: VideoEncoder,- tiling_config: TilingConfig | None = None,- high_quality_hdr: bool = False,- ) -> list[ConditioningItem]:- """Create conditioning items for video generation."""- conditionings: list[ConditioningItem] = []+ decoded = decoded[::2]+ return decoded- scale = self.reference_downscale_factor- if scale != 1 and (height % scale != 0 or width % scale != 0):- raise ValueError(- f"Output dimensions ({height}x{width}) must be divisible by reference_downscale_factor ({scale})"- )- ref_height = height // scale- ref_width = width // scale-- # In high-quality HDR mode, load half the frames then duplicate each one.- load_frame_cap = (num_frames + 1) // 2 if high_quality_hdr else num_frames-- for video_path, strength in video_conditioning:- video = torch.cat(- list(- load_video_conditioning_hdr(- video_path=video_path,- height=ref_height,- width=ref_width,- frame_cap=load_frame_cap,- dtype=self.dtype,- device=self.device,- transfer=self.hdr_transform,- resize_mode=ResizeMode.REFLECT_PAD,- )- ),- dim=2,- )- if high_quality_hdr:- video = video.repeat_interleave(2, dim=2)[:, :, :num_frames, :, :]- if tiling_config is not None and ref_height * ref_width > self._tiled_vae_encode_threshold:- encoded_video = video_encoder.tiled_encode(video, _encode_tiling_config(tiling_config))- else:- encoded_video = video_encoder(video)-- cond = VideoConditionByReferenceLatent(- latent=encoded_video,- downscale_factor=scale,- strength=strength,- )- conditionings.append(cond)-- if video_conditioning:- logger.info("[HDR IC-LoRA] Added %d video conditioning(s)", len(video_conditioning))-- return conditionings---# ----------------------------------------------------------------------------# CLI helpers-# ------------------------------------------------------------------------------def _make_tiling_config(- spatial_tile: int = DEFAULT_SPATIAL_TILE,- spatial_overlap: int = DEFAULT_SPATIAL_OVERLAP,- temporal_tile: int = DEFAULT_TEMPORAL_TILE,- temporal_overlap: int = DEFAULT_TEMPORAL_OVERLAP,-) -> TilingConfig:- """Build a TilingConfig from explicit sizes.- The defaults (1280 px spatial tile, 256 px overlap; 32 temporal frames,- 16 overlap) are suitable for H100-80 GB. On GPUs with less VRAM,- reduce the spatial tile size (e.g. ``spatial_tile=768``).- """- from ltx_core.tiling import DimensionSizeConfig, TileSizeConfig # noqa: PLC0415-- return TileSizeConfig(- height=DimensionSizeConfig(tile_size=spatial_tile, overlap=spatial_overlap),- width=DimensionSizeConfig(tile_size=spatial_tile, overlap=spatial_overlap),- frames=DimensionSizeConfig(tile_size=temporal_tile, overlap=temporal_overlap),- )--_VIDEO_SUFFIXES = {".mp4", ".mov"}---def _collect_videos(input_path: Path) -> list[Path]:- """Return a list of .mp4/.mov files from *input_path* (file or directory)."""- if input_path.is_file():- return [input_path]- if input_path.is_dir():- return sorted(p for p in input_path.iterdir() if p.is_file() and p.suffix.lower() in _VIDEO_SUFFIXES)- logger.error("Input %s is not a file or directory", input_path)- return []---def _process_single_video( # noqa: PLR0913- pipeline: HDRICLoraPipeline,- video_path: Path,- vid_w: int,- vid_h: int,- num_frames: int,- frame_rate: float,- output_dir: Path,- tiling_config: TilingConfig,- seed: int,- skip_mp4: bool,- exr_executor: "ThreadPoolExecutor", # noqa: F821- exr_futures: list,- high_quality_hdr: bool = False,-) -> None:- """Run inference on a single video: generate EXR frames + optional H.264 .mp4 preview."""- import gc # noqa: PLC0415- import time # noqa: PLC0415-- from ltx_pipelines.utils.media_io import encode_exr_sequence_to_mp4, save_exr_tensor # noqa: PLC0415-- output_mp4 = output_dir / f"{video_path.stem}.mp4"- exr_dir = output_dir / f"{video_path.stem}_exr"-- t0 = time.time()- hdr_video = pipeline(- seed=seed,- height=vid_h,- width=vid_w,- num_frames=num_frames,- frame_rate=frame_rate,- video_conditioning=[(str(video_path), 1.0)],- tiling_config=tiling_config,- high_quality_hdr=high_quality_hdr,- )-- exr_dir.mkdir(parents=True, exist_ok=True)- for j in range(hdr_video.shape[0]):- frame_cpu = hdr_video[j].cpu().clone()- path = exr_dir / f"frame_{j:05d}.exr"- exr_futures.append(exr_executor.submit(save_exr_tensor, frame_cpu, str(path), True))-- del hdr_video- gc.collect()- empty_device_cache()-- if not skip_mp4:- # Wait for EXR saves to finish before encoding.- for fut in exr_futures:- fut.result()- logger.info("Encoding H.264 sRGB preview: %s", video_path.name)- encode_exr_sequence_to_mp4(exr_dir, output_mp4, frame_rate)-- elapsed = time.time() - t0- logger.info("Decode + encode: %.1fs | %s", elapsed, output_mp4)---# ----------------------------------------------------------------------------# CLI entry point-# ------------------------------------------------------------------------------def _build_arg_parser() -> "argparse.ArgumentParser": # noqa: F821- """Build the argument parser for HDR IC-LoRA batch inference."""- import argparse # noqa: PLC0415-- parser = argparse.ArgumentParser(- description="HDR IC-LoRA inference: EXR frames + tonemapped ProRes .mov.",- # Prevent ``--hdr`` from abbreviating to ``--hdr-lora`` (native HDR flag is not supported here).- allow_abbrev=False,- epilog="""\-Resolution & frame constraints-------------------------------- * Width and height must each be divisible by 32.- * Frame count must satisfy (frames - 1) %% 8 == 0.- Valid counts: 1, 9, 17, 25, ..., 121, 129, 137, 145, 153, 161.--Max frames by resolution (fp8_cast, bfloat16 VAE, tiled decode)----------------------------------------------------------------- Resolution 80 GB (H100) 48 GB (A6000)- ------------------------------------------------- 720p 1280x720 161+ frames 161+ frames- 1080p 1920x1080 161+ frames 161+ frames- 2K 2048x1080 161+ frames 161+ frames- 1440p 2560x1440 161+ frames 137 frames- 4K 3840x2160 121 frames 49 frames- 4K 4096x2160 105 frames 49 frames-- Estimates from ltx_pipelines.utils.vram_budget. Run- python -c "from ltx_pipelines.utils.vram_budget import \\- max_frames_for_resolution as mf; print(mf(W, H, vram_gb=GB))"- to check your specific resolution and GPU.-- * The tiled-encode threshold (%(tiled_threshold)s px) and the default- tiling config (%(stile)s px spatial tile) are tuned for 80 GB.- On lower-VRAM GPUs pass --spatial-tile 768 (or smaller).-"""- % {"tiled_threshold": TILED_VAE_ENCODE_PIXEL_THRESHOLD, "stile": DEFAULT_SPATIAL_TILE},- formatter_class=argparse.RawDescriptionHelpFormatter,- )- parser.add_argument("--input", required=True, help="Single .mp4 or directory of .mp4 videos.")- parser.add_argument("--output-dir", required=True, help="Directory for .mov and EXR folders.")- parser.add_argument("--hdr-lora", required=True, help="HDR IC-LoRA .safetensors file.")- parser.add_argument("--text-embeddings", required=True, help="Pre-computed text embeddings (.safetensors file).")- parser.add_argument("--distilled-checkpoint-path", required=True, help="Distilled model checkpoint (.safetensors).")- parser.add_argument("--spatial-upsampler-path", required=True, help="Spatial upsampler (.safetensors).")- parser.add_argument(- "--num-frames",- type=int,- default=DEFAULT_NUM_FRAMES,- help=f"Number of output frames. Must satisfy (n-1) %% 8 == 0 (default: {DEFAULT_NUM_FRAMES}).",- )- parser.add_argument(- "--spatial-tile",- type=int,- default=DEFAULT_SPATIAL_TILE,- help=f"Spatial tile size in pixels for tiled VAE decode (default: {DEFAULT_SPATIAL_TILE}). "- "Reduce on lower-VRAM GPUs (e.g. 768 for 48 GB).",- )- parser.add_argument("--skip-mp4", action="store_true", help="Skip H.264 MP4 encoding, only produce EXR.")- parser.add_argument("--seed", type=int, default=10, help="Random seed (default: 10).")- parser.add_argument(- "--offload",- dest="offload_mode",- type=OffloadMode,- default=OffloadMode.NONE,- choices=list(OffloadMode),- help=(- "Weight offloading strategy. "- "'none' keeps all weights on GPU (default). "- "'cpu' pins weights in CPU RAM, streams to GPU per layer. "- "'disk' reads weights from disk on demand (lowest memory). "- "Example: --offload cpu"- ),- )- parser.add_argument(- "--high-quality",- action="store_true",- help="High-quality HDR mode. Generates at 2x frame count internally "- "and keeps every other frame for smoother output. ~2x slower.",- )- parser.add_argument(- "--video-vae-path",- default=None,- help=(- "Optional path to a separate video VAE checkpoint (.safetensors). "- "When set, encoding/decoding use this file instead of "- "--distilled-checkpoint-path. Decoder kind is selected from file metadata. "- "Diffusion VAEs require the natten extra "- "(uv sync --package ltx-core --extra natten)."- ),- )- parser.add_argument(- "--diffvae-optimization",- type=DiffVAEMode,- default=DiffVAEMode.CHUNKED_EAGER,- choices=list(DiffVAEMode),- help=(- "DiffVAE decode optimization preset. "- "'chunked_eager' (default): deferred stage-4, W-chunks=4, cutlass-fna. "- "'chunked_compile': same chunking with torch.compile (det stages off). "- "'combined_compile': combined context, full compile (highest VRAM, fastest warm). "- "Ignored for convolutional VAEs."- ),- )- return parser@torch.inference_mode()def main() -> None:- """Batch HDR IC-LoRA inference: per-frame EXR + tonemapped ProRes .mov."""- import time # noqa: PLC0415- from concurrent.futures import ThreadPoolExecutor # noqa: PLC0415-- from ltx_pipelines.utils.media_io import get_videostream_metadata # noqa: PLC0415-logging.basicConfig(level=logging.INFO)+ args = hdr_ic_lora_arg_parser().parse_args()- args = _build_arg_parser().parse_args()- high_quality = args.high_quality- num_frames = args.num_frames-- tiling_config = _make_tiling_config(spatial_tile=args.spatial_tile)-- input_path = Path(args.input)- output_dir = Path(args.output_dir)- output_dir.mkdir(parents=True, exist_ok=True)-- videos = _collect_videos(input_path)- if not videos:- logger.error("No valid videos to process.")- return- logger.info("Found %d video(s), generating %d frames each", len(videos), num_frames)-- logger.info("Loading pipeline...")- # HDR uses precomputed embeddings — no text encoder. CLI boundary builds ModelPaths; the- # pipeline only consumes that object (and non-path args like LoRA / embeddings file).- model_paths = ModelPaths.from_monolith(- args.distilled_checkpoint_path,- gemma_root=None,- video_vae_path=args.video_vae_path,- )+ logger.info("Loading HDRICLoraPipeline...")pipeline = HDRICLoraPipeline(- model_paths=model_paths,- spatial_upsampler_path=args.spatial_upsampler_path,+ model_paths=args.model_paths,hdr_lora=args.hdr_lora,text_embeddings_path=args.text_embeddings,offload_mode=args.offload_mode,+ quantization=None if args.no_quantization else _DEFAULT_QUANTIZATION,diffvae_optimization=args.diffvae_optimization,)- logger.info("Pipeline loaded.")-- exr_executor = ThreadPoolExecutor(max_workers=4)- exr_futures: list = []-- total_t0 = time.time()- successes = 0-- for i, video_path in enumerate(videos, 1):- meta = get_videostream_metadata(str(video_path))- vid_w, vid_h = meta.width, meta.height- logger.info("%s", "=" * 60)- logger.info("[%d/%d] %s (%dx%d, %df)", i, len(videos), video_path.name, vid_w, vid_h, num_frames)-- _process_single_video(- pipeline=pipeline,- video_path=video_path,- vid_w=vid_w,- vid_h=vid_h,- num_frames=num_frames,- frame_rate=meta.fps,- output_dir=output_dir,- tiling_config=tiling_config,- seed=args.seed,- skip_mp4=args.skip_mp4,- exr_executor=exr_executor,- exr_futures=exr_futures,- high_quality_hdr=high_quality,- )- successes += 1-- infer_elapsed = time.time() - total_t0- logger.info("%s", "=" * 60)- logger.info("All inference done in %.0fs (%d/%d OK)", infer_elapsed, successes, len(videos))-- if exr_futures:- t0 = time.time()- logger.info("Waiting for %d EXR saves...", len(exr_futures))- for fut in exr_futures:- fut.result()- exr_wait = time.time() - t0- if exr_wait > 0.1:- logger.info("EXR save wait: %.1fs", exr_wait)-- logger.info("Total wall time: %.0fs", time.time() - total_t0)++ output_path = Path(args.output_path)+ acescct_hdr, fps = pipeline(+ video=args.input,+ seed=args.seed,+ tiling_config=AUTO_TILING,+ high_quality_hdr=args.high_quality,+ keyframe_strength=None if args.no_keyframes else args.keyframe_strength,+ )++ encode_video(+ video=acescct_hdr,+ fps=round(fps),+ audio=None,+ output_path=str(output_path),+ video_chunks_number=1,+ color_space=args.exr_colorspace,+ )+ logger.info("Done → %s (+ EXR)", args.output_path)if __name__ == "__main__":diff --git a/packages/ltx-pipelines/src/ltx_pipelines/ic_lora.py b/packages/ltx-pipelines/src/ltx_pipelines/ic_lora.pyindex b427e5a..1b89696 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/ic_lora.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/ic_lora.py@@ -1,4 +1,8 @@import logging+from collections.abc import Iterator, Sequence+from dataclasses import dataclass, replace+from itertools import pairwise+from typing import NoReturnimport torch@@ -11,16 +15,37 @@ from ltx_core.model.transformer.compiling import CompilationConfigfrom ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, VideoEncoder, get_video_chunks_numberfrom ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy+from ltx_core.tiling import TileCountConfig, TileSizeConfigfrom ltx_core.types import VideoPixelShape+from ltx_pipelines.chunks import (+ ChunkConfig,+ DecodedChunk,+ SequentialVideoFrameSource,+ decode_chunks,+ denoise_chunks,+ generate_uniform_chunks,+ pipeline_output_from_chunks,+ replace_video_conditionings,+ spatially_upsample_chunks,+ split_decoded_chunks,+)+from ltx_pipelines.chunks.conditionings import (+ assert_image_frames_in_clip,+ image_conditionings_for_chunk,+ reference_video_conditionings_for_chunk,+)+from ltx_pipelines.chunks.state import Chunk, MakeVideoConditioningsfrom ltx_pipelines.iclora_utils import (- append_ic_lora_reference_video_conditionings,read_lora_reference_downscale_factor,read_lora_reference_temporal_scale_factor,)from ltx_pipelines.utils.args import (- ImageConditioningInput,VideoConditioningAction,VideoMaskConditioningAction,+ add_chunk_layout_args,+ add_generated_keyframes_arg,+ add_keyframe_decode_arg,+ chunk_config_from_args,default_2_stage_distilled_arg_parser,resolve_cli_params,)@@ -33,27 +58,227 @@ from ltx_pipelines.utils.blocks import (VideoUpsampler,)from ltx_pipelines.utils.constants import (+ DISTILLED_SIGMA_VALUES,DISTILLED_SIGMAS,+ LTX_2_3_PARAMS,+ STAGE_2_DISTILLED_SIGMA_VALUES,STAGE_2_DISTILLED_SIGMAS,)-from ltx_pipelines.utils.denoisers import SimpleDenoiserfrom ltx_pipelines.utils.helpers import (+ assert_generated_keyframes_request,assert_resolution,- combined_image_conditionings,ensure_tiling_config,get_device,+ snap_frames_to_grid,tiling_scale_factors_for_vae,)from ltx_pipelines.utils.media_io import (- HDRColorSpace,+ EXRColorSpace,decode_video_by_frame,encode_video,+ is_exr_dir,resolve_hdr_color_space,vae_dtype_for_hdr,video_preprocess,)from ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, PipelineOutput+from ltx_pipelines.utils.tiled_diffusion import (+ DiffusionTilingConfig,+ FixedSizeSpatialTiling,+ diffusion_stage_with_tiling,+)+from ltx_pipelines.utils.types import (+ ImageConditioningInput,+ OffloadMode,+ PipelineOutput,+ VideoAudio,+)+++@dataclass(frozen=True)+class ICLoraStageConfig:+ """One IC-LoRA diffusion stage in a target-resolution recipe.+ Attributes:+ resolution_divisor: Stage output resolution relative to the requested output.+ ``2`` means half resolution and ``1`` means the requested resolution.+ Consecutive stages must keep the same divisor or drop by exactly 2x.+ When the divisor is unchanged the pipeline reuses the previous latent;+ when it halves (for example ``2`` to ``1``, or ``4`` to ``2``) the+ built-in 2x spatial upsampler runs.+ apply_ic_lora: Whether this stage runs in context. When true the+ pipeline's LoRAs are loaded and the reference-video conditionings+ are attached; when false the stage runs the bare checkpoint, which+ is what the original stage 2 did.+ sigmas: Diffusion sigma schedule for this stage.+ tiling: Optional transformer tiling. This is independent of VAE decode+ tiling and blends tile predictions inside every diffusion step.+ """++ resolution_divisor: int+ apply_ic_lora: bool+ sigmas: tuple[float, ...]+ tiling: DiffusionTilingConfig | None = None++ def __post_init__(self) -> None:+ if self.resolution_divisor < 1:+ raise ValueError(f"resolution_divisor must be >= 1, got {self.resolution_divisor}")+ if len(self.sigmas) < 2:+ raise ValueError("A stage sigma schedule must contain at least two values")+++DEFAULT_IC_LORA_STAGES = (+ ICLoraStageConfig(resolution_divisor=2, apply_ic_lora=True, sigmas=tuple(DISTILLED_SIGMA_VALUES)),+ ICLoraStageConfig(resolution_divisor=1, apply_ic_lora=False, sigmas=tuple(STAGE_2_DISTILLED_SIGMA_VALUES)),+)+DEFAULT_IC_LORA_TILE_HEIGHT = LTX_2_3_PARAMS.stage_2_height+DEFAULT_IC_LORA_TILE_WIDTH = LTX_2_3_PARAMS.stage_2_width+++def spatial_tiled_ic_lora_stages(+ *,+ tile_height: int,+ tile_width: int,+ overlap_fraction: float = 0.5,+ apply_ic_lora: tuple[bool, bool] = (True, True),+) -> tuple[ICLoraStageConfig, ICLoraStageConfig]:+ """Build the existing two-stage recipe with per-step spatial tiling.+ Tiles use the requested rectangular size on both stages. An axis smaller+ than its tile remains untiled. Overlap is expressed as a fraction of each+ axis and blended with the core tiling subsystem's trapezoidal masks.+ Unlike :data:`DEFAULT_IC_LORA_STAGES`, stage 2 keeps the IC-LoRA and its+ reference conditioning. Stage 2 enters at sigma 0.909, so an untiled stage 2+ can recover structure from the upsampled full-canvas latent alone. A tiled+ stage 2 cannot: each window sees only its own crop at normalized positions,+ so without the reference every window regenerates its own content from near+ noise and the result stops following the driving video.+ """+ if tile_height < 64 or tile_width < 64:+ raise ValueError("tile_height and tile_width must be at least 64 pixels")+ if tile_height % 32 or tile_width % 32:+ raise ValueError("tile_height and tile_width must be divisible by 32")+ if not 0.0 <= overlap_fraction <= 0.5:+ raise ValueError(f"overlap_fraction must be in [0, 0.5], got {overlap_fraction}")++ height_overlap = int(tile_height * overlap_fraction) // 32 * 32+ width_overlap = int(tile_width * overlap_fraction) // 32 * 32+ tiling = FixedSizeSpatialTiling(+ height=tile_height,+ width=tile_width,+ height_overlap=height_overlap,+ width_overlap=width_overlap,+ )+ return (+ ICLoraStageConfig(+ resolution_divisor=2,+ apply_ic_lora=apply_ic_lora[0],+ sigmas=tuple(DISTILLED_SIGMA_VALUES),+ tiling=tiling,+ ),+ ICLoraStageConfig(+ resolution_divisor=1,+ apply_ic_lora=apply_ic_lora[1],+ sigmas=tuple(STAGE_2_DISTILLED_SIGMA_VALUES),+ tiling=tiling,+ ),+ )+++def resolve_ic_lora_stages(+ *,+ height: int,+ width: int,+ tile: bool = False,+ tile_height: int | None = None,+ tile_width: int | None = None,+ stage_2_ic_lora: bool = False,+ skip_stage_2: bool = False,+) -> tuple[ICLoraStageConfig, ...]:+ """Two-stage CLI recipe: optional transformer tiling, optional stage-2 IC-LoRA.+ The CLI is always this two-stage ladder. Longer recipes use+ ``ICLoraPipeline(stages=...)`` in Python.+ ``tile_height`` / ``tile_width`` require ``tile``. When tiling is on they+ default to :data:`DEFAULT_IC_LORA_TILE_HEIGHT` /+ :data:`DEFAULT_IC_LORA_TILE_WIDTH`.+ """+ if not tile:+ if tile_height is not None or tile_width is not None:+ raise ValueError("--tile-height and --tile-width require --tile")+ if not stage_2_ic_lora:+ return DEFAULT_IC_LORA_STAGES+ return (+ DEFAULT_IC_LORA_STAGES[0],+ replace(DEFAULT_IC_LORA_STAGES[1], apply_ic_lora=True),+ )++ resolved_height = DEFAULT_IC_LORA_TILE_HEIGHT if tile_height is None else tile_height+ resolved_width = DEFAULT_IC_LORA_TILE_WIDTH if tile_width is None else tile_width+ stage_2_is_tiled = (not skip_stage_2) and (height > resolved_height or width > resolved_width)+ if stage_2_is_tiled and not stage_2_ic_lora:+ raise ValueError("Tiled full-resolution stages need IC-LoRA on that stage. Pass --stage-2-ic-lora.")+ return spatial_tiled_ic_lora_stages(+ tile_height=resolved_height,+ tile_width=resolved_width,+ apply_ic_lora=(True, stage_2_ic_lora),+ )+++def _reference_encode_tiling(+ stage: ICLoraStageConfig,+ tiling_config: TilingConfig | AutoTiling | None,+) -> TilingConfig | AutoTiling | None:+ """Tiling for a stage's guide encode.+ Only a tiled stage encodes its guide in tiles. An untiled stage encodes the+ full canvas in one pass, so it must not inherit the pipeline's decode tiling:+ that would change the reference latent, and with it every default-recipe run.+ """+ return tiling_config if stage.tiling is not None else None+++def _concrete_reference_encode_tiling(+ stage: ICLoraStageConfig,+ tiling_config: TilingConfig | AutoTiling | None,+) -> TilingConfig | None:+ """Reference VAE encode tiling for chunked IC-LoRA (concrete config only)."""+ resolved = _reference_encode_tiling(stage, tiling_config)+ if resolved is None:+ return None+ if isinstance(resolved, TileSizeConfig | TileCountConfig):+ return resolved+ return None+++_IC_LORA_OOM = getattr(torch, "OutOfMemoryError", torch.cuda.OutOfMemoryError)+++def reraise_ic_lora_oom(exc: BaseException, *, tile: bool) -> NoReturn:+ """Re-raise GPU OOM with the CLI flags that usually recover the run."""+ if tile:+ hint = "GPU out of memory. Try smaller --tile-height / --tile-width, or --offload cpu."+ else:+ hint = "GPU out of memory. For large --height/--width pass --tile, or --offload cpu."+ raise type(exc)(f"{exc}\n\n{hint}") from exc+++@dataclass(frozen=True)+class _ICLoraRunContext:+ generator: torch.Generator+ noiser: GaussianNoiser+ dtype: torch.dtype+ vae_dtype: torch.dtype+ images: list[ImageConditioningInput]+ video_context: torch.Tensor+ audio_context: torch.Tensor+ num_frames: int+ height: int+ width: int+ frame_rate: float+ tiling_config: TilingConfig+ active_stages: tuple[ICLoraStageConfig, ...]+ video_conditioning: list[tuple[str, float]]+ conditioning_attention_strength: float+ conditioning_attention_mask: torch.Tensor | None+ decode_with_keyframes: bool+ color_space: EXRColorSpace | Noneclass ICLoraPipeline:@@ -80,6 +305,7 @@ class ICLoraPipeline:alloc_trim_strategy: AllocatorTrimStrategy = AllocatorTrimStrategy.TRIM,prompt_enhancer_gemma_root: str | None = None,diffvae_optimization: DiffVAEMode = DiffVAEMode.CHUNKED_EAGER,+ stages: Sequence[ICLoraStageConfig] | None = None,) -> None:self.device = device or get_device()self.dtype = torch.bfloat16@@ -100,18 +326,11 @@ class ICLoraPipeline:registry=registry,alloc_trim_strategy=alloc_trim_strategy,)- self.stage_1 = DiffusionStage.from_checkpoint(- model_paths.transformer(),- self.dtype,- self.device,- loras=tuple(loras),- quantization=quantization,- registry=registry,- compilation_config=compilation_config,- offload_mode=offload_mode,- alloc_trim_strategy=alloc_trim_strategy,- )- self.stage_2 = DiffusionStage.from_checkpoint(+ self._loras = tuple(loras)+ self.stages = tuple(stages) if stages is not None else DEFAULT_IC_LORA_STAGES+ self._validate_stages(self.stages)++ self._diffusion_stage = DiffusionStage.from_checkpoint(model_paths.transformer(),self.dtype,self.device,@@ -151,7 +370,7 @@ class ICLoraPipeline:# so inference can resize/subsample reference videos to match training conditions.self.reference_downscale_factor = 1self.reference_temporal_scale_factor = 1- for lora in loras:+ for lora in self._loras:scale = read_lora_reference_downscale_factor(lora.path)if scale != 1:if self.reference_downscale_factor not in (1, scale):@@ -171,6 +390,189 @@ class ICLoraPipeline:)self.reference_temporal_scale_factor = temporal+ def _resolve_active_stages(+ self,+ *,+ skip_stage_2: bool,+ stage_1_sigmas: torch.Tensor,+ stage_2_sigmas: torch.Tensor,+ ) -> tuple[ICLoraStageConfig, ...]:+ active_stages = self.stages+ if self.stages is DEFAULT_IC_LORA_STAGES:+ active_stages = tuple(+ ICLoraStageConfig(+ resolution_divisor=stage.resolution_divisor,+ apply_ic_lora=stage.apply_ic_lora,+ sigmas=tuple(sigmas.tolist()),+ tiling=stage.tiling,+ )+ for stage, sigmas in zip(+ self.stages,+ (stage_1_sigmas, stage_2_sigmas),+ strict=True,+ )+ )+ if skip_stage_2:+ active_stages = active_stages[:1]+ return active_stages++ def _prepare_run( # noqa: PLR0913+ self,+ *,+ prompt: str,+ seed: int,+ height: int,+ width: int,+ num_frames: int,+ frame_rate: float,+ images: list[ImageConditioningInput],+ video_conditioning: list[tuple[str, float]],+ enhance_prompt: bool,+ enhance_static_cache: bool,+ vae_dtype: torch.dtype | None,+ tiling_config: TilingConfig | AutoTiling | None,+ conditioning_attention_strength: float,+ skip_stage_2: bool,+ conditioning_attention_mask: torch.Tensor | None,+ stage_1_sigmas: torch.Tensor,+ stage_2_sigmas: torch.Tensor,+ color_space: EXRColorSpace | None,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ ) -> _ICLoraRunContext:+ images = self.image_conditioner.resolve_crf(images)+ assert_generated_keyframes_request(+ decode_with_keyframes,+ generated_keyframes,+ self._diffusion_stage,+ )+ active_stages = self._resolve_active_stages(+ skip_stage_2=skip_stage_2,+ stage_1_sigmas=stage_1_sigmas,+ stage_2_sigmas=stage_2_sigmas,+ )+ first_divisor = active_stages[0].resolution_divisor+ assert_resolution(+ height=height,+ width=width,+ is_two_stage=len(active_stages) > 1,+ divisor=32 * first_divisor,+ )+ if not (0.0 <= conditioning_attention_strength <= 1.0):+ raise ValueError(+ f"conditioning_attention_strength must be in [0.0, 1.0], got {conditioning_attention_strength}"+ )++ resolved_num_frames = snap_frames_to_grid(num_frames)+ generator = torch.Generator(device=self.device).manual_seed(seed)+ noiser = GaussianNoiser(generator=generator)+ resolved_vae_dtype = self.dtype if vae_dtype is None else vae_dtype++ (ctx_p,) = self.prompt_encoder(+ [prompt],+ enhance_first_prompt=enhance_prompt,+ enhance_static_cache=enhance_static_cache,+ enhance_prompt_image=images[0][0] if len(images) > 0 else None,+ )+ video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding++ scale_factors = tiling_scale_factors_for_vae(self.video_decoder.checkpoint_path)+ resolved_tiling_config = ensure_tiling_config(+ tiling_config,+ scale_factors=scale_factors,+ vae_checkpoint_path=self.video_decoder.checkpoint_path,+ video_shape=VideoPixelShape(+ batch=1,+ frames=resolved_num_frames,+ height=height,+ width=width,+ fps=frame_rate,+ ),+ diffvae_optimization=self.video_decoder.diffvae_optimization,+ device=self.device,+ keyframes=decode_with_keyframes,+ )++ return _ICLoraRunContext(+ generator=generator,+ noiser=noiser,+ dtype=self.dtype,+ vae_dtype=resolved_vae_dtype,+ images=images,+ video_context=video_context,+ audio_context=audio_context,+ num_frames=resolved_num_frames,+ height=height,+ width=width,+ frame_rate=frame_rate,+ tiling_config=resolved_tiling_config,+ active_stages=active_stages,+ video_conditioning=video_conditioning,+ conditioning_attention_strength=conditioning_attention_strength,+ conditioning_attention_mask=conditioning_attention_mask,+ decode_with_keyframes=decode_with_keyframes,+ color_space=color_space,+ )++ def _video_conditionings(+ self,+ ctx: _ICLoraRunContext,+ stage_config: ICLoraStageConfig,+ frame_sources: dict[str, SequentialVideoFrameSource],+ ) -> MakeVideoConditionings:+ assert_image_frames_in_clip(ctx.images, ctx.num_frames)+ encode_tiling = _concrete_reference_encode_tiling(stage_config, ctx.tiling_config)++ def make(chunk: Chunk) -> list[ConditioningItem]:+ if chunk.video is None:+ return []++ def encode(enc: VideoEncoder) -> list[ConditioningItem]:+ items = [+ *image_conditionings_for_chunk(+ chunk,+ images=ctx.images,+ video_encoder=enc,+ color_space=ctx.color_space,+ ),+ *reference_video_conditionings_for_chunk(+ chunk,+ video_conditioning=ctx.video_conditioning if stage_config.apply_ic_lora else (),+ video_encoder=enc,+ downscale_factor=self.reference_downscale_factor,+ reference_temporal_scale_factor=self.reference_temporal_scale_factor,+ conditioning_attention_strength=ctx.conditioning_attention_strength,+ conditioning_attention_mask=ctx.conditioning_attention_mask,+ encode_tiling=encode_tiling,+ color_space=ctx.color_space,+ frame_sources=frame_sources,+ ),+ ]+ return items++ return self.image_conditioner(encode)++ return make++ @staticmethod+ def _validate_stages(stages: Sequence[ICLoraStageConfig]) -> None:+ if not stages:+ raise ValueError("IC-LoRA requires at least one diffusion stage")+ for current, following in pairwise(stages):+ same_res = following.resolution_divisor == current.resolution_divisor+ upsample_2x = current.resolution_divisor == following.resolution_divisor * 2+ if not (same_res or upsample_2x):+ raise ValueError(+ "Consecutive IC-LoRA stages must keep the same resolution_divisor "+ "or drop by exactly 2x, "+ f"got {current.resolution_divisor} then {following.resolution_divisor}"+ )+ if stages[-1].resolution_divisor != 1:+ raise ValueError(+ "The final IC-LoRA stage must run at the requested resolution "+ f"(resolution_divisor=1), got {stages[-1].resolution_divisor}"+ )+def __call__( # noqa: PLR0913self,prompt: str,@@ -190,7 +592,10 @@ class ICLoraPipeline:conditioning_attention_mask: torch.Tensor | None = None,stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS,stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,- color_space: HDRColorSpace | None = None,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ color_space: EXRColorSpace | None = None,+ chunk_config: ChunkConfig | None = None,) -> PipelineOutput:"""Generate video with IC-LoRA conditioning.@@ -221,195 +626,188 @@ class ICLoraPipeline:conditioning_attention_strength.When None (default): scalar conditioning_attention_strength is useddirectly.+ generated_keyframes: Per-chunk slot budget (int) or explicit global pixel indices (with seam anchors).+ decode_with_keyframes: Decode with generated slots as DiffVAE anchors and carry+ overlap planes into the following chunk as fixed keyframe conditioning.+ chunk_config: Optional temporal chunk layout. ``None`` plans one window over+ the snapped clip (same output as before chunk streaming existed).Returns:- PipelineOutput with decoded video and audio. ``keyframes`` is ``None``.+ PipelineOutput with decoded video and audio."""- images = self.image_conditioner.resolve_crf(images)- assert_resolution(height=height, width=width, is_two_stage=True)- if not (0.0 <= conditioning_attention_strength <= 1.0):- raise ValueError(- f"conditioning_attention_strength must be in [0.0, 1.0], got {conditioning_attention_strength}"- )-- generator = torch.Generator(device=self.device).manual_seed(seed)- noiser = GaussianNoiser(generator=generator)- if vae_dtype is None:- vae_dtype = self.dtype-- (ctx_p,) = self.prompt_encoder(- [prompt],- enhance_first_prompt=enhance_prompt,- enhance_static_cache=enhance_static_cache,- enhance_prompt_image=images[0][0] if len(images) > 0 else None,- )- video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding-- scale_factors = tiling_scale_factors_for_vae(self.video_decoder.checkpoint_path)- tiling_config = ensure_tiling_config(- tiling_config,- scale_factors=scale_factors,- vae_checkpoint_path=self.video_decoder.checkpoint_path,- video_shape=VideoPixelShape(batch=1, frames=num_frames, height=height, width=width, fps=frame_rate),- diffvae_optimization=self.video_decoder.diffvae_optimization,- device=self.device,- )-- # Stage 1: Initial low resolution video generation.- stage_1_output_shape = VideoPixelShape(- batch=1,- frames=num_frames,- width=width // 2,- height=height // 2,- fps=frame_rate,- )-- # Encode conditionings using the video encoder block- stage_1_conditionings = self.image_conditioner(- lambda enc: self._create_conditionings(- images=images,- video_conditioning=video_conditioning,- height=stage_1_output_shape.height,- width=stage_1_output_shape.width,- video_encoder=enc,- num_frames=num_frames,- conditioning_attention_strength=conditioning_attention_strength,- conditioning_attention_mask=conditioning_attention_mask,- color_space=color_space,- )- )-- stage_1_sigmas = stage_1_sigmas.to(dtype=torch.float32, device=self.device)-- video_state, audio_state = self.stage_1(- denoiser=SimpleDenoiser(video_context, audio_context),- sigmas=stage_1_sigmas,- noiser=noiser,- width=stage_1_output_shape.width,- height=stage_1_output_shape.height,- frames=num_frames,- fps=frame_rate,- video=ModalitySpec(- context=video_context,- conditionings=stage_1_conditionings,- ),- audio=ModalitySpec(- context=audio_context,- ),- )-- if skip_stage_2:- # Skip Stage 2: Decode directly from Stage 1 output at half resolution- logging.info("[IC-LoRA] Skipping Stage 2 (--skip-stage-2 enabled)")- decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)- decoded_audio = self.audio_decoder(audio_state.latent)- return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)-- # Stage 2: Upsample and refine the video at higher resolution with distilled LORA.- upscaled_video_latent = self.upsampler(video_state.latent[:1])-- stage_2_sigmas = stage_2_sigmas.to(dtype=torch.float32, device=self.device)- stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate)- stage_2_conditionings = self.image_conditioner(- lambda enc: combined_image_conditionings(- images=images,- height=stage_2_output_shape.height,- width=stage_2_output_shape.width,- video_encoder=enc,- dtype=self.dtype,- device=self.device,- color_space=color_space,- )- )-- video_state, audio_state = self.stage_2(- denoiser=SimpleDenoiser(video_context, audio_context),- sigmas=stage_2_sigmas,- noiser=noiser,- width=width,+ chunks, num_frames, tiling_config = self.stream_chunks(+ prompt=prompt,+ seed=seed,height=height,- frames=num_frames,- fps=frame_rate,- video=ModalitySpec(- context=video_context,- conditionings=stage_2_conditionings,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=upscaled_video_latent,- ),- audio=ModalitySpec(- context=audio_context,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=audio_state.latent,- ),+ width=width,+ num_frames=num_frames,+ frame_rate=frame_rate,+ images=images,+ video_conditioning=video_conditioning,+ enhance_prompt=enhance_prompt,+ enhance_static_cache=enhance_static_cache,+ vae_dtype=vae_dtype,+ tiling_config=tiling_config,+ conditioning_attention_strength=conditioning_attention_strength,+ skip_stage_2=skip_stage_2,+ conditioning_attention_mask=conditioning_attention_mask,+ stage_1_sigmas=stage_1_sigmas,+ stage_2_sigmas=stage_2_sigmas,+ generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,+ color_space=color_space,+ chunk_config=chunk_config,)+ return pipeline_output_from_chunks(chunks, num_frames=num_frames, tiling_config=tiling_config)- decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)- decoded_audio = self.audio_decoder(audio_state.latent)- return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)-- def _create_conditionings(+ def stream_chunks( # noqa: PLR0913self,- images: list[ImageConditioningInput],- video_conditioning: list[tuple[str, float]],+ prompt: str,+ seed: int,height: int,width: int,num_frames: int,- video_encoder: VideoEncoder,+ frame_rate: float,+ images: list[ImageConditioningInput],+ video_conditioning: list[tuple[str, float]],+ enhance_prompt: bool = False,+ enhance_static_cache: bool = False,+ vae_dtype: torch.dtype | None = None,+ tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,conditioning_attention_strength: float = 1.0,+ skip_stage_2: bool = False,conditioning_attention_mask: torch.Tensor | None = None,- color_space: HDRColorSpace | None = None,- ) -> list[ConditioningItem]:- """- Create conditioning items for video generation.- Args:- conditioning_attention_strength: Scalar attention weight in [0, 1].- If conditioning_attention_mask is also provided, the downsampled mask- is multiplied by this strength. Otherwise this scalar is passed- directly as the attention mask.- conditioning_attention_mask: Optional pixel-space attention mask with shape- (B, 1, F_pixel, H_pixel, W_pixel) matching the reference video's- pixel dimensions. Downsampled to latent space with causal temporal- handling, then multiplied by conditioning_attention_strength.- Returns:- List of conditioning items. IC-LoRA conditionings are appended last.+ stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS,+ stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ color_space: EXRColorSpace | None = None,+ chunk_config: ChunkConfig | None = None,+ ) -> tuple[Iterator[DecodedChunk], int, TilingConfig]:+ """Generate a video as a stream of decoded temporal chunks.+ ``chunk_config=None`` plans a single chunk covering the snapped clip, which is+ how :meth:`__call__` runs. Video conditionings are attached per diffusion stage+ immediately before each :func:`~ltx_pipelines.chunks.denoise_chunks` pass.+ Temporal chunking composes with per-stage spatial transformer tiling inside+ each denoise step."""- conditionings = combined_image_conditionings(- images=images,- height=height,- width=width,- video_encoder=video_encoder,- dtype=self.dtype,- device=self.device,- color_space=color_space,- )-- append_ic_lora_reference_video_conditionings(- conditionings,- video_conditioning,+ ctx = self._prepare_run(+ prompt=prompt,+ seed=seed,height=height,width=width,num_frames=num_frames,- video_encoder=video_encoder,- dtype=self.dtype,- device=self.device,- reference_downscale_factor=self.reference_downscale_factor,- reference_temporal_scale_factor=self.reference_temporal_scale_factor,+ frame_rate=frame_rate,+ images=images,+ video_conditioning=video_conditioning,+ enhance_prompt=enhance_prompt,+ enhance_static_cache=enhance_static_cache,+ vae_dtype=vae_dtype,+ tiling_config=tiling_config,conditioning_attention_strength=conditioning_attention_strength,+ skip_stage_2=skip_stage_2,conditioning_attention_mask=conditioning_attention_mask,- tiling_config=None,+ stage_1_sigmas=stage_1_sigmas,+ stage_2_sigmas=stage_2_sigmas,color_space=color_space,+ generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,+ )+ if chunk_config is None:+ chunk_config = ChunkConfig(chunk_pixel_frames=ctx.num_frames, next_video_carry_frames=0)++ target = VideoPixelShape(+ batch=1,+ frames=ctx.num_frames,+ height=ctx.height // ctx.active_stages[0].resolution_divisor,+ width=ctx.width // ctx.active_stages[0].resolution_divisor,+ fps=ctx.frame_rate,+ )+ frame_sources: dict[str, SequentialVideoFrameSource] = {+ path: SequentialVideoFrameSource(path, self.device)+ for path, _ in ctx.video_conditioning+ if not is_exr_dir(path)+ }++ stage_1_divisor = ctx.active_stages[0].resolution_divisor+ chunks: Iterator[Chunk] = generate_uniform_chunks(+ target=target._replace(+ height=ctx.height // stage_1_divisor,+ width=ctx.width // stage_1_divisor,+ ),+ context=VideoAudio(video=ctx.video_context, audio=ctx.audio_context),+ device=self.device,+ dtype=ctx.dtype,+ config=chunk_config,+ video_scale_factors=self._diffusion_stage.video_scale_factors,+ generated_keyframes=generated_keyframes,)- if video_conditioning:- logging.info("[IC-LoRA] Added %d video conditioning(s)", len(video_conditioning))+ for stage_index, stage_config in enumerate(ctx.active_stages):+ if stage_index > 0:+ prev_config = ctx.active_stages[stage_index - 1]+ if prev_config.resolution_divisor > stage_config.resolution_divisor:+ if prev_config.resolution_divisor != stage_config.resolution_divisor * 2:+ raise ValueError(+ "Unsupported resolution transition from divisor "+ f"{prev_config.resolution_divisor} to {stage_config.resolution_divisor}: "+ "spatial upsampling only supports 2x"+ )+ chunks = spatially_upsample_chunks(chunks, self.upsampler)+ chunks = replace_video_conditionings(+ chunks,+ self._video_conditionings(ctx, stage_config, frame_sources),+ )++ sigmas = torch.tensor(stage_config.sigmas, dtype=torch.float32, device=self.device)+ stage = diffusion_stage_with_tiling(+ self._diffusion_stage.with_loras(self._loras if stage_config.apply_ic_lora else ()),+ stage_config.tiling,+ )+ stage_height = ctx.height // stage_config.resolution_divisor+ stage_width = ctx.width // stage_config.resolution_divisor+ logging.info(+ "[IC-LoRA] Stage %d/%d: %dx%d, ic_lora=%s, tiled=%s",+ stage_index + 1,+ len(ctx.active_stages),+ stage_width,+ stage_height,+ stage_config.apply_ic_lora,+ stage_config.tiling is not None,+ )+ chunks = denoise_chunks(+ chunks,+ stage,+ sigmas=sigmas,+ noiser=ctx.noiser,+ fps=ctx.frame_rate,+ )- return conditionings+ def decoded() -> Iterator[DecodedChunk]:+ try:+ yield from decode_chunks(+ chunks,+ self.video_decoder,+ self.audio_decoder,+ fps=ctx.frame_rate,+ tiling_config=ctx.tiling_config,+ generator=ctx.generator,+ dtype=ctx.vae_dtype,+ keyframes=ctx.decode_with_keyframes,+ )+ finally:+ for source in frame_sources.values():+ source.close()++ return (decoded(), ctx.num_frames, ctx.tiling_config)@torch.inference_mode()def main() -> None:logging.basicConfig(level=logging.INFO)params = resolve_cli_params(distilled=True)- parser = default_2_stage_distilled_arg_parser(params=params)+ parser = add_chunk_layout_args(+ add_keyframe_decode_arg(add_generated_keyframes_arg(default_2_stage_distilled_arg_parser(params=params)))+ )parser.add_argument("--video-conditioning",action=VideoConditioningAction,@@ -445,6 +843,43 @@ def main() -> None:"(height//2, width//2). Useful for faster iteration or when GPU memory is limited."),)+ parser.add_argument(+ "--stage-2-ic-lora",+ action="store_true",+ help=(+ "Keep the IC-LoRA and reference video on stage 2 as well as stage 1. "+ "Default stage 2 runs the bare checkpoint. Required when --tile makes stage 2 "+ "larger than the tile window."+ ),+ )+ parser.add_argument(+ "--tile",+ action="store_true",+ help=(+ "Tile each transformer step over a fixed spatial window so large --height/--width "+ "fits in memory. Off by default; 1080-class sizes stay the untiled two-stage recipe. "+ f"Default window is {DEFAULT_IC_LORA_TILE_HEIGHT}x{DEFAULT_IC_LORA_TILE_WIDTH} "+ "(override with --tile-height / --tile-width)."+ ),+ )+ parser.add_argument(+ "--tile-height",+ type=int,+ default=None,+ help=(+ f"Tile window height in pixels when --tile is set (default: {DEFAULT_IC_LORA_TILE_HEIGHT}). "+ "Must be at least 64 and divisible by 32. Requires --tile."+ ),+ )+ parser.add_argument(+ "--tile-width",+ type=int,+ default=None,+ help=(+ f"Tile window width in pixels when --tile is set (default: {DEFAULT_IC_LORA_TILE_WIDTH}). "+ "Must be at least 64 and divisible by 32. Requires --tile."+ ),+ )args = parser.parse_args()# Load mask video if provided via --conditioning-attention-mask@@ -460,48 +895,76 @@ def main() -> None:num_frames=args.num_frames,)- pipeline = ICLoraPipeline(- model_paths=args.model_paths,- spatial_upsampler_path=args.spatial_upsampler_path,- loras=tuple(args.lora) if args.lora else (),- quantization=args.quantization,- compilation_config=args.compile,- offload_mode=args.offload_mode,- prompt_enhancer_gemma_root=args.prompt_enhancer_gemma_root,- diffvae_optimization=args.diffvae_optimization,- )- hdr = resolve_hdr_color_space(- images=args.images,- video_paths=[path for path, _ in args.video_conditioning],- hdr=args.hdr,- )- vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- result = pipeline(- prompt=args.prompt,- seed=args.seed,- height=args.height,- width=args.width,- num_frames=args.num_frames,- frame_rate=args.frame_rate,- images=args.images,- video_conditioning=args.video_conditioning,- enhance_prompt=args.enhance_prompt,- enhance_static_cache=args.enhance_static_cache,- vae_dtype=vae_dtype,- color_space=hdr,- tiling_config=AUTO_TILING,- conditioning_attention_strength=conditioning_attention_strength,- skip_stage_2=args.skip_stage_2,- conditioning_attention_mask=conditioning_attention_mask,- )- encode_video(- video=result.video,- fps=args.frame_rate,- audio=result.audio,- output_path=args.output_path,- video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),- color_space=hdr,- )+ try:+ pipeline = ICLoraPipeline(+ model_paths=args.model_paths,+ spatial_upsampler_path=args.spatial_upsampler_path,+ loras=tuple(args.lora) if args.lora else (),+ quantization=args.quantization,+ compilation_config=args.compile,+ offload_mode=args.offload_mode,+ prompt_enhancer_gemma_root=args.prompt_enhancer_gemma_root,+ diffvae_optimization=args.diffvae_optimization,+ stages=resolve_ic_lora_stages(+ height=args.height,+ width=args.width,+ tile=args.tile,+ tile_height=args.tile_height,+ tile_width=args.tile_width,+ stage_2_ic_lora=args.stage_2_ic_lora,+ skip_stage_2=args.skip_stage_2,+ ),+ )+ hdr = resolve_hdr_color_space(+ images=args.images,+ video_paths=[path for path, _ in args.video_conditioning],+ hdr=args.hdr,+ )+ vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)+ chunk_config = chunk_config_from_args(args)+ chunks, num_frames, tiling_config = pipeline.stream_chunks(+ prompt=args.prompt,+ seed=args.seed,+ height=args.height,+ width=args.width,+ num_frames=args.num_frames,+ frame_rate=args.frame_rate,+ images=args.images,+ video_conditioning=args.video_conditioning,+ enhance_prompt=args.enhance_prompt,+ enhance_static_cache=args.enhance_static_cache,+ vae_dtype=vae_dtype,+ color_space=hdr,+ tiling_config=AUTO_TILING,+ conditioning_attention_strength=conditioning_attention_strength,+ skip_stage_2=args.skip_stage_2,+ conditioning_attention_mask=conditioning_attention_mask,+ generated_keyframes=args.num_generated_keyframes,+ decode_with_keyframes=args.decode_with_keyframes,+ chunk_config=chunk_config,+ )+ if chunk_config is not None:+ video, audio, audio_sampling_rate = split_decoded_chunks(chunks)+ video_chunks_number = 1+ else:+ result = pipeline_output_from_chunks(+ chunks,+ num_frames=num_frames,+ tiling_config=tiling_config,+ )+ video, audio, audio_sampling_rate = result.video, result.audio, None+ video_chunks_number = get_video_chunks_number(result.num_frames, result.tiling_config)+ encode_video(+ video=video,+ fps=args.frame_rate,+ audio=audio,+ output_path=args.output_path,+ video_chunks_number=video_chunks_number,+ color_space=hdr,+ audio_sampling_rate=audio_sampling_rate,+ )+ except _IC_LORA_OOM as exc:+ reraise_ic_lora_oom(exc, tile=args.tile)def _load_mask_video(diff --git a/packages/ltx-pipelines/src/ltx_pipelines/iclora_utils.py b/packages/ltx-pipelines/src/ltx_pipelines/iclora_utils.pyindex d7fb0e1..e768864 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/iclora_utils.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/iclora_utils.py@@ -1,30 +1,32 @@"""Shared IC-LoRA helpers: LoRA metadata, mask downsampling, reference-video conditioning.-Used by ``ic_lora`` and ``dubit`` (video reference path only). Dub-It audio helpers live in ``dubit.py``.+Used by ``ic_lora`` and ``dubit``."""from __future__ import annotationsimport logging+from collections.abc import Iteratorimport torchfrom einops import rearrangefrom safetensors import safe_open+from ltx_core.components.patchifiers import AudioPatchifierfrom ltx_core.conditioning import (ConditioningItem,ConditioningItemAttentionStrengthWrapper,VideoConditionByReferenceLatent,)from ltx_core.model.video_vae import TilingConfig, VideoEncoder-from ltx_core.types import VideoLatentShape+from ltx_core.types import AudioLatentShape, SpatioTemporalScaleFactors, VideoLatentShapefrom ltx_pipelines.utils.media_io import (ResizeMode,decode_video_by_frame,is_exr_dir,- load_exr_folder_conditioning_hdr,+ load_exr_as_hdr_conditioning,video_preprocess,)-from ltx_pipelines.utils.media_io.color_config import HDRColorSpace+from ltx_pipelines.utils.media_io.color_config import EXRColorSpacedef read_lora_reference_downscale_factor(lora_path: str) -> int:@@ -90,13 +92,28 @@ def temporal_subsample(video: torch.Tensor, temporal_scale_factor: int) -> torchreturn video[:, :, indices]-def append_ic_lora_reference_video_conditionings( # noqa: PLR0913+def _reference_prefix_latent_frames(+ prefix_pixel_frames: int, temporal_scale_factor: int, video_scale_factors: SpatioTemporalScaleFactors+) -> int:+ """Number of leading reference latents whose target-time span touches ``prefix_pixel_frames``."""+ if prefix_pixel_frames < 0:+ raise ValueError(f"prefix_pixel_frames must be >= 0, got {prefix_pixel_frames}")+ if temporal_scale_factor <= 0:+ raise ValueError(f"temporal_scale_factor must be > 0, got {temporal_scale_factor}")+ if prefix_pixel_frames == 0:+ return 0+ target_temporal_stride = video_scale_factors.time * temporal_scale_factor+ return 1 + (prefix_pixel_frames + target_temporal_stride - 2) // target_temporal_stride+++def append_ic_lora_reference_video_conditionings( # noqa: PLR0912, PLR0913conditionings: list[ConditioningItem],video_conditioning: list[tuple[str, float]],*,height: int,width: int,num_frames: int,+ starting_frame: int = 0,video_encoder: VideoEncoder,dtype: torch.dtype,device: torch.device,@@ -105,9 +122,15 @@ def append_ic_lora_reference_video_conditionings( # noqa: PLR0913conditioning_attention_strength: float,conditioning_attention_mask: torch.Tensor | None,tiling_config: TilingConfig | None = None,- color_space: HDRColorSpace | None = None,+ color_space: EXRColorSpace | None = None,+ frames: Iterator[torch.Tensor] | None = None,+ reference_prefix_frames: int = 0,) -> None:- """Append :class:`VideoConditionByReferenceLatent` items for each reference path."""+ """Append reference items, excluding tokens that touch an already-carried prefix.+ The full pixel window is encoded so the causal VAE receives the same temporal+ context and grid as the target chunk. Prefix removal happens only after encoding;+ retained tokens keep their original temporal-grid indices through ``first_latent_frame``.+ """scale = reference_downscale_factorif scale != 1 and (height % scale != 0 or width % scale != 0):raise ValueError(@@ -124,13 +147,14 @@ def append_ic_lora_reference_video_conditionings( # noqa: PLR0913)video = torch.cat(list(- load_exr_folder_conditioning_hdr(- exr_dir=video_path,- height=ref_height,- width=ref_width,+ load_exr_as_hdr_conditioning(+ video_path,+ ref_height,+ ref_width,+ dtype,+ device,frame_cap=num_frames,- dtype=dtype,- device=device,+ frame_start=starting_frame,color_space=color_space,resize_mode=ResizeMode.REFLECT_PAD,)@@ -138,7 +162,13 @@ def append_ic_lora_reference_video_conditionings( # noqa: PLR0913dim=2,)else:- frame_gen = decode_video_by_frame(path=video_path, frame_cap=num_frames, device=device)+ frame_gen = (+ frames+ if frames is not None+ else decode_video_by_frame(+ path=video_path, starting_frame=starting_frame, frame_cap=num_frames, device=device+ )+ )video = video_preprocess(frame_gen, ref_height, ref_width, dtype, device)if reference_temporal_scale_factor > 1:video = temporal_subsample(video, reference_temporal_scale_factor)@@ -146,13 +176,39 @@ def append_ic_lora_reference_video_conditionings( # noqa: PLR0913encoded_video = video_encoder.tiled_encode(video, tiling_config)else:encoded_video = video_encoder(video)- reference_video_shape = VideoLatentShape.from_torch_shape(encoded_video.shape)+ full_reference_shape = VideoLatentShape.from_torch_shape(encoded_video.shape)if conditioning_attention_mask is not None:latent_mask = downsample_mask_video_to_latent(mask=conditioning_attention_mask,- target_latent_shape=reference_video_shape,+ target_latent_shape=full_reference_shape,)+ else:+ latent_mask = None++ first_latent_frame = _reference_prefix_latent_frames(+ reference_prefix_frames,+ reference_temporal_scale_factor,+ video_encoder.video_scale_factors,+ )+ if first_latent_frame >= full_reference_shape.frames:+ raise ValueError(+ f"reference_prefix_frames ({reference_prefix_frames}) removes the entire reference "+ f"window ({full_reference_shape.frames} latent frames)"+ )+ if first_latent_frame:+ encoded_video = encoded_video[:, :, first_latent_frame:]+ if latent_mask is not None:+ latent_mask = rearrange(+ latent_mask,+ "b (f h w) -> b f h w",+ f=full_reference_shape.frames,+ h=full_reference_shape.height,+ w=full_reference_shape.width,+ )[:, first_latent_frame:]+ latent_mask = rearrange(latent_mask, "b f h w -> b (f h w)")++ if latent_mask is not None:attn_mask = latent_mask * conditioning_attention_strengthelif conditioning_attention_strength < 1.0:attn_mask = conditioning_attention_strength@@ -164,7 +220,30 @@ def append_ic_lora_reference_video_conditionings( # noqa: PLR0913downscale_factor=scale,temporal_scale_factor=reference_temporal_scale_factor,strength=strength,+ first_latent_frame=first_latent_frame,)if attn_mask is not None:cond = ConditioningItemAttentionStrengthWrapper(cond, attention_mask=attn_mask)conditionings.append(cond)+++def patchify_audio_reference_latent(+ vae_latents: torch.Tensor,+ *,+ negative_positions: bool,+ device: torch.device,+) -> tuple[torch.Tensor, torch.Tensor]:+ """Patchify audio VAE latents and build RoPE positions (optional negative shift for reference)."""+ patchifier = AudioPatchifier(patch_size=1)+ patchified = patchifier.patchify(vae_latents)+ b, c, _t, mel_bins = vae_latents.shape+ seq_len = patchified.shape[1]+ latent_coords = patchifier.get_patch_grid_bounds(+ output_shape=AudioLatentShape(batch=b, channels=c, frames=seq_len, mel_bins=mel_bins),+ device=device,+ )+ positions = latent_coords.to(dtype=torch.float32)+ if negative_positions:+ aud_dur = positions[:, :, -1, 1].max().item()+ positions = positions - aud_dur - 0.04+ return patchified, positionsdiff --git a/packages/ltx-pipelines/src/ltx_pipelines/keyframe_interpolation.py b/packages/ltx-pipelines/src/ltx_pipelines/keyframe_interpolation.pyindex cca1dd5..ca96a77 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/keyframe_interpolation.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/keyframe_interpolation.py@@ -18,7 +18,6 @@ from ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicyfrom ltx_core.types import VideoPixelShapefrom ltx_pipelines.utils.args import (- ImageConditioningInput,default_2_stage_arg_parser,resolve_cli_params,)@@ -36,19 +35,26 @@ from ltx_pipelines.utils.constants import (from ltx_pipelines.utils.denoisers import FactoryGuidedDenoiser, SimpleDenoiserfrom ltx_pipelines.utils.helpers import (assert_resolution,+ create_initial_av_latents,ensure_tiling_config,get_device,image_conditionings_by_adding_guiding_latent,tiling_scale_factors_for_vae,)from ltx_pipelines.utils.media_io import (- HDRColorSpace,+ EXRColorSpace,encode_video,resolve_hdr_color_space,vae_dtype_for_hdr,)from ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, PipelineOutput+from ltx_pipelines.utils.types import (+ ImageConditioningInput,+ ModalitySpec,+ OffloadMode,+ PipelineOutput,+ VideoAudio,+)class KeyframeInterpolationPipeline:@@ -163,7 +169,7 @@ class KeyframeInterpolationPipeline:max_batch_size: int = 1,stage_1_sigmas: torch.Tensor | None = None,stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,- color_space: HDRColorSpace | None = None,+ color_space: EXRColorSpace | None = None,) -> PipelineOutput:images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=True)@@ -226,6 +232,15 @@ class KeyframeInterpolationPipeline:negative_context=a_context_n,)+ video_latent, audio_latent = create_initial_av_latents(+ width=stage_1_output_shape.width,+ height=stage_1_output_shape.height,+ frames=num_frames,+ fps=frame_rate,+ device=self.device,+ dtype=self.dtype,+ video_scale_factors=self.stage_1.video_scale_factors,+ )video_state, audio_state = self.stage_1(denoiser=FactoryGuidedDenoiser(v_context=v_context_p,@@ -235,16 +250,18 @@ class KeyframeInterpolationPipeline:),sigmas=sigmas,noiser=noiser,- width=stage_1_output_shape.width,- height=stage_1_output_shape.height,- frames=num_frames,- fps=frame_rate,- video=ModalitySpec(- context=v_context_p,- conditionings=stage_1_conditionings,- ),- audio=ModalitySpec(- context=a_context_p,+ modalities=VideoAudio(+ video=ModalitySpec(+ latent=video_latent,+ conditioning_fps=frame_rate,+ context=v_context_p,+ conditionings=stage_1_conditionings,+ ),+ audio=ModalitySpec(+ latent=audio_latent,+ conditioning_fps=frame_rate,+ context=a_context_p,+ ),),max_batch_size=max_batch_size,)@@ -270,26 +287,26 @@ class KeyframeInterpolationPipeline:denoiser=SimpleDenoiser(v_context_p, a_context_p),sigmas=stage_2_sigmas,noiser=noiser,- width=width,- height=height,- frames=num_frames,- fps=frame_rate,- video=ModalitySpec(- context=v_context_p,- conditionings=stage_2_conditionings,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=upscaled_video_latent,- ),- audio=ModalitySpec(- context=a_context_p,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=audio_state.latent,+ modalities=VideoAudio(+ video=ModalitySpec(+ latent=upscaled_video_latent,+ conditioning_fps=frame_rate,+ context=v_context_p,+ conditionings=stage_2_conditionings,+ noise_scale=stage_2_sigmas[0].item(),+ ),+ audio=ModalitySpec(+ latent=audio_state.latent,+ conditioning_fps=frame_rate,+ context=a_context_p,+ noise_scale=stage_2_sigmas[0].item(),+ ),),)decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)decoded_audio = self.audio_decoder(audio_state.latent)- return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)+ return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config)@torch.inference_mode()diff --git a/packages/ltx-pipelines/src/ltx_pipelines/retake.py b/packages/ltx-pipelines/src/ltx_pipelines/retake.pyindex b86745a..cdf2ad4 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/retake.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/retake.py@@ -32,13 +32,14 @@ from ltx_pipelines.utils.constants import DISTILLED_SIGMAS, detect_paramsfrom ltx_pipelines.utils.denoisers import GuidedDenoiser, SimpleDenoiserfrom ltx_pipelines.utils.helpers import (audio_latent_from_file,+ create_initial_audio_latent,ensure_tiling_config,get_device,tiling_scale_factors_for_vae,video_latent_from_file,)from ltx_pipelines.utils.media_io import (- HDRColorSpace,+ EXRColorSpace,encode_video,get_videostream_metadata,is_exr_dir,@@ -46,7 +47,7 @@ from ltx_pipelines.utils.media_io import (vae_dtype_for_hdr,)from ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, PipelineOutput+from ltx_pipelines.utils.types import ModalitySpec, OffloadMode, PipelineOutput, VideoAudioclass RetakePipeline:@@ -168,7 +169,7 @@ class RetakePipeline:tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,max_batch_size: int = 1,sigmas: torch.Tensor | None = None,- color_space: HDRColorSpace | None = None,+ color_space: EXRColorSpace | None = None,) -> PipelineOutput:"""Regenerate ``[start_time, end_time]`` of the source video (retake).Parameters@@ -205,8 +206,7 @@ class RetakePipeline:Returns-------PipelineOutput- Decoded video, audio, frame count, tiling, ``keyframes=None``, and the- video latent used for decode when retained (may be ``None``).+ Decoded video, audio, frame count, and tiling config."""if start_time >= end_time:raise ValueError(f"start_time ({start_time}) must be less than end_time ({end_time})")@@ -265,20 +265,30 @@ class RetakePipeline:v_context_p, a_context_p = contexts[0].video_encoding, contexts[0].audio_encodingvideo_modality_spec = ModalitySpec(+ latent=initial_video_latent,+ conditioning_fps=output_shape.fps,context=v_context_p,conditionings=[TemporalRegionMask(start_time=start_time, end_time=end_time, fps=output_shape.fps)]if regenerate_videoelse [],- initial_latent=initial_video_latent,frozen=not regenerate_video,)+ scratch_audio = initial_audio_latent is None+ if scratch_audio:+ # Source has no audio track: generate from scratch on the encoded video canvas.+ initial_audio_latent = create_initial_audio_latent(+ initial_video_latent,+ fps=output_shape.fps,+ video_scale_factors=self.stage.video_scale_factors,+ )audio_modality_spec = ModalitySpec(+ latent=initial_audio_latent,+ conditioning_fps=output_shape.fps,context=a_context_p,conditionings=[TemporalRegionMask(start_time=start_time, end_time=end_time, fps=output_shape.fps)]- if (initial_audio_latent is not None and regenerate_audio)+ if (not scratch_audio and regenerate_audio)else [],- initial_latent=initial_audio_latent,- frozen=initial_audio_latent is not None and not regenerate_audio,+ frozen=not scratch_audio and not regenerate_audio,)# Build denoiser and resolve sigma schedule.@@ -313,21 +323,14 @@ class RetakePipeline:denoiser=denoiser,sigmas=sigmas,noiser=noiser,- width=output_shape.width,- height=output_shape.height,- frames=output_shape.frames,- fps=output_shape.fps,- video=video_modality_spec,- audio=audio_modality_spec,+ modalities=VideoAudio(video=video_modality_spec, audio=audio_modality_spec),max_batch_size=max_batch_size,)decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)decoded_audio = self.audio_decoder(audio_state.latent)- return PipelineOutput(- decoded_video, decoded_audio, output_shape.frames, tiling_config, None, video_state.latent- )+ return PipelineOutput(decoded_video, decoded_audio, output_shape.frames, tiling_config)@torch.inference_mode()diff --git a/packages/ltx-pipelines/src/ltx_pipelines/t2a_one_stage.py b/packages/ltx-pipelines/src/ltx_pipelines/t2a_one_stage.pyindex 4d9a6d6..4c1848b 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/t2a_one_stage.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/t2a_one_stage.py@@ -15,7 +15,7 @@ from ltx_core.loader.registry import Registryfrom ltx_core.model.transformer import LTXV_AUDIO_ONLY_MODEL_COMFY_RENAMING_MAP, LTXAudioOnlyModelConfiguratorfrom ltx_core.model.transformer.compiling import CompilationConfigfrom ltx_core.quantization import QuantizationPolicy-from ltx_core.types import Audio+from ltx_core.types import Audio, AudioLatentShapefrom ltx_pipelines.utils import get_devicefrom ltx_pipelines.utils.args import (default_1_stage_t2a_arg_parser,@@ -32,12 +32,7 @@ from ltx_pipelines.utils.blocks import (from ltx_pipelines.utils.denoisers import FactoryGuidedDenoiserfrom ltx_pipelines.utils.media_io import encode_audiofrom ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode--# Placeholder pixel dimensions used for ``VideoPixelShape`` construction.-# Audio-only generation reads ``frames`` and ``fps`` from the pixel shape via-# ``AudioLatentShape.from_video_pixel_shape`` (height/width are unused).-_AUDIO_ONLY_PLACEHOLDER_RES = 512+from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode, VideoAudioclass T2AOneStagePipeline:@@ -45,8 +40,8 @@ class T2AOneStagePipeline:Single-stage text-to-audio generation pipeline.Generates audio at the target duration in a single diffusion pass withclassifier-free guidance (CFG) on the audio modality only. The video- modality is fully absent — the transformer runs audio-only by passing- ``video=None`` to the ``DiffusionStage``.+ modality is fully absent — the transformer runs audio-only via+ ``VideoAudio(audio=...)``.Assumes full non distilled model is provided in the checkpoint_path."""@@ -159,12 +154,19 @@ class T2AOneStagePipeline:),sigmas=sigmas,noiser=noiser,- width=_AUDIO_ONLY_PLACEHOLDER_RES,- height=_AUDIO_ONLY_PLACEHOLDER_RES,- frames=num_frames,- fps=frame_rate,- video=None,- audio=ModalitySpec(context=a_context_p),+ modalities=VideoAudio(+ audio=ModalitySpec(+ latent=torch.zeros(+ *AudioLatentShape.from_duration(+ batch=1, duration=float(num_frames) / float(frame_rate)+ ).to_torch_shape(),+ device=self.device,+ dtype=self.dtype,+ ),+ conditioning_fps=frame_rate,+ context=a_context_p,+ ),+ ),max_batch_size=max_batch_size,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_one_stage.py b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_one_stage.pyindex f8407a2..a9dd0cc 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_one_stage.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_one_stage.py@@ -19,8 +19,8 @@ from ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicyfrom ltx_core.types import VideoPixelShapefrom ltx_pipelines.utils.args import (- ImageConditioningInput,add_generated_keyframes_arg,+ add_keyframe_decode_arg,default_1_stage_arg_parser,resolve_cli_params,)@@ -36,24 +36,33 @@ from ltx_pipelines.utils.blocks import ()from ltx_pipelines.utils.denoisers import FactoryGuidedDenoiserfrom ltx_pipelines.utils.helpers import (+ assert_generated_keyframes_request,assert_resolution,combined_image_conditionings,+ create_initial_av_latents,decode_keyframes_from_slots,ensure_tiling_config,generated_keyframe_conditionings,get_device,- has_generated_keyframes,resolve_generated_keyframes,tiling_scale_factors_for_vae,)from ltx_pipelines.utils.media_io import (- HDRColorSpace,+ EXRColorSpace,encode_video,resolve_hdr_color_space,vae_dtype_for_hdr,)from ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode, PipelineOutput+from ltx_pipelines.utils.types import (+ DEFAULT_AUTO_DURATION,+ AutoDuration,+ ImageConditioningInput,+ ModalitySpec,+ OffloadMode,+ PipelineOutput,+ VideoAudio,+)class TI2VidOneStagePipeline:@@ -150,14 +159,14 @@ class TI2VidOneStagePipeline:tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,max_batch_size: int = 1,sigmas: torch.Tensor | None = None,- color_space: HDRColorSpace | None = None,+ color_space: EXRColorSpace | None = None,generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,) -> PipelineOutput:require_num_frames_source(num_frames, self.duration_predictor)images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=False)- if has_generated_keyframes(generated_keyframes):- self.stage.assert_generated_keyframes_supported()+ assert_generated_keyframes_request(decode_with_keyframes, generated_keyframes, self.stage)generator = torch.Generator(device=self.device).manual_seed(seed)noiser = GaussianNoiser(generator=generator)@@ -190,6 +199,7 @@ class TI2VidOneStagePipeline:video_shape=VideoPixelShape(batch=1, frames=num_frames, height=height, width=width, fps=frame_rate),diffvae_optimization=self.video_decoder.diffvae_optimization,device=self.device,+ keyframes=decode_with_keyframes,)stage_1_conditionings = self.image_conditioner(@@ -218,6 +228,15 @@ class TI2VidOneStagePipeline:negative_context=a_context_n,)+ video_latent, audio_latent = create_initial_av_latents(+ width=width,+ height=height,+ frames=num_frames,+ fps=frame_rate,+ device=self.device,+ dtype=self.dtype,+ video_scale_factors=self.stage.video_scale_factors,+ )video_state, audio_state = self.stage(denoiser=FactoryGuidedDenoiser(v_context=v_context_p,@@ -227,35 +246,51 @@ class TI2VidOneStagePipeline:),sigmas=sigmas,noiser=noiser,- width=width,- height=height,- frames=num_frames,- fps=frame_rate,- video=ModalitySpec(- context=v_context_p,- conditionings=stage_1_conditionings,- ),- audio=ModalitySpec(- context=a_context_p,+ modalities=VideoAudio(+ video=ModalitySpec(+ latent=video_latent,+ conditioning_fps=frame_rate,+ context=v_context_p,+ conditionings=stage_1_conditionings,+ ),+ audio=ModalitySpec(+ latent=audio_latent,+ conditioning_fps=frame_rate,+ context=a_context_p,+ ),),max_batch_size=max_batch_size,)- decoded_video = self.video_decoder(video_state.latent, tiling_config, generator=generator, dtype=vae_dtype)- decoded_audio = self.audio_decoder(audio_state.latent)- keyframes = decode_keyframes_from_slots(- video_state.generated_keyframes,- resolve_generated_keyframes(generated_keyframes, num_frames),- num_frames,+ decode_keyframes = None+ if decode_with_keyframes:+ keyframe_positions = resolve_generated_keyframes(generated_keyframes, num_frames)+ decode_keyframes = decode_keyframes_from_slots(+ video_state.generated_keyframes,+ keyframe_positions,+ num_frames,+ )+ if decode_keyframes is None:+ raise RuntimeError("decode_with_keyframes was set but no keyframe slots were produced")++ decoded_video = self.video_decoder(+ video_state.latent,+ tiling_config,+ generator=generator,+ dtype=vae_dtype,+ keyframes=decode_keyframes,)- return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, keyframes, video_state.latent)+ decoded_audio = self.audio_decoder(audio_state.latent)+ return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config)@torch.inference_mode()def main() -> None:logging.basicConfig(level=logging.INFO)params = resolve_cli_params()- parser = add_generated_keyframes_arg(default_1_stage_arg_parser(params=params, supports_auto_duration=True))+ parser = add_keyframe_decode_arg(+ add_generated_keyframes_arg(default_1_stage_arg_parser(params=params, supports_auto_duration=True))+ )args = parser.parse_args()pipeline = TI2VidOneStagePipeline(model_paths=args.model_paths,@@ -301,6 +336,7 @@ def main() -> None:max_batch_size=args.max_batch_size,tiling_config=AUTO_TILING,generated_keyframes=args.num_generated_keyframes,+ decode_with_keyframes=args.decode_with_keyframes,)encode_video(diff --git a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.py b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.pyindex 08454dd..afe063e 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages.py@@ -1,5 +1,6 @@import logging-from collections.abc import Sequence+from collections.abc import Iterator, Sequence+from dataclasses import dataclassimport torch@@ -11,6 +12,7 @@ from ltx_core.components.guiders import ()from ltx_core.components.noisers import GaussianNoiserfrom ltx_core.components.schedulers import LTX2Scheduler+from ltx_core.conditioning import ConditioningItemfrom ltx_core.loader import LoraPathStrengthAndSDOpsfrom ltx_core.loader.registry import Registryfrom ltx_core.model.transformer.compiling import CompilationConfig@@ -18,9 +20,28 @@ from ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig, get_from ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicyfrom ltx_core.types import VideoPixelShape+from ltx_pipelines.chunks import (+ Chunk,+ ChunkConfig,+ DecodedChunk,+ MakeVideoConditionings,+ decode_chunks,+ denoise_chunks,+ generate_uniform_chunks,+ pipeline_output_from_chunks,+ spatially_upsample_chunks,+ split_decoded_chunks,+)+from ltx_pipelines.chunks.conditionings import (+ assert_image_frames_in_clip,+ image_conditionings_for_chunk,+ images_for_chunk,+)from ltx_pipelines.utils.args import (- ImageConditioningInput,+ add_chunk_layout_args,add_generated_keyframes_arg,+ add_keyframe_decode_arg,+ chunk_config_from_args,default_2_stage_arg_parser,resolve_cli_params,)@@ -38,24 +59,47 @@ from ltx_pipelines.utils.blocks import (from ltx_pipelines.utils.constants import (STAGE_2_DISTILLED_SIGMAS,)-from ltx_pipelines.utils.denoisers import FactoryGuidedDenoiser, SimpleDenoiser+from ltx_pipelines.utils.denoisers import FactoryGuidedDenoiserfrom ltx_pipelines.utils.helpers import (+ assert_generated_keyframes_request,assert_resolution,- combined_image_conditionings,ensure_tiling_config,- generated_keyframe_conditionings,get_device,- has_generated_keyframes,+ snap_frames_to_grid,tiling_scale_factors_for_vae,)-from ltx_pipelines.utils.media_io import (- HDRColorSpace,- encode_video,- resolve_hdr_color_space,- vae_dtype_for_hdr,-)+from ltx_pipelines.utils.media_io import EXRColorSpace, encode_video, resolve_hdr_color_space, vae_dtype_for_hdrfrom ltx_pipelines.utils.model_paths import ModelPaths-from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode, PipelineOutput+from ltx_pipelines.utils.types import (+ DEFAULT_AUTO_DURATION,+ AutoDuration,+ ImageConditioningInput,+ OffloadMode,+ PipelineOutput,+ VideoAudio,+)+++@dataclass(frozen=True)+class _TI2VidRunContext:+ """Setup snapshot for :meth:`TI2VidTwoStagesPipeline.stream_chunks`.+ Built by :meth:`TI2VidTwoStagesPipeline._prepare_run`.+ """++ generator: torch.Generator+ noiser: GaussianNoiser+ dtype: torch.dtype+ vae_dtype: torch.dtype+ #: ``images`` with every unset CRF filled in, so callers do not re-resolve it.+ images: list[ImageConditioningInput]+ v_context_p: torch.Tensor+ a_context_p: torch.Tensor+ v_context_n: torch.Tensor+ a_context_n: torch.Tensor+ num_frames: int+ tiling_config: TilingConfig+ stage_1_width: int+ stage_1_height: intclass TI2VidTwoStagesPipeline:@@ -156,40 +200,34 @@ class TI2VidTwoStagesPipeline:alloc_trim_strategy=alloc_trim_strategy,)- def __call__( # noqa: PLR0913+ def _prepare_run( # noqa: PLR0913self,+ *,prompt: str,negative_prompt: str,seed: int,height: int,width: int,frame_rate: float,- num_inference_steps: int,- video_guider_params: MultiModalGuiderParams | MultiModalGuiderFactory,- audio_guider_params: MultiModalGuiderParams | MultiModalGuiderFactory,images: list[ImageConditioningInput],- num_frames: int | AutoDuration = DEFAULT_AUTO_DURATION,- vae_dtype: torch.dtype | None = None,- tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,- enhance_prompt: bool = False,- enhance_static_cache: bool = False,- max_batch_size: int = 1,- stage_1_sigmas: torch.Tensor | None = None,- stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,- color_space: HDRColorSpace | None = None,- generated_keyframes: int | Sequence[int] = 0,- ) -> PipelineOutput:+ num_frames: int | AutoDuration,+ vae_dtype: torch.dtype | None,+ tiling_config: TilingConfig | AutoTiling | None,+ enhance_prompt: bool,+ enhance_static_cache: bool,+ generated_keyframes: int | Sequence[int],+ decode_with_keyframes: bool,+ ) -> _TI2VidRunContext:+ """Validate inputs, encode prompts, and resolve frame count / tiling before chunk planning."""require_num_frames_source(num_frames, self.duration_predictor)images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=True)- if has_generated_keyframes(generated_keyframes):- self.stage_1.assert_generated_keyframes_supported()+ assert_generated_keyframes_request(decode_with_keyframes, generated_keyframes, self.stage_1)generator = torch.Generator(device=self.device).manual_seed(seed)noiser = GaussianNoiser(generator=generator)dtype = torch.bfloat16- if vae_dtype is None:- vae_dtype = dtype+ resolved_vae_dtype = dtype if vae_dtype is None else vae_dtypectx_p, ctx_n = self.prompt_encoder([prompt, negative_prompt],@@ -200,122 +238,245 @@ class TI2VidTwoStagesPipeline:v_context_p, a_context_p = ctx_p.video_encoding, ctx_p.audio_encodingv_context_n, a_context_n = ctx_n.video_encoding, ctx_n.audio_encoding- num_frames = resolve_num_frames(- num_frames,- self.duration_predictor,- video_encoding=v_context_p,- audio_encoding=a_context_p,- frame_rate=frame_rate,+ resolved_num_frames = snap_frames_to_grid(+ resolve_num_frames(+ num_frames,+ self.duration_predictor,+ video_encoding=v_context_p,+ audio_encoding=a_context_p,+ frame_rate=frame_rate,+ ))scale_factors = tiling_scale_factors_for_vae(self.video_decoder.checkpoint_path)- tiling_config = ensure_tiling_config(+ resolved_tiling_config = ensure_tiling_config(tiling_config,scale_factors=scale_factors,vae_checkpoint_path=self.video_decoder.checkpoint_path,- video_shape=VideoPixelShape(batch=1, frames=num_frames, height=height, width=width, fps=frame_rate),+ video_shape=VideoPixelShape(+ batch=1, frames=resolved_num_frames, height=height, width=width, fps=frame_rate+ ),diffvae_optimization=self.video_decoder.diffvae_optimization,device=self.device,+ keyframes=decode_with_keyframes,)- # Stage 1: Generate video at half resolution with CFG guidance.- stage_1_output_shape = VideoPixelShape(- batch=1,- frames=num_frames,- width=width // 2,- height=height // 2,- fps=frame_rate,+ return _TI2VidRunContext(+ generator=generator,+ noiser=noiser,+ dtype=dtype,+ vae_dtype=resolved_vae_dtype,+ images=images,+ v_context_p=v_context_p,+ a_context_p=a_context_p,+ v_context_n=v_context_n,+ a_context_n=a_context_n,+ num_frames=resolved_num_frames,+ tiling_config=resolved_tiling_config,+ stage_1_width=width // 2,+ stage_1_height=height // 2,)- stage_1_conditionings = self.image_conditioner(- lambda enc: combined_image_conditionings(- images=images,- height=stage_1_output_shape.height,- width=stage_1_output_shape.width,- video_encoder=enc,- dtype=dtype,- device=self.device,- color_space=color_space,++ def _video_conditionings(+ self,+ images: list[ImageConditioningInput],+ num_frames: int,+ color_space: EXRColorSpace | None,+ ) -> MakeVideoConditionings:+ assert_image_frames_in_clip(images, num_frames)++ def make(chunk: Chunk) -> list[ConditioningItem]:+ if chunk.video is None or not images_for_chunk(chunk, images):+ return []+ return self.image_conditioner(+ lambda enc: image_conditionings_for_chunk(+ chunk,+ images=images,+ video_encoder=enc,+ color_space=color_space,+ ))++ return make++ def __call__( # noqa: PLR0913+ self,+ prompt: str,+ negative_prompt: str,+ seed: int,+ height: int,+ width: int,+ frame_rate: float,+ num_inference_steps: int,+ video_guider_params: MultiModalGuiderParams | MultiModalGuiderFactory,+ audio_guider_params: MultiModalGuiderParams | MultiModalGuiderFactory,+ images: list[ImageConditioningInput],+ num_frames: int | AutoDuration = DEFAULT_AUTO_DURATION,+ vae_dtype: torch.dtype | None = None,+ tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,+ enhance_prompt: bool = False,+ enhance_static_cache: bool = False,+ max_batch_size: int = 1,+ stage_1_sigmas: torch.Tensor | None = None,+ stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,+ color_space: EXRColorSpace | None = None,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ chunk_config: ChunkConfig | None = None,+ ) -> PipelineOutput:+ """Generate a video.+ ``chunk_config=None`` plans a single chunk covering the snapped clip.+ """+ chunks, num_frames, tiling_config = self.stream_chunks(+ prompt=prompt,+ negative_prompt=negative_prompt,+ seed=seed,+ height=height,+ width=width,+ frame_rate=frame_rate,+ num_inference_steps=num_inference_steps,+ video_guider_params=video_guider_params,+ audio_guider_params=audio_guider_params,+ images=images,+ num_frames=num_frames,+ vae_dtype=vae_dtype,+ tiling_config=tiling_config,+ enhance_prompt=enhance_prompt,+ enhance_static_cache=enhance_static_cache,+ max_batch_size=max_batch_size,+ stage_1_sigmas=stage_1_sigmas,+ stage_2_sigmas=stage_2_sigmas,+ color_space=color_space,+ generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,+ chunk_config=chunk_config,+ )+ return pipeline_output_from_chunks(chunks, num_frames=num_frames, tiling_config=tiling_config)++ def stream_chunks( # noqa: PLR0913+ self,+ prompt: str,+ negative_prompt: str,+ seed: int,+ height: int,+ width: int,+ frame_rate: float,+ num_inference_steps: int,+ video_guider_params: MultiModalGuiderParams | MultiModalGuiderFactory,+ audio_guider_params: MultiModalGuiderParams | MultiModalGuiderFactory,+ images: list[ImageConditioningInput],+ num_frames: int | AutoDuration = DEFAULT_AUTO_DURATION,+ vae_dtype: torch.dtype | None = None,+ tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING,+ enhance_prompt: bool = False,+ enhance_static_cache: bool = False,+ max_batch_size: int = 1,+ stage_1_sigmas: torch.Tensor | None = None,+ stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,+ color_space: EXRColorSpace | None = None,+ generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ chunk_config: ChunkConfig | None = None,+ ) -> tuple[Iterator[DecodedChunk], int, TilingConfig]:+ """Generate a video as a stream of decoded chunks.+ ``chunk_config=None`` plans a single chunk covering the snapped clip.+ """+ ctx = self._prepare_run(+ prompt=prompt,+ negative_prompt=negative_prompt,+ seed=seed,+ height=height,+ width=width,+ frame_rate=frame_rate,+ images=images,+ num_frames=num_frames,+ vae_dtype=vae_dtype,+ tiling_config=tiling_config,+ enhance_prompt=enhance_prompt,+ enhance_static_cache=enhance_static_cache,+ generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,)- stage_1_conditionings.extend(generated_keyframe_conditionings(generated_keyframes, num_frames))+ if chunk_config is None:+ chunk_config = ChunkConfig(chunk_pixel_frames=ctx.num_frames, next_video_carry_frames=0)sigmas = (stage_1_sigmas if stage_1_sigmas is not None else self._scheduler.execute(steps=num_inference_steps)).to(dtype=torch.float32, device=self.device)+ stage_2_sigmas = stage_2_sigmas.to(dtype=torch.float32, device=self.device)- video_state, audio_state = self.stage_1(- denoiser=FactoryGuidedDenoiser(- v_context=v_context_p,- a_context=a_context_p,+ def make_denoiser(chunk: Chunk) -> FactoryGuidedDenoiser:+ return FactoryGuidedDenoiser(+ v_context=chunk.video_context,+ a_context=chunk.audio_context,video_guider_factory=create_multimodal_guider_factory(- params=video_guider_params,- negative_context=v_context_n,+ params=video_guider_params, negative_context=ctx.v_context_n),audio_guider_factory=create_multimodal_guider_factory(- params=audio_guider_params,- negative_context=a_context_n,+ params=audio_guider_params, negative_context=ctx.a_context_n),- ),+ )++ target = VideoPixelShape(+ batch=1,+ frames=ctx.num_frames,+ height=ctx.stage_1_height,+ width=ctx.stage_1_width,+ fps=frame_rate,+ )+ chunks = generate_uniform_chunks(+ target=target,+ context=VideoAudio(video=ctx.v_context_p, audio=ctx.a_context_p),+ device=self.device,+ dtype=ctx.dtype,+ config=chunk_config,+ video_scale_factors=self.stage_1.video_scale_factors,+ make_video_conditionings=self._video_conditionings(ctx.images, ctx.num_frames, color_space),+ generated_keyframes=generated_keyframes,+ )+ base = denoise_chunks(+ chunks,+ self.stage_1,sigmas=sigmas,- noiser=noiser,- width=stage_1_output_shape.width,- height=stage_1_output_shape.height,- frames=num_frames,+ noiser=ctx.noiser,fps=frame_rate,- video=ModalitySpec(context=v_context_p, conditionings=stage_1_conditionings),- audio=ModalitySpec(context=a_context_p),max_batch_size=max_batch_size,+ make_denoiser=make_denoiser,)-- # Stage 2: Upsample and refine the video at higher resolution with distilled LoRA.- upscaled_video_latent = self.upsampler(video_state.latent[:1])-- stage_2_sigmas = stage_2_sigmas.to(dtype=torch.float32, device=self.device)- stage_2_conditionings = self.image_conditioner(- lambda enc: combined_image_conditionings(- images=images,- height=height,- width=width,- video_encoder=enc,- dtype=dtype,- device=self.device,- color_space=color_space,- )- )-- # Stage 2 refines video only; discard its audio. On the multi-GPU path stage-2 audio- # runs under partial tiled/TDP video context, so the full-context stage-1 audio is kept.- video_state, _ = self.stage_2(- denoiser=SimpleDenoiser(v_context=v_context_p, a_context=a_context_p),+ upscaled = spatially_upsample_chunks(base, self.upsampler)+ refined = denoise_chunks(+ upscaled,+ self.stage_2,sigmas=stage_2_sigmas,- noiser=noiser,- width=width,- height=height,- frames=num_frames,+ noiser=ctx.noiser,fps=frame_rate,- video=ModalitySpec(- context=v_context_p,- conditionings=stage_2_conditionings,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=upscaled_video_latent,- ),- audio=ModalitySpec(- context=a_context_p,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=audio_state.latent,+ freeze_audio=True,+ )+ return (+ decode_chunks(+ refined,+ self.video_decoder,+ self.audio_decoder,+ fps=frame_rate,+ tiling_config=ctx.tiling_config,+ generator=ctx.generator,+ dtype=ctx.vae_dtype,+ keyframes=decode_with_keyframes,),+ ctx.num_frames,+ ctx.tiling_config,)- decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)- decoded_audio = self.audio_decoder(audio_state.latent)- return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)-@torch.inference_mode()def main() -> None:logging.basicConfig(level=logging.INFO)params = resolve_cli_params()- parser = add_generated_keyframes_arg(default_2_stage_arg_parser(params=params, supports_auto_duration=True))+ parser = add_chunk_layout_args(+ add_keyframe_decode_arg(+ add_generated_keyframes_arg(default_2_stage_arg_parser(params=params, supports_auto_duration=True))+ )+ )args = parser.parse_args()pipeline = TI2VidTwoStagesPipeline(model_paths=args.model_paths,@@ -330,7 +491,24 @@ def main() -> None:)hdr = resolve_hdr_color_space(images=args.images, hdr=args.hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- result = pipeline(+ chunk_config = chunk_config_from_args(args)+ video_guider_params = MultiModalGuiderParams(+ cfg_scale=args.video_cfg_guidance_scale,+ stg_scale=args.video_stg_guidance_scale,+ rescale_scale=args.video_rescale_scale,+ modality_scale=args.a2v_guidance_scale,+ skip_step=args.video_skip_step,+ stg_blocks=args.video_stg_blocks,+ )+ audio_guider_params = MultiModalGuiderParams(+ cfg_scale=args.audio_cfg_guidance_scale,+ stg_scale=args.audio_stg_guidance_scale,+ rescale_scale=args.audio_rescale_scale,+ modality_scale=args.v2a_guidance_scale,+ skip_step=args.audio_skip_step,+ stg_blocks=args.audio_stg_blocks,+ )+ chunks, num_frames, tiling_config = pipeline.stream_chunks(prompt=args.prompt,negative_prompt=args.negative_prompt,seed=args.seed,@@ -339,22 +517,8 @@ def main() -> None:num_frames=args.num_frames,frame_rate=args.frame_rate,num_inference_steps=args.num_inference_steps,- video_guider_params=MultiModalGuiderParams(- cfg_scale=args.video_cfg_guidance_scale,- stg_scale=args.video_stg_guidance_scale,- rescale_scale=args.video_rescale_scale,- modality_scale=args.a2v_guidance_scale,- skip_step=args.video_skip_step,- stg_blocks=args.video_stg_blocks,- ),- audio_guider_params=MultiModalGuiderParams(- cfg_scale=args.audio_cfg_guidance_scale,- stg_scale=args.audio_stg_guidance_scale,- rescale_scale=args.audio_rescale_scale,- modality_scale=args.v2a_guidance_scale,- skip_step=args.audio_skip_step,- stg_blocks=args.audio_stg_blocks,- ),+ video_guider_params=video_guider_params,+ audio_guider_params=audio_guider_params,images=args.images,vae_dtype=vae_dtype,color_space=hdr,@@ -363,15 +527,28 @@ def main() -> None:max_batch_size=args.max_batch_size,tiling_config=AUTO_TILING,generated_keyframes=args.num_generated_keyframes,+ decode_with_keyframes=args.decode_with_keyframes,+ chunk_config=chunk_config,)-+ if chunk_config is not None:+ video, audio, audio_sampling_rate = split_decoded_chunks(chunks)+ video_chunks_number = 1+ else:+ result = pipeline_output_from_chunks(+ chunks,+ num_frames=num_frames,+ tiling_config=tiling_config,+ )+ video, audio, audio_sampling_rate = result.video, result.audio, None+ video_chunks_number = get_video_chunks_number(result.num_frames, result.tiling_config)encode_video(- video=result.video,+ video=video,fps=args.frame_rate,- audio=result.audio,+ audio=audio,output_path=args.output_path,- video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),+ video_chunks_number=video_chunks_number,color_space=hdr,+ audio_sampling_rate=audio_sampling_rate,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq.py b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq.pyindex 824df73..854ea94 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq.py@@ -4,10 +4,10 @@ from collections.abc import Sequenceimport torchfrom ltx_core.allocator_trim_strategy import AllocatorTrimStrategy-from ltx_core.components.diffusion_steps import Res2sDiffusionStepfrom ltx_core.components.guiders import MultiModalGuider, MultiModalGuiderParamsfrom ltx_core.components.noisers import GaussianNoiserfrom ltx_core.components.schedulers import LTX2Scheduler+from ltx_core.conditioning import VideoGeneratedKeyframeSlotsfrom ltx_core.loader import LoraPathStrengthAndSDOpsfrom ltx_core.loader.registry import Registryfrom ltx_core.model.transformer.compiling import CompilationConfig@@ -16,8 +16,8 @@ from ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicyfrom ltx_core.types import VideoLatentShape, VideoPixelShapefrom ltx_pipelines.utils.args import (- ImageConditioningInput,add_generated_keyframes_arg,+ add_keyframe_decode_arg,hq_2_stage_arg_parser,)from ltx_pipelines.utils.blocks import (@@ -37,23 +37,34 @@ from ltx_pipelines.utils.constants import ()from ltx_pipelines.utils.denoisers import GuidedDenoiser, SimpleDenoiserfrom ltx_pipelines.utils.helpers import (+ assert_generated_keyframes_request,assert_resolution,combined_image_conditionings,+ create_initial_av_latents,+ decode_keyframes_from_slots,ensure_tiling_config,generated_keyframe_conditionings,get_device,- has_generated_keyframes,+ resolve_generated_keyframes,tiling_scale_factors_for_vae,)from ltx_pipelines.utils.media_io import (- HDRColorSpace,+ EXRColorSpace,encode_video,resolve_hdr_color_space,vae_dtype_for_hdr,)from ltx_pipelines.utils.model_paths import ModelPathsfrom ltx_pipelines.utils.samplers import res2s_audio_video_denoising_loop-from ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration, ModalitySpec, OffloadMode, PipelineOutput+from ltx_pipelines.utils.types import (+ DEFAULT_AUTO_DURATION,+ AutoDuration,+ ImageConditioningInput,+ ModalitySpec,+ OffloadMode,+ PipelineOutput,+ VideoAudio,+)class TI2VidTwoStagesHQPipeline:@@ -191,14 +202,14 @@ class TI2VidTwoStagesHQPipeline:max_batch_size: int = 1,stage_1_sigmas: torch.Tensor | None = None,stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS,- color_space: HDRColorSpace | None = None,+ color_space: EXRColorSpace | None = None,generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,) -> PipelineOutput:require_num_frames_source(num_frames, self.duration_predictor)images = self.image_conditioner.resolve_crf(images)assert_resolution(height=height, width=width, is_two_stage=True)- if has_generated_keyframes(generated_keyframes):- self.stage_1.assert_generated_keyframes_supported()+ assert_generated_keyframes_request(decode_with_keyframes, generated_keyframes, self.stage_1)generator = torch.Generator(device=self.device).manual_seed(seed)noiser = GaussianNoiser(generator=generator)@@ -231,8 +242,11 @@ class TI2VidTwoStagesHQPipeline:video_shape=VideoPixelShape(batch=1, frames=num_frames, height=height, width=width, fps=frame_rate),diffvae_optimization=self.video_decoder.diffvae_optimization,device=self.device,+ keyframes=decode_with_keyframes,)+ keyframe_positions = resolve_generated_keyframes(generated_keyframes, num_frames)+# Stage 1: Generate video at half resolution with CFG guidance using res2s sampler.stage_1_output_shape = VideoPixelShape(batch=1,@@ -254,8 +268,6 @@ class TI2VidTwoStagesHQPipeline:)stage_1_conditionings.extend(generated_keyframe_conditionings(generated_keyframes, num_frames))- stepper = Res2sDiffusionStep()-if stage_1_sigmas is None:empty_latent = torch.empty(VideoLatentShape.from_pixel_shape(@@ -266,6 +278,15 @@ class TI2VidTwoStagesHQPipeline:stage_1_sigmas = self._scheduler.execute(latent=empty_latent, steps=num_inference_steps)sigmas = stage_1_sigmas.to(dtype=torch.float32, device=self.device)+ video_latent, audio_latent = create_initial_av_latents(+ width=stage_1_output_shape.width,+ height=stage_1_output_shape.height,+ frames=num_frames,+ fps=frame_rate,+ device=self.device,+ dtype=self.dtype,+ video_scale_factors=self.stage_1.video_scale_factors,+ )video_state, audio_state = self.stage_1(denoiser=GuidedDenoiser(v_context=v_context_p,@@ -281,13 +302,19 @@ class TI2VidTwoStagesHQPipeline:),sigmas=sigmas,noiser=noiser,- stepper=stepper,- width=stage_1_output_shape.width,- height=stage_1_output_shape.height,- frames=num_frames,- fps=frame_rate,- video=ModalitySpec(context=v_context_p, conditionings=stage_1_conditionings),- audio=ModalitySpec(context=a_context_p),+ modalities=VideoAudio(+ video=ModalitySpec(+ latent=video_latent,+ conditioning_fps=frame_rate,+ context=v_context_p,+ conditionings=stage_1_conditionings,+ ),+ audio=ModalitySpec(+ latent=audio_latent,+ conditioning_fps=frame_rate,+ context=a_context_p,+ ),+ ),loop=res2s_audio_video_denoising_loop,max_batch_size=max_batch_size,)@@ -308,6 +335,15 @@ class TI2VidTwoStagesHQPipeline:color_space=color_space,))+ if decode_with_keyframes:+ if video_state.generated_keyframes is None:+ raise RuntimeError("Stage 1 did not return generated_keyframes despite requesting slots")+ stage_2_conditionings.append(+ VideoGeneratedKeyframeSlots(+ pixel_frame_indices=keyframe_positions,+ initial_keyframes=self.upsampler(video_state.generated_keyframes),+ )+ )# Stage 2 refines video only; discard its audio. On the multi-GPU path stage-2 audio# runs under partial tiled/TDP video context, so the full-context stage-1 audio is kept.@@ -315,34 +351,51 @@ class TI2VidTwoStagesHQPipeline:denoiser=SimpleDenoiser(v_context=v_context_p, a_context=a_context_p),sigmas=stage_2_sigmas,noiser=noiser,- stepper=stepper,- width=width,- height=height,- frames=num_frames,- fps=frame_rate,- video=ModalitySpec(- context=v_context_p,- conditionings=stage_2_conditionings,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=upscaled_video_latent,- ),- audio=ModalitySpec(- context=a_context_p,- noise_scale=stage_2_sigmas[0].item(),- initial_latent=audio_state.latent,+ modalities=VideoAudio(+ video=ModalitySpec(+ latent=upscaled_video_latent,+ conditioning_fps=frame_rate,+ context=v_context_p,+ conditionings=stage_2_conditionings,+ noise_scale=stage_2_sigmas[0].item(),+ ),+ audio=ModalitySpec(+ latent=audio_state.latent,+ conditioning_fps=frame_rate,+ context=a_context_p,+ noise_scale=stage_2_sigmas[0].item(),+ ),),loop=res2s_audio_video_denoising_loop,)- decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype)+ decode_keyframes = None+ if decode_with_keyframes:+ decode_keyframes = decode_keyframes_from_slots(+ video_state.generated_keyframes,+ keyframe_positions,+ num_frames,+ )+ if decode_keyframes is None:+ raise RuntimeError("decode_with_keyframes was set but no keyframe slots were produced")++ decoded_video = self.video_decoder(+ video_state.latent,+ tiling_config,+ generator,+ dtype=vae_dtype,+ keyframes=decode_keyframes,+ )decoded_audio = self.audio_decoder(audio_state.latent)- return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config, None, video_state.latent)+ return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config)@torch.inference_mode()def main() -> None:logging.basicConfig(level=logging.INFO)- parser = add_generated_keyframes_arg(hq_2_stage_arg_parser(params=LTX_2_3_HQ_PARAMS, supports_auto_duration=True))+ parser = add_keyframe_decode_arg(+ add_generated_keyframes_arg(hq_2_stage_arg_parser(params=LTX_2_3_HQ_PARAMS, supports_auto_duration=True))+ )args = parser.parse_args()pipeline = TI2VidTwoStagesHQPipeline(model_paths=args.model_paths,@@ -392,6 +445,7 @@ def main() -> None:max_batch_size=args.max_batch_size,tiling_config=AUTO_TILING,generated_keyframes=args.num_generated_keyframes,+ decode_with_keyframes=args.decode_with_keyframes,)encode_video(diff --git a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq_mgpu.py b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq_mgpu.pyindex b9ed69f..273fb35 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq_mgpu.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_hq_mgpu.py@@ -38,7 +38,7 @@ from ltx_pipelines.multigpu.vae_builders import DistributedDecoderBuilderfrom ltx_pipelines.multigpu.weight_tracker import TransformerWeightTrackerfrom ltx_pipelines.ti2vid_two_stages_hq import TI2VidTwoStagesHQPipelinefrom ltx_pipelines.utils.constants import TDP_DISTILLED_SIGMAS-from ltx_pipelines.utils.media_io import HDRColorSpace, encode_video, resolve_hdr_color_space, vae_dtype_for_hdr+from ltx_pipelines.utils.media_io import EXRColorSpace, encode_video, resolve_hdr_color_space, vae_dtype_for_hdrfrom ltx_pipelines.utils.model_paths import ModelPathsfrom ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration@@ -178,8 +178,9 @@ class TI2VidTwoStagesHQRunner(MGPURunner):images: list | None = None,enhance_prompt: bool = False,enhance_static_cache: bool = False,- hdr: HDRColorSpace | None = None,+ hdr: EXRColorSpace | None = None,generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,) -> Iterator[str | None]:# The pipeline raises ValueError on invalid input (symmetric across ranks); the controller# catches that and turns it into a recoverable RunnerError. Anything else is fatal.@@ -203,6 +204,7 @@ class TI2VidTwoStagesHQRunner(MGPURunner):enhance_prompt=enhance_prompt,enhance_static_cache=enhance_static_cache,generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,stage_2_sigmas=TDP_DISTILLED_SIGMAS,)if dist.get_rank() != _DRIVER_RANK:@@ -220,11 +222,13 @@ class TI2VidTwoStagesHQRunner(MGPURunner):if __name__ == "__main__":- from ltx_pipelines.utils.args import add_generated_keyframes_arg, hq_2_stage_arg_parser+ from ltx_pipelines.utils.args import add_generated_keyframes_arg, add_keyframe_decode_arg, hq_2_stage_arg_parserfrom ltx_pipelines.utils.constants import LTX_2_3_HQ_PARAMSlogging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")- parser = add_generated_keyframes_arg(hq_2_stage_arg_parser(params=LTX_2_3_HQ_PARAMS, supports_auto_duration=True))+ parser = add_keyframe_decode_arg(+ add_generated_keyframes_arg(hq_2_stage_arg_parser(params=LTX_2_3_HQ_PARAMS, supports_auto_duration=True))+ )args = parser.parse_args()vae_queue = torch.multiprocessing.get_context("spawn").SimpleQueue()@@ -272,6 +276,7 @@ if __name__ == "__main__":enhance_static_cache=args.enhance_static_cache,hdr=args.hdr,generated_keyframes=args.num_generated_keyframes,+ decode_with_keyframes=args.decode_with_keyframes,):pass # drive the job to completion; the runner writes the file as a side effectfinally:diff --git a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_mgpu.py b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_mgpu.pyindex 5699d42..d1f8196 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_mgpu.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/ti2vid_two_stages_mgpu.py@@ -21,12 +21,12 @@ from ltx_core.components.guiders import MultiModalGuiderParamsfrom ltx_core.loader import LTXV_LORA_COMFY_RENAMING_MAP, LoraPathStrengthAndSDOpsfrom ltx_core.loader.registry import ModelRegistryfrom ltx_core.model.transformer.compiling import CompilationConfig-from ltx_core.model.video_vae import get_video_chunks_numberfrom ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.multigpu.transformer.attention import AttentionManagerfrom ltx_core.quantization import QuantizationPolicyfrom ltx_core.quantization.fp8_cast import build_policy as _build_fp8_cast_policyfrom ltx_core.tiling import DimensionTilingConfig, TileCountConfig, balanced_tile_split+from ltx_pipelines.chunks import ChunkConfig, split_decoded_chunksfrom ltx_pipelines.multigpu.controller import MGPUControllerfrom ltx_pipelines.multigpu.gemma_builders import AccelerateGemmaBuilderfrom ltx_pipelines.multigpu.runner import MGPURunner@@ -36,7 +36,7 @@ from ltx_pipelines.multigpu.vae_builders import DistributedDecoderBuilderfrom ltx_pipelines.multigpu.weight_tracker import TransformerWeightTrackerfrom ltx_pipelines.ti2vid_two_stages import TI2VidTwoStagesPipelinefrom ltx_pipelines.utils.constants import TDP_DISTILLED_SIGMAS-from ltx_pipelines.utils.media_io import HDRColorSpace, encode_video, resolve_hdr_color_space, vae_dtype_for_hdr+from ltx_pipelines.utils.media_io import EXRColorSpace, encode_video, resolve_hdr_color_space, vae_dtype_for_hdrfrom ltx_pipelines.utils.model_paths import ModelPathsfrom ltx_pipelines.utils.types import DEFAULT_AUTO_DURATION, AutoDuration@@ -177,57 +177,72 @@ class TI2VidTwoStagesRunner(MGPURunner):images: list | None = None,enhance_prompt: bool = False,enhance_static_cache: bool = False,- hdr: HDRColorSpace | None = None,+ hdr: EXRColorSpace | None = None,generated_keyframes: int | Sequence[int] = 0,+ decode_with_keyframes: bool = False,+ chunk_config: ChunkConfig | None = None,) -> Iterator[str | None]:# The pipeline raises ValueError on invalid input (symmetric across ranks); the controller# catches that and turns it into a recoverable RunnerError. Anything else is fatal.hdr = resolve_hdr_color_space(images=images or [], hdr=hdr)vae_dtype = vae_dtype_for_hdr(hdr, torch.bfloat16)- result = self._pipeline(+ chunks, _, _ = self._pipeline.stream_chunks(prompt=prompt,negative_prompt=negative_prompt,seed=seed,height=height,width=width,- num_frames=num_frames,frame_rate=frame_rate,num_inference_steps=num_inference_steps,video_guider_params=video_guider_params,audio_guider_params=audio_guider_params,images=images or [],+ num_frames=num_frames,vae_dtype=vae_dtype,- color_space=hdr,tiling_config=None,enhance_prompt=enhance_prompt,enhance_static_cache=enhance_static_cache,- generated_keyframes=generated_keyframes,stage_2_sigmas=TDP_DISTILLED_SIGMAS,+ color_space=hdr,+ generated_keyframes=generated_keyframes,+ decode_with_keyframes=decode_with_keyframes,+ chunk_config=chunk_config,)if dist.get_rank() != _DRIVER_RANK:- yield None # workers: nothing to encode+ for _ in chunks:+ pass+ yield Nonereturn+ video, audio, audio_sampling_rate = split_decoded_chunks(chunks)encode_video(- video=result.video,+ video=video,fps=frame_rate,- audio=result.audio,+ audio=audio,output_path=output_path,- video_chunks_number=get_video_chunks_number(result.num_frames, result.tiling_config),+ video_chunks_number=1,color_space=hdr,+ audio_sampling_rate=audio_sampling_rate,)yield output_pathif __name__ == "__main__":from ltx_pipelines.utils.args import (+ add_chunk_layout_args,add_generated_keyframes_arg,+ add_keyframe_decode_arg,+ chunk_config_from_args,default_2_stage_arg_parser,resolve_cli_params,)logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")params = resolve_cli_params()- parser = add_generated_keyframes_arg(default_2_stage_arg_parser(params=params, supports_auto_duration=True))+ parser = add_chunk_layout_args(+ add_keyframe_decode_arg(+ add_generated_keyframes_arg(default_2_stage_arg_parser(params=params, supports_auto_duration=True))+ )+ )args = parser.parse_args()vae_queue = torch.multiprocessing.get_context("spawn").SimpleQueue()@@ -273,6 +288,8 @@ if __name__ == "__main__":enhance_static_cache=args.enhance_static_cache,hdr=args.hdr,generated_keyframes=args.num_generated_keyframes,+ decode_with_keyframes=args.decode_with_keyframes,+ chunk_config=chunk_config_from_args(args),):pass # drive the job to completion; the runner writes the file as a side effectfinally:diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/__init__.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/__init__.pyindex af47961..6d0cc5e 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/__init__.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/__init__.py@@ -9,7 +9,9 @@ from ltx_pipelines.utils.blocks import ()from ltx_pipelines.utils.denoisers import FactoryGuidedDenoiser, GuidedDenoiser, SimpleDenoiserfrom ltx_pipelines.utils.helpers import (+ assert_generated_keyframes_request,assert_resolution,+ assert_stage_supports_generated_keyframes,cleanup_memory,combined_image_conditionings,decode_keyframes_from_slots,@@ -26,7 +28,14 @@ from ltx_pipelines.utils.samplers import (gradient_estimating_euler_denoising_loop,res2s_audio_video_denoising_loop,)-from ltx_pipelines.utils.types import DenoisedLatentResult, Denoiser, ModalitySpec, PipelineOutput+from ltx_pipelines.utils.types import (+ DenoisedLatentResult,+ Denoiser,+ ImageConditioningInput,+ ModalitySpec,+ PipelineOutput,+ VideoAudio,+)__all__ = ["AudioConditioner",@@ -37,13 +46,17 @@ __all__ = ["FactoryGuidedDenoiser","GuidedDenoiser","ImageConditioner",+ "ImageConditioningInput","ModalitySpec","PipelineOutput","PromptEncoder","SimpleDenoiser",+ "VideoAudio","VideoDecoder","VideoUpsampler",+ "assert_generated_keyframes_request","assert_resolution",+ "assert_stage_supports_generated_keyframes","cleanup_memory","combined_image_conditionings","decode_keyframes_from_slots",diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/args.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/args.pyindex 1a98735..e369035 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/args.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/args.py@@ -1,46 +1,73 @@import argparse+import enumimport jsonimport loggingimport sysfrom collections.abc import Sequencefrom pathlib import Path-from typing import Any, NamedTuple+from typing import Anyfrom ltx_core.loader import LTXV_LORA_COMFY_RENAMING_MAP, LoraPathStrengthAndSDOpsfrom ltx_core.model.transformer.compiling import CompilationConfigfrom ltx_core.model.video_vae.transformer import DiffVAEModefrom ltx_core.quantization import QuantizationPolicy+from ltx_pipelines.chunks import ChunkConfigfrom ltx_pipelines.utils.constants import (DEFAULT_LORA_STRENGTH,DEFAULT_NEGATIVE_PROMPT,LTX_2_3_HQ_PARAMS,LTX_2_3_PARAMS,+ LTX_2_4_PARAMS,PipelineParams,detect_params,)+from ltx_pipelines.utils.media_io.color_config import EXRColorSpace+from ltx_pipelines.utils.media_io.exr import is_exr_dir+from ltx_pipelines.utils.media_io.inputs import EXRVideoInput, VideoInputfrom ltx_pipelines.utils.quantization_factory import QuantizationKind-from ltx_pipelines.utils.types import AutoDuration, OffloadMode+from ltx_pipelines.utils.types import AutoDuration, ImageConditioningInput, OffloadModelogger = logging.getLogger(__name__)+class HDRICLoraInputColorSpace(str, enum.Enum):+ """Supported HDR IC-LoRA input colorspaces."""++ SRGB_GAMMA = "srgb_gamma"+ SRGB = "srgb"+ ACESCG = "acescg"+ ACESCCT = "acescct"+++_VIDEO_GAMMA: dict[HDRICLoraInputColorSpace, bool] = {+ HDRICLoraInputColorSpace.SRGB_GAMMA: True,+ HDRICLoraInputColorSpace.SRGB: False,+}++_EXR_SPACES: dict[HDRICLoraInputColorSpace, EXRColorSpace] = {+ HDRICLoraInputColorSpace.SRGB: EXRColorSpace.SRGB_LINEAR,+ HDRICLoraInputColorSpace.ACESCG: EXRColorSpace.ACESCG,+ HDRICLoraInputColorSpace.ACESCCT: EXRColorSpace.ACESCCT,+}++_VIDEO_SUFFIXES = frozenset({".mp4", ".mov"})++def add_hdr_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:"""Add ``--hdr`` colour-space flag. Behaviour is implemented in ``media_io``."""- from ltx_pipelines.utils.media_io.color_config import HDRColorSpace # noqa: PLC0415+ names = [m.name for m in EXRColorSpace]- names = [m.name for m in HDRColorSpace]-- def _parse_hdr(value: str) -> HDRColorSpace:+ def _parse_hdr(value: str) -> EXRColorSpace:key = value.upper()try:- return HDRColorSpace[key]+ return EXRColorSpace[key]except KeyError as exc:raise argparse.ArgumentTypeError(f"invalid --hdr {value!r}; choose from {', '.join(names)}") from excparser.add_argument("--hdr",type=_parse_hdr,- choices=[HDRColorSpace[n] for n in names],+ choices=[EXRColorSpace[n] for n in names],default=None,metavar="{" + ",".join(names) + "}",help=(@@ -51,20 +78,6 @@ def add_hdr_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:return parser-class ImageConditioningInput(NamedTuple):- """An image to condition on, with the H.264 CRF it should be re-compressed at.- Leaving ``crf`` unset means "use whatever matches the model": the pipeline fills it in- from the checkpoint it runs (``ImageConditioner.resolve_crf``), since the value the model- was trained with is a property of the model generation. Pass ``crf`` explicitly to- override it, including ``0`` to skip re-compression entirely.- """-- path: str- frame_idx: int- strength: float- crf: int | None = None--class VideoConditioningAction(argparse.Action):def __call__(self,@@ -366,22 +379,7 @@ def _resolve_num_frames(namespace: argparse.Namespace) -> None:namespace.num_frames = namespace.auto_duration if namespace.auto_duration is not None else AutoDuration()-def _is_exr_file(path: str | Path) -> bool:- return Path(path).is_file() and str(path).lower().endswith(".exr")---def _verify_sequence_path(flag: str, path: str) -> None:- """Video/sequence flags accept a video file or a directory of ``*.exr`` frames."""- from ltx_pipelines.utils.media_io import is_exr_dir # noqa: PLC0415-- p = Path(path)- if _is_exr_file(path):- raise SystemExit(f"{flag} '{path}' is a single .exr file; pass a directory of *.exr frames.")- if p.is_dir() and not is_exr_dir(path):- raise SystemExit(f"{flag} '{path}' is a directory without *.exr frames.")---def _verify_media_path_args(namespace: argparse.Namespace) -> None: # noqa: PLR0912+def _verify_media_path_args(namespace: argparse.Namespace) -> None:"""Validate HDR/SDR path shapes and couple retake ``--frame-rate`` to EXR folders.Rules:* ``--image``: a still file (``.exr`` or PNG/JPEG). Not a directory.@@ -393,8 +391,6 @@ def _verify_media_path_args(namespace: argparse.Namespace) -> None: # noqa: PLR* Dub-It ``--reference-video``: video file only (fps + audio from the container). EXRfolders / single ``.exr`` files are rejected."""- from ltx_pipelines.utils.media_io import is_exr_dir # noqa: PLC0415-modality: list[tuple[str, str, bool]] = [] # (flag, path, is_exr)for img in getattr(namespace, "images", None) or []:@@ -437,17 +433,7 @@ def _verify_media_path_args(namespace: argparse.Namespace) -> None: # noqa: PLRif is_exr_dir(video_path):modality.append(("--video-path", video_path, True))if hasattr(namespace, "frame_rate"):- if is_exr_dir(video_path):- if namespace.frame_rate is None:- raise SystemExit(- f"--video-path '{video_path}' is an EXR-frame folder; --frame-rate is required "- "(EXR sequences have no container fps)."- )- elif namespace.frame_rate is not None:- raise SystemExit(- "--frame-rate is only valid when --video-path is an EXR-frame folder; "- "for video files the container fps is used."- )+ _verify_sequence_frame_rate("--video-path", video_path, namespace.frame_rate)if any(is_exr for _, _, is_exr in modality) and getattr(namespace, "hdr", None) is None:raise SystemExit("EXR input requires --hdr {SRGB_LINEAR,ACESCG,ACESCCT} to declare the source colour space.")@@ -464,9 +450,79 @@ class _PipelineArgumentParser(argparse.ArgumentParser):_resolve_model_paths(ns)_resolve_num_frames(ns)_verify_media_path_args(ns)+ _resolve_hdr_ic_lora_input(ns)return ns+def _is_exr_file(path: str | Path) -> bool:+ return Path(path).is_file() and str(path).lower().endswith(".exr")+++def _verify_sequence_path(flag: str, path: str) -> None:+ """Video/sequence flags accept a video file or a directory of ``*.exr`` frames."""+ p = Path(path)+ if _is_exr_file(path):+ raise SystemExit(f"{flag} '{path}' is a single .exr file; pass a directory of *.exr frames.")+ if p.is_dir() and not is_exr_dir(path):+ raise SystemExit(f"{flag} '{path}' is a directory without *.exr frames.")+++def _verify_sequence_frame_rate(flag: str, path: str, frame_rate: float | None) -> None:+ """Require ``--frame-rate`` for EXR-frame folders; forbid it for video files."""+ if is_exr_dir(path):+ if frame_rate is None:+ raise SystemExit(+ f"{flag} '{path}' is an EXR-frame folder; --frame-rate is required "+ "(EXR sequences have no container fps)."+ )+ elif frame_rate is not None:+ raise SystemExit(+ f"--frame-rate is only valid when {flag} is an EXR-frame folder; for video files the container fps is used."+ )+++def _resolve_hdr_ic_lora_input(namespace: argparse.Namespace) -> None:+ """Map ``--input`` / ``--input-colorspace`` / ``--frame-rate`` to VideoInput or EXRVideoInput."""+ has_input = hasattr(namespace, "input")+ has_colorspace = hasattr(namespace, "input_colorspace")+ if has_input != has_colorspace:+ raise SystemExit("--input and --input-colorspace are required together")+ if not has_colorspace:+ return+ input_path = namespace.input+ if input_path is None:+ raise SystemExit("HDR IC-LoRA requires --input")++ _verify_sequence_path("--input", input_path)++ try:+ cs = HDRICLoraInputColorSpace(namespace.input_colorspace)+ except ValueError:+ raise SystemExit(+ f"invalid --input-colorspace {namespace.input_colorspace!r}; "+ f"expected one of {', '.join(m.value for m in HDRICLoraInputColorSpace)}"+ ) from None++ path = Path(input_path)+ fps = getattr(namespace, "frame_rate", None)++ if not is_exr_dir(path):+ if path.suffix.lower() not in _VIDEO_SUFFIXES:+ raise SystemExit(f"expected an MP4/MOV file or a directory of *.exr frames; got {path}")+ if cs not in _VIDEO_GAMMA:+ raise SystemExit(f"--input-colorspace {cs.value} expects a directory of *.exr frames; got {path}")+ if fps is not None:+ raise SystemExit("--frame-rate is only valid for an EXR-frame folder")+ namespace.input = VideoInput(path, gamma_encoded=_VIDEO_GAMMA[cs])+ return++ if cs not in _EXR_SPACES:+ raise SystemExit(f"--input-colorspace {cs.value} expects an MP4/MOV file; got EXR frames at {path}")+ if fps is None:+ raise SystemExit("EXR-frame folder requires --frame-rate")+ namespace.input = EXRVideoInput(path, color_space=_EXR_SPACES[cs], frame_rate=fps)++def detect_checkpoint_path(distilled: bool = False) -> str:"""Pre-parse argv to extract the checkpoint path before building the full parser.Prefers monolith ``--checkpoint-path`` / ``--distilled-checkpoint-path``, then@@ -505,11 +561,24 @@ def resolve_cli_params(distilled: bool = False) -> PipelineParams:return detect_params(detect_checkpoint_path(distilled=distilled))-def basic_arg_parser(- params: PipelineParams = LTX_2_3_PARAMS,+def add_model_args(+ parser: argparse.ArgumentParser,+ *,+ params: PipelineParams,distilled: bool = False,+ text_encoder: bool = True,+ audio_vae: bool = True,+ duration_head: bool = True,) -> argparse.ArgumentParser:- parser = _PipelineArgumentParser()+ """Add the model-component path flags.+ One flag group per component, so a pipeline declares only the components it loads and+ ``model_paths_from_namespace`` sees exactly those. Turning a component off matters beyond+ tidiness for ``text_encoder``: that switch covers ``--gemma-root`` *and*+ ``--text-encoder-path``, the monolith and split halves of one component, and+ ``model_paths_from_namespace`` requires ``--gemma-root`` in monolith mode only when the+ parser declares it. A CLI with precomputed embeddings must therefore leave it out rather+ than accept it and ignore it.+ """if distilled:parser.add_argument("--distilled-checkpoint-path",@@ -541,16 +610,17 @@ def basic_arg_parser(f"Higher values improve quality but increase generation time (default: {params.num_inference_steps})."),)- parser.add_argument(- "--gemma-root",- type=resolve_existing_path,- required=False,- default=None,- help=(- "Path to the Gemma text encoder HF directory (monolith mode). "- "Omit when using --text-encoder-path (split single-file TE)."- ),- )+ if text_encoder:+ parser.add_argument(+ "--gemma-root",+ type=resolve_existing_path,+ required=False,+ default=None,+ help=(+ "Path to the Gemma text encoder HF directory (monolith mode). "+ "Omit when using --text-encoder-path (split single-file TE)."+ ),+ )parser.add_argument("--transformer-path",type=resolve_existing_path,@@ -560,12 +630,13 @@ def basic_arg_parser("Provide the subset of split flags this pipeline needs; unused may be omitted."),)- parser.add_argument(- "--text-encoder-path",- type=resolve_existing_path,- default=None,- help="Split layout: Gemma + text_embedding_projection single-file safetensors.",- )+ if text_encoder:+ parser.add_argument(+ "--text-encoder-path",+ type=resolve_existing_path,+ default=None,+ help="Split layout: Gemma + text_embedding_projection single-file safetensors.",+ )parser.add_argument("--video-vae-path",type=resolve_existing_path,@@ -576,18 +647,83 @@ def basic_arg_parser("(e.g. a distilled DiffVAE). Decoder kind is selected from file metadata."),)+ if audio_vae:+ parser.add_argument(+ "--audio-vae-path",+ type=resolve_existing_path,+ default=None,+ help="Split layout: audio VAE + vocoder safetensors.",+ )+ if duration_head:+ parser.add_argument(+ "--duration-head-path",+ type=resolve_existing_path,+ default=None,+ help="Split layout: duration head safetensors (omit if unused / unavailable).",+ )+ return parser+++def add_seed_arg(+ parser: argparse.ArgumentParser,+ *,+ params: PipelineParams,+) -> argparse.ArgumentParser:+ """Add ``--seed``."""parser.add_argument(- "--audio-vae-path",- type=resolve_existing_path,- default=None,- help="Split layout: audio VAE + vocoder safetensors.",+ "--seed",+ type=int,+ default=params.seed,+ help=f"Random seed for reproducible generation (default: {params.seed}).",)+ return parser+++def add_offload_arg(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:+ """Add ``--offload``, the weight offloading strategy."""parser.add_argument(- "--duration-head-path",- type=resolve_existing_path,- default=None,- help="Split layout: duration head safetensors (omit if unused / unavailable).",+ "--offload",+ dest="offload_mode",+ type=OffloadMode,+ default=OffloadMode.NONE,+ choices=list(OffloadMode),+ help=(+ "Weight offloading strategy. "+ "'none' keeps all weights on GPU (default). "+ "'cpu' pins weights in CPU RAM, streams to GPU per layer. "+ "'disk' reads weights from disk on demand (lowest memory). "+ "Example: --offload cpu"+ ),)+ return parser+++def add_diffvae_optimization_arg(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:+ """Add ``--diffvae-optimization``, the DiffVAE decode preset."""+ parser.add_argument(+ "--diffvae-optimization",+ type=DiffVAEMode,+ default=DiffVAEMode.CHUNKED_EAGER,+ choices=list(DiffVAEMode),+ help=(+ "DiffVAE decode optimization preset. "+ "'chunked_eager' (default): deferred stage-4, W-chunks=4, cutlass-fna. "+ "'chunked_compile': same chunking with torch.compile (det stages off). "+ "'combined_compile': combined context, full compile (highest VRAM, fastest warm). "+ "'blackwell_dsl': deferred stage-4 + CuTe DSL NA/fused stage-5 (datacenter Blackwell). "+ "Ignored for convolutional VAEs. "+ "Example: --diffvae-optimization combined_compile"+ ),+ )+ return parser+++def basic_arg_parser(+ params: PipelineParams = LTX_2_3_PARAMS,+ distilled: bool = False,+) -> argparse.ArgumentParser:+ parser = _PipelineArgumentParser()+ add_model_args(parser, params=params, distilled=distilled)parser.add_argument("--prompt",type=str,@@ -600,12 +736,7 @@ def basic_arg_parser(required=True,help="Path to the output video file (MP4 format).",)- parser.add_argument(- "--seed",- type=int,- default=params.seed,- help=f"Random seed for reproducible generation (default: {params.seed}).",- )+ add_seed_arg(parser, params=params)parser.add_argument("--lora",dest="lora",@@ -650,21 +781,7 @@ def basic_arg_parser(except ValueError as e:raise argparse.ArgumentTypeError(f"must be an integer, got {value}") from e- # Weight offloading- parser.add_argument(- "--offload",- dest="offload_mode",- type=OffloadMode,- default=OffloadMode.NONE,- choices=list(OffloadMode),- help=(- "Weight offloading strategy. "- "'none' keeps all weights on GPU (default). "- "'cpu' pins weights in CPU RAM, streams to GPU per layer. "- "'disk' reads weights from disk on demand (lowest memory). "- "Example: --offload cpu"- ),- )+ add_offload_arg(parser)parser.add_argument("--max-batch-size",@@ -713,21 +830,7 @@ def basic_arg_parser("--compile inductor_config='{\"max_autotune\": true}'"),)- parser.add_argument(- "--diffvae-optimization",- type=DiffVAEMode,- default=DiffVAEMode.CHUNKED_EAGER,- choices=list(DiffVAEMode),- help=(- "DiffVAE decode optimization preset. "- "'chunked_eager' (default): deferred stage-4, W-chunks=4, cutlass-fna. "- "'chunked_compile': same chunking with torch.compile (det stages off). "- "'combined_compile': combined context, full compile (highest VRAM, fastest warm). "- "'blackwell_dsl': deferred stage-4 + CuTe DSL NA/fused stage-5 (datacenter Blackwell). "- "Ignored for convolutional VAEs. "- "Example: --diffvae-optimization combined_compile"- ),- )+ add_diffvae_optimization_arg(parser)return parser@@ -855,6 +958,88 @@ def add_generated_keyframes_arg(parser: argparse.ArgumentParser) -> argparse.Argreturn parser+def add_keyframe_decode_arg(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:+ """Add ``--decode-with-keyframes`` to a pipeline that supports generated keyframe slots."""+ parser.add_argument(+ "--decode-with-keyframes",+ action="store_true",+ default=False,+ help=(+ "Decode the output video through the keyframe-aware DiffVAE path, using the "+ "generated keyframe slots as anchors. Requires --num-generated-keyframes > 0 and "+ "a keyframe-trained video VAE. Conv VAEs log a warning and decode without anchors."+ ),+ )+ return parser+++def chunk_config_from_args(args: argparse.Namespace) -> ChunkConfig | None:+ """Build ``ChunkConfig`` from CLI args, or ``None`` when chunking is disabled."""+ chunked = getattr(args, "chunked", False)+ chunk_pixel_frames = getattr(args, "chunk_pixel_frames", None)+ chunk_carry_frames = getattr(args, "chunk_carry_frames", None)+ chunk_blend_frames = getattr(args, "chunk_blend_frames", None)+ if not chunked and chunk_pixel_frames is None and chunk_carry_frames is None and chunk_blend_frames is None:+ return None+ kwargs: dict[str, int] = {}+ if chunk_pixel_frames is not None:+ kwargs["chunk_pixel_frames"] = chunk_pixel_frames+ if chunk_carry_frames is not None:+ kwargs["next_video_carry_frames"] = chunk_carry_frames+ if chunk_blend_frames is not None:+ kwargs["overlap_blend_frames"] = chunk_blend_frames+ return ChunkConfig(**kwargs)+++def add_chunk_layout_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:+ """Add chunking flags for long-video mode.+ With ``--chunked`` or any layout flag, ``stream_chunks`` uses a windowed layout.+ Omitted sizing values use ``ChunkConfig`` defaults (97 pixel frames, 25-pixel carry,+ crossfade over the full carry). With no chunk flags, the clip runs as one window.+ """+ parser.add_argument(+ "--chunked",+ action="store_true",+ help=(+ "Generate long clips in overlapping temporal windows using the default chunk "+ "layout (97-frame windows, 25-frame carry, crossfade over the full overlap). "+ "Override the layout with --chunk-pixel-frames, --chunk-carry-frames, "+ "and --chunk-blend-frames."+ ),+ )+ parser.add_argument(+ "--chunk-pixel-frames",+ type=int,+ default=None,+ help=(+ "Pixel frames in each chunked window (default: 97 when --chunk-carry-frames is set). "+ "Must be a causal-grid length such as 97 (8k+1). The stitched clip floors --num-frames "+ "to the causal grid when it is off-grid (for example 240 becomes 233); smaller windows "+ "produce more chunks."+ ),+ )+ parser.add_argument(+ "--chunk-carry-frames",+ type=int,+ default=None,+ help=(+ "Pixel frames each chunk passes to the next chunk for overlap continuity "+ "(default: 25 when --chunk-pixel-frames is set). Must be on the causal grid (8k+1), "+ "at least 17 when chunking, and less than the chunk window."+ ),+ )+ parser.add_argument(+ "--chunk-blend-frames",+ type=int,+ default=None,+ help=(+ "Decoded video frames crossfaded at each chunk seam (default: the full carry). "+ "Must be between 0 and --chunk-carry-frames; 0 uses a hard cut."+ ),+ )+ return parser++def video_editing_arg_parser(distilled: bool = True,) -> argparse.ArgumentParser:@@ -887,6 +1072,120 @@ def video_editing_arg_parser(return parser+def hdr_ic_lora_arg_parser(params: PipelineParams = LTX_2_4_PARAMS) -> argparse.ArgumentParser:+ """Argument parser for ACEScct SDR→HDR IC-LoRA (one-stage).+ Media checks (``--input`` / ``--input-colorspace`` / ``--frame-rate``) run inside+ :class:`_PipelineArgumentParser.parse_args`.+ """++ def _parse_exr_colorspace(value: str) -> EXRColorSpace:+ key = value.upper()+ try:+ return EXRColorSpace[key]+ except KeyError as exc:+ raise argparse.ArgumentTypeError(+ f"invalid --exr-colorspace {value!r}; choose from {', '.join(cs.value for cs in EXRColorSpace)}"+ ) from exc++ parser = _PipelineArgumentParser(+ description="ACEScct SDR→HDR IC-LoRA (one-stage). CLI: IDT + EXR/HLG via encode_video.",+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,+ )+ parser.add_argument(+ "--input",+ type=resolve_existing_path,+ required=True,+ help=(+ "One input: MP4/MOV when --input-colorspace is srgb_gamma or srgb, or a directory of "+ "*.exr frames when srgb, acescg, or acescct. "+ "Output length matches the source (frame count must be 8k+1)."+ ),+ )+ parser.add_argument(+ "--output-path",+ type=resolve_path,+ required=True,+ help="Path to the HLG master MP4 (EXR frames go beside it as <stem>_<exr-colorspace>_exr/).",+ )+ parser.add_argument(+ "--exr-colorspace",+ type=_parse_exr_colorspace,+ choices=list(EXRColorSpace),+ default=EXRColorSpace.ACESCG,+ metavar="{" + ",".join(cs.value for cs in EXRColorSpace) + "}",+ help=(+ "Colour space of the EXR sidecar beside --output-path. "+ "acescg / srgb_linear write scene-linear; acescct writes VAE log codes. "+ "HLG master is always BT.2020/HLG. Default: acescg."+ ),+ )+ parser.add_argument("--hdr-lora", type=resolve_existing_path, required=True)+ parser.add_argument(+ "--text-embeddings",+ type=resolve_existing_path,+ required=True,+ help=".safetensors with video_context.",+ )+ # Prompts arrive as precomputed embeddings and there is no audio or duration prediction,+ # so only the transformer and video VAE components are declared.+ add_model_args(+ parser,+ params=params,+ distilled=True,+ text_encoder=False,+ audio_vae=False,+ duration_head=False,+ )+ parser.add_argument(+ "--input-colorspace",+ type=HDRICLoraInputColorSpace,+ choices=list(HDRICLoraInputColorSpace),+ default=HDRICLoraInputColorSpace.SRGB_GAMMA,+ help=(+ "Source encoding: srgb_gamma=display MP4/MOV (EOTF→ACEScct); "+ "srgb=linear Rec.709 MP4/MOV or EXR directory; acescg/acescct=EXR directory."+ ),+ )+ parser.add_argument(+ "--frame-rate",+ type=float,+ default=None,+ help="Required for EXR-frame directories; must not be set for MP4/MOV (container fps).",+ )+ add_seed_arg(parser, params=params)+ parser.add_argument(+ "--high-quality",+ action="store_true",+ help=(+ "High-quality HDR mode. Generates at 2x frame count internally "+ "and keeps every other frame for smoother output. ~2x slower."+ ),+ )+ add_offload_arg(parser)+ parser.add_argument("--no-quantization", action="store_true", help="Disable FP8 cast on the transformer.")+ add_diffvae_optimization_arg(parser)+ parser.add_argument(+ "--no-keyframes",+ action="store_true",+ help=(+ "Disable DFR-style seam keyframes. They are on by default: every "+ "resolve_canvas x8 border gets a generated HDR slot and a 1-frame SDR "+ "guide. Requires a transformer with use_keyframes_abs_pos_embedding "+ "and --video-vae-path pointing at a keyframe-trained video VAE."+ ),+ )+ parser.add_argument(+ "--keyframe-strength",+ type=float,+ default=0.95,+ help=(+ "DFR seam keyframe strength when keyframes are on (the default; "+ "ignored with --no-keyframes). Default: 0.95."+ ),+ )+ return parser++def dubit_arg_parser(params: PipelineParams = LTX_2_3_PARAMS,) -> argparse.ArgumentParser:diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/blocks.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/blocks.pyindex 03d41de..e279c41 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/blocks.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/blocks.py@@ -18,11 +18,9 @@ import torchfrom ltx_core.allocator_trim_strategy import AllocatorTrimStrategyfrom ltx_core.batch_split import BatchSplitAdapterfrom ltx_core.block_streaming import DISK_CPU_SLOTS, StreamingModelBuilder-from ltx_core.components.diffusion_steps import EulerDiffusionStepfrom ltx_core.components.noisers import Noiserfrom ltx_core.components.patchifiers import AudioPatchifier, VideoLatentPatchifier-from ltx_core.components.protocols import DiffusionStepProtocol-from ltx_core.conditioning import VideoGeneratedKeyframeSlots+from ltx_core.conditioning import ConditioningItem, VideoGeneratedKeyframeSlotsfrom ltx_core.duration_head import (DURATION_HEAD_KEY_OPS,DurationHead,@@ -99,12 +97,11 @@ from ltx_core.types import (LatentState,SpatioTemporalScaleFactors,VideoLatentShape,- VideoPixelShape,)-from ltx_pipelines.utils.args import ImageConditioningInputfrom ltx_pipelines.utils.constants import detect_paramsfrom ltx_pipelines.utils.gpu_model import gpu_modelfrom ltx_pipelines.utils.helpers import (+ assert_stage_supports_generated_keyframes,cleanup_memory,create_noised_state,generate_enhanced_prompt,@@ -112,7 +109,14 @@ from ltx_pipelines.utils.helpers import ()from ltx_pipelines.utils.model_paths import ModelPathsfrom ltx_pipelines.utils.samplers import euler_denoising_loop-from ltx_pipelines.utils.types import AutoDuration, Denoiser, ModalitySpec, OffloadMode+from ltx_pipelines.utils.types import (+ AutoDuration,+ Denoiser,+ ImageConditioningInput,+ ModalitySpec,+ OffloadMode,+ VideoAudio,+)_ENCODE_MODEL_TYPES = frozenset({"gemma3", "gemma4", "gemma4_unified"})@@ -126,6 +130,8 @@ ModelWrapper = Callable[[torch.nn.Module, "LatentTools | None"], torch.nn.ModuleT = TypeVar("T")_M = TypeVar("_M", bound=torch.nn.Module)+DenoisingLoop = Callable[..., VideoAudio[LatentState]]+# ---------------------------------------------------------------------------# Internal helpers@@ -230,7 +236,7 @@ def _build_state(dtype=dtype,device=device,noise_scale=spec.noise_scale,- initial_latent=spec.initial_latent,+ initial_latent=spec.latent,)if spec.frozen:state = replace(@@ -320,22 +326,13 @@ class DiffusionStage:``__init__`` itself takes an already-built builder.``model_configurator`` / ``model_sd_ops`` let callers (e.g. the audio-onlyT2A pipeline) override the model class configurator and the state-dict key- mapping. A quantization policy that pins its own configurator takes- precedence over ``model_configurator``.+ mapping."""- # A quantization policy may pin its own configurator; otherwise use the one- # provided by the caller (defaults to the audio-video LTXModelConfigurator).- configurator = (- quantization.model_configurator- if quantization is not None and quantization.model_configurator is not None- else model_configurator- )-transformer_builder: ModelBuilderProtocol[LTXModelProtocol]if offload_mode == OffloadMode.NONE:transformer_builder = Builder(model_path=checkpoint_path,- model_class_configurator=configurator,+ model_class_configurator=model_configurator,model_sd_ops=model_sd_ops,loras=tuple(loras),registry=registry or ModelRegistry(cache_models=True, cache_weights=False),@@ -343,7 +340,7 @@ class DiffusionStage:else:transformer_builder = cls._build_streaming_builder(checkpoint_path=checkpoint_path,- configurator=configurator,+ configurator=model_configurator,model_sd_ops=model_sd_ops,loras=tuple(loras),quantization=quantization,@@ -409,27 +406,21 @@ class DiffusionStage:transformer_config = self._transformer_builder.model_config().get("transformer", {})return bool(transformer_config.get("use_keyframes_abs_pos_embedding", False))- def assert_generated_keyframes_supported(self) -> None:- """Raise unless this stage's checkpoint declares the keyframe embedding.- Call this from a pipeline's ``__call__`` preamble, before any model is built: the answer- comes from the checkpoint config alone, so an unsupported request should fail immediately- rather than after the text encoder has been loaded. :meth:`__call__` re-checks as a backstop- for callers that build conditioning items directly.- """- if self.supports_generated_keyframes:+ def _assert_supports_conditionings(self, conditionings: Sequence[ConditioningItem] | None) -> None:+ if conditionings is None or self.supports_generated_keyframes:return- raise ValueError(- f"Generated keyframe slots were requested, but the checkpoint at "- f"{self._transformer_builder.checkpoint} does not set 'use_keyframes_abs_pos_embedding' "- f"in its transformer config, so it has no keyframe absolute-position embedding. Use a "- f"generated-keyframe checkpoint or drop the keyframe request."- )+ if any(isinstance(item, VideoGeneratedKeyframeSlots) for item in conditionings):+ assert_stage_supports_generated_keyframes(self)- def _assert_supports_conditionings(self, video: ModalitySpec | None) -> None:- if video is None or self.supports_generated_keyframes:- return- if any(isinstance(item, VideoGeneratedKeyframeSlots) for item in video.conditionings):- self.assert_generated_keyframes_supported()+ @property+ def dtype(self) -> torch.dtype:+ """Dtype this stage builds its transformer and sizes its latents in."""+ return self._dtype++ @property+ def device(self) -> torch.device:+ """Device this stage builds its transformer and sizes its latents on."""+ return self._devicedef with_attention(self, attention: AttentionFunction | AttentionCallable | None) -> "DiffusionStage":"""Return a new ``DiffusionStage`` that pins the transformer build to ``attention``.@@ -519,76 +510,70 @@ class DiffusionStage:return self._streaming_transformer_ctx()return gpu_model(self._build_transformer(**kwargs), alloc_trim_strategy=self._alloc_trim_strategy)- def __call__( # noqa: PLR0913+ def __call__(self,denoiser: Denoiser,sigmas: torch.Tensor,noiser: Noiser,- width: int,- height: int,- frames: int,- fps: float,- video: ModalitySpec | None = None,- audio: ModalitySpec | None = None,- stepper: DiffusionStepProtocol | None = None,- loop: Callable[..., tuple[LatentState | None, LatentState | None]] | None = None,+ modalities: VideoAudio[ModalitySpec],+ loop: DenoisingLoop | None = None,max_batch_size: int = 1,- audio_fps: float | None = None,- ) -> tuple[LatentState | None, LatentState | None]:+ ) -> VideoAudio[LatentState]:"""Build transformer -> run denoising loop -> free transformer.- Returns ``(video_state | None, audio_state | None)`` with cleared- conditionings and unpatchified latents for present modalities.- ``fps`` is the transformer's time base: it sets RoPE time (``pixel_frame / fps``)- and, by default, the audio latent's duration (``frames / fps``). ``audio_fps``- decouples the two for callers that hand the transformer a time base other than the- clip's real frame rate -- audio is then sized from ``frames / audio_fps``, so its- duration still matches playback. Omitted -> same as ``fps``.+ Returns a :class:`VideoAudio` of unpatchified :class:`LatentState` with cleared+ conditionings for present modalities."""+ video, audio = modalitiesif video is None and audio is None:- raise ValueError("At least one of `video` or `audio` must be provided")- self._assert_supports_conditionings(video)+ raise ValueError("At least one of `modalities.video` or `modalities.audio` must be provided")+ if video is not None:+ self._assert_supports_conditionings(video.conditionings)if loop is None:loop = euler_denoising_loop- if stepper is None:- stepper = EulerDiffusionStep()- pixel_shape = VideoPixelShape(batch=1, frames=frames, height=height, width=width, fps=fps)- audio_pixel_shape = pixel_shape if audio_fps is None else pixel_shape._replace(fps=audio_fps)+ video_latent = video.latent if video is not None else None+ audio_latent = audio.latent if audio is not None else None+ conditioning_fps = video.conditioning_fps if video is not None else None# Build video_tools up front so it can be forwarded to the transformer# context (required by TiledDataParallelBuilder in multi-GPU mode).- video_tools: LatentTools | None = None- if video is not None:- v_shape = VideoLatentShape.from_pixel_shape(- pixel_shape,+ video_tools = (+ VideoLatentTools(+ VideoLatentPatchifier(patch_size=1),+ VideoLatentShape.from_torch_shape(video_latent.shape),+ conditioning_fps,scale_factors=self.video_scale_factors,)- video_tools = VideoLatentTools(- VideoLatentPatchifier(patch_size=1), v_shape, fps, scale_factors=self.video_scale_factors- )+ if video_latent is not None+ else None+ )mode = "streaming" if self._is_streaming else "standard"logger.info("Building transformer (%s) from %s", mode, self._transformer_builder.checkpoint)with self._transformer_ctx(video_tools=video_tools) as built:transformer = built if self._model_wrapper is None else self._model_wrapper(built, video_tools)logger.info(- "Running denoising loop (%d steps, %dx%d %d frames @ %.1f fps)",+ "Running denoising loop (%d steps, video latent %s, audio latent %s @ %.1f fps)",len(sigmas) - 1,- width,- height,- frames,- fps,+ tuple(video_latent.shape) if video_latent is not None else None,+ tuple(audio_latent.shape) if audio_latent is not None else None,+ conditioning_fps,)video_state: LatentState | None = Noneif video is not None and video_tools is not None:video_state = _build_state(video, video_tools, noiser, self._dtype, self._device)- audio_tools: LatentTools | None = None+ audio_tools = (+ AudioLatentTools(+ AudioPatchifier(patch_size=1),+ AudioLatentShape.from_torch_shape(audio_latent.shape),+ )+ if audio_latent is not None+ else None+ )audio_state: LatentState | None = None- if audio is not None:- a_shape = AudioLatentShape.from_video_pixel_shape(audio_pixel_shape)- audio_tools = AudioLatentTools(AudioPatchifier(patch_size=1), a_shape)+ if audio is not None and audio_tools is not None:audio_state = _build_state(audio, audio_tools, noiser, self._dtype, self._device)wrapped = BatchSplitAdapter(transformer, max_batch_size=max_batch_size) # type: ignore[arg-type]@@ -596,7 +581,6 @@ class DiffusionStage:sigmas=sigmas,video_state=video_state,audio_state=audio_state,- stepper=stepper,transformer=wrapped,denoiser=denoiser,)@@ -608,16 +592,14 @@ class DiffusionStage:audio_state = audio_tools.clear_conditioning(audio_state)audio_state = audio_tools.unpatchify(audio_state)- return video_state, audio_state+ return VideoAudio(video_state, audio_state)class RecordingDiffusionStage:"""Wraps a :class:`DiffusionStage` and records the states each call produced.- Diagnostics wrapper for a stage's intermediate ``LatentState``s. Generated keyframes that- already sit at final output resolution are on ``PipelineOutput.keyframes``; this wrapper- remains the way to inspect per-stage states (including half-res stage-1 slots) without a- lifecycle callback. Pipelines hold their stage in a plain attribute, so a caller- substitutes this in::+ Diagnostics wrapper for a stage's intermediate ``LatentState``s. Use this to inspect+ per-stage states (including half-res stage-1 slots) without a lifecycle callback. Pipelines+ hold their stage in a plain attribute, so a caller substitutes this in::pipeline.stage = RecordingDiffusionStage(pipeline.stage)result = pipeline(...)keyframes = pipeline.stage.generated_keyframes@@ -632,12 +614,12 @@ class RecordingDiffusionStage:self.video_states: list[LatentState] = []self.audio_states: list[LatentState | None] = []- def __call__(self, *args: object, **kwargs: object) -> tuple[LatentState | None, LatentState | None]:+ def __call__(self, *args: object, **kwargs: object) -> VideoAudio[LatentState]:video_state, audio_state = self._stage(*args, **kwargs) # type: ignore[arg-type]if video_state is not None:self.video_states.append(video_state)self.audio_states.append(audio_state)- return video_state, audio_state+ return VideoAudio(video_state, audio_state)@propertydef generated_keyframes(self) -> torch.Tensor | None:@@ -1174,6 +1156,7 @@ class VideoDecoder:*,dtype: torch.dtype | None = None,keyframes: DecodeKeyframes | None = None,+ device_fn: Callable[[int], str | torch.device] | None = None,) -> Iterator[torch.Tensor]:"""Decode *latent* to pixel-space video chunks. Decoder freed after exhaustion.``dtype`` overrides the constructor dtype for this call only (e.g. float32 for@@ -1189,6 +1172,8 @@ class VideoDecoder:logger.info("Building video decoder from %s", self._checkpoint_path)decoder = self._prepared_builder().build(device=self._device, dtype=build_dtype).eval()extra = {} if keyframes is None else {"keyframes": keyframes}+ if device_fn is not None:+ extra["device_fn"] = device_fnchunks = decoder.decode_video(latent, tiling_config, generator, **extra)return _cleanup_iter(chunks,@@ -1205,8 +1190,9 @@ class VideoDecoder:) -> Iterator[torch.Tensor]:"""Decode each latent as its own one-frame clip on one VAE build, then free it.A causal VAE cannot decode stacked independent planes without bleeding neighbours.- Dist builds still decode locally on every rank; this does not go through the- split/gather ``decode_video`` path whose workers yield nothing.+ A Dist build splits the list across its ranks and gathers the pixels back, so every+ rank returns the whole list; it does not go through the volume-splitting+ ``decode_video`` path, whose workers yield nothing."""if not latents:return iter(())diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/denoisers.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/denoisers.pyindex 7be1190..bc41cfd 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/denoisers.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/denoisers.py@@ -20,7 +20,7 @@ from ltx_core.guidance.perturbations import (from ltx_core.model.transformer import X0Modelfrom ltx_core.types import LatentStatefrom ltx_pipelines.utils.helpers import modality_from_latent_state-from ltx_pipelines.utils.types import DenoisedLatentResult+from ltx_pipelines.utils.types import DenoisedLatentResult, VideoAudio_POSITIVE_ONLY_GUIDER = MultiModalGuider(params=MultiModalGuiderParams(cfg_scale=1.0, stg_scale=0.0, modality_scale=1.0),@@ -72,7 +72,7 @@ def _guided_denoise( # noqa: PLR0913,PLR0915last_denoised_audio: torch.Tensor | None,step_index: int,force_uncond_pass: bool = False,-) -> tuple[DenoisedLatentResult | None, DenoisedLatentResult | None]:+) -> VideoAudio[DenoisedLatentResult]:"""Core guided denoising — batches all guidance passes into one transformer call.Collects per-pass contexts first, then builds a single batched Modalityper present modality via :func:`modality_from_latent_state`. When wrapped@@ -88,7 +88,7 @@ def _guided_denoise( # noqa: PLR0913,PLR0915if v_skip and a_skip:video_result = DenoisedLatentResult.result_or_none(denoised=last_denoised_video)audio_result = DenoisedLatentResult.result_or_none(denoised=last_denoised_audio)- return video_result, audio_result+ return VideoAudio(video_result, audio_result)if video_state is not None and v_context is None:raise ValueError("v_context is required when video_state is provided")@@ -201,7 +201,7 @@ def _guided_denoise( # noqa: PLR0913,PLR0915denoised_video = last_denoised_video if v_skip else video_guider.calculate(cond_v, uncond_v, ptb_v, mod_v)denoised_audio = last_denoised_audio if a_skip else audio_guider.calculate(cond_a, uncond_a, ptb_a, mod_a)- return (+ return VideoAudio(DenoisedLatentResult.result_or_none(denoised=denoised_video, uncond=uncond_v, cond=cond_v, ptb=ptb_v, mod=mod_v),@@ -231,7 +231,7 @@ class SimpleDenoiser:audio_state: LatentState | None,sigmas: torch.Tensor,step_index: int,- ) -> tuple[DenoisedLatentResult | None, DenoisedLatentResult | None]:+ ) -> VideoAudio[DenoisedLatentResult]:# Modality.sigma is (B,); expand the scalar schedule value per modality so a rank-stable# sigma reaches the (compiled) block instead of a 0-d scalar that recompiles on sigma.ndim.sigma = sigmas[step_index]@@ -246,7 +246,7 @@ class SimpleDenoiser:else None)denoised_video, denoised_audio = transformer(video=pos_video, audio=pos_audio, perturbations=None)- return (+ return VideoAudio(DenoisedLatentResult.result_or_none(denoised=denoised_video),DenoisedLatentResult.result_or_none(denoised=denoised_audio),)@@ -281,7 +281,7 @@ class GuidedDenoiser:audio_state: LatentState | None,sigmas: torch.Tensor,step_index: int,- ) -> tuple[DenoisedLatentResult | None, DenoisedLatentResult | None]:+ ) -> VideoAudio[DenoisedLatentResult]:guided_denoise_result_v, guided_denoise_result_a = _guided_denoise(transformer=transformer,video_state=video_state,@@ -298,7 +298,7 @@ class GuidedDenoiser:)self._last_denoised_video = guided_denoise_result_v.denoisedself._last_denoised_audio = guided_denoise_result_a.denoised- return guided_denoise_result_v, guided_denoise_result_a+ return VideoAudio(guided_denoise_result_v, guided_denoise_result_a)class FactoryGuidedDenoiser:@@ -328,7 +328,7 @@ class FactoryGuidedDenoiser:audio_state: LatentState | None,sigmas: torch.Tensor,step_index: int,- ) -> tuple[DenoisedLatentResult | None, DenoisedLatentResult | None]:+ ) -> VideoAudio[DenoisedLatentResult]:if self._sigma_vals_cached is None:self._sigma_vals_cached = sigmas.detach().cpu().tolist()sigma_val = self._sigma_vals_cached[step_index]@@ -358,4 +358,4 @@ class FactoryGuidedDenoiser:)self._last_denoised_video = guided_denoise_result_v.denoisedself._last_denoised_audio = guided_denoise_result_a.denoised- return guided_denoise_result_v, guided_denoise_result_a+ return VideoAudio(guided_denoise_result_v, guided_denoise_result_a)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/helpers.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/helpers.pyindex 2025029..bc54583 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/helpers.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/helpers.py@@ -1,5 +1,8 @@+from __future__ import annotations+import loggingfrom collections.abc import Sequence+from typing import TYPE_CHECKINGimport torch@@ -36,7 +39,6 @@ from ltx_core.types import (VideoLatentShape,VideoPixelShape,)-from ltx_pipelines.utils.args import ImageConditioningInputfrom ltx_pipelines.utils.media_io import (ResizeMode,decode_audio_from_file,@@ -44,12 +46,16 @@ from ltx_pipelines.utils.media_io import (decode_video_from_file,get_videostream_fps,is_exr_dir,- load_exr_folder_conditioning_hdr,+ load_exr_as_hdr_conditioning,load_image_and_preprocess,resize_aspect_ratio_preserving,video_preprocess,)-from ltx_pipelines.utils.media_io.color_config import HDRColorSpace+from ltx_pipelines.utils.media_io.color_config import EXRColorSpace+from ltx_pipelines.utils.types import ImageConditioningInput++if TYPE_CHECKING:+ from ltx_pipelines.utils.blocks import DiffusionStagelogger = logging.getLogger(__name__)@@ -62,6 +68,70 @@ def cleanup_memory() -> None:cleanup_accelerator_memory()+def create_initial_video_latent(+ *,+ width: int,+ height: int,+ frames: int,+ fps: float,+ device: torch.device,+ dtype: torch.dtype,+ scale_factors: SpatioTemporalScaleFactors,+) -> torch.Tensor:+ """Allocate a zero video latent from pixel ``width`` / ``height`` / ``frames``."""+ pixel_shape = VideoPixelShape(batch=1, frames=frames, height=height, width=width, fps=fps)+ shape = VideoLatentShape.from_pixel_shape(pixel_shape, scale_factors=scale_factors)+ return torch.zeros(*shape.to_torch_shape(), device=device, dtype=dtype)+++def create_initial_audio_latent(+ video_latent: torch.Tensor,+ *,+ fps: float,+ video_scale_factors: SpatioTemporalScaleFactors,+) -> torch.Tensor:+ """Allocate a zero audio latent whose duration matches ``video_latent``.+ ``video_scale_factors`` are the video VAE's spatiotemporal factors (audio has none of+ its own). Pass the same value used to size ``video_latent``.+ """+ video_shape = VideoLatentShape.from_torch_shape(video_latent.shape)+ audio_shape = AudioLatentShape.from_duration(+ batch=video_shape.batch,+ duration=float(video_shape.upscale(video_scale_factors).frames) / float(fps),+ )+ return torch.zeros(+ *audio_shape.to_torch_shape(),+ device=video_latent.device,+ dtype=video_latent.dtype,+ )+++def create_initial_av_latents(+ *,+ width: int,+ height: int,+ frames: int,+ fps: float,+ device: torch.device,+ dtype: torch.dtype,+ video_scale_factors: SpatioTemporalScaleFactors,+) -> tuple[torch.Tensor, torch.Tensor]:+ """Allocate matching zero video and audio latents.+ ``video_scale_factors`` are the video VAE's spatiotemporal factors. Audio duration+ follows the video canvas those factors produce.+ """+ video_latent = create_initial_video_latent(+ width=width,+ height=height,+ frames=frames,+ fps=fps,+ device=device,+ dtype=dtype,+ scale_factors=video_scale_factors,+ )+ return video_latent, create_initial_audio_latent(video_latent, fps=fps, video_scale_factors=video_scale_factors)++# Historical Conv VAE ``TilingConfig.default()`` spatial long-side + temporal chunk# (main ``latent_tile_splitters`` aspect-coupled a single 768px tile to H/W)._CONV_AUTO_LONG_SIDE = DimensionSizeConfig(tile_size=768, overlap=64)@@ -184,7 +254,7 @@ def video_latent_from_file(start_time: float = 0.0,max_duration: float | None = None,tiling_config: TilingConfig | None = None,- color_space: HDRColorSpace | None = None,+ color_space: EXRColorSpace | None = None,) -> torch.Tensor | None:"""Load video from a file or EXR-frame folder, and encode to latents.Args:@@ -217,13 +287,13 @@ def video_latent_from_file(frame_cap = max(1, round(max_duration * fps))frames = torch.cat(list(- load_exr_folder_conditioning_hdr(- exr_dir=file_path,- height=output_shape.height,- width=output_shape.width,+ load_exr_as_hdr_conditioning(+ file_path,+ output_shape.height,+ output_shape.width,+ dtype,+ device,frame_cap=frame_cap,- dtype=dtype,- device=device,color_space=color_space,resize_mode=ResizeMode.CENTER_CROP,frame_start=frame_start,@@ -289,7 +359,7 @@ def combined_image_conditionings(video_encoder: VideoEncoder,dtype: torch.dtype,device: torch.device,- color_space: HDRColorSpace | None = None,+ color_space: EXRColorSpace | None = None,) -> list[ConditioningItem]:"""Create a list of conditionings by replacing the latent at the first frame with the encoded image if presentand using other encoded images as the keyframe conditionings."""@@ -328,7 +398,7 @@ def image_conditionings_by_replacing_latent(video_encoder: VideoEncoder,dtype: torch.dtype,device: torch.device,- color_space: HDRColorSpace | None = None,+ color_space: EXRColorSpace | None = None,) -> list[ConditioningItem]:conditionings = []for img in images:@@ -360,7 +430,7 @@ def image_conditionings_by_adding_guiding_latent(video_encoder: VideoEncoder,dtype: torch.dtype,device: torch.device,- color_space: HDRColorSpace | None = None,+ color_space: EXRColorSpace | None = None,) -> list[ConditioningItem]:conditionings = []for img in images:@@ -394,6 +464,34 @@ def evenly_spaced_keyframe_positions(num_keyframes: int, num_frames: int) -> lisreturn torch.linspace(0, num_frames - 1, num_keyframes + 2).round().to(torch.int64).tolist()[1:-1]+def assert_stage_supports_generated_keyframes(stage: DiffusionStage) -> None:+ """Raise unless ``stage``'s checkpoint declares the keyframe absolute-position embedding."""+ if stage.supports_generated_keyframes:+ return+ raise ValueError(+ f"Generated keyframe slots were requested, but the checkpoint at "+ f"{stage._transformer_builder.checkpoint} does not set 'use_keyframes_abs_pos_embedding' "+ f"in its transformer config, so it has no keyframe absolute-position embedding. Use a "+ f"generated-keyframe checkpoint or drop the keyframe request."+ )+++def assert_generated_keyframes_request(+ decode_with_keyframes: bool,+ generated_keyframes: int | Sequence[int],+ stage: DiffusionStage,+) -> None:+ """Validate generated-keyframe and keyframe-decode requests before building models."""+ if has_generated_keyframes(generated_keyframes):+ assert_stage_supports_generated_keyframes(stage)+ return+ if decode_with_keyframes:+ raise ValueError(+ "decode_with_keyframes requires generated keyframe slots; pass "+ "generated_keyframes > 0 or an explicit position list."+ )++def has_generated_keyframes(generated_keyframes: int | Sequence[int]) -> bool:"""Whether a ``generated_keyframes`` request asks for any slots.Callers must not test the argument's truthiness directly: a ``Sequence`` may be a tensor or andiff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/__init__.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/__init__.pyindex 30bc3e6..02f43b9 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/__init__.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/__init__.py@@ -1,9 +1,11 @@"""Media I/O: decode, encode, EXR, resize, and colour-config helpers."""from ltx_pipelines.utils.media_io.color_config import (- HDRColorSpace,+ EXRColorSpace,decode_hdr_video,resolve_hdr_color_space,+ srgb_to_acescct,+ to_working_space,vae_dtype_for_hdr,)from ltx_pipelines.utils.media_io.decode import (@@ -16,20 +18,22 @@ from ltx_pipelines.utils.media_io.decode import (get_videostream_fps,get_videostream_metadata,load_image_and_preprocess,- load_video_conditioning_hdr,+ load_video_as_hdr_conditioning,preprocess,video_preprocess,)-from ltx_pipelines.utils.media_io.encode import encode_audio, encode_video+from ltx_pipelines.utils.media_io.encode import encode_audio, encode_sdr_h264, encode_videofrom ltx_pipelines.utils.media_io.exr import (encode_exr_sequence_to_mp4,+ exr_colorspace_tag,+ exr_dir_label,is_exr_dir,- load_exr_conditioning_hdr,- load_exr_folder_conditioning_hdr,- load_exr_image_conditioning_hdr,+ load_exr_as_hdr_conditioning,+ load_exr_image_as_hdr_conditioning,read_exr,save_exr_tensor,)+from ltx_pipelines.utils.media_io.inputs import EXRVideoInput, VideoInputfrom ltx_pipelines.utils.media_io.range_map import from_vae_range, normalize_images, to_vae_rangefrom ltx_pipelines.utils.media_io.resize import (ResizeMode,@@ -40,8 +44,10 @@ from ltx_pipelines.utils.media_io.resize import ()__all__ = [- "HDRColorSpace",+ "EXRColorSpace",+ "EXRVideoInput","ResizeMode",+ "VideoInput","align_resolution","decode_audio_from_file","decode_hdr_video",@@ -51,17 +57,19 @@ __all__ = ["decode_video_from_file","encode_audio","encode_exr_sequence_to_mp4",+ "encode_sdr_h264","encode_single_frame","encode_video",+ "exr_colorspace_tag",+ "exr_dir_label","from_vae_range","get_videostream_fps","get_videostream_metadata","is_exr_dir",- "load_exr_conditioning_hdr",- "load_exr_folder_conditioning_hdr",- "load_exr_image_conditioning_hdr",+ "load_exr_as_hdr_conditioning",+ "load_exr_image_as_hdr_conditioning","load_image_and_preprocess",- "load_video_conditioning_hdr",+ "load_video_as_hdr_conditioning","normalize_images","preprocess","read_exr",@@ -70,7 +78,9 @@ __all__ = ["resize_aspect_ratio_preserving","resolve_hdr_color_space","save_exr_tensor",+ "srgb_to_acescct","to_vae_range",+ "to_working_space","vae_dtype_for_hdr","video_preprocess",]diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/color_config.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/color_config.pyindex 52536c9..b6d75ce 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/color_config.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/color_config.py@@ -1,4 +1,4 @@-"""HDR colour-space policy for pipelines (``HDRColorSpace`` + resolve helpers)."""+"""EXR colour-space policy for pipelines."""from __future__ import annotations@@ -7,17 +7,14 @@ from collections.abc import Iterablefrom pathlib import Pathimport torch+from torch import Tensorfrom ltx_core.color.primaries import Primaries-from ltx_core.hdr import HDRTransfer+from ltx_core.hdr import srgb_eotf_to_linear, to_acescct_working_space, to_hdr_linear-class HDRColorSpace(enum.Enum):- """Explicit HDR source / working colour space (CLI ``--hdr``).- ``None`` at call sites means SDR. Members:- * ``SRGB_LINEAR`` / ``ACESCG`` — scene-linear; compress via ACEScct on load.- * ``ACESCCT`` — already ACEScct log working codes; no load-time transfer.- """+class EXRColorSpace(enum.Enum):+ """Colour space of an EXR plate."""SRGB_LINEAR = "srgb_linear"ACESCG = "acescg"@@ -26,42 +23,37 @@ class HDRColorSpace(enum.Enum):@propertydef is_log_working(self) -> bool:"""True when the VAE signal is already ACEScct log (no load-time transfer)."""- return self is HDRColorSpace.ACESCCT+ return self is EXRColorSpace.ACESCCT@propertydef source_primaries(self) -> Primaries:match self:- case HDRColorSpace.ACESCG | HDRColorSpace.ACESCCT:- return Primaries.ACESCG+ case EXRColorSpace.ACESCG | EXRColorSpace.ACESCCT:+ return Primaries.AP1case _:return Primaries.REC709- @property- def transfer(self) -> HDRTransfer:- """Curve for the VAE working space (always defined; today always ACEScct).- Whether to *apply* it depends on the call site:- * load — compress only when not :attr:`is_log_working`- * EXR write — decompress only when writing linear EXR- * HLG — always decompress to Rec.709 linear- """- match self:- case HDRColorSpace.SRGB_LINEAR | HDRColorSpace.ACESCG | HDRColorSpace.ACESCCT:- return HDRTransfer.ACESCCT- case _:- raise ValueError(f"No transfer defined for {self!r}.")- def exr_output_tags(self) -> tuple[Primaries, str]:- """``(primaries, colorSpace_tag)`` for :func:`save_exr_tensor`."""- match self:- case HDRColorSpace.ACESCCT:- return Primaries.ACESCG, "ACEScct"- case HDRColorSpace.ACESCG:- return Primaries.ACESCG, "ACEScg"- case HDRColorSpace.SRGB_LINEAR:- return Primaries.REC709, "sRGB"+def to_working_space(video: Tensor, current_colorspace: EXRColorSpace) -> Tensor:+ """Map HDR float RGB of ``current_colorspace`` into ACEScct ``[0, 1]`` (channel-first)."""+ if current_colorspace.is_log_working:+ return video.float().clamp(0.0, 1.0)+ return to_acescct_working_space(video.float(), source_primaries=current_colorspace.source_primaries)+++def srgb_to_acescct(video: Tensor, *, gamma_encoded: bool) -> Tensor:+ """Rec.709 float RGB → ACEScct ``[0, 1]``. ``gamma_encoded`` applies the sRGB EOTF first."""+ if not video.is_floating_point():+ raise ValueError(+ f"srgb_to_acescct expects float RGB; got dtype={video.dtype}. Normalize integer pixels before calling."+ )+ video = video.float()+ if gamma_encoded:+ video = srgb_eotf_to_linear(video)+ return to_acescct_working_space(video, source_primaries=Primaries.REC709)-def vae_dtype_for_hdr(hdr: HDRColorSpace | None, default: torch.dtype) -> torch.dtype:+def vae_dtype_for_hdr(hdr: EXRColorSpace | None, default: torch.dtype) -> torch.dtype:"""VAE decode dtype: float32 for HDR, else ``default`` (pipelines use bf16 today)."""return torch.float32 if hdr is not None else default@@ -82,8 +74,8 @@ def _has_exr_input(def resolve_hdr_color_space(images: Iterable[object] = (),video_paths: Iterable[str | Path] = (),- hdr: HDRColorSpace | None = None,-) -> HDRColorSpace | None:+ hdr: EXRColorSpace | None = None,+) -> EXRColorSpace | None:"""Return the explicit ``--hdr`` value, or raise if EXR inputs lack it.``None`` means SDR."""@@ -94,10 +86,9 @@ def resolve_hdr_color_space(def decode_hdr_video(decoded_video: torch.Tensor,- transfer: HDRTransfer,out_primaries: Primaries = Primaries.REC709,) -> torch.Tensor:- """VAE decode ``[F,H,W,C]`` in ``[0,1]`` → scene-linear HDR float32."""+ """VAE decode ``[F,H,W,C]`` in ``[0,1]`` ACEScct → scene-linear HDR float32."""video = decoded_video.float().permute(3, 0, 1, 2).unsqueeze(0)- hdr = transfer.to_linear(video, out_primaries=out_primaries)+ hdr = to_hdr_linear(video, out_primaries=out_primaries)return hdr[0].permute(1, 2, 3, 0).contiguous()diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/decode.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/decode.pyindex 2fd19f1..010248a 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/decode.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/decode.py@@ -14,10 +14,12 @@ import torchfrom PIL import ExifTags, Image, ImageCms, UnidentifiedImageErrorfrom torch._prims_common import DeviceLikeType-from ltx_core.hdr import HDRTransferfrom ltx_core.types import Audio, VideoPixelShape-from ltx_pipelines.utils.media_io.color_config import HDRColorSpace-from ltx_pipelines.utils.media_io.exr import is_exr_dir, load_exr_image_conditioning_hdr+from ltx_pipelines.utils.media_io.color_config import EXRColorSpace, srgb_to_acescct+from ltx_pipelines.utils.media_io.exr import (+ is_exr_dir,+ load_exr_image_as_hdr_conditioning,+)from ltx_pipelines.utils.media_io.range_map import normalize_images, to_vae_rangefrom ltx_pipelines.utils.media_io.resize import (ResizeMode,@@ -50,7 +52,7 @@ def load_image_and_preprocess(dtype: torch.dtype,device: torch.device,crf: int,- color_space: HDRColorSpace | None = None,+ color_space: EXRColorSpace | None = None,) -> torch.Tensor:"""Loads an image from a path and preprocesses it for conditioning.@@ -63,7 +65,7 @@ def load_image_and_preprocess(raise ValueError("EXR input requires --hdr {SRGB_LINEAR,ACESCG,ACESCCT} to declare the source colour space.")- return load_exr_image_conditioning_hdr(+ return load_exr_image_as_hdr_conditioning(exr_path=image_path,height=height,width=width,@@ -96,44 +98,40 @@ def video_preprocess(Returns:Tensor of shape (1, C, F, height, width) with values in [-1, 1]."""- result: torch.Tensor | None = None+ # Collect frames and concatenate once: per-frame cat reserves O(F^2) CUDA+ # cache blocks when expandable segments are unavailable.+ processed: list[torch.Tensor] = []for f in frames:frame = resize_and_center_crop(f.to(torch.float32), height, width)- frame = normalize_images(frame, device, dtype)- result = frame if result is None else torch.cat([result, frame], dim=2)- if result is None:+ processed.append(normalize_images(frame, device, dtype))+ if not processed:raise ValueError("video_preprocess received an empty frame generator; no frames were decoded from the source.")- return result+ return torch.cat(processed, dim=2)-def load_video_conditioning_hdr(- video_path: str,+def load_video_as_hdr_conditioning(+ video_path: str | Path,height: int,width: int,frame_cap: int,dtype: torch.dtype,device: torch.device,- transfer: HDRTransfer = HDRTransfer.LOGC3,+ *,+ gamma_encoded: bool = False,+ frame_start: int = 0,resize_mode: ResizeMode = ResizeMode.CENTER_CROP,) -> Iterator[torch.Tensor]:- """Load a video and yield preprocessed frames for HDR IC-LoRA conditioning.- Decodes through the standard path and applies the LDR compression that- matches training. Callers are responsible for providing Rec.709 SDR- input — the HDR IC-LoRA was trained on that color space.- Args:- transfer: Working-space transfer; ``compress_ldr`` is identity clamp for- all cases (SDR display-range input).- resize_mode: How to fit the video to the target resolution.- Yields:- Per-frame tensors of shape ``(1, C, 1, height, width)``.- """+ """Load an MP4/MOV and yield ACEScct VAE-range frames ``(1, C, 1, height, width)``."""resize_fn = resize_and_reflect_pad if resize_mode is ResizeMode.REFLECT_PAD else resize_and_center_crop-- for f in decode_video_by_frame(path=video_path, frame_cap=frame_cap, device=device):- frame = resize_fn(f.to(torch.float32), height, width)- ldr = (frame / 255.0).clamp(0.0, 1.0)- compressed = transfer.compress_ldr(ldr)- yield to_vae_range(compressed).to(device=device, dtype=dtype)+ for f in decode_video_by_frame(+ path=str(video_path), frame_cap=frame_cap, device=device, starting_frame=frame_start+ ):+ ldr = (f[0].float() / 255.0).clamp(0.0, 1.0)+ native = ldr.permute(2, 0, 1).unsqueeze(0).unsqueeze(2)+ working = srgb_to_acescct(native, gamma_encoded=gamma_encoded)+ working_hwc = working[0, :, 0].permute(1, 2, 0).contiguous()+ frame = resize_fn(working_hwc, height, width)+ yield to_vae_range(frame).to(device=device, dtype=dtype)def decode_image(image_path: str) -> np.ndarray:@@ -169,7 +167,7 @@ def decode_image(image_path: str) -> np.ndarray:image = image.convert("RGB")return np.array(image, dtype=np.uint8)- except UnidentifiedImageError as err:+ except (UnidentifiedImageError, OSError) as err:raise ValueError(f"Cannot decode image file '{image_path}'.") from errdiff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/encode.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/encode.pyindex 48d6931..ae07fc4 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/encode.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/encode.py@@ -17,14 +17,14 @@ import torchfrom tqdm import tqdmfrom ltx_core.color.audio_mux import prepare_audio_stream as _prepare_audio_stream-from ltx_core.color.audio_mux import validate_audio_waveform as _validate_audio_waveform+from ltx_core.color.audio_mux import validate_audio_waveformfrom ltx_core.color.audio_mux import write_audio as _write_audiofrom ltx_core.color.hlg import encode_linear_hdr_frames_to_hlg_mp4from ltx_core.color.primaries import Primariesfrom ltx_core.color.yuv import FrameConverter, PixelFormat, yuv420p_bt709_converter_from ltx_core.types import Audio-from ltx_pipelines.utils.media_io.color_config import HDRColorSpace, decode_hdr_video-from ltx_pipelines.utils.media_io.exr import save_exr_tensor+from ltx_pipelines.utils.media_io.color_config import EXRColorSpace, decode_hdr_video+from ltx_pipelines.utils.media_io.exr import exr_colorspace_tag, exr_dir_label, save_exr_tensorlogger = logging.getLogger(__name__)@@ -33,47 +33,55 @@ def _encode_hdr_video_outputs(chunks: Iterator[torch.Tensor],output_path: Path,fps: float,- color_space: HDRColorSpace,+ color_space: EXRColorSpace,*,max_workers: int = 8,- audio: Audio | None = None,+ audio: Iterator[Audio] | None = None,device: torch.device | None = None,) -> Path:- """Stream a VAE decode to half EXR frames plus a BT.2020/HLG master.+ """Write EXR frames plus a BT.2020/HLG master.One pass over ``chunks`` feeds two independent sinks:* **HLG** — always Rec.709 scene-linear (``decode_hdr_video`` default).- * **EXR** — matches ``color_space``: log codes when :attr:`~HDRColorSpace.is_log_working`,+ * **EXR** — matches ``color_space``: log codes when :attr:`~EXRColorSpace.is_log_working`,else scene-linear in ``color_space.source_primaries`` (reuse the HLG tensor when thatis already Rec.709).- Peak memory stays proportional to one chunk rather than the whole clip.+ Chunks are collected first so a stitch iterator can be pulled before HLG+ (which takes a single :class:`~ltx_core.types.Audio`). EXR and HLG then share+ that list.Args:chunks: Per-chunk VAE decode output, each ``[F, H, W, C]`` float in ``[0, 1]``(the compressed working-space signal).- output_path: Destination of the HLG master. EXR frames go to ``<stem>_exr/``.+ output_path: Destination of the HLG master. EXR frames go to+ ``<stem>_<label>_exr/`` where ``label`` is :func:`~ltx_pipelines.utils.media_io.exr.exr_dir_label`.fps: Output frame rate.color_space: HDR colour space for EXR tags / linear EXR primaries.max_workers: Number of EXR writer threads.- audio: Optional stereo track muxed into the HLG master.+ audio: Optional stereo track muxed into the HLG master. Drain of ``chunks``+ fills a lazy stitch iterator; pull it before HLG.device: Device for the HLG colour conversion. Defaults to CUDA when available.Returns:The directory the EXR frames were written to.Raises:ValueError: If ``chunks`` yields nothing."""- transfer = color_space.transfer- exr_dir = output_path.parent / f"{output_path.stem}_exr"+ exr_dir = output_path.parent / f"{output_path.stem}_{exr_dir_label(color_space)}_exr"exr_dir.mkdir(parents=True, exist_ok=True)- exr_primaries, exr_color_space = color_space.exr_output_tags()+ exr_primaries = color_space.source_primaries+ exr_color_space = exr_colorspace_tag(color_space)frames_written = 0+ chunk_list = list(chunks)+ mux_audio = next(audio, None) if audio is not None else None+ if mux_audio is not None:+ validate_audio_waveform(mux_audio)def hlg_chunks() -> Iterator[torch.Tensor]:"""Write EXR for each chunk, then yield Rec.709 linear for the HLG encoder."""nonlocal frames_writtenwith ThreadPoolExecutor(max_workers=max_workers) as executor:pending: deque[Future[None]] = deque()- for chunk in chunks:+ for chunk in chunk_list:# HLG sink: always Rec.709 scene-linear.- hlg_linear = decode_hdr_video(chunk, transfer)+ hlg_linear = decode_hdr_video(chunk)# EXR sink: independent of HLG (reuse only when pixels already match).if color_space.is_log_working:@@ -81,7 +89,7 @@ def _encode_hdr_video_outputs(elif color_space.source_primaries is Primaries.REC709:exr_hdr = hlg_linearelse:- exr_hdr = decode_hdr_video(chunk, transfer, out_primaries=color_space.source_primaries)+ exr_hdr = decode_hdr_video(chunk, out_primaries=color_space.source_primaries)for frame in exr_hdr:path = exr_dir / f"frame_{frames_written:05d}.exr"@@ -100,12 +108,17 @@ def _encode_hdr_video_outputs(logger.info("Encoding BT.2020/HLG/10-bit master%s: %s",- " (with audio)" if audio is not None else "",+ " (with audio)" if mux_audio is not None else "",output_path,)# Empty ``chunks`` raises inside the HLG encoder (after EXR side effects are none).encode_linear_hdr_frames_to_hlg_mp4(- hlg_chunks(), output_path, fps=fps, primaries=Primaries.REC709, audio=audio, device=device+ hlg_chunks(),+ output_path,+ fps=fps,+ primaries=Primaries.REC709,+ audio=mux_audio,+ device=device,)logger.info("Wrote %d EXR frames (%s/%s) to %s",@@ -117,57 +130,47 @@ def _encode_hdr_video_outputs(return exr_dir-def encode_video(- video: torch.Tensor | Iterator[torch.Tensor],+def _open_video_stream(+ container: av.container.Container,+ fps: int,+ height: int,+ width: int,+ frame_converter: FrameConverter,+ crf: int,+ preset: str,+ thread_count: int,+) -> av.video.VideoStream:+ stream = container.add_stream("libx264", rate=int(fps), options={"crf": str(crf), "preset": preset})+ stream.width = width+ stream.height = height+ stream.pix_fmt = "yuv420p"+ stream.codec_context.thread_count = thread_count+ stream.codec_context.thread_type = "FRAME"+ if frame_converter.color_space is not None:+ stream.codec_context.colorspace = frame_converter.color_space.av_colorspace+ if frame_converter.color_range is not None:+ stream.codec_context.color_range = frame_converter.color_range.av_color_range+ return stream+++def encode_sdr_h264(+ video: Iterator[torch.Tensor],+ *,fps: int,- audio: Audio | None,output_path: str,video_chunks_number: int,+ audio: Iterator[Audio] | None = None,+ audio_sampling_rate: int | None = None,frame_converter: FrameConverter = yuv420p_bt709_converter_,crf: int = 19,preset: str = "veryfast",thread_count: int = 0,- *,- color_space: HDRColorSpace | None = None,-) -> Path | None:- """Encode RGB frames to video; SDR H.264 or HDR EXR+HLG when ``color_space`` is set.- Args:- video: RGB frames as a ``(F, H, W, C)`` float ``[0, 1]`` tensor, or an iterator of- such per-chunk tensors (e.g. the VAE decoder output). An empty iterator raises.- For HDR this is the compressed working-space signal from VAE decode.- fps: Output frame rate.- audio: Audio track to mux, or None for a video-only file. Waveform must be stereo- ``(2, N)`` or ``(N, 2)``.- output_path: Destination path. Parent directories are created if missing.- Partial SDR output is removed if encoding fails. HDR writes EXR under- ``<stem>_exr/`` and an HLG master to this path.- video_chunks_number: Number of chunks yielded by ``video``, for the progress bar- (SDR path only).- frame_converter: Float-to-pixel converter (default YUV420p BT.709); SDR only.- crf: libx264 constant rate factor; lower is higher quality (0-51); SDR only.- preset: libx264 speed/compression preset; SDR only.- thread_count: libx264 thread count (0 = auto); SDR only.- color_space: HDR colour space for the encode sink. ``None`` (default) is SDR.- When set, writes half EXR frames + HLG master.- Returns:- EXR output directory when HDR, else ``None``.- Raises:- ValueError: On an empty ``video`` or a non-stereo ``audio.waveform``.+) -> None:+ """Mux RGB frame chunks to SDR H.264 (optional AAC).+ Pass :func:`~ltx_pipelines.chunks.deferred_stitch_audio` (and ``audio_sampling_rate``)+ when audio is assembled while ``video`` is consumed. Pull the iterator only after+ video drain."""- if audio is not None:- _validate_audio_waveform(audio)-- if isinstance(video, torch.Tensor):- video = iter([video])-- if color_space is not None:- return _encode_hdr_video_outputs(- video,- Path(output_path),- fps=float(fps),- color_space=color_space,- audio=audio,- )def convert(chunk: torch.Tensor) -> torch.Tensor:return frame_converter(chunk.movedim(-1, -3))@@ -183,26 +186,16 @@ def encode_video(height = first_chunk.shape[-2] * 2 // 3width = first_chunk.shape[-1]- # PyAV/FFmpeg won't create missing parent directories; do it so a nested- # --output-path (e.g. /tmp/run/clip.mp4) doesn't fail at mux time.Path(output_path).parent.mkdir(parents=True, exist_ok=True)container = av.open(output_path, mode="w")success = Falsetry:- stream = container.add_stream("libx264", rate=int(fps), options={"crf": str(crf), "preset": preset})- stream.width = width- stream.height = height- stream.pix_fmt = "yuv420p"- stream.codec_context.thread_count = thread_count- stream.codec_context.thread_type = "FRAME"- if frame_converter.color_space is not None:- stream.codec_context.colorspace = frame_converter.color_space.av_colorspace- if frame_converter.color_range is not None:- stream.codec_context.color_range = frame_converter.color_range.av_color_range-+ stream = _open_video_stream(container, fps, height, width, frame_converter, crf, preset, thread_count)+ audio_stream = Noneif audio is not None:- audio_stream = _prepare_audio_stream(container, audio.sampling_rate)-+ if audio_sampling_rate is None:+ raise ValueError("audio_sampling_rate is required when muxing audio")+ audio_stream = _prepare_audio_stream(container, audio_sampling_rate)av_format = frame_converter.pixel_format.av_formatdef cpu_chunks() -> Generator[np.ndarray, None, None]:@@ -218,14 +211,97 @@ def encode_video(progress_total=video_chunks_number,)- if audio is not None:- _write_audio(container, audio_stream, audio)+ mux_audio = next(audio, None) if audio is not None else None+ if mux_audio is not None:+ validate_audio_waveform(mux_audio)+ assert audio_stream is not None+ _write_audio(container, audio_stream, mux_audio)success = Truefinally:container.close()if not success:Path(output_path).unlink(missing_ok=True)- logger.info(f"Video saved to {output_path}")+ logger.info("Video saved to %s", output_path)+++def encode_video( # noqa: PLR0913+ video: torch.Tensor | Iterator[torch.Tensor],+ fps: int,+ audio: Audio | Iterator[Audio] | None,+ output_path: str,+ video_chunks_number: int,+ frame_converter: FrameConverter = yuv420p_bt709_converter_,+ crf: int = 19,+ preset: str = "veryfast",+ thread_count: int = 0,+ *,+ color_space: EXRColorSpace | None = None,+ audio_sampling_rate: int | None = None,+) -> Path | None:+ """Encode RGB frames to video; SDR H.264 or HDR EXR+HLG when ``color_space`` is set.+ Args:+ video: RGB frames as a ``(F, H, W, C)`` float ``[0, 1]`` tensor, or an iterator of+ such per-chunk tensors (e.g. the VAE decoder output). An empty iterator raises.+ For HDR this is the compressed working-space signal from VAE decode.+ fps: Output frame rate.+ audio: Audio to mux, an iterator yielding audio after ``video`` is consumed,+ or None for a video-only file. Pass+ :func:`~ltx_pipelines.chunks.deferred_stitch_audio` when parts are collected+ while ``video`` is consumed, and set ``audio_sampling_rate`` so AAC can open+ before any video packets (SDR). HDR drains ``video`` first, then pulls that+ iterator and passes one :class:`~ltx_core.types.Audio` to HLG. Waveforms must+ be stereo ``(2, N)`` or ``(N, 2)``.+ output_path: Destination path. Parent directories are created if missing.+ Partial SDR output is removed if encoding fails. HDR writes EXR under+ ``<stem>_<label>_exr/`` (see :func:`~ltx_pipelines.utils.media_io.exr.exr_dir_label`) and an+ video_chunks_number: Number of chunks yielded by ``video``, for the progress bar+ (SDR path only).+ frame_converter: Float-to-pixel converter (default YUV420p BT.709); SDR only.+ crf: libx264 constant rate factor; lower is higher quality (0-51); SDR only.+ preset: libx264 speed/compression preset; SDR only.+ thread_count: libx264 thread count (0 = auto); SDR only.+ color_space: HDR colour space for the encode sink. ``None`` (default) is SDR.+ When set, writes half EXR frames + HLG master.+ audio_sampling_rate: AAC sample rate. Inferred when ``audio`` is an+ :class:`~ltx_core.types.Audio`; required for an audio iterator on the SDR path.+ Returns:+ EXR output directory when HDR, else ``None``.+ Raises:+ ValueError: On an empty ``video``, a non-stereo ``audio`` waveform, or conflicting+ explicit and embedded audio sampling rates.+ """+ if isinstance(audio, Audio):+ if audio_sampling_rate is not None and audio_sampling_rate != audio.sampling_rate:+ raise ValueError(+ f"audio_sampling_rate {audio_sampling_rate} does not match audio sampling rate {audio.sampling_rate}"+ )+ audio_sampling_rate = audio.sampling_rate+ audio = iter((audio,))++ if isinstance(video, torch.Tensor):+ video = iter([video])++ if color_space is not None:+ return _encode_hdr_video_outputs(+ video,+ Path(output_path),+ fps=float(fps),+ color_space=color_space,+ audio=audio,+ )++ encode_sdr_h264(+ video,+ fps=fps,+ output_path=output_path,+ video_chunks_number=video_chunks_number,+ audio=audio,+ audio_sampling_rate=audio_sampling_rate,+ frame_converter=frame_converter,+ crf=crf,+ preset=preset,+ thread_count=thread_count,+ )return None@@ -235,7 +311,7 @@ def encode_audio(audio: Audio, output_path: str) -> None:the only difference is a PCM (``pcm_s16le``) stream in a WAV container instead ofthe AAC stream used for muxed video."""- _validate_audio_waveform(audio)+ validate_audio_waveform(audio)Path(output_path).parent.mkdir(parents=True, exist_ok=True)container = av.open(output_path, mode="w")audio_stream = container.add_stream("pcm_s16le", rate=audio.sampling_rate)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/exr.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/exr.pyindex 48ad0ca..874f9b0 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/exr.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/exr.py@@ -13,13 +13,29 @@ import OpenImageIOimport torchfrom ltx_core.color.primaries import Primaries-from ltx_pipelines.utils.media_io.color_config import HDRColorSpace+from ltx_pipelines.utils.media_io.color_config import EXRColorSpace, to_working_spacefrom ltx_pipelines.utils.media_io.range_map import to_vae_rangefrom ltx_pipelines.utils.media_io.resize import ResizeMode, resize_and_center_crop, resize_and_reflect_padlogger = logging.getLogger(__name__)+def exr_dir_label(color_space: EXRColorSpace) -> str:+ """Path token for HDR EXR dirs."""+ return color_space.value+++def exr_colorspace_tag(color_space: EXRColorSpace) -> str:+ """OpenEXR ``colorSpace`` attribute (transfer). Chromaticities come from ``source_primaries``."""+ match color_space:+ case EXRColorSpace.ACESCCT:+ return "ACEScct"+ case EXRColorSpace.ACESCG:+ return "ACEScg"+ case EXRColorSpace.SRGB_LINEAR:+ return "sRGB"++def is_exr_dir(path: str | Path) -> bool:"""Return True if *path* is a directory that directly contains ``*.exr`` files."""p = Path(path)@@ -57,7 +73,7 @@ def _exr_paths_for_conditioning(path: str | Path) -> list[Path]:raise ValueError(f"EXR conditioning path must be a .exr file or a directory of EXRs; got {path!r}")-def load_exr_conditioning_hdr(+def load_exr_as_hdr_conditioning(path: str | Path,height: int,width: int,@@ -66,14 +82,14 @@ def load_exr_conditioning_hdr(*,frame_cap: int,frame_start: int = 0,- color_space: HDRColorSpace,+ color_space: EXRColorSpace,resize_mode: ResizeMode = ResizeMode.REFLECT_PAD,) -> Iterator[torch.Tensor]:"""Load EXR still(s) as HDR conditioning for the VAE.``path`` may be a single ``.exr`` or a directory of ``*.exr`` frames (sortedlexicographically). Colour handling follows ``color_space``:- * ``SRGB_LINEAR`` / ``ACESCG`` — compress via :meth:`HDRTransfer.to_working_space`- (ACEScct) from the matching source primaries.+ * ``SRGB_LINEAR`` / ``ACESCG`` — compress via :func:`~ltx_core.hdr.to_acescct_working_space`+ from the matching source primaries.* ``ACESCCT`` — already working-space log codes; clamp then :func:`to_vae_range`(no transfer).Yields:@@ -91,17 +107,13 @@ def load_exr_conditioning_hdr(breakpixels = read_exr(fp).to(device=device, dtype=torch.float32) # [H, W, 3]frame = resize_fn(pixels, height, width) # [1, 3, 1, H, W]- if color_space.is_log_working:- # Already working-space codes; clamp file noise into the legal range.- working = frame.clamp(0.0, 1.0)- else:- working = color_space.transfer.to_working_space(frame, source_primaries=color_space.source_primaries)+ working = to_working_space(frame, color_space)yield to_vae_range(working).to(device=device, dtype=dtype)count += 1if count < frame_cap:logger.warning(- "load_exr_conditioning_hdr: requested %d frames from '%s' (frame_start=%d) "+ "load_exr_as_hdr_conditioning: requested %d frames from '%s' (frame_start=%d) ""but only %d were available — conditioning is shorter than the generation length.",frame_cap,path,@@ -110,47 +122,22 @@ def load_exr_conditioning_hdr()-def load_exr_folder_conditioning_hdr(- exr_dir: str | Path,- height: int,- width: int,- frame_cap: int,- dtype: torch.dtype,- device: torch.device,- color_space: HDRColorSpace,- resize_mode: ResizeMode = ResizeMode.REFLECT_PAD,- frame_start: int = 0,-) -> Iterator[torch.Tensor]:- """Load a folder of EXR frames as HDR conditioning. See :func:`load_exr_conditioning_hdr`."""- return load_exr_conditioning_hdr(- exr_dir,- height,- width,- dtype,- device,- frame_cap=frame_cap,- frame_start=frame_start,- color_space=color_space,- resize_mode=resize_mode,- )---def load_exr_image_conditioning_hdr(+def load_exr_image_as_hdr_conditioning(exr_path: str | Path,height: int,width: int,dtype: torch.dtype,device: torch.device,- color_space: HDRColorSpace,+ color_space: EXRColorSpace,resize_mode: ResizeMode = ResizeMode.CENTER_CROP,) -> torch.Tensor:"""Load a single EXR still as HDR image conditioning for the VAE.- Thin wrapper over :func:`load_exr_conditioning_hdr` (default center-crop).+ Thin wrapper over :func:`load_exr_as_hdr_conditioning` (default center-crop).Returns:Tensor ``(1, C, 1, height, width)`` in VAE range ``[-1, 1]``."""return next(- load_exr_conditioning_hdr(+ load_exr_as_hdr_conditioning(exr_path,height,width,diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/inputs.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/inputs.pynew file mode 100644index 0000000..65e0cff--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/media_io/inputs.py@@ -0,0 +1,25 @@+"""Ingest handles for HDR IC-LoRA: MP4/MOV vs an EXR-frame folder."""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path++from ltx_pipelines.utils.media_io.color_config import EXRColorSpace+++@dataclass(frozen=True, slots=True)+class VideoInput:+ """MP4/MOV source. ``gamma_encoded`` is display-referred sRGB (IEC 61966-2-1 EOTF)."""++ path: Path+ gamma_encoded: bool+++@dataclass(frozen=True, slots=True)+class EXRVideoInput:+ """EXR-frame folder with a declared plate colour space and playback fps."""++ dir: Path+ color_space: EXRColorSpace+ frame_rate: floatdiff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/model_paths.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/model_paths.pyindex 9489ec2..1fe7541 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/model_paths.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/model_paths.py@@ -172,7 +172,18 @@ def model_paths_from_namespace(namespace: argparse.Namespace) -> ModelPaths:duration_head_path=split_values["duration_head_path"],)- if monolith_ckpt is None or gemma_root is None:+ if monolith_ckpt is None:+ raise SystemExit(+ "Provide either monolith args (--checkpoint-path or --distilled-checkpoint-path "+ "+ --gemma-root) or one or more split pack flags "+ "(--transformer-path, --text-encoder-path, --audio-vae-path, "+ "--duration-head-path). --video-vae-path fills the video VAE slot in either mode."+ )++ # Parsers that declare ``--gemma-root`` (basic_arg_parser) must supply it in monolith+ # mode. HDR ACEScct CLIs omit the flag entirely and use precomputed embeddings —+ # ``gemma_root`` stays ``None`` (see ``ModelPaths.from_monolith``).+ if gemma_root is None and hasattr(namespace, "gemma_root"):raise SystemExit("Provide either monolith args (--checkpoint-path or --distilled-checkpoint-path ""+ --gemma-root) or one or more split pack flags "diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/samplers.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/samplers.pyindex 8c477c4..2130b55 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/samplers.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/samplers.py@@ -9,6 +9,7 @@ from tqdm import tqdmfrom ltx_core.components.diffusion_steps import (EulerAncestralDiffusionStep,EulerCfgPpDiffusionStep,+ EulerDiffusionStep,Res2sDiffusionStep,)from ltx_core.components.protocols import DiffusionStepProtocol@@ -17,7 +18,7 @@ from ltx_core.model.transformer import X0Modelfrom ltx_core.utils import to_denoised, to_velocityfrom ltx_pipelines.utils.helpers import post_process_latent, timesteps_from_maskfrom ltx_pipelines.utils.res2s import get_res2s_coefficients-from ltx_pipelines.utils.types import DenoisedLatentResult, Denoiser, LatentState+from ltx_pipelines.utils.types import DenoisedLatentResult, Denoiser, LatentState, VideoAudiologger = logging.getLogger(__name__)@@ -40,14 +41,14 @@ def euler_denoising_loop(sigmas: torch.Tensor,video_state: LatentState | None,audio_state: LatentState | None,- stepper: DiffusionStepProtocol,transformer: X0Model,denoiser: Denoiser,-) -> tuple[LatentState | None, LatentState | None]:+) -> VideoAudio[LatentState]:"""Perform the joint audio-video denoising loop over a diffusion schedule.Either ``video_state`` or ``audio_state`` may be ``None`` for absent- modalities; the absent modality is passed through unchanged.+ modalities; the absent modality is passed through unchanged. Each step is+ an :class:`~ltx_core.components.diffusion_steps.EulerDiffusionStep`.### Parameterssigmas:A 1D tensor of noise levels (diffusion sigmas) defining the sampling@@ -56,20 +57,18 @@ def euler_denoising_loop(The current video :class:`LatentState`, or ``None`` if video is absent.audio_state:The current audio :class:`LatentState`, or ``None`` if audio is absent.- stepper:- An implementation of :class:`DiffusionStepProtocol` that updates a- latent given the current latent, its denoised estimate, the full- ``sigmas`` schedule, and the current step index.transformer:The diffusion model passed to the denoiser at each step.denoiser:A callable implementing :class:`Denoiser`. It is invoked as``denoiser(transformer, video_state, audio_state, sigmas, step_index)``- and must return a :class:`~ltx_pipelines.utils.types.DenoisedLatentResult`.+ and must return a :class:`~ltx_pipelines.utils.types.VideoAudio` of+ :class:`~ltx_pipelines.utils.types.DenoisedLatentResult`.### Returns- tuple[LatentState | None, LatentState | None]- Final ``(video_state, audio_state)`` after the denoising loop.+ VideoAudio[LatentState]+ Final video and audio :class:`LatentState` after the denoising loop."""+ stepper = EulerDiffusionStep()for step_idx, _ in enumerate(tqdm(sigmas[:-1])):video_result, audio_result = denoiser(transformer, video_state, audio_state, sigmas, step_idx)denoised_video = video_result.denoised if video_result is not None else None@@ -78,18 +77,17 @@ def euler_denoising_loop(video_state = _step_state(video_state, denoised_video, stepper, sigmas, step_idx)audio_state = _step_state(audio_state, denoised_audio, stepper, sigmas, step_idx)- return (video_state, audio_state)+ return VideoAudio(video_state, audio_state)def gradient_estimating_euler_denoising_loop(sigmas: torch.Tensor,video_state: LatentState | None,audio_state: LatentState | None,- stepper: DiffusionStepProtocol,transformer: X0Model,denoiser: Denoiser,ge_gamma: float = 2.0,-) -> tuple[LatentState | None, LatentState | None]:+) -> VideoAudio[LatentState]:"""Perform the joint audio-video denoising loop using gradient-estimation sampling.Same interface as :func:`euler_denoising_loop` with an additional@@ -99,10 +97,11 @@ def gradient_estimating_euler_denoising_loop(Gradient estimation coefficient controlling the velocity correction term.Default is 2.0. Paper: https://openreview.net/pdf?id=o2ND9v0CeK### Returns- tuple[LatentState | None, LatentState | None]+ VideoAudio[LatentState]See :func:`euler_denoising_loop` for return value description."""+ stepper = EulerDiffusionStep()previous_audio_velocity = Noneprevious_video_velocity = None@@ -131,7 +130,7 @@ def gradient_estimating_euler_denoising_loop(video_state = replace(video_state, latent=denoised_video)if audio_state is not None and denoised_audio is not None:audio_state = replace(audio_state, latent=denoised_audio)- return video_state, audio_state+ return VideoAudio(video_state, audio_state)if video_state is not None and denoised_video is not None:previous_video_velocity, denoised_video = update_velocity_and_sample(@@ -149,7 +148,7 @@ def gradient_estimating_euler_denoising_loop(audio_state, latent=stepper.step(audio_state.latent, denoised_audio, sigmas, step_idx))- return (video_state, audio_state)+ return VideoAudio(video_state, audio_state)def _get_plain_noise(x: torch.Tensor, generator: torch.Generator) -> torch.Tensor:@@ -209,7 +208,6 @@ def res2s_audio_video_denoising_loop( # noqa: PLR0913,PLR0915,PLR0912sigmas: torch.Tensor,video_state: LatentState | None,audio_state: LatentState | None,- stepper: DiffusionStepProtocol,transformer: X0Model,denoiser: Denoiser,noise_seed: int = -1,@@ -220,14 +218,14 @@ def res2s_audio_video_denoising_loop( # noqa: PLR0913,PLR0915,PLR0912new_noise_fn: Callable[[torch.Tensor, torch.Generator], torch.Tensor] = _get_new_noise,model_dtype: torch.dtype = torch.bfloat16,legacy_mode: bool = True,-) -> tuple[LatentState | None, LatentState | None]:+) -> VideoAudio[LatentState]:"""Joint audio-video denoising loop using the res_2s second-order sampler.Iterates over the diffusion schedule with a two-stage Runge-Kutta step:evaluates the denoiser at the current point and at a midpoint (with SDEnoise), then combines both with RK coefficients. Supports anchor-point- refinement (bong iteration) and optional SDE noise injection. Requires- :class:`Res2sDiffusionStep` as ``stepper``.+ refinement (bong iteration) and optional SDE noise injection. Each update+ is a :class:`Res2sDiffusionStep`.Either modality may be ``None`` (absent).### Parameterstransformer:@@ -250,9 +248,10 @@ def res2s_audio_video_denoising_loop( # noqa: PLR0913,PLR0915,PLR0912model_dtype:Dtype for latent state updates (e.g. bfloat16).### Returns- tuple[LatentState | None, LatentState | None]- Final ``(video_state, audio_state)`` after the denoising loop.+ VideoAudio[LatentState]+ Final video and audio :class:`LatentState` after the denoising loop."""+ stepper = Res2sDiffusionStep()# Determine device from whichever state is presentpresent_state = video_state or audio_stateif present_state is None:@@ -273,9 +272,6 @@ def res2s_audio_video_denoising_loop( # noqa: PLR0913,PLR0915,PLR0912# substep eta is always default 0.5 for compatibility with original implementation.substep_noise_injecting_fn = partial(sde_noise_injecting_fn, step_noise_generator=substep_noise_generator, eta=0.5)- if not isinstance(stepper, Res2sDiffusionStep):- raise ValueError("stepper must be an instance of Res2sDiffusionStep")-n_full_steps = len(sigmas) - 1# inject minimal sigma value to avoid division by zeroif sigmas[-1] == 0:@@ -444,7 +440,7 @@ def res2s_audio_video_denoising_loop( # noqa: PLR0913,PLR0915,PLR0912denoised_audio_1 = post_process_latent(denoised_audio_1, audio_state.denoise_mask, audio_state.clean_latent)audio_state = replace(audio_state, latent=denoised_audio_1.to(model_dtype))- return video_state, audio_state+ return VideoAudio(video_state, audio_state)@dataclass(frozen=True)@@ -496,7 +492,7 @@ def _ancestral_euler_denoising_loop(model_dtype: torch.dtype,draw_noise: bool,make_step_fn: Callable[[DenoisedLatentResult | None, str], Callable[..., torch.Tensor]],-) -> tuple[LatentState | None, LatentState | None]:+) -> VideoAudio[LatentState]:"""Shared driver for the ancestral (noise-injecting) Euler denoising loops.Steps each present modality in float32, re-applies the conditioning mask@@ -517,7 +513,7 @@ def _ancestral_euler_denoising_loop(returns (before the terminal-sigma check), so it can also validate thedenoiser output. ``modality`` is ``"video"`` or ``"audio"``.### Returns- tuple[LatentState | None, LatentState | None]+ VideoAudio[LatentState]Final ``(video_state, audio_state)`` after the denoising loop."""if video_state is None and audio_state is None:@@ -560,28 +556,28 @@ def _ancestral_euler_denoising_loop(if terminal_step:break- return states["video"], states["audio"]+ return VideoAudio(states["video"], states["audio"])def euler_ancestral_denoising_loop(sigmas: torch.Tensor,video_state: LatentState | None,audio_state: LatentState | None,- stepper: EulerAncestralDiffusionStep,transformer: X0Model,denoiser: Denoiser,noise_seed: int = -1,new_noise_fn: Callable[[torch.Tensor, torch.Generator], torch.Tensor] = _get_plain_noise,model_dtype: torch.dtype = torch.bfloat16,-) -> tuple[LatentState | None, LatentState | None]:+ eta: float = 1.0,+ s_noise: float = 1.0,+) -> VideoAudio[LatentState]:"""Joint audio-video denoising loop using the ancestral (SDE) Euler sampler.Each step takes a deterministic Euler step to an intermediate ``sigma_down``and renoises back up to the next sigma; see:class:`~ltx_core.components.diffusion_steps.EulerAncestralDiffusionStep`.Works with any denoiser (no ``uncond`` prediction required). With- ``stepper=EulerAncestralDiffusionStep(eta=0.0)`` this reduces to- :func:`euler_denoising_loop`.+ ``eta=0.0`` this reduces to :func:`euler_denoising_loop`.Either ``video_state`` or ``audio_state`` may be ``None`` for absentmodalities. When both are present, noise is drawn from the same seededgenerator (video first, audio second).@@ -592,9 +588,6 @@ def euler_ancestral_denoising_loop(Current video :class:`~ltx_core.types.LatentState`, or ``None``.audio_state:Current audio :class:`~ltx_core.types.LatentState`, or ``None``.- stepper:- :class:`~ltx_core.components.diffusion_steps.EulerAncestralDiffusionStep`- instance carrying ``eta`` and ``s_noise`` parameters.transformer:The diffusion model passed to the denoiser at each step.denoiser:@@ -608,13 +601,18 @@ def euler_ancestral_denoising_loop(model_dtype:Dtype for latent state updates. Default ``bfloat16``. Pass``torch.float32`` to keep the sampling trajectory in full precision.+ eta:+ Stochastic noise injection strength passed to each+ :meth:`~ltx_core.components.diffusion_steps.EulerAncestralDiffusionStep.step`.+ ``0`` is a plain Euler step; ``1`` is fully ancestral. Default ``1.0``.+ s_noise:+ Scale on the injected noise. Default ``1.0``. At ``0`` the step still+ applies its variance-preserving rescale.### Returns- tuple[LatentState | None, LatentState | None]+ VideoAudio[LatentState]Final ``(video_state, audio_state)`` after the denoising loop."""- if not isinstance(stepper, EulerAncestralDiffusionStep):- raise ValueError(f"stepper must be an instance of EulerAncestralDiffusionStep, got {type(stepper).__name__}")-+ stepper = EulerAncestralDiffusionStep()return _ancestral_euler_denoising_loop(sigmas=sigmas,video_state=video_state,@@ -626,9 +624,8 @@ def euler_ancestral_denoising_loop(model_dtype=model_dtype,# Gated on eta alone: at s_noise=0 the step still applies its variance-preserving# rescale, so it must not fall back to the noise-free branch.- draw_noise=stepper.eta > 0,- # The ancestral step needs nothing beyond the standard arguments.- make_step_fn=lambda _result, _modality: stepper.step,+ draw_noise=eta > 0,+ make_step_fn=lambda _result, _modality: partial(stepper.step, eta=eta, s_noise=s_noise),)@@ -636,13 +633,14 @@ def euler_cfg_pp_denoising_loop(sigmas: torch.Tensor,video_state: LatentState | None,audio_state: LatentState | None,- stepper: EulerCfgPpDiffusionStep,transformer: X0Model,denoiser: Denoiser,noise_seed: int = -1,new_noise_fn: Callable[[torch.Tensor, torch.Generator], torch.Tensor] = _get_plain_noise,model_dtype: torch.dtype = torch.bfloat16,-) -> tuple[LatentState | None, LatentState | None]:+ eta: float = 1.0,+ s_noise: float = 1.0,+) -> VideoAudio[LatentState]:"""Joint audio-video denoising loop using the CFG++ corrected Euler sampler.Applies the CFG++ update rule at each step: the ODE derivative is computed@@ -660,9 +658,6 @@ def euler_cfg_pp_denoising_loop(Current video :class:`~ltx_core.types.LatentState`, or ``None``.audio_state:Current audio :class:`~ltx_core.types.LatentState`, or ``None``.- stepper:- :class:`~ltx_core.components.diffusion_steps.EulerCfgPpDiffusionStep`- instance carrying ``eta`` and ``s_noise`` parameters.transformer:The diffusion model passed to the denoiser at each step.denoiser:@@ -675,15 +670,20 @@ def euler_cfg_pp_denoising_loop(:func:`_get_new_noise` for the normalized variant used in res2s.model_dtype:Dtype for latent state updates. Default ``bfloat16``.+ eta:+ Stochastic noise injection strength passed to each+ :meth:`~ltx_core.components.diffusion_steps.EulerCfgPpDiffusionStep.step`.+ Default ``1.0``.+ s_noise:+ Scale on the injected noise. Default ``1.0``.### Returns- tuple[LatentState | None, LatentState | None]- Final ``(video_state, audio_state)`` after the denoising loop.+ VideoAudio[LatentState]+ Final video and audio :class:`LatentState` after the denoising loop."""- if not isinstance(stepper, EulerCfgPpDiffusionStep):- raise ValueError(f"stepper must be an instance of EulerCfgPpDiffusionStep, got {type(stepper).__name__}")+ stepper = EulerCfgPpDiffusionStep()def make_step_fn(result: DenoisedLatentResult | None, modality: str) -> Callable[..., torch.Tensor]:- """Bind the modality's uncond prediction into the CFG++ step."""+ """Bind the modality's uncond prediction and the loop's noise scales into the CFG++ step."""uncond = result.uncond if result is not None else Noneif not isinstance(uncond, torch.Tensor):raise ValueError(@@ -691,7 +691,7 @@ def euler_cfg_pp_denoising_loop("Use GuidedDenoiser or FactoryGuidedDenoiser with cfg_scale != 1 ""or force_uncond_pass=True and a negative_context.")- return partial(stepper.step, uncond_denoised=uncond)+ return partial(stepper.step, uncond_denoised=uncond, eta=eta, s_noise=s_noise)return _ancestral_euler_denoising_loop(sigmas=sigmas,@@ -702,6 +702,6 @@ def euler_cfg_pp_denoising_loop(noise_seed=noise_seed,new_noise_fn=new_noise_fn,model_dtype=model_dtype,- draw_noise=stepper.eta > 0 and stepper.s_noise > 0,+ draw_noise=eta > 0 and s_noise > 0,make_step_fn=make_step_fn,)diff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/tiled_diffusion.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/tiled_diffusion.pynew file mode 100644index 0000000..b5ef2e2--- /dev/null+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/tiled_diffusion.py@@ -0,0 +1,151 @@+"""Shared single-GPU transformer tiling for diffusion stages."""++from __future__ import annotations++from collections.abc import Sequence+from dataclasses import dataclass+from typing import TYPE_CHECKING++import torch++from ltx_core.modality_tiling import VideoModalityTilingHelper+from ltx_core.model.transformer.modality import Modality+from ltx_core.model.video_vae import TilingConfig+from ltx_core.tiling import DEFAULT_SPLIT_OPERATION, SplitOperation, Tile, split_by_size_pinned+from ltx_core.tools import LatentTools, VideoLatentTools+from ltx_core.types import SpatioTemporalScaleFactors+from ltx_pipelines.utils.blocks import DiffusionStage++if TYPE_CHECKING:+ from ltx_core.guidance.perturbations import BatchedPerturbationConfig+++@dataclass(frozen=True)+class FixedSizeSpatialTiling:+ """Fixed transformer windows with a minimum overlap in pixel units.+ Every tile remains exactly ``height`` by ``width`` unless the full canvas is+ smaller on that axis. First and last tile origins are pinned to the canvas;+ interior origins are redistributed so the requested overlap is a minimum.+ """++ height: int+ width: int+ height_overlap: int+ width_overlap: int++ def to_splitters(+ self,+ scale_factors: SpatioTemporalScaleFactors,+ min_tile_size: tuple[int, int, int] | None = None,+ *,+ causal_temporal: bool = False,+ ) -> tuple[SplitOperation, SplitOperation, SplitOperation]:+ """Resolve fixed pixel windows onto the transformer's latent grid."""+ del min_tile_size, causal_temporal+ values = (+ ("height", self.height, self.height_overlap, scale_factors.height),+ ("width", self.width, self.width_overlap, scale_factors.width),+ )+ for axis, size, overlap, scale in values:+ if size % scale or overlap % scale:+ raise ValueError(f"{axis} tile size and overlap must be divisible by {scale}")+ return (+ DEFAULT_SPLIT_OPERATION,+ split_by_size_pinned(self.height // scale_factors.height, self.height_overlap // scale_factors.height),+ split_by_size_pinned(self.width // scale_factors.width, self.width_overlap // scale_factors.width),+ )+++DiffusionTilingConfig = TilingConfig | FixedSizeSpatialTiling+++def diffusion_stage_with_tiling(+ stage: DiffusionStage,+ tiling: DiffusionTilingConfig | None,+) -> DiffusionStage:+ """Return a diffusion stage that tiles each transformer call when ``tiling`` is set."""+ if tiling is None:+ return stage++ def wrap(model: torch.nn.Module, tools: LatentTools | None) -> torch.nn.Module:+ if not isinstance(tools, VideoLatentTools):+ raise TypeError(f"Spatial tiling requires video tools, got {type(tools).__name__}")+ return TiledDiffusionModel(model, video_tools=tools, tiling=tiling)++ return stage.with_model_wrapper(wrap)+++class TiledDiffusionModel(torch.nn.Module):+ """Run one transformer call over sequential video tiles and blend its prediction.+ The single-GPU counterpart of+ :class:`~ltx_core.multigpu.transformer.tiled_data_parallel.TiledDataParallelModelWrapper`:+ same :class:`VideoModalityTilingHelper`, same trapezoidal blend masks, same+ conditioning-token filtering. Tiles run here rather than round-robin across+ ranks. This wraps the ``X0Model`` instead of the bare velocity model, so it+ blends x0 predictions; ``to_denoised`` is affine in the velocity and every+ tile sees the same per-token timesteps, so with blend weights summing to 1+ the two are the same value.+ The sampler still owns one full-canvas latent and advances it once per diffusion+ step. This wrapper only changes how that step's model prediction is evaluated:+ each tile runs sequentially, and overlapping predictions are accumulated with+ the tiling subsystem's separable trapezoidal masks.+ ``seams`` are optional known temporal handover cells. They are used by DFR to+ denoise overlap for context and then discard it instead of blending. Ordinary+ spatial IC-LoRA tiling leaves them empty.+ """++ def __init__(+ self,+ model: torch.nn.Module,+ *,+ video_tools: VideoLatentTools,+ tiling: DiffusionTilingConfig,+ seams: Sequence[int] = (),+ normalize_positions: bool = True,+ ) -> None:+ super().__init__()+ self.model = model+ self._normalize_positions = normalize_positions+ self._helper = VideoModalityTilingHelper(tiling, video_tools, seams=seams) # type: ignore[arg-type]++ @property+ def num_blocks(self) -> int:+ """Number of transformer blocks in the wrapped model."""+ return self.model.num_blocks++ @property+ def tiles(self) -> list[Tile]:+ """Tiles walked by every transformer call, in blend order."""+ return self._helper.tiles++ def forward(+ self,+ video: Modality | None,+ audio: Modality | None,+ perturbations: BatchedPerturbationConfig | None,+ ) -> tuple[torch.Tensor | None, torch.Tensor | None]:+ """Evaluate and blend one full-canvas model prediction."""+ if video is None:+ return self.model(video, audio, perturbations)++ denoised_video: torch.Tensor | None = None+ denoised_audio: torch.Tensor | None = None+ for tile in self._helper.tiles:+ tiled_video, context = self._helper.tile_modality(+ video,+ tile,+ normalize_positions=self._normalize_positions,+ )+ tile_video, tile_audio = self.model(tiled_video, audio, perturbations)+ if tile_video is None:+ raise RuntimeError("Transformer returned no video prediction for a video tile")+ denoised_video = self._helper.blend(tile_video, tile, context, denoised_video)+ if tile_audio is not None:+ denoised_audio = tile_audio if denoised_audio is None else denoised_audio + tile_audio++ if denoised_video is None:+ raise RuntimeError("Tiled transformer produced no video prediction")+ if denoised_audio is not None:+ # Every tile sees the full audio stream with a different video context.+ denoised_audio = denoised_audio / len(self._helper.tiles)+ return denoised_video, denoised_audiodiff --git a/packages/ltx-pipelines/src/ltx_pipelines/utils/types.py b/packages/ltx-pipelines/src/ltx_pipelines/utils/types.pyindex 8bc372b..e7b11a6 100644--- a/packages/ltx-pipelines/src/ltx_pipelines/utils/types.py+++ b/packages/ltx-pipelines/src/ltx_pipelines/utils/types.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom collections.abc import Iteratorfrom dataclasses import dataclass, fieldfrom enum import Enum-from typing import NamedTuple, Protocol+from typing import Generic, NamedTuple, Protocol, TypeVarimport torch@@ -11,37 +11,39 @@ from ltx_core.components.patchifiers import AudioPatchifier, VideoLatentPatchififrom ltx_core.conditioning import ConditioningItemfrom ltx_core.model.transformer import X0Modelfrom ltx_core.model.video_vae import TilingConfig-from ltx_core.model.video_vae.keyframes import DecodeKeyframesfrom ltx_core.types import Audio, LatentStatefrom ltx_pipelines.utils.constants import VIDEO_LATENT_CHANNELS, VIDEO_SCALE_FACTORS+_T = TypeVar("_T")+class PipelineOutput(NamedTuple):"""Return type of every video pipeline ``__call__``.A ``NamedTuple`` rather than a bare tuple so adding fields fails loudly at anycall site that unpacks a fixed arity. Prefer attribute access(``result.video``, ``result.audio``, ...) over positional unpack.- Trailing extras are optional:- * ``keyframes`` -- filled only when the run produced generated slots already at- **final** output resolution. ``keyframes.pixel_frame_indices`` stay on that- pixel grid. Half-res stage-1 slots are not a substitute: if the pipeline never- upscaled them to the final canvas, this field is ``None``.- * ``video_latent`` -- the final video latent ``video`` was decoded from, when the- pipeline retains it for keyframe-aware re-decode. ``None`` when not retained.+ Keyframe-aware decoding is decided inside the pipeline via ``decode_with_keyframes``;+ the returned ``video`` iterator already reflects that choice."""video: Iterator[torch.Tensor]audio: Audionum_frames: inttiling_config: TilingConfig | None- #: Generated keyframe slots already at **final** output resolution, with- #: ``pixel_frame_indices`` on that pixel grid. ``None`` when the run produced none, or- #: when slots exist only at a coarser scale the pipeline never upscaled.- keyframes: DecodeKeyframes | None- #: The final video latent ``video`` was decoded from, when retained. Re-decoding through- #: ``decode_video(keyframes=)`` needs this together with ``keyframes``; re-encoding decoded- #: pixels would not reproduce it. ``None`` when the pipeline does not keep the latent.- video_latent: torch.Tensor | None+++class ImageConditioningInput(NamedTuple):+ """An image to condition on, with the H.264 CRF it should be re-compressed at.+ Leaving ``crf`` unset means "use whatever matches the model": the pipeline fills it in+ from the checkpoint it runs (``ImageConditioner.resolve_crf``), since the value the model+ was trained with is a property of the model generation. Pass ``crf`` explicitly to+ override it, including ``0`` to skip re-compression entirely.+ """++ path: str+ frame_idx: int+ strength: float+ crf: int | None = Noneclass PipelineComponents:@@ -77,8 +79,7 @@ class DenoisedLatentResult:``denoised`` is the final blended prediction for this modality.The remaining fields carry the per-pass raw outputs from ``_guided_denoise``(all ``None`` for ``SimpleDenoiser``). Denoisers return a- ``(video_result, audio_result)`` tuple; either element may be ``None``- for absent modalities.+ :class:`VideoAudio` of these results; omit the absent side."""denoised: torch.Tensor@@ -101,6 +102,24 @@ class DenoisedLatentResult:return cls(denoised=denoised, uncond=uncond, cond=cond, ptb=ptb, mod=mod)+@dataclass(frozen=True)+class VideoAudio(Generic[_T]):+ """Video and audio values for one multimodal step.+ Either side may be omitted (defaults to ``None``) when that modality is+ absent. At least one side is required. Unpacks as ``(video, audio)``.+ """++ video: _T | None = None+ audio: _T | None = None++ def __post_init__(self) -> None:+ if self.video is None and self.audio is None:+ raise ValueError("VideoAudio requires at least one of video or audio")++ def __iter__(self) -> Iterator[_T | None]:+ return iter((self.video, self.audio))++class Denoiser(Protocol):"""Protocol for a denoiser that receives the transformer at call time.The transformer is not stored — it is passed as the first argument so the@@ -112,8 +131,8 @@ class Denoiser(Protocol):sigmas: 1-D tensor of sigma values for each diffusion step.step_index: Index of the current denoising step.Returns:- A ``(video_result, audio_result)`` tuple of :class:`DenoisedLatentResult`,- either may be ``None`` for absent modalities.+ A :class:`VideoAudio` of :class:`DenoisedLatentResult`; omit the+ absent side."""def __call__(@@ -123,7 +142,7 @@ class Denoiser(Protocol):audio_state: LatentState | None,sigmas: torch.Tensor,step_index: int,- ) -> tuple[DenoisedLatentResult | None, DenoisedLatentResult | None]: ...+ ) -> VideoAudio[DenoisedLatentResult]: ...@dataclass(frozen=True)@@ -131,16 +150,25 @@ class ModalitySpec:"""Specification for one modality passed to a diffusion stage.Carries everything needed to build the initial noised latent stateand run the denoising loop for a single modality (video or audio).- Tools are created by ``DiffusionStage`` from pixel-space dimensions.+ ``latent`` is the latent to denoise, and it is the stage's only source of shape --+ latent tools are derived from it. A first stage seeds it with zeros from+ :func:`~ltx_pipelines.utils.helpers.create_initial_video_latent` (or its audio+ counterpart); later stages pass the previous stage's output, optionally upscaled.``frozen=True`` zeros the denoise mask and marks the resulting ``LatentState``so ``Modality.sigma`` is forced to 0 (not only per-token timesteps).+ ``conditioning_fps`` is the transformer's video time base when video is present.+ Callers pass it on every spec, including audio, so multimodal steps share one+ time base; the stage reads it from the video spec only today. Playback fps for+ decode/mux and audio latent duration are decided elsewhere+ (``create_initial_audio_latent``, export), not on this field."""+ latent: torch.Tensor+ conditioning_fps: floatcontext: torch.Tensor | None = Noneconditionings: list[ConditioningItem] = field(default_factory=list)noise_scale: float = 1.0frozen: bool = False- initial_latent: torch.Tensor | None = None@dataclass(frozen=True)diff --git a/packages/ltx-trainer/pyproject.toml b/packages/ltx-trainer/pyproject.tomlindex 84cfa6c..8294196 100644--- a/packages/ltx-trainer/pyproject.toml+++ b/packages/ltx-trainer/pyproject.toml@@ -1,6 +1,6 @@[project]name = "ltx-trainer"-version = "1.3.0"+version = "1.4.0"description = "LTX-2 training, democratized."readme = "README.md"authors = [diff --git a/packages/ltx-trainer/scripts/process_dataset.py b/packages/ltx-trainer/scripts/process_dataset.pyindex 57fc69c..92b450a 100755--- a/packages/ltx-trainer/scripts/process_dataset.py+++ b/packages/ltx-trainer/scripts/process_dataset.py@@ -23,7 +23,12 @@ from pathlib import Pathimport typerfrom decode_latents import LatentsDecoderfrom process_captions import compute_captions_embeddings-from process_videos import (+from rich.console import Console++from ltx_trainer import logger+from ltx_trainer.gpu_utils import free_gpu_memory_context+from ltx_trainer.model_loader import read_video_scale_factors, resolve_video_vae_path+from ltx_trainer.process_videos import (compute_audio_latents,compute_audio_masks,compute_latents,@@ -32,11 +37,6 @@ from process_videos import (detect_dataset_columns,parse_resolution_buckets,)-from rich.console import Console--from ltx_trainer import logger-from ltx_trainer.gpu_utils import free_gpu_memory_context-from ltx_trainer.model_loader import read_video_scale_factors, resolve_video_vae_pathconsole = Console()diff --git a/packages/ltx-trainer/scripts/process_videos.py b/packages/ltx-trainer/scripts/process_videos.pyindex 1a7c94a..fa5ea1f 100755--- a/packages/ltx-trainer/scripts/process_videos.py+++ b/packages/ltx-trainer/scripts/process_videos.py@@ -1,1519 +1,6 @@#!/usr/bin/env python3-"""-Compute latent representations for video generation training.-This module provides functionality for processing video and image files, including:-- Loading videos/images from various file formats (CSV, JSON, JSONL)-- Resizing, cropping, and transforming media-- MediaDataset for video-only preprocessing workflows-- BucketSampler for grouping videos by resolution-Can be used as a standalone script:- python scripts/process_videos.py dataset.csv --resolution-buckets 768x768x25 \- --output-dir /path/to/output --model-path /path/to/ltx-checkpoint.safetensors-"""--import json-import math-import os-from collections.abc import Callable-from pathlib import Path-from typing import Any--import numpy as np-import pandas as pd-import torch-import torchaudio-import typer-from accelerate import PartialState-from pillow_heif import register_heif_opener-from rich.console import Console-from rich.progress import (- BarColumn,- MofNCompleteColumn,- Progress,- SpinnerColumn,- TaskProgressColumn,- TextColumn,- TimeElapsedColumn,- TimeRemainingColumn,-)-from torch.utils.data import DataLoader, Dataset, Subset-from torchvision import transforms-from torchvision.transforms import InterpolationMode-from torchvision.transforms.functional import crop, resize, to_tensor-from torchvision.transforms.functional import resize as tv_resize-from transformers.utils.logging import disable_progress_bar--from ltx_core.model.audio_vae import AudioProcessor-from ltx_core.types import VIDEO_SCALE_FACTORS, Audio, SpatioTemporalScaleFactors-from ltx_trainer import logger-from ltx_trainer.model_loader import (- load_audio_vae_encoder,- load_video_vae_encoder,- read_video_scale_factors,- resolve_audio_vae_path,- resolve_video_vae_path,-)-from ltx_trainer.utils import open_image_as_srgb-from ltx_trainer.video_utils import get_video_frame_count, read_video--disable_progress_bar()--# Register HEIF/HEIC support-register_heif_opener()--# Audio constants-AUDIO_LATENT_CHANNELS = 8-AUDIO_FREQUENCY_BINS = 16--DEFAULT_TILE_SIZE = 512 # Spatial tile size in pixels (must be ≥64 and divisible by 32)-DEFAULT_TILE_OVERLAP = 128 # Spatial tile overlap in pixels (must be divisible by 32)--app = typer.Typer(- pretty_exceptions_enable=False,- no_args_is_help=True,- help="Process videos/images and save latent representations for video generation training.",-)---def _clamp_01(x: torch.Tensor) -> torch.Tensor:- return x.clamp_(0, 1)---class MediaDataset(Dataset):- """- Dataset for processing video and image files.- This dataset is designed for media preprocessing workflows where you need to:- - Load and preprocess videos/images- - Apply resizing and cropping transformations- - Handle different resolution buckets- - Filter out invalid media files- - Optionally extract audio from video files- """-- def __init__(- self,- dataset_file: str | Path,- main_media_column: str,- video_column: str,- resolution_buckets: list[tuple[int, int, int]],- reshape_mode: str = "center",- with_audio: bool = False,- temporal_subsample_factor: int = 1,- ) -> None:- """- Initialize the media dataset.- Args:- dataset_file: Path to CSV/JSON/JSONL metadata file- video_column: Column name for video paths in the metadata file- resolution_buckets: List of (frames, height, width) tuples- reshape_mode: How to crop videos ("center", "random")- with_audio: Whether to extract audio from video files- temporal_subsample_factor: Factor for VAE-aligned temporal subsampling.- When > 1, keeps frame 0 then takes every Nth frame from frame 1 onwards.- """- super().__init__()-- self.dataset_file = Path(dataset_file)- self.main_media_column = main_media_column- self.resolution_buckets = resolution_buckets- self.reshape_mode = reshape_mode- self.with_audio = with_audio- self.temporal_subsample_factor = temporal_subsample_factor-- # First load main media paths- self.main_media_paths = self._load_video_paths(main_media_column)-- # Then load reference video paths- self.video_paths = self._load_video_paths(video_column)-- # Filter out videos with insufficient frames- self._filter_valid_videos()-- self.max_target_frames = max(self.resolution_buckets, key=lambda x: x[0])[0]-- # Set up video transforms- self.transforms = transforms.Compose(- [- transforms.Lambda(_clamp_01),- transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True),- ]- )-- def __len__(self) -> int:- return len(self.video_paths)-- def __getitem__(self, index: int) -> dict[str, Any]:- """Get a single video/image with metadata, and optionally audio."""- if isinstance(index, list):- # Special case for BucketSampler - return cached data- return index-- video_path: Path = self.video_paths[index]-- # Compute relative path of the video- data_root = self.dataset_file.parent- relative_path = str(_output_relative(video_path, data_root))- media_relative_path = str(_output_relative(self.main_media_paths[index], data_root))-- if video_path.suffix.lower() in [".png", ".jpg", ".jpeg"]:- media_tensor = self._preprocess_image(video_path)- fps = 1.0- audio_data = None # Images don't have audio- else:- media_tensor, fps = self._preprocess_video(video_path)-- # Extract audio if enabled- if self.with_audio:- # Calculate target duration from the processed video frames- # This ensures audio is trimmed to match the exact video duration- # media_tensor is [C, F, H, W] so shape[1] is num_frames- target_duration = media_tensor.shape[1] / fps- audio_data = self._extract_audio(video_path, target_duration)- else:- audio_data = None-- # media_tensor is [C, F, H, W] format for VAE compatibility- _, num_frames, height, width = media_tensor.shape-- result = {- "video": media_tensor,- "relative_path": relative_path,- "main_media_relative_path": media_relative_path,- "video_metadata": {- "num_frames": num_frames,- "height": height,- "width": width,- "fps": fps,- },- }-- # Add audio data if available- if audio_data is not None:- result["audio"] = audio_data-- return result-- @staticmethod- def _extract_audio(video_path: Path, target_duration: float) -> dict[str, torch.Tensor | int] | None:- """Extract audio track from a video file, trimmed/padded to match video duration."""- audio = _load_audio_from_file(video_path, max_duration=target_duration)- if audio is None:- return None-- # Pad if shorter than target (_load_audio_from_file only trims, doesn't pad)- target_samples = int(target_duration * audio.sampling_rate)- if audio.waveform.shape[-1] < target_samples:- padding = target_samples - audio.waveform.shape[-1]- waveform = torch.nn.functional.pad(audio.waveform, (0, padding))- logger.warning(f"Padded audio to {target_duration:.2f} seconds for {video_path}")- else:- waveform = audio.waveform-- return {"waveform": waveform, "sample_rate": audio.sampling_rate}-- def _load_video_paths(self, column: str) -> list[Path]:- """Load video paths from the specified data source, validating existence."""- paths = _load_paths_from_dataset(self.dataset_file, column)- invalid = [p for p in paths if not p.is_file()]- if invalid:- raise ValueError(f"Found {len(invalid)} invalid paths in '{column}'. First few: {invalid[:5]}")- return paths-- def _filter_valid_videos(self) -> None:- """Filter out videos with insufficient frames."""- original_length = len(self.video_paths)- valid_video_paths = []- valid_main_media_paths = []- min_frames_required = min(self.resolution_buckets, key=lambda x: x[0])[0]-- for i, video_path in enumerate(self.video_paths):- if video_path.suffix.lower() in [".png", ".jpg", ".jpeg"]:- valid_video_paths.append(video_path)- valid_main_media_paths.append(self.main_media_paths[i])- continue-- try:- frame_count = get_video_frame_count(video_path)-- if frame_count >= min_frames_required:- valid_video_paths.append(video_path)- valid_main_media_paths.append(self.main_media_paths[i])- else:- logger.warning(- f"Skipping video at {video_path} - has {frame_count} frames, "- f"which is less than the minimum required frames ({min_frames_required})"- )- except Exception as e:- logger.warning(f"Failed to read video at {video_path}: {e!s}")-- # Update both path lists to maintain synchronization- self.video_paths = valid_video_paths- self.main_media_paths = valid_main_media_paths-- if len(self.video_paths) < original_length:- logger.warning(- f"Filtered out {original_length - len(self.video_paths)} videos with insufficient frames. "- f"Proceeding with {len(self.video_paths)} valid videos."- )-- def _preprocess_image(self, path: Path) -> torch.Tensor:- """Preprocess a single image by resizing and applying transforms."""- image = open_image_as_srgb(path)- image = to_tensor(image)- image = image.unsqueeze(0) # Add frame dimension [1, C, H, W] for bucket selection-- # Find nearest resolution bucket and resize- nearest_bucket = self._get_resolution_bucket_for_item(image)- _, target_height, target_width = nearest_bucket- image_resized = self._resize_and_crop(image, target_height, target_width)- # _resize_and_crop returns [C, H, W] for single-frame input (squeeze removes dim 0)-- # Apply transforms- image = self.transforms(image_resized) # [C, H, W] -> [C, H, W]-- # Add frame dimension in VAE format: [C, H, W] -> [C, 1, H, W]- image = image.unsqueeze(1)- return image-- def _preprocess_video(self, path: Path) -> tuple[torch.Tensor, float]:- """Preprocess a video by loading, resizing, and applying transforms.- Returns:- Tuple of (video tensor in [C, F, H, W] format, fps)- """- # Load video frames up to max_target_frames- video, fps = read_video(path, max_frames=self.max_target_frames)-- nearest_bucket = self._get_resolution_bucket_for_item(video)- target_num_frames, target_height, target_width = nearest_bucket- frames_resized = self._resize_and_crop(video, target_height, target_width)-- # Trim video to target number of frames- frames_resized = frames_resized[:target_num_frames]-- # VAE-aligned temporal subsampling: keep frame 0, then every Nth frame- if self.temporal_subsample_factor > 1:- indices = _compute_temporal_subsample_indices(target_num_frames, self.temporal_subsample_factor)- frames_resized = frames_resized[indices]-- # Apply transforms to each frame and stack- video = torch.stack([self.transforms(frame) for frame in frames_resized], dim=0)-- # Permute [F,C,H,W] -> [C,F,H,W] for VAE compatibility- # After DataLoader batching, this becomes [B,C,F,H,W] which VAE expects- video = video.permute(1, 0, 2, 3).contiguous()-- return video, fps-- def _get_resolution_bucket_for_item(self, media_tensor: torch.Tensor) -> tuple[int, int, int]:- """Get the nearest resolution bucket for the given media tensor."""- num_frames, _, height, width = media_tensor.shape-- def distance(bucket: tuple[int, int, int]) -> tuple:- bucket_num_frames, bucket_height, bucket_width = bucket- # Lexicographic key:- # 1) minimize aspect-ratio diff (in log-scale, for invariance to shorter/longer ARs)- # 2) prefer buckets with more frames (by using negative)- # 3) prefer buckets with larger spatial area (by using negative)- return (- abs(math.log(width / height) - math.log(bucket_width / bucket_height)),- -bucket_num_frames,- -(bucket_height * bucket_width),- )-- # Keep only buckets with <= available frames- relevant_buckets = [b for b in self.resolution_buckets if b[0] <= num_frames]- if not relevant_buckets:- raise ValueError(f"No resolution buckets have <= {num_frames} frames. Available: {self.resolution_buckets}")-- # Find the bucket with the minimal distance (according to the function above) to the media item's shape.- nearest_bucket = min(relevant_buckets, key=distance)-- return nearest_bucket-- def _resize_and_crop(self, media_tensor: torch.Tensor, target_height: int, target_width: int) -> torch.Tensor:- """Resize and crop tensor to target size."""- # Get current dimensions- current_height, current_width = media_tensor.shape[2], media_tensor.shape[3]-- # Calculate aspect ratios to determine which dimension to resize first- current_aspect = current_width / current_height- target_aspect = target_width / target_height-- # Resize while maintaining aspect ratio - scale to make the smaller dimension fit- if current_aspect > target_aspect:- # Current is wider than target, so scale by height- new_width = int(current_width * target_height / current_height)- media_tensor = resize(- media_tensor,- size=[target_height, new_width], # type: ignore- interpolation=InterpolationMode.BICUBIC,- )- else:- # Current is taller than target, so scale by width- new_height = int(current_height * target_width / current_width)- media_tensor = resize(- media_tensor,- size=[new_height, target_width],- interpolation=InterpolationMode.BICUBIC,- )-- # Update dimensions after resize- current_height, current_width = media_tensor.shape[2], media_tensor.shape[3]- media_tensor = media_tensor.squeeze(0)-- # Calculate how much we need to crop from each dimension- delta_h = current_height - target_height- delta_w = current_width - target_width-- # Determine crop position based on reshape mode- if self.reshape_mode == "random":- # Random crop position- top = np.random.randint(0, delta_h + 1)- left = np.random.randint(0, delta_w + 1)- elif self.reshape_mode == "center":- # Center crop- top, left = delta_h // 2, delta_w // 2- else:- raise ValueError(f"Unsupported reshape mode: {self.reshape_mode}")-- # Perform the final crop to exact target dimensions- media_tensor = crop(media_tensor, top=top, left=left, height=target_height, width=target_width)- return media_tensor---def _compute_temporal_subsample_indices(num_frames: int, factor: int) -> list[int]:- """Compute VAE-aligned temporal subsample indices.- Keeps frame 0 (the VAE's standalone first-frame latent), then takes every- ``factor``-th frame from frame 1 onwards. This ensures each resulting- 8-frame VAE group spans ``factor`` groups of the original video.- """- if factor == 1:- return list(range(num_frames))- return [0, *list(range(1, num_frames, factor))]---def compute_latents( # noqa: PLR0912, PLR0913, PLR0915- dataset_file: str | Path,- video_column: str,- resolution_buckets: list[tuple[int, int, int]],- output_dir: str,- model_path: str,- video_vae_path: str | None = None,- audio_vae_path: str | None = None,- main_media_column: str | None = None,- reshape_mode: str = "center",- batch_size: int = 1,- device: str = "cuda",- vae_tiling: bool = False,- with_audio: bool = False,- audio_output_dir: str | None = None,- num_dataloader_workers: int = 4,- overwrite: bool = False,- temporal_subsample_factor: int = 1,-) -> None:- """- Process videos and save latent representations.- Under ``accelerate launch``, each process handles an interleaved shard of- the dataset (rank/world read from ``accelerate.PartialState``). Already-- computed ``.pt`` outputs are skipped unless ``overwrite=True``; writes are- atomic so an interrupted run is safe to resume.- Args:- dataset_file: Path to metadata file (CSV/JSON/JSONL) containing video paths- video_column: Column name for video paths in the metadata file- resolution_buckets: List of (frames, height, width) tuples- output_dir: Directory to save video latents- model_path: Path to LTX-2 checkpoint (.safetensors)- reshape_mode: How to crop videos ("center", "random")- main_media_column: Column name for main media paths (if different from video_column)- batch_size: Batch size for processing- device: Device to use for computation- vae_tiling: Whether to enable VAE tiling- with_audio: Whether to extract and encode audio from videos- audio_output_dir: Directory to save audio latents (required if with_audio=True)- num_dataloader_workers: Number of DataLoader worker processes (0 for in-process loading)- overwrite: Re-process every item even if its output exists. Use when rerunning with- changed parameters (different model, resolution, etc.) so stale outputs are replaced.- temporal_subsample_factor: Factor for VAE-aligned temporal subsampling of reference videos- """- video_vae_path = resolve_video_vae_path(model_path, video_vae_path)- # Video VAE compression factors, derived from the checkpoint config (default 32x32x8).- scale_factors = read_video_scale_factors(video_vae_path)-- # Validate temporal subsampling compatibility with resolution buckets- if temporal_subsample_factor > 1:- for frames, _h, _w in resolution_buckets:- pixel_frames_minus_one = frames - 1- if pixel_frames_minus_one % temporal_subsample_factor != 0:- raise ValueError(- f"Frame count {frames} is not compatible with "- f"temporal_subsample_factor={temporal_subsample_factor}. "- f"(frames - 1) must be divisible by the factor."- )- subsampled = 1 + pixel_frames_minus_one // temporal_subsample_factor- if (subsampled - 1) % scale_factors.time != 0:- raise ValueError(- f"After temporal subsampling {frames} → {subsampled} frames, "- f"result does not satisfy (frames - 1) % {scale_factors.time} == 0."- )-- if with_audio and audio_output_dir is None:- raise ValueError("audio_output_dir must be provided when with_audio=True")-- console = Console()- torch_device = torch.device(device)-- dataset = MediaDataset(- dataset_file=dataset_file,- main_media_column=main_media_column or video_column,- video_column=video_column,- resolution_buckets=resolution_buckets,- reshape_mode=reshape_mode,- with_audio=with_audio,- temporal_subsample_factor=temporal_subsample_factor,- )- logger.info(f"Loaded {len(dataset)} valid media files")-- output_path = Path(output_dir)- output_path.mkdir(parents=True, exist_ok=True)-- audio_output_path: Path | None = None- if with_audio:- audio_output_path = Path(audio_output_dir)- audio_output_path.mkdir(parents=True, exist_ok=True)-- # Audio processing requires batch_size=1; must be applied before the dataloader is built.- if with_audio and batch_size > 1:- logger.warning("Audio processing requires batch_size=1. Overriding batch_size to 1.")- batch_size = 1-- data_root = Path(dataset_file).parent-- def _is_done(idx: int) -> bool:- rel = _output_relative(dataset.main_media_paths[idx], data_root).with_suffix(".pt")- if not (output_path / rel).is_file():- return False- return audio_output_path is None or (audio_output_path / rel).is_file()-- dataloader = _build_sharded_dataloader(- dataset,- batch_size=batch_size,- num_workers=num_dataloader_workers,- is_done=_is_done,- overwrite=overwrite,- )- if dataloader is None:- return-- with console.status(f"[bold]Loading video VAE encoder from [cyan]{video_vae_path}[/]...", spinner="dots"):- vae = load_video_vae_encoder(video_vae_path, device=torch_device, dtype=torch.bfloat16)-- audio_vae_encoder = None- audio_processor = None- if with_audio:- # Resolved here so a video-only run never has to name a split pack's audio VAE.- audio_vae_path = resolve_audio_vae_path(model_path, audio_vae_path)- with console.status(f"[bold]Loading audio VAE encoder from [cyan]{audio_vae_path}[/]...", spinner="dots"):- audio_vae_encoder = load_audio_vae_encoder(- checkpoint_path=audio_vae_path,- device=torch_device,- dtype=torch.float32, # Audio VAE needs float32 for quality. TODO: re-test with bfloat16.- )- audio_processor = AudioProcessor(- target_sample_rate=audio_vae_encoder.sample_rate,- mel_bins=audio_vae_encoder.mel_bins,- mel_hop_length=audio_vae_encoder.mel_hop_length,- n_fft=audio_vae_encoder.n_fft,- ).to(torch_device)-- # Track audio statistics- audio_success_count = 0- audio_skip_count = 0-- # Process batches- with Progress(- SpinnerColumn(),- TextColumn("[progress.description]{task.description}"),- BarColumn(),- TaskProgressColumn(),- MofNCompleteColumn(),- TimeElapsedColumn(),- TimeRemainingColumn(),- console=console,- ) as progress:- task = progress.add_task("Processing videos", total=len(dataloader))-- for batch in dataloader:- # Get video tensor - shape is [B, F, C, H, W] from DataLoader- video = batch["video"]-- # Encode video- with torch.inference_mode():- video_latent_data = _encode_video(- vae=vae, video=video, use_tiling=vae_tiling, scale_factors=scale_factors- )-- # Save latents for each item in batch- for i in range(len(batch["relative_path"])):- output_rel_path = Path(batch["main_media_relative_path"][i]).with_suffix(".pt")- output_file = output_path / output_rel_path-- # Create output directory maintaining structure- output_file.parent.mkdir(parents=True, exist_ok=True)-- # Store the latent's effective fps (= source_fps / subsample factor).- # Downstream position math expects the rate the saved latents actually have.- effective_fps = batch["video_metadata"]["fps"][i].item() / temporal_subsample_factor- latent_data = {- "latents": video_latent_data["latents"][i].cpu().contiguous(), # [C, F', H', W']- "num_frames": video_latent_data["num_frames"],- "height": video_latent_data["height"],- "width": video_latent_data["width"],- "fps": effective_fps,- }-- _atomic_save(latent_data, output_file)-- # Process audio if enabled (audio is already extracted by the dataset)- if with_audio:- audio_batch = batch.get("audio")- if audio_batch is not None:- # Extract the i-th item from batched audio data- # DataLoader collates [channels, samples] -> [batch, channels, samples]- audio_data = Audio(- waveform=audio_batch["waveform"][i],- sampling_rate=audio_batch["sample_rate"][i].item(),- )-- # Encode audio- with torch.inference_mode():- audio_latents = _encode_audio(audio_vae_encoder, audio_processor, audio_data)-- # Save audio latents- audio_output_file = audio_output_path / output_rel_path- audio_output_file.parent.mkdir(parents=True, exist_ok=True)-- audio_save_data = {- "latents": audio_latents["latents"].cpu().contiguous(),- "num_time_steps": audio_latents["num_time_steps"],- "frequency_bins": audio_latents["frequency_bins"],- "duration": audio_latents["duration"],- }-- _atomic_save(audio_save_data, audio_output_file)- audio_success_count += 1- else:- # Video has no audio track- audio_skip_count += 1-- progress.advance(task)-- logger.info(f"Processed {len(dataloader.dataset)} videos -> {output_path}") # type: ignore[arg-type]- if with_audio:- logger.info(- f"Audio processing: {audio_success_count} videos with audio, "- f"{audio_skip_count} videos without audio (skipped)"- )---def _encode_video(- vae: torch.nn.Module,- video: torch.Tensor,- dtype: torch.dtype | None = None,- use_tiling: bool = False,- tile_size: int = DEFAULT_TILE_SIZE,- tile_overlap: int = DEFAULT_TILE_OVERLAP,- scale_factors: SpatioTemporalScaleFactors = VIDEO_SCALE_FACTORS,-) -> dict[str, torch.Tensor | int]:- """Encode video into non-patchified latent representation.- Args:- vae: Video VAE encoder model- video: Input tensor of shape [B, C, F, H, W] (batch, channels, frames, height, width)- This is the format expected by the VAE encoder.- dtype: Target dtype for output latents- use_tiling: Whether to use spatial tiling for memory efficiency- tile_size: Tile size in pixels (must be divisible by the VAE spatial factor)- tile_overlap: Overlap between tiles in pixels (must be divisible by the VAE spatial factor)- scale_factors: Video VAE spatiotemporal compression factors (default 32x32x8)- Returns:- Dict containing non-patchified latents and shape information:- {- "latents": Tensor[B, C, F', H', W'], # Non-patchified format with batch dim- "num_frames": int, # Latent frame count- "height": int, # Latent height- "width": int, # Latent width- }- """- device = next(vae.parameters()).device- vae_dtype = next(vae.parameters()).dtype-- # Add batch dimension if needed- if video.ndim == 4:- video = video.unsqueeze(0) # [C, F, H, W] -> [B, C, F, H, W]-- video = video.to(device=device, dtype=vae_dtype)-- # Choose encoding method based on tiling flag- if use_tiling:- latents = _tiled_encode_video(- vae=vae,- video=video,- tile_size=tile_size,- tile_overlap=tile_overlap,- scale_factors=scale_factors,- )- else:- # Encode video - VAE expects [B, C, F, H, W], returns [B, C, F', H', W']- latents = vae(video)-- if dtype is not None:- latents = latents.to(dtype=dtype)-- _, _, num_frames, height, width = latents.shape-- return {- "latents": latents, # [B, C, F', H', W']- "num_frames": num_frames,- "height": height,- "width": width,- }---def _tiled_encode_video( # noqa: PLR0912, PLR0915- vae: torch.nn.Module,- video: torch.Tensor,- tile_size: int = DEFAULT_TILE_SIZE,- tile_overlap: int = DEFAULT_TILE_OVERLAP,- scale_factors: SpatioTemporalScaleFactors = VIDEO_SCALE_FACTORS,-) -> torch.Tensor:- """Encode video using spatial tiling for memory efficiency.- Splits the video into overlapping spatial tiles, encodes each tile separately,- and blends the results using linear feathering in the overlap regions.- Args:- vae: Video VAE encoder model- video: Input tensor of shape [B, C, F, H, W]- tile_size: Tile size in pixels (must be divisible by 32)- tile_overlap: Overlap between tiles in pixels (must be divisible by 32)- Returns:- Encoded latent tensor [B, C_latent, F_latent, H_latent, W_latent]- """- batch, _channels, frames, height, width = video.shape- device = video.device- dtype = video.dtype-- # Spatial tiling assumes a square spatial compression (height factor == width factor).- spatial_factor = scale_factors.height-- # Validate tile parameters- if tile_size % spatial_factor != 0:- raise ValueError(f"tile_size must be divisible by {spatial_factor}, got {tile_size}")- if tile_overlap % spatial_factor != 0:- raise ValueError(f"tile_overlap must be divisible by {spatial_factor}, got {tile_overlap}")- if tile_overlap >= tile_size:- raise ValueError(f"tile_overlap ({tile_overlap}) must be less than tile_size ({tile_size})")-- # If video fits in a single tile, use regular encoding- if height <= tile_size and width <= tile_size:- return vae(video)-- # Calculate output dimensions from the VAE compression factors- # (e.g. the default 32x32x8: H -> H/32, W -> W/32, F -> 1 + (F-1)/8)- output_height = height // scale_factors.height- output_width = width // scale_factors.width- output_frames = 1 + (frames - 1) // scale_factors.time-- # Latent channels are 128 across all supported VAE variants.- latent_channels = 128-- # Initialize output and weight tensors- output = torch.zeros(- (batch, latent_channels, output_frames, output_height, output_width),- device=device,- dtype=dtype,- )- weights = torch.zeros(- (batch, 1, output_frames, output_height, output_width),- device=device,- dtype=dtype,- )-- # Calculate tile positions with overlap- # Step size is tile_size - tile_overlap- step_h = tile_size - tile_overlap- step_w = tile_size - tile_overlap-- h_positions = list(range(0, max(1, height - tile_overlap), step_h))- w_positions = list(range(0, max(1, width - tile_overlap), step_w))-- # Ensure last tile covers the edge- if h_positions[-1] + tile_size < height:- h_positions.append(height - tile_size)- if w_positions[-1] + tile_size < width:- w_positions.append(width - tile_size)-- # Remove duplicates and sort- h_positions = sorted(set(h_positions))- w_positions = sorted(set(w_positions))-- # Overlap in latent space- overlap_out_h = tile_overlap // scale_factors.height- overlap_out_w = tile_overlap // scale_factors.width-- # Process each tile- for h_pos in h_positions:- for w_pos in w_positions:- # Calculate tile boundaries in input space- h_start = max(0, h_pos)- w_start = max(0, w_pos)- h_end = min(h_start + tile_size, height)- w_end = min(w_start + tile_size, width)-- # Ensure tile dimensions are divisible by the VAE spatial factor- tile_h = ((h_end - h_start) // scale_factors.height) * scale_factors.height- tile_w = ((w_end - w_start) // scale_factors.width) * scale_factors.width-- if tile_h < scale_factors.height or tile_w < scale_factors.width:- continue-- # Adjust end positions- h_end = h_start + tile_h- w_end = w_start + tile_w-- # Extract tile- tile = video[:, :, :, h_start:h_end, w_start:w_end]-- # Encode tile- encoded_tile = vae(tile)-- # Get actual encoded dimensions- _, _, tile_out_frames, tile_out_height, tile_out_width = encoded_tile.shape-- # Calculate output positions- out_h_start = h_start // scale_factors.height- out_w_start = w_start // scale_factors.width- out_h_end = min(out_h_start + tile_out_height, output_height)- out_w_end = min(out_w_start + tile_out_width, output_width)-- # Trim encoded tile if necessary- actual_tile_h = out_h_end - out_h_start- actual_tile_w = out_w_end - out_w_start- encoded_tile = encoded_tile[:, :, :, :actual_tile_h, :actual_tile_w]-- # Create blending mask with linear feathering at edges- mask = torch.ones(- (1, 1, tile_out_frames, actual_tile_h, actual_tile_w),- device=device,- dtype=dtype,- )-- # Apply feathering at edges (linear blend in overlap regions)- # Left edge- if h_pos > 0 and overlap_out_h > 0 and overlap_out_h < actual_tile_h:- fade_in = torch.linspace(0.0, 1.0, overlap_out_h + 2, device=device, dtype=dtype)[1:-1]- mask[:, :, :, :overlap_out_h, :] *= fade_in.view(1, 1, 1, -1, 1)-- # Right edge (bottom in height dimension)- if h_end < height and overlap_out_h > 0 and overlap_out_h < actual_tile_h:- fade_out = torch.linspace(1.0, 0.0, overlap_out_h + 2, device=device, dtype=dtype)[1:-1]- mask[:, :, :, -overlap_out_h:, :] *= fade_out.view(1, 1, 1, -1, 1)-- # Top edge (left in width dimension)- if w_pos > 0 and overlap_out_w > 0 and overlap_out_w < actual_tile_w:- fade_in = torch.linspace(0.0, 1.0, overlap_out_w + 2, device=device, dtype=dtype)[1:-1]- mask[:, :, :, :, :overlap_out_w] *= fade_in.view(1, 1, 1, 1, -1)-- # Bottom edge (right in width dimension)- if w_end < width and overlap_out_w > 0 and overlap_out_w < actual_tile_w:- fade_out = torch.linspace(1.0, 0.0, overlap_out_w + 2, device=device, dtype=dtype)[1:-1]- mask[:, :, :, :, -overlap_out_w:] *= fade_out.view(1, 1, 1, 1, -1)-- # Accumulate weighted results- output[:, :, :, out_h_start:out_h_end, out_w_start:out_w_end] += encoded_tile * mask- weights[:, :, :, out_h_start:out_h_end, out_w_start:out_w_end] += mask-- # Normalize by weights (avoid division by zero)- output = output / (weights + 1e-8)-- return output---def _encode_audio(- audio_vae_encoder: torch.nn.Module,- audio_processor: torch.nn.Module,- audio: Audio,-) -> dict[str, torch.Tensor | int | float]:- """Encode audio waveform into latent representation.- Args:- audio_vae_encoder: Audio VAE encoder model from ltx-core- audio_processor: AudioProcessor for waveform-to-spectrogram conversion- audio: Audio container with waveform tensor and sampling rate.- Returns:- Dict containing audio latents and shape information:- {- "latents": Tensor[C, T, F], # Non-patchified format- "num_time_steps": int,- "frequency_bins": int,- "duration": float,- }- """- device = next(audio_vae_encoder.parameters()).device- dtype = next(audio_vae_encoder.parameters()).dtype-- waveform = audio.waveform.to(device=device, dtype=dtype)-- # Add batch dimension if needed: [channels, samples] -> [batch, channels, samples]- if waveform.dim() == 2:- waveform = waveform.unsqueeze(0)-- # Convert to stereo if needed (audio VAE expects 2 channels)- # Channel order for surround: 5.1=[L,R,C,LFE,Ls,Rs], 7.1=[L,R,C,LFE,Ls,Rs,Lb,Rb]- num_channels = waveform.shape[1]- if num_channels == 1:- # Mono to stereo: duplicate the channel- waveform = waveform.repeat(1, 2, 1)- elif num_channels == 6:- # 5.1 downmix with normalized weights (sum to 1.0)- # Original: L = L + 0.707*C + 0.707*Ls, weights sum = 2.414- w_main = 1.0 / 2.414 # ~0.414- w_other = 0.707 / 2.414 # ~0.293- left = w_main * waveform[:, 0, :] + w_other * waveform[:, 2, :] + w_other * waveform[:, 4, :]- right = w_main * waveform[:, 1, :] + w_other * waveform[:, 2, :] + w_other * waveform[:, 5, :]- waveform = torch.stack([left, right], dim=1)- elif num_channels == 8:- # 7.1 downmix with normalized weights (sum to 1.0)- # Original: L = L + 0.707*C + 0.707*Ls + 0.707*Lb, weights sum = 3.121- w_main = 1.0 / 3.121 # ~0.320- w_other = 0.707 / 3.121 # ~0.227- center = waveform[:, 2, :]- left = w_main * waveform[:, 0, :] + w_other * (center + waveform[:, 4, :] + waveform[:, 6, :])- right = w_main * waveform[:, 1, :] + w_other * (center + waveform[:, 5, :] + waveform[:, 7, :])- waveform = torch.stack([left, right], dim=1)- elif num_channels > 2:- # Unknown layout: average all channels to mono, then duplicate to stereo- logger.warning(f"Unknown audio channel layout ({num_channels} channels), using mean downmix")- mono = waveform.mean(dim=1, keepdim=True)- waveform = mono.repeat(1, 2, 1)-- # Calculate duration- duration = waveform.shape[-1] / audio.sampling_rate-- # Convert waveform to mel spectrogram using AudioProcessor- mel_spectrogram = audio_processor.waveform_to_mel(Audio(waveform=waveform, sampling_rate=audio.sampling_rate))- mel_spectrogram = mel_spectrogram.to(dtype=dtype)-- # Encode mel spectrogram to latents- latents = audio_vae_encoder(mel_spectrogram)-- # latents shape: [batch, channels, time, freq] = [1, 8, T, 16]- _, _channels, time_steps, freq_bins = latents.shape-- return {- "latents": latents.squeeze(0), # [C, T, F] - remove batch dim- "num_time_steps": time_steps,- "frequency_bins": freq_bins,- "duration": duration,- }---AUDIO_FILE_EXTENSIONS = {".wav", ".mp3", ".flac", ".ogg", ".aac", ".m4a"}-VIDEO_FILE_EXTENSIONS = {".mp4", ".avi", ".mov", ".mkv", ".webm"}-IMAGE_FILE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".heic", ".heif", ".bmp", ".tiff", ".webp"}---def compute_video_masks(- dataset_file: str | Path,- mask_column: str,- latents_dir: str,- output_dir: str,- main_media_column: str | None = None,- overwrite: bool = False,- scale_factors: SpatioTemporalScaleFactors = VIDEO_SCALE_FACTORS,-) -> None:- """Preprocess video mask files to latent-space binary masks.- For each sample, loads the mask video/image, applies the same spatial- resize/crop as the target video (read from saved latent metadata), downsamples- to latent dimensions, binarizes, and saves as a .pt tensor.- Args:- dataset_file: Path to metadata file (CSV/JSON/JSONL).- mask_column: Column name containing mask video/image paths.- latents_dir: Directory containing the target video latents (for reading- spatial/temporal metadata to ensure mask alignment).- output_dir: Directory to save mask .pt files.- main_media_column: Column for output file naming (defaults to mask_column).- scale_factors: Video VAE spatiotemporal compression factors (default 32x32x8),- used to map latent mask dimensions back to pixel space and downsample.- """- dataset_path = Path(dataset_file)- data_root = dataset_path.parent- latents_path = Path(latents_dir)- output_path = Path(output_dir)- output_path.mkdir(parents=True, exist_ok=True)-- naming_column = main_media_column or mask_column- mask_paths = _load_paths_from_dataset(dataset_path, mask_column)- naming_paths = _load_paths_from_dataset(dataset_path, naming_column) if naming_column != mask_column else mask_paths-- success = 0- for mask_file, naming_file in zip(mask_paths, naming_paths, strict=True):- rel_path = _output_relative(naming_file, data_root)- latent_file = latents_path / rel_path.with_suffix(".pt")- out_file = output_path / rel_path.with_suffix(".pt")-- if not latent_file.exists():- logger.warning(f"No target latent found at {latent_file}, skipping mask {mask_file}")- continue-- if not overwrite and out_file.is_file():- continue-- target_meta = torch.load(latent_file, map_location="cpu", weights_only=True)- latent_f = target_meta["num_frames"]- latent_h = target_meta["height"]- latent_w = target_meta["width"]- pixel_h = latent_h * scale_factors.height- pixel_w = latent_w * scale_factors.width- pixel_f = (latent_f - 1) * scale_factors.time + 1-- # Load mask as video or image- if mask_file.suffix.lower() in IMAGE_FILE_EXTENSIONS:- img = to_tensor(open_image_as_srgb(mask_file)).mean(dim=0, keepdim=True) # [1, H, W]- img = tv_resize(img.unsqueeze(0), [pixel_h, pixel_w]).squeeze(0) # [1, H, W]- mask_pixels = img.expand(pixel_f, -1, -1) # tile across frames → [F, H, W]- else:- frames, _ = read_video(str(mask_file), max_frames=pixel_f) # [F, C, H, W]- frames = frames[:pixel_f].mean(dim=1) # grayscale → [F, H, W]- frames = torch.nn.functional.interpolate(- frames.unsqueeze(1), size=(pixel_h, pixel_w), mode="nearest"- ).squeeze(1) # [F, H, W]- mask_pixels = frames-- # Downsample to latent dims: [F, H, W] → [F', H', W']- mask_latent = torch.nn.functional.avg_pool2d(- mask_pixels.unsqueeze(1), kernel_size=scale_factors.height- ).squeeze(1) # [F, H', W'] → spatial done- # Temporal: max-pool over groups of scale_factors.time frames (any masked frame masks the group)- f_spatial = mask_latent.shape[0]- pad_f = (scale_factors.time - f_spatial % scale_factors.time) % scale_factors.time- if pad_f > 0:- mask_latent = torch.nn.functional.pad(mask_latent, (0, 0, 0, 0, 0, pad_f))- h_prime, w_prime = mask_latent.shape[1], mask_latent.shape[2]- mask_latent = mask_latent.reshape(-1, scale_factors.time, h_prime, w_prime).amax(dim=1)[:latent_f]-- # Binarize- mask_latent = (mask_latent > 0.5).float()-- out_file.parent.mkdir(parents=True, exist_ok=True)- _atomic_save({"mask": mask_latent}, out_file)- success += 1-- logger.info(f"Mask preprocessing complete: {success} masks saved to {output_path}")---def compute_audio_masks(- dataset_file: str | Path,- mask_column: str,- audio_latents_dir: str,- output_dir: str,- main_media_column: str | None = None,- overwrite: bool = False,-) -> None:- """Preprocess audio mask files to latent-space binary masks.- For each sample, loads the mask (a 1D waveform-like signal or a simple tensor),- resamples it to match the target audio latent temporal length, binarizes, and saves.- Args:- dataset_file: Path to metadata file (CSV/JSON/JSONL).- mask_column: Column name containing mask file paths (.wav or .pt).- audio_latents_dir: Directory containing the target audio latents (for reading- temporal metadata to ensure mask alignment).- output_dir: Directory to save mask .pt files.- main_media_column: Column for output file naming (defaults to mask_column).- """- dataset_path = Path(dataset_file)- data_root = dataset_path.parent- audio_latents_path = Path(audio_latents_dir)- output_path = Path(output_dir)- output_path.mkdir(parents=True, exist_ok=True)-- naming_column = main_media_column or mask_column- mask_paths = _load_paths_from_dataset(dataset_path, mask_column)- naming_paths = _load_paths_from_dataset(dataset_path, naming_column) if naming_column != mask_column else mask_paths-- success = 0- for mask_file, naming_file in zip(mask_paths, naming_paths, strict=True):- rel_path = _output_relative(naming_file, data_root)- latent_file = audio_latents_path / rel_path.with_suffix(".pt")- out_file = output_path / rel_path.with_suffix(".pt")-- if not latent_file.exists():- logger.warning(f"No target audio latent found at {latent_file}, skipping mask {mask_file}")- continue-- if not overwrite and out_file.is_file():- continue-- target_meta = torch.load(latent_file, map_location="cpu", weights_only=True)- latent_t = target_meta["num_time_steps"]-- # Load mask: .pt file (raw tensor) or .wav (use amplitude envelope)- if mask_file.suffix == ".pt":- raw_mask = torch.load(mask_file, map_location="cpu", weights_only=True)- if isinstance(raw_mask, dict):- raw_mask = raw_mask.get("mask", next(iter(raw_mask.values())))- raw_mask = raw_mask.float().flatten()- else:- audio = _load_audio_from_file(mask_file)- if audio is None:- logger.warning(f"Could not load audio mask from {mask_file}")- continue- raw_mask = audio.waveform.abs().mean(dim=0) # mono amplitude envelope-- # Resample to target audio latent length- mask_resampled = torch.nn.functional.interpolate(- raw_mask.unsqueeze(0).unsqueeze(0), size=latent_t, mode="nearest"- ).squeeze() # [latent_t]-- mask_binary = (mask_resampled > 0.5).float()-- out_file.parent.mkdir(parents=True, exist_ok=True)- _atomic_save({"mask": mask_binary}, out_file)- success += 1-- logger.info(f"Audio mask preprocessing complete: {success} masks saved to {output_path}")---def compute_audio_latents( # noqa: PLR0915- dataset_file: str | Path,- audio_column: str,- output_dir: str,- model_path: str,- audio_vae_path: str | None = None,- main_media_column: str | None = None,- max_duration: float | None = None,- duration_buckets: list[float] | None = None,- device: str = "cuda",- overwrite: bool = False,-) -> None:- """Encode audio files into latent representations.- Supports standalone audio files (.wav, .mp3, etc.) and audio tracks- extracted from video files (.mp4, etc.).- Args:- dataset_file: Path to metadata file (CSV/JSON/JSONL).- audio_column: Column name containing audio file paths.- output_dir: Directory to save audio latents.- model_path: Path to LTX-2 checkpoint (.safetensors).- main_media_column: Column for output file naming (defaults to audio_column).- Ensures alignment with other latent directories.- max_duration: Maximum audio duration in seconds. Audio is trimmed if longer.- Mutually exclusive with duration_buckets.- duration_buckets: List of allowed durations in seconds (e.g. [2.0, 4.0, 8.0]).- Each audio file is matched to the largest bucket that fits its duration,- then trimmed to exactly that length. Files shorter than the smallest- bucket are skipped. Ensures uniform lengths for batched training.- device: Device to use for computation.- """- console = Console()- torch_device = torch.device(device)-- dataset_path = Path(dataset_file)- data_root = dataset_path.parent- output_path = Path(output_dir)- output_path.mkdir(parents=True, exist_ok=True)-- naming_column = main_media_column or audio_column- audio_paths = _load_paths_from_dataset(dataset_path, audio_column)- naming_paths = (- _load_paths_from_dataset(dataset_path, naming_column) if naming_column != audio_column else audio_paths- )-- audio_vae_path = resolve_audio_vae_path(model_path, audio_vae_path)- with console.status(f"[bold]Loading audio VAE encoder from [cyan]{audio_vae_path}[/]...", spinner="dots"):- audio_vae_encoder = load_audio_vae_encoder(- checkpoint_path=audio_vae_path,- device=torch_device,- dtype=torch.float32,- )- audio_processor = AudioProcessor(- target_sample_rate=audio_vae_encoder.sample_rate,- mel_bins=audio_vae_encoder.mel_bins,- mel_hop_length=audio_vae_encoder.mel_hop_length,- n_fft=audio_vae_encoder.n_fft,- ).to(torch_device)-- sorted_buckets = sorted(duration_buckets, reverse=True) if duration_buckets else None- success_count = 0- skip_count = 0-- with Progress(- SpinnerColumn(),- TextColumn("[progress.description]{task.description}"),- BarColumn(),- TaskProgressColumn(),- MofNCompleteColumn(),- TimeElapsedColumn(),- TimeRemainingColumn(),- console=console,- ) as progress:- task = progress.add_task("Encoding audio", total=len(audio_paths))-- for audio_path, naming_path in zip(audio_paths, naming_paths, strict=True):- rel_path = _output_relative(naming_path, data_root)- output_file = output_path / rel_path.with_suffix(".pt")- output_file.parent.mkdir(parents=True, exist_ok=True)-- if not overwrite and output_file.is_file():- success_count += 1- progress.advance(task)- continue-- # Load audio (no trimming yet — need full duration for bucket matching)- audio = _load_audio_from_file(audio_path)- if audio is None:- skip_count += 1- progress.advance(task)- continue-- file_duration = audio.waveform.shape[-1] / audio.sampling_rate-- # Determine target duration: bucket matching, max_duration cap, or full file- target_duration = file_duration- if sorted_buckets:- bucket = next((b for b in sorted_buckets if b <= file_duration), None)- if bucket is None:- logger.warning(- f"Skipping {audio_path.name} ({file_duration:.1f}s) — shorter than "- f"smallest bucket ({sorted_buckets[-1]:.1f}s)"- )- skip_count += 1- progress.advance(task)- continue- target_duration = bucket- elif max_duration is not None:- target_duration = min(file_duration, max_duration)-- # Trim to target duration- target_samples = int(target_duration * audio.sampling_rate)- trimmed_waveform = audio.waveform[:, :target_samples]- audio = Audio(waveform=trimmed_waveform, sampling_rate=audio.sampling_rate)-- with torch.inference_mode():- audio_latents = _encode_audio(audio_vae_encoder, audio_processor, audio)-- _atomic_save(- {- "latents": audio_latents["latents"].cpu().contiguous(),- "num_time_steps": audio_latents["num_time_steps"],- "frequency_bins": audio_latents["frequency_bins"],- "duration": audio_latents["duration"],- },- output_file,- )- success_count += 1- progress.advance(task)-- logger.info(f"Audio encoding complete: {success_count} encoded, {skip_count} skipped. Saved to {output_path}")---def _output_relative(path: Path, data_root: Path) -> Path:- """Relative path used to name a sample's cached output, mirroring the input layout.- Normally media lives under the dataset directory and this is just the path relative to it.- If a media path is absolute or otherwise outside the dataset directory (e.g. a one-off- metadata file that references media elsewhere), mirror its absolute structure under the- output directory instead of raising, so out-of-tree media stays collision-free.- """- try:- return path.relative_to(data_root)- except ValueError:- return Path(*path.parts[1:]) if path.is_absolute() else path---def _load_paths_from_dataset(dataset_file: Path, column: str) -> list[Path]:- """Load file paths from a dataset column, resolving relative to the dataset file's directory."""- data_root = dataset_file.parent-- if dataset_file.suffix == ".csv":- df = pd.read_csv(dataset_file)- if column not in df.columns:- raise ValueError(f"Column '{column}' not found in CSV file")- return [data_root / Path(str(v).strip()) for v in df[column].tolist()]-- if dataset_file.suffix == ".json":- with open(dataset_file, encoding="utf-8") as f:- data = json.load(f)- if not isinstance(data, list):- raise ValueError("JSON file must contain a list of objects")- return [data_root / Path(entry[column].strip()) for entry in data]-- if dataset_file.suffix == ".jsonl":- paths = []- with open(dataset_file, encoding="utf-8") as f:- for line in f:- entry = json.loads(line)- paths.append(data_root / Path(entry[column].strip()))- return paths-- raise ValueError(f"Unsupported dataset format: {dataset_file.suffix}")---def _load_audio_from_file(audio_path: Path, max_duration: float | None = None) -> Audio | None:- """Load audio from an audio or video file, optionally trimming to max_duration."""- try:- waveform, sample_rate = torchaudio.load(str(audio_path))- except Exception:- logger.debug(f"Could not load audio from {audio_path}")- return None-- if max_duration is not None:- max_samples = int(max_duration * sample_rate)- if waveform.shape[-1] > max_samples:- waveform = waveform[:, :max_samples]-- return Audio(waveform=waveform, sampling_rate=sample_rate)---def detect_dataset_columns(dataset_file: str | Path) -> set[str]:- """Read column names from a dataset file without loading all data."""- path = Path(dataset_file)- if path.suffix == ".csv":- df = pd.read_csv(path, nrows=0)- return set(df.columns)- if path.suffix == ".json":- with open(path, encoding="utf-8") as f:- data = json.load(f)- return set(data[0].keys()) if isinstance(data, list) and data else set()- if path.suffix == ".jsonl":- with open(path, encoding="utf-8") as f:- return set(json.loads(f.readline()).keys())- return set()---def parse_resolution_buckets(- resolution_buckets_str: str,- scale_factors: SpatioTemporalScaleFactors = VIDEO_SCALE_FACTORS,-) -> list[tuple[int, int, int]]:- """Parse resolution buckets from string format to list of tuples (frames, height, width).- ``scale_factors`` are the video VAE's spatiotemporal compression factors (default 32x32x8);- width/height must be multiples of the spatial factors and frames must satisfy- ``f % scale_factors.time == 1``.- """- resolution_buckets = []- for bucket_str in resolution_buckets_str.split(";"):- w, h, f = map(int, bucket_str.split("x"))-- if w % scale_factors.width != 0 or h % scale_factors.height != 0:- raise typer.BadParameter(- f"Width and height must be multiples of {scale_factors.width}x{scale_factors.height}, got {w}x{h}",- param_hint="resolution-buckets",- )-- if f % scale_factors.time != 1:- raise typer.BadParameter(- f"Number of frames must be a multiple of {scale_factors.time} plus 1, got {f}",- param_hint="resolution-buckets",- )-- resolution_buckets.append((f, h, w))- return resolution_buckets---def compute_scaled_resolution_buckets(- resolution_buckets: list[tuple[int, int, int]],- scale_factor: int,- scale_factors: SpatioTemporalScaleFactors = VIDEO_SCALE_FACTORS,-) -> list[tuple[int, int, int]]:- """Compute scaled resolution buckets and validate the results.- ``scale_factors`` are the video VAE's spatiotemporal compression factors (default 32x32x8),- used to check the post-scale dimensions are still VAE-aligned.- """- if scale_factor == 1:- return resolution_buckets-- scaled_buckets = []- for frames, height, width in resolution_buckets:- # Validate that scale factor evenly divides the dimensions- if height % scale_factor != 0:- raise ValueError(- f"Height {height} is not evenly divisible by scale factor {scale_factor}. "- f"Choose a scale factor that divides {height} evenly."- )- if width % scale_factor != 0:- raise ValueError(- f"Width {width} is not evenly divisible by scale factor {scale_factor}. "- f"Choose a scale factor that divides {width} evenly."- )-- scaled_height = height // scale_factor- scaled_width = width // scale_factor-- # Validate scaled dimensions are divisible by VAE spatial factor- if scaled_height % scale_factors.height != 0:- raise ValueError(- f"Scaled height {scaled_height} (from {height} / {scale_factor}) "- f"is not divisible by {scale_factors.height}. "- f"Choose a different scale factor or adjust your resolution buckets."- )- if scaled_width % scale_factors.width != 0:- raise ValueError(- f"Scaled width {scaled_width} (from {width} / {scale_factor}) "- f"is not divisible by {scale_factors.width}. "- f"Choose a different scale factor or adjust your resolution buckets."- )-- scaled_buckets.append((frames, scaled_height, scaled_width))-- return scaled_buckets---def _atomic_save(data: Any, out: Path) -> None: # noqa: ANN401- """Save to ``out`` atomically via per-PID temp file + replace.- Crash mid-write leaves an orphan ``.tmp.<pid>`` file that the skip logic- ignores. The per-PID suffix makes concurrent writes from multiple ranks- collision-free.- """- tmp = out.with_suffix(f"{out.suffix}.tmp.{os.getpid()}")- torch.save(data, tmp)- tmp.replace(out)---def _build_sharded_dataloader(- dataset: Dataset,- *,- batch_size: int,- num_workers: int,- is_done: Callable[[int], bool],- overwrite: bool,-) -> DataLoader | None:- """Return a DataLoader over this rank's interleaved shard of ``dataset``.- When ``overwrite`` is False, items whose outputs already exist (per- ``is_done``) are filtered out. Returns ``None`` if this rank has nothing- to do, so the caller can early-return without loading any models.- """- state = PartialState()- todo = [i for i in range(state.process_index, len(dataset), state.num_processes) if overwrite or not is_done(i)]- if not todo:- logger.info(f"Rank {state.process_index}/{state.num_processes}: nothing to do")- return None- logger.info(f"Rank {state.process_index}/{state.num_processes}: processing {len(todo):,} of {len(dataset):,} items")- return DataLoader(Subset(dataset, todo), batch_size=batch_size, shuffle=False, num_workers=num_workers)---def main( # noqa: PLR0913- dataset_file: str = typer.Argument(- ...,- help="Path to metadata file (CSV/JSON/JSONL) containing video paths",- ),- resolution_buckets: str = typer.Option(- ...,- help='Resolution buckets in format "WxHxF;WxHxF;..." (e.g. "768x768x25;512x512x49")',- ),- output_dir: str = typer.Option(- ...,- help="Output directory to save video latents",- ),- model_path: str = typer.Option(- ...,- help="Path to the unified checkpoint or split transformer safetensors",- ),- video_vae_path: str | None = typer.Option(- default=None,- help="Split-pack video VAE safetensors (defaults to --model-path for unified checkpoints)",- ),- audio_vae_path: str | None = typer.Option(- default=None,- help="Split-pack audio VAE safetensors (defaults to --model-path for unified checkpoints)",- ),- video_column: str = typer.Option(- default="media_path",- help="Column name in the dataset JSON/JSONL/CSV file containing video paths",- ),- batch_size: int = typer.Option(- default=1,- help="Batch size for processing",- ),- device: str = typer.Option(- default="cuda",- help="Device to use for computation",- ),- vae_tiling: bool = typer.Option(- default=False,- help="Enable VAE tiling for larger video resolutions",- ),- reshape_mode: str = typer.Option(- default="center",- help="How to crop videos: 'center' or 'random'",- ),- with_audio: bool = typer.Option(- default=False,- help="Extract and encode audio from video files",- ),- audio_output_dir: str | None = typer.Option(- default=None,- help="Output directory for audio latents (required if --with-audio is set)",- ),- overwrite: bool = typer.Option(- default=False,- help="Re-encode every item even if its output exists. Use when rerunning with "- "changed parameters (different model, resolution, etc.) so stale outputs are replaced.",- ),-) -> None:- """Process videos/images and save latent representations for video generation training.- This script processes videos and images from metadata files and saves latent representations- that can be used for training video generation models. The output latents will maintain- the same folder structure and naming as the corresponding media files.- For multi-GPU preprocessing, invoke under ``accelerate launch`` -- each process- will handle an interleaved shard of the dataset.- Examples:- # Process videos from a CSV file- python scripts/process_videos.py dataset.csv --resolution-buckets 768x768x25 \\- --output-dir ./latents --model-path /path/to/ltx-checkpoint.safetensors- # Process videos from a JSON file with custom video column- python scripts/process_videos.py dataset.json --resolution-buckets 768x768x25 \\- --output-dir ./latents --model-path /path/to/ltx-checkpoint.safetensors --video-column "video_path"- # Enable VAE tiling to save GPU VRAM- python scripts/process_videos.py dataset.csv --resolution-buckets 1024x1024x25 \\- --output-dir ./latents --model-path /path/to/ltx-checkpoint.safetensors --vae-tiling- # Process videos with audio- python scripts/process_videos.py dataset.csv --resolution-buckets 768x768x25 \\- --output-dir ./latents --model-path /path/to/ltx-checkpoint.safetensors \\- --with-audio --audio-output-dir ./audio_latents- """-- # Validate dataset file exists- if not Path(dataset_file).is_file():- raise typer.BadParameter(f"Dataset file not found: {dataset_file}")-- # Validate audio parameters- if with_audio and audio_output_dir is None:- raise typer.BadParameter("--audio-output-dir is required when --with-audio is set")-- # Parse resolution buckets, validating against the checkpoint's VAE compression factors.- scale_factors = read_video_scale_factors(resolve_video_vae_path(model_path, video_vae_path))- parsed_resolution_buckets = parse_resolution_buckets(resolution_buckets, scale_factors)-- if len(parsed_resolution_buckets) > 1:- logger.warning(- "Using multiple resolution buckets. "- "When training with multiple resolution buckets, you must use a batch size of 1."- )-- # Process latents- compute_latents(- dataset_file=dataset_file,- video_column=video_column,- resolution_buckets=parsed_resolution_buckets,- output_dir=output_dir,- model_path=model_path,- video_vae_path=video_vae_path,- audio_vae_path=audio_vae_path,- reshape_mode=reshape_mode,- batch_size=batch_size,- device=device,- vae_tiling=vae_tiling,- with_audio=with_audio,- audio_output_dir=audio_output_dir,- overwrite=overwrite,- )-+from ltx_trainer.process_videos import appif __name__ == "__main__":app()diff --git a/packages/ltx-trainer/src/ltx_trainer/__init__.py b/packages/ltx-trainer/src/ltx_trainer/__init__.pyindex 56efa40..bdf7bab 100644--- a/packages/ltx-trainer/src/ltx_trainer/__init__.py+++ b/packages/ltx-trainer/src/ltx_trainer/__init__.py@@ -1,8 +1,6 @@import loggingimport os-import sysfrom logging import getLogger-from pathlib import Pathfrom rich.logging import RichHandler@@ -38,7 +36,3 @@ info = logger.infowarning = logger.warningerror = logger.errorcritical = logger.critical---# Add the root directory to the Python path so we can import from scripts.-sys.path.insert(0, str(Path(__file__).parent.parent.parent))diff --git a/packages/ltx-trainer/src/ltx_trainer/process_videos.py b/packages/ltx-trainer/src/ltx_trainer/process_videos.pynew file mode 100755index 0000000..1a7c94a--- /dev/null+++ b/packages/ltx-trainer/src/ltx_trainer/process_videos.py@@ -0,0 +1,1519 @@+#!/usr/bin/env python3++"""+Compute latent representations for video generation training.+This module provides functionality for processing video and image files, including:+- Loading videos/images from various file formats (CSV, JSON, JSONL)+- Resizing, cropping, and transforming media+- MediaDataset for video-only preprocessing workflows+- BucketSampler for grouping videos by resolution+Can be used as a standalone script:+ python scripts/process_videos.py dataset.csv --resolution-buckets 768x768x25 \+ --output-dir /path/to/output --model-path /path/to/ltx-checkpoint.safetensors+"""++import json+import math+import os+from collections.abc import Callable+from pathlib import Path+from typing import Any++import numpy as np+import pandas as pd+import torch+import torchaudio+import typer+from accelerate import PartialState+from pillow_heif import register_heif_opener+from rich.console import Console+from rich.progress import (+ BarColumn,+ MofNCompleteColumn,+ Progress,+ SpinnerColumn,+ TaskProgressColumn,+ TextColumn,+ TimeElapsedColumn,+ TimeRemainingColumn,+)+from torch.utils.data import DataLoader, Dataset, Subset+from torchvision import transforms+from torchvision.transforms import InterpolationMode+from torchvision.transforms.functional import crop, resize, to_tensor+from torchvision.transforms.functional import resize as tv_resize+from transformers.utils.logging import disable_progress_bar++from ltx_core.model.audio_vae import AudioProcessor+from ltx_core.types import VIDEO_SCALE_FACTORS, Audio, SpatioTemporalScaleFactors+from ltx_trainer import logger+from ltx_trainer.model_loader import (+ load_audio_vae_encoder,+ load_video_vae_encoder,+ read_video_scale_factors,+ resolve_audio_vae_path,+ resolve_video_vae_path,+)+from ltx_trainer.utils import open_image_as_srgb+from ltx_trainer.video_utils import get_video_frame_count, read_video++disable_progress_bar()++# Register HEIF/HEIC support+register_heif_opener()++# Audio constants+AUDIO_LATENT_CHANNELS = 8+AUDIO_FREQUENCY_BINS = 16++DEFAULT_TILE_SIZE = 512 # Spatial tile size in pixels (must be ≥64 and divisible by 32)+DEFAULT_TILE_OVERLAP = 128 # Spatial tile overlap in pixels (must be divisible by 32)++app = typer.Typer(+ pretty_exceptions_enable=False,+ no_args_is_help=True,+ help="Process videos/images and save latent representations for video generation training.",+)+++def _clamp_01(x: torch.Tensor) -> torch.Tensor:+ return x.clamp_(0, 1)+++class MediaDataset(Dataset):+ """+ Dataset for processing video and image files.+ This dataset is designed for media preprocessing workflows where you need to:+ - Load and preprocess videos/images+ - Apply resizing and cropping transformations+ - Handle different resolution buckets+ - Filter out invalid media files+ - Optionally extract audio from video files+ """++ def __init__(+ self,+ dataset_file: str | Path,+ main_media_column: str,+ video_column: str,+ resolution_buckets: list[tuple[int, int, int]],+ reshape_mode: str = "center",+ with_audio: bool = False,+ temporal_subsample_factor: int = 1,+ ) -> None:+ """+ Initialize the media dataset.+ Args:+ dataset_file: Path to CSV/JSON/JSONL metadata file+ video_column: Column name for video paths in the metadata file+ resolution_buckets: List of (frames, height, width) tuples+ reshape_mode: How to crop videos ("center", "random")+ with_audio: Whether to extract audio from video files+ temporal_subsample_factor: Factor for VAE-aligned temporal subsampling.+ When > 1, keeps frame 0 then takes every Nth frame from frame 1 onwards.+ """+ super().__init__()++ self.dataset_file = Path(dataset_file)+ self.main_media_column = main_media_column+ self.resolution_buckets = resolution_buckets+ self.reshape_mode = reshape_mode+ self.with_audio = with_audio+ self.temporal_subsample_factor = temporal_subsample_factor++ # First load main media paths+ self.main_media_paths = self._load_video_paths(main_media_column)++ # Then load reference video paths+ self.video_paths = self._load_video_paths(video_column)++ # Filter out videos with insufficient frames+ self._filter_valid_videos()++ self.max_target_frames = max(self.resolution_buckets, key=lambda x: x[0])[0]++ # Set up video transforms+ self.transforms = transforms.Compose(+ [+ transforms.Lambda(_clamp_01),+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True),+ ]+ )++ def __len__(self) -> int:+ return len(self.video_paths)++ def __getitem__(self, index: int) -> dict[str, Any]:+ """Get a single video/image with metadata, and optionally audio."""+ if isinstance(index, list):+ # Special case for BucketSampler - return cached data+ return index++ video_path: Path = self.video_paths[index]++ # Compute relative path of the video+ data_root = self.dataset_file.parent+ relative_path = str(_output_relative(video_path, data_root))+ media_relative_path = str(_output_relative(self.main_media_paths[index], data_root))++ if video_path.suffix.lower() in [".png", ".jpg", ".jpeg"]:+ media_tensor = self._preprocess_image(video_path)+ fps = 1.0+ audio_data = None # Images don't have audio+ else:+ media_tensor, fps = self._preprocess_video(video_path)++ # Extract audio if enabled+ if self.with_audio:+ # Calculate target duration from the processed video frames+ # This ensures audio is trimmed to match the exact video duration+ # media_tensor is [C, F, H, W] so shape[1] is num_frames+ target_duration = media_tensor.shape[1] / fps+ audio_data = self._extract_audio(video_path, target_duration)+ else:+ audio_data = None++ # media_tensor is [C, F, H, W] format for VAE compatibility+ _, num_frames, height, width = media_tensor.shape++ result = {+ "video": media_tensor,+ "relative_path": relative_path,+ "main_media_relative_path": media_relative_path,+ "video_metadata": {+ "num_frames": num_frames,+ "height": height,+ "width": width,+ "fps": fps,+ },+ }++ # Add audio data if available+ if audio_data is not None:+ result["audio"] = audio_data++ return result++ @staticmethod+ def _extract_audio(video_path: Path, target_duration: float) -> dict[str, torch.Tensor | int] | None:+ """Extract audio track from a video file, trimmed/padded to match video duration."""+ audio = _load_audio_from_file(video_path, max_duration=target_duration)+ if audio is None:+ return None++ # Pad if shorter than target (_load_audio_from_file only trims, doesn't pad)+ target_samples = int(target_duration * audio.sampling_rate)+ if audio.waveform.shape[-1] < target_samples:+ padding = target_samples - audio.waveform.shape[-1]+ waveform = torch.nn.functional.pad(audio.waveform, (0, padding))+ logger.warning(f"Padded audio to {target_duration:.2f} seconds for {video_path}")+ else:+ waveform = audio.waveform++ return {"waveform": waveform, "sample_rate": audio.sampling_rate}++ def _load_video_paths(self, column: str) -> list[Path]:+ """Load video paths from the specified data source, validating existence."""+ paths = _load_paths_from_dataset(self.dataset_file, column)+ invalid = [p for p in paths if not p.is_file()]+ if invalid:+ raise ValueError(f"Found {len(invalid)} invalid paths in '{column}'. First few: {invalid[:5]}")+ return paths++ def _filter_valid_videos(self) -> None:+ """Filter out videos with insufficient frames."""+ original_length = len(self.video_paths)+ valid_video_paths = []+ valid_main_media_paths = []+ min_frames_required = min(self.resolution_buckets, key=lambda x: x[0])[0]++ for i, video_path in enumerate(self.video_paths):+ if video_path.suffix.lower() in [".png", ".jpg", ".jpeg"]:+ valid_video_paths.append(video_path)+ valid_main_media_paths.append(self.main_media_paths[i])+ continue++ try:+ frame_count = get_video_frame_count(video_path)++ if frame_count >= min_frames_required:+ valid_video_paths.append(video_path)+ valid_main_media_paths.append(self.main_media_paths[i])+ else:+ logger.warning(+ f"Skipping video at {video_path} - has {frame_count} frames, "+ f"which is less than the minimum required frames ({min_frames_required})"+ )+ except Exception as e:+ logger.warning(f"Failed to read video at {video_path}: {e!s}")++ # Update both path lists to maintain synchronization+ self.video_paths = valid_video_paths+ self.main_media_paths = valid_main_media_paths++ if len(self.video_paths) < original_length:+ logger.warning(+ f"Filtered out {original_length - len(self.video_paths)} videos with insufficient frames. "+ f"Proceeding with {len(self.video_paths)} valid videos."+ )++ def _preprocess_image(self, path: Path) -> torch.Tensor:+ """Preprocess a single image by resizing and applying transforms."""+ image = open_image_as_srgb(path)+ image = to_tensor(image)+ image = image.unsqueeze(0) # Add frame dimension [1, C, H, W] for bucket selection++ # Find nearest resolution bucket and resize+ nearest_bucket = self._get_resolution_bucket_for_item(image)+ _, target_height, target_width = nearest_bucket+ image_resized = self._resize_and_crop(image, target_height, target_width)+ # _resize_and_crop returns [C, H, W] for single-frame input (squeeze removes dim 0)++ # Apply transforms+ image = self.transforms(image_resized) # [C, H, W] -> [C, H, W]++ # Add frame dimension in VAE format: [C, H, W] -> [C, 1, H, W]+ image = image.unsqueeze(1)+ return image++ def _preprocess_video(self, path: Path) -> tuple[torch.Tensor, float]:+ """Preprocess a video by loading, resizing, and applying transforms.+ Returns:+ Tuple of (video tensor in [C, F, H, W] format, fps)+ """+ # Load video frames up to max_target_frames+ video, fps = read_video(path, max_frames=self.max_target_frames)++ nearest_bucket = self._get_resolution_bucket_for_item(video)+ target_num_frames, target_height, target_width = nearest_bucket+ frames_resized = self._resize_and_crop(video, target_height, target_width)++ # Trim video to target number of frames+ frames_resized = frames_resized[:target_num_frames]++ # VAE-aligned temporal subsampling: keep frame 0, then every Nth frame+ if self.temporal_subsample_factor > 1:+ indices = _compute_temporal_subsample_indices(target_num_frames, self.temporal_subsample_factor)+ frames_resized = frames_resized[indices]++ # Apply transforms to each frame and stack+ video = torch.stack([self.transforms(frame) for frame in frames_resized], dim=0)++ # Permute [F,C,H,W] -> [C,F,H,W] for VAE compatibility+ # After DataLoader batching, this becomes [B,C,F,H,W] which VAE expects+ video = video.permute(1, 0, 2, 3).contiguous()++ return video, fps++ def _get_resolution_bucket_for_item(self, media_tensor: torch.Tensor) -> tuple[int, int, int]:+ """Get the nearest resolution bucket for the given media tensor."""+ num_frames, _, height, width = media_tensor.shape++ def distance(bucket: tuple[int, int, int]) -> tuple:+ bucket_num_frames, bucket_height, bucket_width = bucket+ # Lexicographic key:+ # 1) minimize aspect-ratio diff (in log-scale, for invariance to shorter/longer ARs)+ # 2) prefer buckets with more frames (by using negative)+ # 3) prefer buckets with larger spatial area (by using negative)+ return (+ abs(math.log(width / height) - math.log(bucket_width / bucket_height)),+ -bucket_num_frames,+ -(bucket_height * bucket_width),+ )++ # Keep only buckets with <= available frames+ relevant_buckets = [b for b in self.resolution_buckets if b[0] <= num_frames]+ if not relevant_buckets:+ raise ValueError(f"No resolution buckets have <= {num_frames} frames. Available: {self.resolution_buckets}")++ # Find the bucket with the minimal distance (according to the function above) to the media item's shape.+ nearest_bucket = min(relevant_buckets, key=distance)++ return nearest_bucket++ def _resize_and_crop(self, media_tensor: torch.Tensor, target_height: int, target_width: int) -> torch.Tensor:+ """Resize and crop tensor to target size."""+ # Get current dimensions+ current_height, current_width = media_tensor.shape[2], media_tensor.shape[3]++ # Calculate aspect ratios to determine which dimension to resize first+ current_aspect = current_width / current_height+ target_aspect = target_width / target_height++ # Resize while maintaining aspect ratio - scale to make the smaller dimension fit+ if current_aspect > target_aspect:+ # Current is wider than target, so scale by height+ new_width = int(current_width * target_height / current_height)+ media_tensor = resize(+ media_tensor,+ size=[target_height, new_width], # type: ignore+ interpolation=InterpolationMode.BICUBIC,+ )+ else:+ # Current is taller than target, so scale by width+ new_height = int(current_height * target_width / current_width)+ media_tensor = resize(+ media_tensor,+ size=[new_height, target_width],+ interpolation=InterpolationMode.BICUBIC,+ )++ # Update dimensions after resize+ current_height, current_width = media_tensor.shape[2], media_tensor.shape[3]+ media_tensor = media_tensor.squeeze(0)++ # Calculate how much we need to crop from each dimension+ delta_h = current_height - target_height+ delta_w = current_width - target_width++ # Determine crop position based on reshape mode+ if self.reshape_mode == "random":+ # Random crop position+ top = np.random.randint(0, delta_h + 1)+ left = np.random.randint(0, delta_w + 1)+ elif self.reshape_mode == "center":+ # Center crop+ top, left = delta_h // 2, delta_w // 2+ else:+ raise ValueError(f"Unsupported reshape mode: {self.reshape_mode}")++ # Perform the final crop to exact target dimensions+ media_tensor = crop(media_tensor, top=top, left=left, height=target_height, width=target_width)+ return media_tensor+++def _compute_temporal_subsample_indices(num_frames: int, factor: int) -> list[int]:+ """Compute VAE-aligned temporal subsample indices.+ Keeps frame 0 (the VAE's standalone first-frame latent), then takes every+ ``factor``-th frame from frame 1 onwards. This ensures each resulting+ 8-frame VAE group spans ``factor`` groups of the original video.+ """+ if factor == 1:+ return list(range(num_frames))+ return [0, *list(range(1, num_frames, factor))]+++def compute_latents( # noqa: PLR0912, PLR0913, PLR0915+ dataset_file: str | Path,+ video_column: str,+ resolution_buckets: list[tuple[int, int, int]],+ output_dir: str,+ model_path: str,+ video_vae_path: str | None = None,+ audio_vae_path: str | None = None,+ main_media_column: str | None = None,+ reshape_mode: str = "center",+ batch_size: int = 1,+ device: str = "cuda",+ vae_tiling: bool = False,+ with_audio: bool = False,+ audio_output_dir: str | None = None,+ num_dataloader_workers: int = 4,+ overwrite: bool = False,+ temporal_subsample_factor: int = 1,+) -> None:+ """+ Process videos and save latent representations.+ Under ``accelerate launch``, each process handles an interleaved shard of+ the dataset (rank/world read from ``accelerate.PartialState``). Already-+ computed ``.pt`` outputs are skipped unless ``overwrite=True``; writes are+ atomic so an interrupted run is safe to resume.+ Args:+ dataset_file: Path to metadata file (CSV/JSON/JSONL) containing video paths+ video_column: Column name for video paths in the metadata file+ resolution_buckets: List of (frames, height, width) tuples+ output_dir: Directory to save video latents+ model_path: Path to LTX-2 checkpoint (.safetensors)+ reshape_mode: How to crop videos ("center", "random")+ main_media_column: Column name for main media paths (if different from video_column)+ batch_size: Batch size for processing+ device: Device to use for computation+ vae_tiling: Whether to enable VAE tiling+ with_audio: Whether to extract and encode audio from videos+ audio_output_dir: Directory to save audio latents (required if with_audio=True)+ num_dataloader_workers: Number of DataLoader worker processes (0 for in-process loading)+ overwrite: Re-process every item even if its output exists. Use when rerunning with+ changed parameters (different model, resolution, etc.) so stale outputs are replaced.+ temporal_subsample_factor: Factor for VAE-aligned temporal subsampling of reference videos+ """+ video_vae_path = resolve_video_vae_path(model_path, video_vae_path)+ # Video VAE compression factors, derived from the checkpoint config (default 32x32x8).+ scale_factors = read_video_scale_factors(video_vae_path)++ # Validate temporal subsampling compatibility with resolution buckets+ if temporal_subsample_factor > 1:+ for frames, _h, _w in resolution_buckets:+ pixel_frames_minus_one = frames - 1+ if pixel_frames_minus_one % temporal_subsample_factor != 0:+ raise ValueError(+ f"Frame count {frames} is not compatible with "+ f"temporal_subsample_factor={temporal_subsample_factor}. "+ f"(frames - 1) must be divisible by the factor."+ )+ subsampled = 1 + pixel_frames_minus_one // temporal_subsample_factor+ if (subsampled - 1) % scale_factors.time != 0:+ raise ValueError(+ f"After temporal subsampling {frames} → {subsampled} frames, "+ f"result does not satisfy (frames - 1) % {scale_factors.time} == 0."+ )++ if with_audio and audio_output_dir is None:+ raise ValueError("audio_output_dir must be provided when with_audio=True")++ console = Console()+ torch_device = torch.device(device)++ dataset = MediaDataset(+ dataset_file=dataset_file,+ main_media_column=main_media_column or video_column,+ video_column=video_column,+ resolution_buckets=resolution_buckets,+ reshape_mode=reshape_mode,+ with_audio=with_audio,+ temporal_subsample_factor=temporal_subsample_factor,+ )+ logger.info(f"Loaded {len(dataset)} valid media files")++ output_path = Path(output_dir)+ output_path.mkdir(parents=True, exist_ok=True)++ audio_output_path: Path | None = None+ if with_audio:+ audio_output_path = Path(audio_output_dir)+ audio_output_path.mkdir(parents=True, exist_ok=True)++ # Audio processing requires batch_size=1; must be applied before the dataloader is built.+ if with_audio and batch_size > 1:+ logger.warning("Audio processing requires batch_size=1. Overriding batch_size to 1.")+ batch_size = 1++ data_root = Path(dataset_file).parent++ def _is_done(idx: int) -> bool:+ rel = _output_relative(dataset.main_media_paths[idx], data_root).with_suffix(".pt")+ if not (output_path / rel).is_file():+ return False+ return audio_output_path is None or (audio_output_path / rel).is_file()++ dataloader = _build_sharded_dataloader(+ dataset,+ batch_size=batch_size,+ num_workers=num_dataloader_workers,+ is_done=_is_done,+ overwrite=overwrite,+ )+ if dataloader is None:+ return++ with console.status(f"[bold]Loading video VAE encoder from [cyan]{video_vae_path}[/]...", spinner="dots"):+ vae = load_video_vae_encoder(video_vae_path, device=torch_device, dtype=torch.bfloat16)++ audio_vae_encoder = None+ audio_processor = None+ if with_audio:+ # Resolved here so a video-only run never has to name a split pack's audio VAE.+ audio_vae_path = resolve_audio_vae_path(model_path, audio_vae_path)+ with console.status(f"[bold]Loading audio VAE encoder from [cyan]{audio_vae_path}[/]...", spinner="dots"):+ audio_vae_encoder = load_audio_vae_encoder(+ checkpoint_path=audio_vae_path,+ device=torch_device,+ dtype=torch.float32, # Audio VAE needs float32 for quality. TODO: re-test with bfloat16.+ )+ audio_processor = AudioProcessor(+ target_sample_rate=audio_vae_encoder.sample_rate,+ mel_bins=audio_vae_encoder.mel_bins,+ mel_hop_length=audio_vae_encoder.mel_hop_length,+ n_fft=audio_vae_encoder.n_fft,+ ).to(torch_device)++ # Track audio statistics+ audio_success_count = 0+ audio_skip_count = 0++ # Process batches+ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ BarColumn(),+ TaskProgressColumn(),+ MofNCompleteColumn(),+ TimeElapsedColumn(),+ TimeRemainingColumn(),+ console=console,+ ) as progress:+ task = progress.add_task("Processing videos", total=len(dataloader))++ for batch in dataloader:+ # Get video tensor - shape is [B, F, C, H, W] from DataLoader+ video = batch["video"]++ # Encode video+ with torch.inference_mode():+ video_latent_data = _encode_video(+ vae=vae, video=video, use_tiling=vae_tiling, scale_factors=scale_factors+ )++ # Save latents for each item in batch+ for i in range(len(batch["relative_path"])):+ output_rel_path = Path(batch["main_media_relative_path"][i]).with_suffix(".pt")+ output_file = output_path / output_rel_path++ # Create output directory maintaining structure+ output_file.parent.mkdir(parents=True, exist_ok=True)++ # Store the latent's effective fps (= source_fps / subsample factor).+ # Downstream position math expects the rate the saved latents actually have.+ effective_fps = batch["video_metadata"]["fps"][i].item() / temporal_subsample_factor+ latent_data = {+ "latents": video_latent_data["latents"][i].cpu().contiguous(), # [C, F', H', W']+ "num_frames": video_latent_data["num_frames"],+ "height": video_latent_data["height"],+ "width": video_latent_data["width"],+ "fps": effective_fps,+ }++ _atomic_save(latent_data, output_file)++ # Process audio if enabled (audio is already extracted by the dataset)+ if with_audio:+ audio_batch = batch.get("audio")+ if audio_batch is not None:+ # Extract the i-th item from batched audio data+ # DataLoader collates [channels, samples] -> [batch, channels, samples]+ audio_data = Audio(+ waveform=audio_batch["waveform"][i],+ sampling_rate=audio_batch["sample_rate"][i].item(),+ )++ # Encode audio+ with torch.inference_mode():+ audio_latents = _encode_audio(audio_vae_encoder, audio_processor, audio_data)++ # Save audio latents+ audio_output_file = audio_output_path / output_rel_path+ audio_output_file.parent.mkdir(parents=True, exist_ok=True)++ audio_save_data = {+ "latents": audio_latents["latents"].cpu().contiguous(),+ "num_time_steps": audio_latents["num_time_steps"],+ "frequency_bins": audio_latents["frequency_bins"],+ "duration": audio_latents["duration"],+ }++ _atomic_save(audio_save_data, audio_output_file)+ audio_success_count += 1+ else:+ # Video has no audio track+ audio_skip_count += 1++ progress.advance(task)++ logger.info(f"Processed {len(dataloader.dataset)} videos -> {output_path}") # type: ignore[arg-type]+ if with_audio:+ logger.info(+ f"Audio processing: {audio_success_count} videos with audio, "+ f"{audio_skip_count} videos without audio (skipped)"+ )+++def _encode_video(+ vae: torch.nn.Module,+ video: torch.Tensor,+ dtype: torch.dtype | None = None,+ use_tiling: bool = False,+ tile_size: int = DEFAULT_TILE_SIZE,+ tile_overlap: int = DEFAULT_TILE_OVERLAP,+ scale_factors: SpatioTemporalScaleFactors = VIDEO_SCALE_FACTORS,+) -> dict[str, torch.Tensor | int]:+ """Encode video into non-patchified latent representation.+ Args:+ vae: Video VAE encoder model+ video: Input tensor of shape [B, C, F, H, W] (batch, channels, frames, height, width)+ This is the format expected by the VAE encoder.+ dtype: Target dtype for output latents+ use_tiling: Whether to use spatial tiling for memory efficiency+ tile_size: Tile size in pixels (must be divisible by the VAE spatial factor)+ tile_overlap: Overlap between tiles in pixels (must be divisible by the VAE spatial factor)+ scale_factors: Video VAE spatiotemporal compression factors (default 32x32x8)+ Returns:+ Dict containing non-patchified latents and shape information:+ {+ "latents": Tensor[B, C, F', H', W'], # Non-patchified format with batch dim+ "num_frames": int, # Latent frame count+ "height": int, # Latent height+ "width": int, # Latent width+ }+ """+ device = next(vae.parameters()).device+ vae_dtype = next(vae.parameters()).dtype++ # Add batch dimension if needed+ if video.ndim == 4:+ video = video.unsqueeze(0) # [C, F, H, W] -> [B, C, F, H, W]++ video = video.to(device=device, dtype=vae_dtype)++ # Choose encoding method based on tiling flag+ if use_tiling:+ latents = _tiled_encode_video(+ vae=vae,+ video=video,+ tile_size=tile_size,+ tile_overlap=tile_overlap,+ scale_factors=scale_factors,+ )+ else:+ # Encode video - VAE expects [B, C, F, H, W], returns [B, C, F', H', W']+ latents = vae(video)++ if dtype is not None:+ latents = latents.to(dtype=dtype)++ _, _, num_frames, height, width = latents.shape++ return {+ "latents": latents, # [B, C, F', H', W']+ "num_frames": num_frames,+ "height": height,+ "width": width,+ }+++def _tiled_encode_video( # noqa: PLR0912, PLR0915+ vae: torch.nn.Module,+ video: torch.Tensor,+ tile_size: int = DEFAULT_TILE_SIZE,+ tile_overlap: int = DEFAULT_TILE_OVERLAP,+ scale_factors: SpatioTemporalScaleFactors = VIDEO_SCALE_FACTORS,+) -> torch.Tensor:+ """Encode video using spatial tiling for memory efficiency.+ Splits the video into overlapping spatial tiles, encodes each tile separately,+ and blends the results using linear feathering in the overlap regions.+ Args:+ vae: Video VAE encoder model+ video: Input tensor of shape [B, C, F, H, W]+ tile_size: Tile size in pixels (must be divisible by 32)+ tile_overlap: Overlap between tiles in pixels (must be divisible by 32)+ Returns:+ Encoded latent tensor [B, C_latent, F_latent, H_latent, W_latent]+ """+ batch, _channels, frames, height, width = video.shape+ device = video.device+ dtype = video.dtype++ # Spatial tiling assumes a square spatial compression (height factor == width factor).+ spatial_factor = scale_factors.height++ # Validate tile parameters+ if tile_size % spatial_factor != 0:+ raise ValueError(f"tile_size must be divisible by {spatial_factor}, got {tile_size}")+ if tile_overlap % spatial_factor != 0:+ raise ValueError(f"tile_overlap must be divisible by {spatial_factor}, got {tile_overlap}")+ if tile_overlap >= tile_size:+ raise ValueError(f"tile_overlap ({tile_overlap}) must be less than tile_size ({tile_size})")++ # If video fits in a single tile, use regular encoding+ if height <= tile_size and width <= tile_size:+ return vae(video)++ # Calculate output dimensions from the VAE compression factors+ # (e.g. the default 32x32x8: H -> H/32, W -> W/32, F -> 1 + (F-1)/8)+ output_height = height // scale_factors.height+ output_width = width // scale_factors.width+ output_frames = 1 + (frames - 1) // scale_factors.time++ # Latent channels are 128 across all supported VAE variants.+ latent_channels = 128++ # Initialize output and weight tensors+ output = torch.zeros(+ (batch, latent_channels, output_frames, output_height, output_width),+ device=device,+ dtype=dtype,+ )+ weights = torch.zeros(+ (batch, 1, output_frames, output_height, output_width),+ device=device,+ dtype=dtype,+ )++ # Calculate tile positions with overlap+ # Step size is tile_size - tile_overlap+ step_h = tile_size - tile_overlap+ step_w = tile_size - tile_overlap++ h_positions = list(range(0, max(1, height - tile_overlap), step_h))+ w_positions = list(range(0, max(1, width - tile_overlap), step_w))++ # Ensure last tile covers the edge+ if h_positions[-1] + tile_size < height:+ h_positions.append(height - tile_size)+ if w_positions[-1] + tile_size < width:+ w_positions.append(width - tile_size)++ # Remove duplicates and sort+ h_positions = sorted(set(h_positions))+ w_positions = sorted(set(w_positions))++ # Overlap in latent space+ overlap_out_h = tile_overlap // scale_factors.height+ overlap_out_w = tile_overlap // scale_factors.width++ # Process each tile+ for h_pos in h_positions:+ for w_pos in w_positions:+ # Calculate tile boundaries in input space+ h_start = max(0, h_pos)+ w_start = max(0, w_pos)+ h_end = min(h_start + tile_size, height)+ w_end = min(w_start + tile_size, width)++ # Ensure tile dimensions are divisible by the VAE spatial factor+ tile_h = ((h_end - h_start) // scale_factors.height) * scale_factors.height+ tile_w = ((w_end - w_start) // scale_factors.width) * scale_factors.width++ if tile_h < scale_factors.height or tile_w < scale_factors.width:+ continue++ # Adjust end positions+ h_end = h_start + tile_h+ w_end = w_start + tile_w++ # Extract tile+ tile = video[:, :, :, h_start:h_end, w_start:w_end]++ # Encode tile+ encoded_tile = vae(tile)++ # Get actual encoded dimensions+ _, _, tile_out_frames, tile_out_height, tile_out_width = encoded_tile.shape++ # Calculate output positions+ out_h_start = h_start // scale_factors.height+ out_w_start = w_start // scale_factors.width+ out_h_end = min(out_h_start + tile_out_height, output_height)+ out_w_end = min(out_w_start + tile_out_width, output_width)++ # Trim encoded tile if necessary+ actual_tile_h = out_h_end - out_h_start+ actual_tile_w = out_w_end - out_w_start+ encoded_tile = encoded_tile[:, :, :, :actual_tile_h, :actual_tile_w]++ # Create blending mask with linear feathering at edges+ mask = torch.ones(+ (1, 1, tile_out_frames, actual_tile_h, actual_tile_w),+ device=device,+ dtype=dtype,+ )++ # Apply feathering at edges (linear blend in overlap regions)+ # Left edge+ if h_pos > 0 and overlap_out_h > 0 and overlap_out_h < actual_tile_h:+ fade_in = torch.linspace(0.0, 1.0, overlap_out_h + 2, device=device, dtype=dtype)[1:-1]+ mask[:, :, :, :overlap_out_h, :] *= fade_in.view(1, 1, 1, -1, 1)++ # Right edge (bottom in height dimension)+ if h_end < height and overlap_out_h > 0 and overlap_out_h < actual_tile_h:+ fade_out = torch.linspace(1.0, 0.0, overlap_out_h + 2, device=device, dtype=dtype)[1:-1]+ mask[:, :, :, -overlap_out_h:, :] *= fade_out.view(1, 1, 1, -1, 1)++ # Top edge (left in width dimension)+ if w_pos > 0 and overlap_out_w > 0 and overlap_out_w < actual_tile_w:+ fade_in = torch.linspace(0.0, 1.0, overlap_out_w + 2, device=device, dtype=dtype)[1:-1]+ mask[:, :, :, :, :overlap_out_w] *= fade_in.view(1, 1, 1, 1, -1)++ # Bottom edge (right in width dimension)+ if w_end < width and overlap_out_w > 0 and overlap_out_w < actual_tile_w:+ fade_out = torch.linspace(1.0, 0.0, overlap_out_w + 2, device=device, dtype=dtype)[1:-1]+ mask[:, :, :, :, -overlap_out_w:] *= fade_out.view(1, 1, 1, 1, -1)++ # Accumulate weighted results+ output[:, :, :, out_h_start:out_h_end, out_w_start:out_w_end] += encoded_tile * mask+ weights[:, :, :, out_h_start:out_h_end, out_w_start:out_w_end] += mask++ # Normalize by weights (avoid division by zero)+ output = output / (weights + 1e-8)++ return output+++def _encode_audio(+ audio_vae_encoder: torch.nn.Module,+ audio_processor: torch.nn.Module,+ audio: Audio,+) -> dict[str, torch.Tensor | int | float]:+ """Encode audio waveform into latent representation.+ Args:+ audio_vae_encoder: Audio VAE encoder model from ltx-core+ audio_processor: AudioProcessor for waveform-to-spectrogram conversion+ audio: Audio container with waveform tensor and sampling rate.+ Returns:+ Dict containing audio latents and shape information:+ {+ "latents": Tensor[C, T, F], # Non-patchified format+ "num_time_steps": int,+ "frequency_bins": int,+ "duration": float,+ }+ """+ device = next(audio_vae_encoder.parameters()).device+ dtype = next(audio_vae_encoder.parameters()).dtype++ waveform = audio.waveform.to(device=device, dtype=dtype)++ # Add batch dimension if needed: [channels, samples] -> [batch, channels, samples]+ if waveform.dim() == 2:+ waveform = waveform.unsqueeze(0)++ # Convert to stereo if needed (audio VAE expects 2 channels)+ # Channel order for surround: 5.1=[L,R,C,LFE,Ls,Rs], 7.1=[L,R,C,LFE,Ls,Rs,Lb,Rb]+ num_channels = waveform.shape[1]+ if num_channels == 1:+ # Mono to stereo: duplicate the channel+ waveform = waveform.repeat(1, 2, 1)+ elif num_channels == 6:+ # 5.1 downmix with normalized weights (sum to 1.0)+ # Original: L = L + 0.707*C + 0.707*Ls, weights sum = 2.414+ w_main = 1.0 / 2.414 # ~0.414+ w_other = 0.707 / 2.414 # ~0.293+ left = w_main * waveform[:, 0, :] + w_other * waveform[:, 2, :] + w_other * waveform[:, 4, :]+ right = w_main * waveform[:, 1, :] + w_other * waveform[:, 2, :] + w_other * waveform[:, 5, :]+ waveform = torch.stack([left, right], dim=1)+ elif num_channels == 8:+ # 7.1 downmix with normalized weights (sum to 1.0)+ # Original: L = L + 0.707*C + 0.707*Ls + 0.707*Lb, weights sum = 3.121+ w_main = 1.0 / 3.121 # ~0.320+ w_other = 0.707 / 3.121 # ~0.227+ center = waveform[:, 2, :]+ left = w_main * waveform[:, 0, :] + w_other * (center + waveform[:, 4, :] + waveform[:, 6, :])+ right = w_main * waveform[:, 1, :] + w_other * (center + waveform[:, 5, :] + waveform[:, 7, :])+ waveform = torch.stack([left, right], dim=1)+ elif num_channels > 2:+ # Unknown layout: average all channels to mono, then duplicate to stereo+ logger.warning(f"Unknown audio channel layout ({num_channels} channels), using mean downmix")+ mono = waveform.mean(dim=1, keepdim=True)+ waveform = mono.repeat(1, 2, 1)++ # Calculate duration+ duration = waveform.shape[-1] / audio.sampling_rate++ # Convert waveform to mel spectrogram using AudioProcessor+ mel_spectrogram = audio_processor.waveform_to_mel(Audio(waveform=waveform, sampling_rate=audio.sampling_rate))+ mel_spectrogram = mel_spectrogram.to(dtype=dtype)++ # Encode mel spectrogram to latents+ latents = audio_vae_encoder(mel_spectrogram)++ # latents shape: [batch, channels, time, freq] = [1, 8, T, 16]+ _, _channels, time_steps, freq_bins = latents.shape++ return {+ "latents": latents.squeeze(0), # [C, T, F] - remove batch dim+ "num_time_steps": time_steps,+ "frequency_bins": freq_bins,+ "duration": duration,+ }+++AUDIO_FILE_EXTENSIONS = {".wav", ".mp3", ".flac", ".ogg", ".aac", ".m4a"}+VIDEO_FILE_EXTENSIONS = {".mp4", ".avi", ".mov", ".mkv", ".webm"}+IMAGE_FILE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".heic", ".heif", ".bmp", ".tiff", ".webp"}+++def compute_video_masks(+ dataset_file: str | Path,+ mask_column: str,+ latents_dir: str,+ output_dir: str,+ main_media_column: str | None = None,+ overwrite: bool = False,+ scale_factors: SpatioTemporalScaleFactors = VIDEO_SCALE_FACTORS,+) -> None:+ """Preprocess video mask files to latent-space binary masks.+ For each sample, loads the mask video/image, applies the same spatial+ resize/crop as the target video (read from saved latent metadata), downsamples+ to latent dimensions, binarizes, and saves as a .pt tensor.+ Args:+ dataset_file: Path to metadata file (CSV/JSON/JSONL).+ mask_column: Column name containing mask video/image paths.+ latents_dir: Directory containing the target video latents (for reading+ spatial/temporal metadata to ensure mask alignment).+ output_dir: Directory to save mask .pt files.+ main_media_column: Column for output file naming (defaults to mask_column).+ scale_factors: Video VAE spatiotemporal compression factors (default 32x32x8),+ used to map latent mask dimensions back to pixel space and downsample.+ """+ dataset_path = Path(dataset_file)+ data_root = dataset_path.parent+ latents_path = Path(latents_dir)+ output_path = Path(output_dir)+ output_path.mkdir(parents=True, exist_ok=True)++ naming_column = main_media_column or mask_column+ mask_paths = _load_paths_from_dataset(dataset_path, mask_column)+ naming_paths = _load_paths_from_dataset(dataset_path, naming_column) if naming_column != mask_column else mask_paths++ success = 0+ for mask_file, naming_file in zip(mask_paths, naming_paths, strict=True):+ rel_path = _output_relative(naming_file, data_root)+ latent_file = latents_path / rel_path.with_suffix(".pt")+ out_file = output_path / rel_path.with_suffix(".pt")++ if not latent_file.exists():+ logger.warning(f"No target latent found at {latent_file}, skipping mask {mask_file}")+ continue++ if not overwrite and out_file.is_file():+ continue++ target_meta = torch.load(latent_file, map_location="cpu", weights_only=True)+ latent_f = target_meta["num_frames"]+ latent_h = target_meta["height"]+ latent_w = target_meta["width"]+ pixel_h = latent_h * scale_factors.height+ pixel_w = latent_w * scale_factors.width+ pixel_f = (latent_f - 1) * scale_factors.time + 1++ # Load mask as video or image+ if mask_file.suffix.lower() in IMAGE_FILE_EXTENSIONS:+ img = to_tensor(open_image_as_srgb(mask_file)).mean(dim=0, keepdim=True) # [1, H, W]+ img = tv_resize(img.unsqueeze(0), [pixel_h, pixel_w]).squeeze(0) # [1, H, W]+ mask_pixels = img.expand(pixel_f, -1, -1) # tile across frames → [F, H, W]+ else:+ frames, _ = read_video(str(mask_file), max_frames=pixel_f) # [F, C, H, W]+ frames = frames[:pixel_f].mean(dim=1) # grayscale → [F, H, W]+ frames = torch.nn.functional.interpolate(+ frames.unsqueeze(1), size=(pixel_h, pixel_w), mode="nearest"+ ).squeeze(1) # [F, H, W]+ mask_pixels = frames++ # Downsample to latent dims: [F, H, W] → [F', H', W']+ mask_latent = torch.nn.functional.avg_pool2d(+ mask_pixels.unsqueeze(1), kernel_size=scale_factors.height+ ).squeeze(1) # [F, H', W'] → spatial done+ # Temporal: max-pool over groups of scale_factors.time frames (any masked frame masks the group)+ f_spatial = mask_latent.shape[0]+ pad_f = (scale_factors.time - f_spatial % scale_factors.time) % scale_factors.time+ if pad_f > 0:+ mask_latent = torch.nn.functional.pad(mask_latent, (0, 0, 0, 0, 0, pad_f))+ h_prime, w_prime = mask_latent.shape[1], mask_latent.shape[2]+ mask_latent = mask_latent.reshape(-1, scale_factors.time, h_prime, w_prime).amax(dim=1)[:latent_f]++ # Binarize+ mask_latent = (mask_latent > 0.5).float()++ out_file.parent.mkdir(parents=True, exist_ok=True)+ _atomic_save({"mask": mask_latent}, out_file)+ success += 1++ logger.info(f"Mask preprocessing complete: {success} masks saved to {output_path}")+++def compute_audio_masks(+ dataset_file: str | Path,+ mask_column: str,+ audio_latents_dir: str,+ output_dir: str,+ main_media_column: str | None = None,+ overwrite: bool = False,+) -> None:+ """Preprocess audio mask files to latent-space binary masks.+ For each sample, loads the mask (a 1D waveform-like signal or a simple tensor),+ resamples it to match the target audio latent temporal length, binarizes, and saves.+ Args:+ dataset_file: Path to metadata file (CSV/JSON/JSONL).+ mask_column: Column name containing mask file paths (.wav or .pt).+ audio_latents_dir: Directory containing the target audio latents (for reading+ temporal metadata to ensure mask alignment).+ output_dir: Directory to save mask .pt files.+ main_media_column: Column for output file naming (defaults to mask_column).+ """+ dataset_path = Path(dataset_file)+ data_root = dataset_path.parent+ audio_latents_path = Path(audio_latents_dir)+ output_path = Path(output_dir)+ output_path.mkdir(parents=True, exist_ok=True)++ naming_column = main_media_column or mask_column+ mask_paths = _load_paths_from_dataset(dataset_path, mask_column)+ naming_paths = _load_paths_from_dataset(dataset_path, naming_column) if naming_column != mask_column else mask_paths++ success = 0+ for mask_file, naming_file in zip(mask_paths, naming_paths, strict=True):+ rel_path = _output_relative(naming_file, data_root)+ latent_file = audio_latents_path / rel_path.with_suffix(".pt")+ out_file = output_path / rel_path.with_suffix(".pt")++ if not latent_file.exists():+ logger.warning(f"No target audio latent found at {latent_file}, skipping mask {mask_file}")+ continue++ if not overwrite and out_file.is_file():+ continue++ target_meta = torch.load(latent_file, map_location="cpu", weights_only=True)+ latent_t = target_meta["num_time_steps"]++ # Load mask: .pt file (raw tensor) or .wav (use amplitude envelope)+ if mask_file.suffix == ".pt":+ raw_mask = torch.load(mask_file, map_location="cpu", weights_only=True)+ if isinstance(raw_mask, dict):+ raw_mask = raw_mask.get("mask", next(iter(raw_mask.values())))+ raw_mask = raw_mask.float().flatten()+ else:+ audio = _load_audio_from_file(mask_file)+ if audio is None:+ logger.warning(f"Could not load audio mask from {mask_file}")+ continue+ raw_mask = audio.waveform.abs().mean(dim=0) # mono amplitude envelope++ # Resample to target audio latent length+ mask_resampled = torch.nn.functional.interpolate(+ raw_mask.unsqueeze(0).unsqueeze(0), size=latent_t, mode="nearest"+ ).squeeze() # [latent_t]++ mask_binary = (mask_resampled > 0.5).float()++ out_file.parent.mkdir(parents=True, exist_ok=True)+ _atomic_save({"mask": mask_binary}, out_file)+ success += 1++ logger.info(f"Audio mask preprocessing complete: {success} masks saved to {output_path}")+++def compute_audio_latents( # noqa: PLR0915+ dataset_file: str | Path,+ audio_column: str,+ output_dir: str,+ model_path: str,+ audio_vae_path: str | None = None,+ main_media_column: str | None = None,+ max_duration: float | None = None,+ duration_buckets: list[float] | None = None,+ device: str = "cuda",+ overwrite: bool = False,+) -> None:+ """Encode audio files into latent representations.+ Supports standalone audio files (.wav, .mp3, etc.) and audio tracks+ extracted from video files (.mp4, etc.).+ Args:+ dataset_file: Path to metadata file (CSV/JSON/JSONL).+ audio_column: Column name containing audio file paths.+ output_dir: Directory to save audio latents.+ model_path: Path to LTX-2 checkpoint (.safetensors).+ main_media_column: Column for output file naming (defaults to audio_column).+ Ensures alignment with other latent directories.+ max_duration: Maximum audio duration in seconds. Audio is trimmed if longer.+ Mutually exclusive with duration_buckets.+ duration_buckets: List of allowed durations in seconds (e.g. [2.0, 4.0, 8.0]).+ Each audio file is matched to the largest bucket that fits its duration,+ then trimmed to exactly that length. Files shorter than the smallest+ bucket are skipped. Ensures uniform lengths for batched training.+ device: Device to use for computation.+ """+ console = Console()+ torch_device = torch.device(device)++ dataset_path = Path(dataset_file)+ data_root = dataset_path.parent+ output_path = Path(output_dir)+ output_path.mkdir(parents=True, exist_ok=True)++ naming_column = main_media_column or audio_column+ audio_paths = _load_paths_from_dataset(dataset_path, audio_column)+ naming_paths = (+ _load_paths_from_dataset(dataset_path, naming_column) if naming_column != audio_column else audio_paths+ )++ audio_vae_path = resolve_audio_vae_path(model_path, audio_vae_path)+ with console.status(f"[bold]Loading audio VAE encoder from [cyan]{audio_vae_path}[/]...", spinner="dots"):+ audio_vae_encoder = load_audio_vae_encoder(+ checkpoint_path=audio_vae_path,+ device=torch_device,+ dtype=torch.float32,+ )+ audio_processor = AudioProcessor(+ target_sample_rate=audio_vae_encoder.sample_rate,+ mel_bins=audio_vae_encoder.mel_bins,+ mel_hop_length=audio_vae_encoder.mel_hop_length,+ n_fft=audio_vae_encoder.n_fft,+ ).to(torch_device)++ sorted_buckets = sorted(duration_buckets, reverse=True) if duration_buckets else None+ success_count = 0+ skip_count = 0++ with Progress(+ SpinnerColumn(),+ TextColumn("[progress.description]{task.description}"),+ BarColumn(),+ TaskProgressColumn(),+ MofNCompleteColumn(),+ TimeElapsedColumn(),+ TimeRemainingColumn(),+ console=console,+ ) as progress:+ task = progress.add_task("Encoding audio", total=len(audio_paths))++ for audio_path, naming_path in zip(audio_paths, naming_paths, strict=True):+ rel_path = _output_relative(naming_path, data_root)+ output_file = output_path / rel_path.with_suffix(".pt")+ output_file.parent.mkdir(parents=True, exist_ok=True)++ if not overwrite and output_file.is_file():+ success_count += 1+ progress.advance(task)+ continue++ # Load audio (no trimming yet — need full duration for bucket matching)+ audio = _load_audio_from_file(audio_path)+ if audio is None:+ skip_count += 1+ progress.advance(task)+ continue++ file_duration = audio.waveform.shape[-1] / audio.sampling_rate++ # Determine target duration: bucket matching, max_duration cap, or full file+ target_duration = file_duration+ if sorted_buckets:+ bucket = next((b for b in sorted_buckets if b <= file_duration), None)+ if bucket is None:+ logger.warning(+ f"Skipping {audio_path.name} ({file_duration:.1f}s) — shorter than "+ f"smallest bucket ({sorted_buckets[-1]:.1f}s)"+ )+ skip_count += 1+ progress.advance(task)+ continue+ target_duration = bucket+ elif max_duration is not None:+ target_duration = min(file_duration, max_duration)++ # Trim to target duration+ target_samples = int(target_duration * audio.sampling_rate)+ trimmed_waveform = audio.waveform[:, :target_samples]+ audio = Audio(waveform=trimmed_waveform, sampling_rate=audio.sampling_rate)++ with torch.inference_mode():+ audio_latents = _encode_audio(audio_vae_encoder, audio_processor, audio)++ _atomic_save(+ {+ "latents": audio_latents["latents"].cpu().contiguous(),+ "num_time_steps": audio_latents["num_time_steps"],+ "frequency_bins": audio_latents["frequency_bins"],+ "duration": audio_latents["duration"],+ },+ output_file,+ )+ success_count += 1+ progress.advance(task)++ logger.info(f"Audio encoding complete: {success_count} encoded, {skip_count} skipped. Saved to {output_path}")+++def _output_relative(path: Path, data_root: Path) -> Path:+ """Relative path used to name a sample's cached output, mirroring the input layout.+ Normally media lives under the dataset directory and this is just the path relative to it.+ If a media path is absolute or otherwise outside the dataset directory (e.g. a one-off+ metadata file that references media elsewhere), mirror its absolute structure under the+ output directory instead of raising, so out-of-tree media stays collision-free.+ """+ try:+ return path.relative_to(data_root)+ except ValueError:+ return Path(*path.parts[1:]) if path.is_absolute() else path+++def _load_paths_from_dataset(dataset_file: Path, column: str) -> list[Path]:+ """Load file paths from a dataset column, resolving relative to the dataset file's directory."""+ data_root = dataset_file.parent++ if dataset_file.suffix == ".csv":+ df = pd.read_csv(dataset_file)+ if column not in df.columns:+ raise ValueError(f"Column '{column}' not found in CSV file")+ return [data_root / Path(str(v).strip()) for v in df[column].tolist()]++ if dataset_file.suffix == ".json":+ with open(dataset_file, encoding="utf-8") as f:+ data = json.load(f)+ if not isinstance(data, list):+ raise ValueError("JSON file must contain a list of objects")+ return [data_root / Path(entry[column].strip()) for entry in data]++ if dataset_file.suffix == ".jsonl":+ paths = []+ with open(dataset_file, encoding="utf-8") as f:+ for line in f:+ entry = json.loads(line)+ paths.append(data_root / Path(entry[column].strip()))+ return paths++ raise ValueError(f"Unsupported dataset format: {dataset_file.suffix}")+++def _load_audio_from_file(audio_path: Path, max_duration: float | None = None) -> Audio | None:+ """Load audio from an audio or video file, optionally trimming to max_duration."""+ try:+ waveform, sample_rate = torchaudio.load(str(audio_path))+ except Exception:+ logger.debug(f"Could not load audio from {audio_path}")+ return None++ if max_duration is not None:+ max_samples = int(max_duration * sample_rate)+ if waveform.shape[-1] > max_samples:+ waveform = waveform[:, :max_samples]++ return Audio(waveform=waveform, sampling_rate=sample_rate)+++def detect_dataset_columns(dataset_file: str | Path) -> set[str]:+ """Read column names from a dataset file without loading all data."""+ path = Path(dataset_file)+ if path.suffix == ".csv":+ df = pd.read_csv(path, nrows=0)+ return set(df.columns)+ if path.suffix == ".json":+ with open(path, encoding="utf-8") as f:+ data = json.load(f)+ return set(data[0].keys()) if isinstance(data, list) and data else set()+ if path.suffix == ".jsonl":+ with open(path, encoding="utf-8") as f:+ return set(json.loads(f.readline()).keys())+ return set()+++def parse_resolution_buckets(+ resolution_buckets_str: str,+ scale_factors: SpatioTemporalScaleFactors = VIDEO_SCALE_FACTORS,+) -> list[tuple[int, int, int]]:+ """Parse resolution buckets from string format to list of tuples (frames, height, width).+ ``scale_factors`` are the video VAE's spatiotemporal compression factors (default 32x32x8);+ width/height must be multiples of the spatial factors and frames must satisfy+ ``f % scale_factors.time == 1``.+ """+ resolution_buckets = []+ for bucket_str in resolution_buckets_str.split(";"):+ w, h, f = map(int, bucket_str.split("x"))++ if w % scale_factors.width != 0 or h % scale_factors.height != 0:+ raise typer.BadParameter(+ f"Width and height must be multiples of {scale_factors.width}x{scale_factors.height}, got {w}x{h}",+ param_hint="resolution-buckets",+ )++ if f % scale_factors.time != 1:+ raise typer.BadParameter(+ f"Number of frames must be a multiple of {scale_factors.time} plus 1, got {f}",+ param_hint="resolution-buckets",+ )++ resolution_buckets.append((f, h, w))+ return resolution_buckets+++def compute_scaled_resolution_buckets(+ resolution_buckets: list[tuple[int, int, int]],+ scale_factor: int,+ scale_factors: SpatioTemporalScaleFactors = VIDEO_SCALE_FACTORS,+) -> list[tuple[int, int, int]]:+ """Compute scaled resolution buckets and validate the results.+ ``scale_factors`` are the video VAE's spatiotemporal compression factors (default 32x32x8),+ used to check the post-scale dimensions are still VAE-aligned.+ """+ if scale_factor == 1:+ return resolution_buckets++ scaled_buckets = []+ for frames, height, width in resolution_buckets:+ # Validate that scale factor evenly divides the dimensions+ if height % scale_factor != 0:+ raise ValueError(+ f"Height {height} is not evenly divisible by scale factor {scale_factor}. "+ f"Choose a scale factor that divides {height} evenly."+ )+ if width % scale_factor != 0:+ raise ValueError(+ f"Width {width} is not evenly divisible by scale factor {scale_factor}. "+ f"Choose a scale factor that divides {width} evenly."+ )++ scaled_height = height // scale_factor+ scaled_width = width // scale_factor++ # Validate scaled dimensions are divisible by VAE spatial factor+ if scaled_height % scale_factors.height != 0:+ raise ValueError(+ f"Scaled height {scaled_height} (from {height} / {scale_factor}) "+ f"is not divisible by {scale_factors.height}. "+ f"Choose a different scale factor or adjust your resolution buckets."+ )+ if scaled_width % scale_factors.width != 0:+ raise ValueError(+ f"Scaled width {scaled_width} (from {width} / {scale_factor}) "+ f"is not divisible by {scale_factors.width}. "+ f"Choose a different scale factor or adjust your resolution buckets."+ )++ scaled_buckets.append((frames, scaled_height, scaled_width))++ return scaled_buckets+++def _atomic_save(data: Any, out: Path) -> None: # noqa: ANN401+ """Save to ``out`` atomically via per-PID temp file + replace.+ Crash mid-write leaves an orphan ``.tmp.<pid>`` file that the skip logic+ ignores. The per-PID suffix makes concurrent writes from multiple ranks+ collision-free.+ """+ tmp = out.with_suffix(f"{out.suffix}.tmp.{os.getpid()}")+ torch.save(data, tmp)+ tmp.replace(out)+++def _build_sharded_dataloader(+ dataset: Dataset,+ *,+ batch_size: int,+ num_workers: int,+ is_done: Callable[[int], bool],+ overwrite: bool,+) -> DataLoader | None:+ """Return a DataLoader over this rank's interleaved shard of ``dataset``.+ When ``overwrite`` is False, items whose outputs already exist (per+ ``is_done``) are filtered out. Returns ``None`` if this rank has nothing+ to do, so the caller can early-return without loading any models.+ """+ state = PartialState()+ todo = [i for i in range(state.process_index, len(dataset), state.num_processes) if overwrite or not is_done(i)]+ if not todo:+ logger.info(f"Rank {state.process_index}/{state.num_processes}: nothing to do")+ return None+ logger.info(f"Rank {state.process_index}/{state.num_processes}: processing {len(todo):,} of {len(dataset):,} items")+ return DataLoader(Subset(dataset, todo), batch_size=batch_size, shuffle=False, num_workers=num_workers)+++def main( # noqa: PLR0913+ dataset_file: str = typer.Argument(+ ...,+ help="Path to metadata file (CSV/JSON/JSONL) containing video paths",+ ),+ resolution_buckets: str = typer.Option(+ ...,+ help='Resolution buckets in format "WxHxF;WxHxF;..." (e.g. "768x768x25;512x512x49")',+ ),+ output_dir: str = typer.Option(+ ...,+ help="Output directory to save video latents",+ ),+ model_path: str = typer.Option(+ ...,+ help="Path to the unified checkpoint or split transformer safetensors",+ ),+ video_vae_path: str | None = typer.Option(+ default=None,+ help="Split-pack video VAE safetensors (defaults to --model-path for unified checkpoints)",+ ),+ audio_vae_path: str | None = typer.Option(+ default=None,+ help="Split-pack audio VAE safetensors (defaults to --model-path for unified checkpoints)",+ ),+ video_column: str = typer.Option(+ default="media_path",+ help="Column name in the dataset JSON/JSONL/CSV file containing video paths",+ ),+ batch_size: int = typer.Option(+ default=1,+ help="Batch size for processing",+ ),+ device: str = typer.Option(+ default="cuda",+ help="Device to use for computation",+ ),+ vae_tiling: bool = typer.Option(+ default=False,+ help="Enable VAE tiling for larger video resolutions",+ ),+ reshape_mode: str = typer.Option(+ default="center",+ help="How to crop videos: 'center' or 'random'",+ ),+ with_audio: bool = typer.Option(+ default=False,+ help="Extract and encode audio from video files",+ ),+ audio_output_dir: str | None = typer.Option(+ default=None,+ help="Output directory for audio latents (required if --with-audio is set)",+ ),+ overwrite: bool = typer.Option(+ default=False,+ help="Re-encode every item even if its output exists. Use when rerunning with "+ "changed parameters (different model, resolution, etc.) so stale outputs are replaced.",+ ),+) -> None:+ """Process videos/images and save latent representations for video generation training.+ This script processes videos and images from metadata files and saves latent representations+ that can be used for training video generation models. The output latents will maintain+ the same folder structure and naming as the corresponding media files.+ For multi-GPU preprocessing, invoke under ``accelerate launch`` -- each process+ will handle an interleaved shard of the dataset.+ Examples:+ # Process videos from a CSV file+ python scripts/process_videos.py dataset.csv --resolution-buckets 768x768x25 \\+ --output-dir ./latents --model-path /path/to/ltx-checkpoint.safetensors+ # Process videos from a JSON file with custom video column+ python scripts/process_videos.py dataset.json --resolution-buckets 768x768x25 \\+ --output-dir ./latents --model-path /path/to/ltx-checkpoint.safetensors --video-column "video_path"+ # Enable VAE tiling to save GPU VRAM+ python scripts/process_videos.py dataset.csv --resolution-buckets 1024x1024x25 \\+ --output-dir ./latents --model-path /path/to/ltx-checkpoint.safetensors --vae-tiling+ # Process videos with audio+ python scripts/process_videos.py dataset.csv --resolution-buckets 768x768x25 \\+ --output-dir ./latents --model-path /path/to/ltx-checkpoint.safetensors \\+ --with-audio --audio-output-dir ./audio_latents+ """++ # Validate dataset file exists+ if not Path(dataset_file).is_file():+ raise typer.BadParameter(f"Dataset file not found: {dataset_file}")++ # Validate audio parameters+ if with_audio and audio_output_dir is None:+ raise typer.BadParameter("--audio-output-dir is required when --with-audio is set")++ # Parse resolution buckets, validating against the checkpoint's VAE compression factors.+ scale_factors = read_video_scale_factors(resolve_video_vae_path(model_path, video_vae_path))+ parsed_resolution_buckets = parse_resolution_buckets(resolution_buckets, scale_factors)++ if len(parsed_resolution_buckets) > 1:+ logger.warning(+ "Using multiple resolution buckets. "+ "When training with multiple resolution buckets, you must use a batch size of 1."+ )++ # Process latents+ compute_latents(+ dataset_file=dataset_file,+ video_column=video_column,+ resolution_buckets=parsed_resolution_buckets,+ output_dir=output_dir,+ model_path=model_path,+ video_vae_path=video_vae_path,+ audio_vae_path=audio_vae_path,+ reshape_mode=reshape_mode,+ batch_size=batch_size,+ device=device,+ vae_tiling=vae_tiling,+ with_audio=with_audio,+ audio_output_dir=audio_output_dir,+ overwrite=overwrite,+ )+++if __name__ == "__main__":+ app()diff --git a/pyproject.toml b/pyproject.tomlindex 658a59b..1ca80f9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -48,10 +48,9 @@ kernels = ["ltx-kernels"]target-version = "py311"line-length = 120exclude = [- # Vendored kernel sources, excluded from our lint/format rules.- "packages/ltx-kernels/src/ltx_kernels/blockwise/functional.py",+ # Vendored kernel sources / hardware glue, excluded from our lint/format rules."packages/ltx-kernels/src/ltx_kernels/blockwise/linear.py",- "packages/ltx-kernels/src/ltx_kernels/blockwise/triton_ops.py",+ "packages/ltx-kernels/src/ltx_kernels/blockwise/ops/gemm.py",][tool.ruff.lint]@@ -98,7 +97,7 @@ ignore = [# Tests for the CuTe DSL kernels. ltx-kernels is an optional, CUDA-host-only install,# so importing it at module level would turn "skipped" into a collection error wherever# it is absent -- which is most of CI.-"packages/ltx-kernels/tests/test_vae_*.py" = ["PLC0415"]+"packages/ltx-kernels/tests/ltx_kernels/test_vae_*.py" = ["PLC0415"]"packages/ltx-core/tests/**/test_dsl_kernels.py" = ["PLC0415"]# NVFP4 tests ``importorskip("ltx_kernels")`` before importing convert/linear/fuse# (which import the extension at module top level).