Repository navigation
Conversation
…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.
There was a problem hiding this comment.
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.
| 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)), | ||
| ) |
There was a problem hiding this comment.
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.
| 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)), | |
| ) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
| 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)), | ||
| ) |
There was a problem hiding this comment.
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.
| 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)), | |
| ) |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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).
| 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 |
There was a problem hiding this comment.
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.
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:
attention_flax.py,transformer_ltx2.py):video_attention_maskandaudio_attention_maskacrossdot_product,flash(Splashsegment_ids),ring, andulyssesattention kernels.has_audio=False) samples while preserving bitwise parity on the default unmasked (masks=None) inference path.data_preprocessing/ltx2_bucketing.py):text_padding_mode=post_connector), per-sample 3D/1D RoPE coordinates, and(data, fsdp, context)shardedsyntheticandpreencoded_npzbatch iterators.trainers/ltx2_trainer.py,train_ltx2.py,configs/ltx2_train.yml,checkpointing_utils.py,ltx2_checkpointer.py):[0, 1000]dynamic-shifted rectified-flow velocity loss (v = eps - x_0) withjnp.wherepad masking, padding-invariant resolution shifting, anduse_cross_timestepsupport for LTX-2.3.LTX2TrainStateacross per-bucket@jax.jitVJP executables and executes unbiased token-weighted gradient accumulation across mixed-bucket windows with a single optimizer update.LoRAParamfiltering with frozen base weights, Orbax checkpoint save/resume (merged or unmerged), Diffusersdiffusion_model.*.safetensorsadapter export compatible withLTX2NNXLoraLoader, and registersLTX2_CHECKPOINTincreate_orbax_checkpoint_manager.Tests
src/maxdiffusion/tests/ltx2/test_transformer_ltx2_masking.py(self-attention & cross-modal mask invariance acrossdot_product,flash, andulysses, plushas_audio=Falsezero-KV guards)src/maxdiffusion/tests/ltx2/test_ltx2_bucketing.py(asymmetric normalization parity, post-connector register guards, heterogeneous landscape+portraitB=2vs unpaddedB=1VJP 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(upstreammasks=Nonebitwise parity, 3-stream padding invariance, compiled HLO1/8sharding & involuntary-remat audit, and 18-step full-param & LoRA convergence)pyink --check --pyink-indentation=2 --line-length=125,ruff check, andpylint(9.49/10) passed.