Skip to content

Perf(LTX2): Comprehensive XLA, Memory, and Transformer Code Quality Optimizations - #422

Open
Perseus14 wants to merge 30 commits into
mainfrom
ltx2-improvements
Open

Perf(LTX2): Comprehensive XLA, Memory, and Transformer Code Quality Optimizations#422
Perseus14 wants to merge 30 commits into
mainfrom
ltx2-improvements

Conversation

@Perseus14

@Perseus14 Perseus14 commented Jun 19, 2026

Copy link
Copy Markdown
Collaborator

LTX2 Improvements, Optimizations & Bug Fixes

This PR introduces a massive overhaul to the LTX2 and LTX2.3 implementations in MaxDiffusion. The primary focus spans architectural cleanliness, persistent memory caching, AOT loop optimizations, layout sharding stability, distributed attention compatibility, and dramatic improvements to end-to-end latency (both compilation and post-processing).

🌟 Architectural & JAX Optimizations

  • Dataclass Contexts: Replaced dictionary-based contexts with flax.struct.dataclass (LTX2BlockContext), significantly improving code readability and type safety across attention mechanisms.
  • Dynamic Float Scales: Shifted floating-point parameters (guidance_scale, stg_scale) out of static_argnames and introduced boolean triggers (do_cfg, do_stg). This drastically minimizes recompilation overhead and tracing stalls.
  • Guidance Path Deduplication: Refactored _apply_ltx2_guidance to heavily deduplicate and unify the computational paths for standard CFG, STG, and audio guidance logic, resulting in a significantly cleaner XLA graph.

⚡ Caching, Loading, and Compilation (Ports of PRs #438 & #443)

  • Cross-Attention KV Cache Introduced: Fully implemented and wired the Cross-Attention KV Cache system for LTX2. By caching the text and audio embedding projections, we eliminate redundant cross-attention compute during every step of the diffusion loop. Added strict checks to reject incompatible caches and properly wired named scopes.
  • Persistent Converted-Weight Caching: Introduced a robust, WAN-style atomic persistent memoization system (try_load_converted_weights) for LTX2. This safely caches converted weights to disk, drastically accelerating model loading on subsequent runs by bypassing redundant conversions.
  • Fast Safetensor Weight Loading: Eliminated memory-heavy torch.load and sequential torch2jax routines in favor of mapping .safetensors concurrently with a ThreadPoolExecutor. Memory ingestion is aggressively parallelized using zero-copy reinterpretation (tensor.view(torch.uint16).numpy().view(ml_dtypes.bfloat16)).
  • AOT Diffusion Caching & Warmup: Swapped @jax.jit for @aot_cache.cached_jit on the main diffusion loop. Integrated 2-step fast-warmup logic (with aot_cache.warmup_mode()) which ensures the full step count is traced when scan_diffusion_loop=True, bypassing prolonged compilations on application startup.
  • ICI-Staged Device Put: Large tensors (>=64MB) are now pushed directly to device 0 and replicated over ICI (when jax.process_count() == 1), rather than enduring slow host-to-device PCIe copies for all devices.

🚀 Post-Processing Latency

  • Zero-Copy NumPy Export: Introduced the np_uint8 pipeline output type and updated the YAML configs to default to it. This entirely bypasses the massive CPU bottleneck of sequentially instantiating PIL.Image objects across 121 frames.
  • Native TPU Vectorized Normalization: Completely bypassed the standard PyTorch/NumPy CPU-based video processor. By executing the tensor normalization (clipping, scaling, and casting to uint8 or float32) as vectorized JAX operations natively on the TPU prior to host transfer, we eliminate massive host-side memory thrashing and CPU iteration overhead.

🌀 Distributed Attention

  • Ulysses & Ring Attention Support: Fully wired ring_attention and ulysses_attention parameters down through all LTX2VideoTransformerBlock instantiations (affecting both nnx.scan and un-scanned eager block initializations).
  • Cross-Attention Axis Fallbacks: Implemented dynamic axis-mapping for NNXAttentionOp in LTX2 cross-attention mechanisms, ensuring layout rules bind properly when Ulysses sharding configurations are enabled.
  • Tile-Size Auto-Tuning: Integrated LTX2/LTX2.3 enhancements specifically targeting tile-size auto-tuning for spatial operations.

📊 Results

DiT Execution Time:

  • v6e-8: 11.2s9.6s
  • 7x-8: 7.8s5.6s

Video Post-Processing Time:

  • v6e-8: 0.200s0.040s
  • 7x-8: 0.500s0.052s

@Perseus14
Perseus14 requested a review from entrpn as a code owner June 19, 2026 21:51
@github-actions

Copy link
Copy Markdown

@Perseus14 Perseus14 self-assigned this Jun 19, 2026
@Perseus14
Perseus14 requested a review from prishajain1 June 19, 2026 21:51
@Perseus14 Perseus14 changed the title LTX2.3 improvements and bug fixes Perf(LTX2): Comprehensive XLA, Memory, and Transformer Code Quality Optimizations Jun 19, 2026
@Perseus14
Perseus14 force-pushed the ltx2-improvements branch 4 times, most recently from 3a13196 to 36e0f5d Compare June 20, 2026 09:59
@github-actions

Copy link
Copy Markdown

🤖 Hi @Perseus14, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@github-actions

Copy link
Copy Markdown

🤖 I'm sorry @Perseus14, but I was unable to process your request. Please see the logs for more details.

@github-actions

Copy link
Copy Markdown

🤖 Hi @Perseus14, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@github-actions

Copy link
Copy Markdown

🤖 I'm sorry @Perseus14, but I was unable to process your request. Please see the logs for more details.

@github-actions

Copy link
Copy Markdown

🤖 Hi @Perseus14, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@github-actions

Copy link
Copy Markdown

🤖 I'm sorry @Perseus14, but I was unable to process your request. Please see the logs for more details.

@github-actions

Copy link
Copy Markdown

🤖 Hi @Perseus14, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@github-actions

Copy link
Copy Markdown

🤖 I'm sorry @Perseus14, but I was unable to process your request. Please see the logs for more details.

@github-actions

Copy link
Copy Markdown

🤖 Hi @Perseus14, I've received your request, and I'm working on it now! You can track my progress in the logs for more details.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

## 📋 Review Summary

This pull request introduces a highly comprehensive set of optimizations and refactorings for the LTX2 model family, delivering significant enhancements to memory usage, model modularity, and JAX compilation behavior. By transforming static continuous hyperparameters into dynamic inputs, the sweep successfully eliminates expensive compilation timeouts while resolving underlying layout mismatches and unneeded computational overhead. The architectural quality of the codebase is substantially improved, particularly in the block consolidation and cleaner RoPE logic.

🔍 General Feedback

  • Exceptional Block Refactoring: The transition of LTX2VideoTransformer3DModel block application to a single unified apply_block helper and an immutable LTX2BlockContext is a masterclass in reducing hazard-prone code duplication.
  • RoPE & Coordinates Cleanup: Removing the duplicated and dead coordinate generation block in prepare_video_coords and simplifying split-RoPE dimension manipulation are excellent and highly effective hygiene improvements.
  • Robustness in Fallbacks & Dtypes: Incorporating proper warning logs for the noise generator fallback and upfront dtype casting for prompt embeddings ensures both runtime reliability and optimal HBM performance.

Comment thread src/maxdiffusion/pipelines/ltx2/ltx2_pipeline.py
Comment thread src/maxdiffusion/generate_ltx2.py
Comment thread src/maxdiffusion/models/ltx2/text_encoders/torchax_text_encoder.py Outdated
Comment thread src/maxdiffusion/pipelines/ltx2/ltx2_pipeline.py Outdated
Comment thread src/maxdiffusion/models/ltx2/text_encoders/torchax_text_encoder.py Outdated
Comment thread src/maxdiffusion/models/ltx2/text_encoders/torchax_text_encoder.py Outdated
Comment thread src/maxdiffusion/pipelines/ltx2/ltx2_pipeline.py Outdated
Comment thread src/maxdiffusion/models/ltx2/text_encoders/torchax_text_encoder.py Outdated
@github-actions

Copy link
Copy Markdown

🤖 I'm sorry @Perseus14, but I was unable to process your request. Please see the logs for more details.

Perseus14 added 21 commits July 29, 2026 09:24
jax.lax.scan bakes iteration count into array shapes, so a 2-step
warmup compiles a different XLA program than the N-step real run,
causing a wasteful double compilation. Only reduce warmup steps when
scan_diffusion_loop=False (Python loop), where per-step JIT compilation
is independent of total iteration count.
@Perseus14
Perseus14 force-pushed the ltx2-improvements branch from 48884c1 to fedbc0d Compare July 29, 2026 09:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants