Skip to content

feat(ltx2): add bucketed joint audio-video training, padding masks, and NNX LoRA - #525

Draft
entrpn wants to merge 6 commits into
mainfrom
jfacevedo/ltx2-bucketed-training
Draft

entrpn wants to merge 6 commits into
mainfrom
jfacevedo/ltx2-bucketed-training

Conversation

@entrpn

@entrpn entrpn commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

Summary

Adds end-to-end joint audio-video rectified-flow DiT training for LTX-2 and LTX-2.3 with 3D/1D spatial-temporal bucketing, padding masks, per-bucket JIT caching, cross-bucket token-weighted gradient accumulation, and NNX LoRA support:

  1. Masked Joint Attention (attention_flax.py, transformer_ltx2.py):
    • Threads optional video_attention_mask and audio_attention_mask across dot_product, flash (Splash segment_ids), ring, and ulysses attention kernels.
    • Derives cross-modal mask defaults and zero-KV NaN guards for video-only (has_audio=False) samples while preserving bitwise parity on the default unmasked (masks=None) inference path.
  2. 3D/1D Spatial-Temporal Bucketing & Mesh Collation (data_preprocessing/ltx2_bucketing.py):
    • Implements serve-identical asymmetric latent normalization (video normalized channel-first before 3D patchify; audio 1D-patchified first then normalized), post-connector learnable-register validation (text_padding_mode=post_connector), per-sample 3D/1D RoPE coordinates, and (data, fsdp, context) sharded synthetic and preencoded_npz batch iterators.
  3. Bucketed Trainer, Cross-Bucket GA, NNX LoRA & Checkpointer Fix (trainers/ltx2_trainer.py, train_ltx2.py, configs/ltx2_train.yml, checkpointing_utils.py, ltx2_checkpointer.py):
    • Implements [0, 1000] dynamic-shifted rectified-flow velocity loss (v = eps - x_0) with jnp.where pad masking, padding-invariant resolution shifting, and use_cross_timestep support for LTX-2.3.
    • Shares a single sharded LTX2TrainState across per-bucket @jax.jit VJP executables and executes unbiased token-weighted gradient accumulation across mixed-bucket windows with a single optimizer update.
    • Adds NNX LoRAParam filtering with frozen base weights, Orbax checkpoint save/resume (merged or unmerged), Diffusers diffusion_model.* .safetensors adapter export compatible with LTX2NNXLoraLoader, and registers LTX2_CHECKPOINT in create_orbax_checkpoint_manager.

Tests

  • src/maxdiffusion/tests/ltx2/test_transformer_ltx2_masking.py (self-attention & cross-modal mask invariance across dot_product, flash, and ulysses, plus has_audio=False zero-KV guards)
  • src/maxdiffusion/tests/ltx2/test_ltx2_bucketing.py (asymmetric normalization parity, post-connector register guards, heterogeneous landscape+portrait B=2 vs unpadded B=1 VJP invariance, and sharded NPZ/synthetic iterators)
  • src/maxdiffusion/tests/ltx2/test_ltx2_trainer.py (per-bucket JIT cache hit counts, cross-bucket token-weighted GA exact single-VJP equivalence, NNX LoRA zero-init/freeze/Diffusers round-trip, and Orbax save/restore)
  • src/maxdiffusion/tests/ltx2/test_ltx2_trainer_bucketing.py (upstream masks=None bitwise parity, 3-stream padding invariance, compiled HLO 1/8 sharding & involuntary-remat audit, and 18-step full-param & LoRA convergence)
  • Linters: pyink --check --pyink-indentation=2 --line-length=125, ruff check, and pylint (9.49/10) passed.

…nd NNX LoRA

Add end-to-end joint audio-video rectified-flow DiT training for LTX-2 and
LTX-2.3 with 3D/1D spatial-temporal bucketing, padding masks, per-bucket JIT
caching, cross-bucket token-weighted gradient accumulation, and NNX LoRA:

- Masked joint attention (attention_flax.py, transformer_ltx2.py): thread
  video_attention_mask and audio_attention_mask across dot_product, flash
  (Splash segment_ids), ring, and ulysses kernels with cross-modal mask
  defaults and zero-KV NaN guards for video-only (has_audio=False) samples,
  preserving bitwise parity on the default unmasked inference path.
- 3D/1D bucketing and sharded collation (ltx2_bucketing.py): implement
  serve-identical asymmetric video/audio latent normalization, post-connector
  learnable-register validation, per-sample 3D/1D RoPE coordinates, and
  (data, fsdp, context) sharded synthetic and pre-encoded NPZ iterators.
- Bucketed trainer and Orbax checkpointer fix (ltx2_trainer.py, train_ltx2.py,
  ltx2_train.yml, checkpointing_utils.py, ltx2_checkpointer.py): implement
  [0, 1000] dynamic-shifted rectified-flow velocity loss with jnp.where pad
  masking, single-TrainState per-bucket JIT cache, exact cross-bucket
  token-weighted gradient accumulation, NNX LoRAParam filtering with Diffusers
  safetensors export, and LTX2_CHECKPOINT Orbax handler registration.
- Verification suites (tests/ltx2/test_*.py): cover 4-device and 8-device
  padding invariance, upstream inference parity, video-only zero-grad isolation,
  compiled HLO sharding/remat audits, and multi-step full-param/LoRA convergence.
@github-actions

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces comprehensive support for LTX-2 and LTX-2.3 joint audio-video training. Key additions include a CLI training entrypoint, a specialized trainer (LTX2Trainer) supporting NNX LoRA and cross-bucket token-weighted gradient accumulation, a robust 3D/1D bucketing and preprocessing pipeline, and extensive masking and padding-invariant attention mechanisms to prevent NaN propagation. The review feedback highlights several important improvements: gathering sharded LoRA parameters across hosts using multihost_utils.process_allgather before saving on process 0, computing has_valid_key globally in attention_flax.py to protect all attention kernels from NaN propagation, correcting the decay steps calculation in the cosine learning rate schedule, and restricting metrics file initialization to the coordinator process to avoid multi-process write conflicts.

Comment on lines +1172 to +1180
lora_export_dir = str(getattr(cfg, "lora_safetensors_export_dir", ""))
if enable_lora and lora_export_dir and jax.process_index() == 0:
out_file = os.path.join(lora_export_dir, f"step_{step:06d}", "ltx2_lora_adapter.safetensors")
save_lora_safetensors(
out_file,
state.params,
lora_alpha=float(getattr(cfg, "lora_alpha", getattr(cfg, "lora_rank", 32))),
scan_layers=bool(getattr(cfg, "scan_layers", True)),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

critical

In multi-host JAX training, state.params is sharded across hosts. Calling jax.device_get or converting to a numpy array directly on process 0 will raise a ValueError because the data is not fully present on the local host. To prevent crashes during LoRA checkpoint export, the sharded parameters must be gathered across all processes using multihost_utils.process_allgather before saving on process 0.

Suggested change
lora_export_dir = str(getattr(cfg, "lora_safetensors_export_dir", ""))
if enable_lora and lora_export_dir and jax.process_index() == 0:
out_file = os.path.join(lora_export_dir, f"step_{step:06d}", "ltx2_lora_adapter.safetensors")
save_lora_safetensors(
out_file,
state.params,
lora_alpha=float(getattr(cfg, "lora_alpha", getattr(cfg, "lora_rank", 32))),
scan_layers=bool(getattr(cfg, "scan_layers", True)),
)
lora_export_dir = str(getattr(cfg, "lora_safetensors_export_dir", ""))
if enable_lora and lora_export_dir:
from jax.experimental import multihost_utils
replicated_params = multihost_utils.process_allgather(state.params)
if jax.process_index() == 0:
out_file = os.path.join(lora_export_dir, f"step_{step:06d}", "ltx2_lora_adapter.safetensors")
save_lora_safetensors(
out_file,
replicated_params,
lora_alpha=float(getattr(cfg, "lora_alpha", getattr(cfg, "lora_rank", 32))),
scan_layers=bool(getattr(cfg, "scan_layers", True)),
)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in the latest commit: save_training_checkpoint now runs multihost_utils.process_allgather(state.params, tiled=True) across all processes when jax.process_count() > 1 before writing .safetensors on process 0.

# Masks enter the dispatcher as canonical [B, K] keep masks. Adapt them
# only after fallback selection because a configured flash kernel may use
# dot-product attention for short sequences.
has_valid_key = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

Computing has_valid_key only in the else branch leaves dot_product attention vulnerable to NaNs when all keys are masked out (e.g., on video-only samples with zero audio tokens). Since attention_flax.py is a shared utility used by multiple models, computing has_valid_key at the start of the function protects all attention kernels (including dot_product) from NaN propagation.

Suggested change
has_valid_key = None
has_valid_key = jnp.any(attention_mask[:, :key.shape[2 if key.ndim == 4 else 1]], axis=-1) if (attention_mask is not None and attention_mask.ndim == 2) else None

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in the latest commit: has_valid_key is now computed ahead of if effective_attention_kernel == "dot_product": so dot_product also zeros out all-masked key rows consistently with flash, ring, and ulysses.

Comment on lines +56 to +63
if schedule_type == "cosine" and total_steps > warmup_steps and total_steps > 0:
learning_rate_scheduler = optax.warmup_cosine_decay_schedule(
init_value=0.0,
peak_value=learning_rate,
warmup_steps=warmup_steps,
decay_steps=max(total_steps, 1),
end_value=float(getattr(config, "lr_end_value", 0.0)),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

In optax.warmup_cosine_decay_schedule, the total schedule length is the sum of warmup_steps and decay_steps. Passing total_steps as decay_steps causes the learning rate decay phase to be longer than intended, meaning the learning rate will not reach end_value at total_steps. To align the total schedule length with total_steps, decay_steps should be set to total_steps - warmup_steps.

Suggested change
if schedule_type == "cosine" and total_steps > warmup_steps and total_steps > 0:
learning_rate_scheduler = optax.warmup_cosine_decay_schedule(
init_value=0.0,
peak_value=learning_rate,
warmup_steps=warmup_steps,
decay_steps=max(total_steps, 1),
end_value=float(getattr(config, "lr_end_value", 0.0)),
)
if schedule_type == "cosine" and total_steps > warmup_steps and total_steps > 0:
learning_rate_scheduler = optax.warmup_cosine_decay_schedule(
init_value=0.0,
peak_value=learning_rate,
warmup_steps=warmup_steps,
decay_steps=max(total_steps - warmup_steps, 1),
end_value=float(getattr(config, "lr_end_value", 0.0)),
)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Verified against Optax's warmup_cosine_decay_schedule implementation: decay_steps is defined as the total schedule length including warmup_steps (Optax internally passes decay_steps=decay_steps - warmup_steps to cosine_decay_schedule). Subtracting warmup_steps again here would double-subtract it and reach end_value early at total_steps - warmup_steps. Added an inline comment clarifying this.

Comment on lines +1207 to +1208
local_metrics_file = open(cfg.metrics_file, "a", encoding="utf8") if getattr(cfg, "metrics_file", "") else None
running_gcs_metrics = [] if getattr(cfg, "gcs_metrics", False) else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

In multi-process/multi-host training, opening the metrics file and initializing GCS metrics on all processes can lead to write conflicts, file corruption, or duplicate entries. These operations should be restricted to the coordinator process (jax.process_index() == 0).

Suggested change
local_metrics_file = open(cfg.metrics_file, "a", encoding="utf8") if getattr(cfg, "metrics_file", "") else None
running_gcs_metrics = [] if getattr(cfg, "gcs_metrics", False) else None
local_metrics_file = open(cfg.metrics_file, "a", encoding="utf8") if (jax.process_index() == 0 and getattr(cfg, "metrics_file", "")) else None
running_gcs_metrics = [] if (jax.process_index() == 0 and getattr(cfg, "gcs_metrics", False)) else None

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in the latest commit: gated local_metrics_file, running_gcs_metrics, and the train_utils.write_metrics(...) call on jax.process_index() == 0 (since write_metrics_locally unconditionally calls file.truncate(0) / file.write(...) when config.metrics_file is non-empty).

…in unit tests

- Enforce jax.default_matmul_precision("float32") and precision=HIGHEST in
  float32 numerical-equivalence unit tests so TPU MXU runs 3-pass IEEE fp32
  instead of 1-pass bfloat16 input rounding on v4-8 CI.
- Propagate self.base.precision into LTX2LoRALinear.__call__ matmuls.
- Allgather sharded LoRA parameters across hosts via
  multihost_utils.process_allgather before process-0 safetensors export.
- Compute has_valid_key ahead of kernel dispatch in attention_flax.py so
  dot_product also zeros out rows whose keys are 100% masked out.
- Restrict local_metrics_file, running_gcs_metrics, and write_metrics I/O to
  jax.process_index() == 0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants