Skip to content
7 changes: 7 additions & 0 deletions src/maxdiffusion/checkpointing/checkpointing_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
FLUX_CHECKPOINT = "FLUX_CHECKPOINT"
WAN_CHECKPOINT = "WAN_CHECKPOINT"
Z_IMAGE_CHECKPOINT = "Z_IMAGE_CHECKPOINT"
LTX2_CHECKPOINT = "LTX2_CHECKPOINT"


def create_orbax_checkpoint_manager(
Expand Down Expand Up @@ -88,6 +89,12 @@ def create_orbax_checkpoint_manager(
"low_noise_transformer_state": ocp.StandardCheckpointHandler(),
"high_noise_transformer_state": ocp.StandardCheckpointHandler(),
}
elif checkpoint_type == LTX2_CHECKPOINT:
item_names = ("ltx2_config", "ltx2_state")
item_handlers = {
"ltx2_config": ocp.JsonCheckpointHandler(),
"ltx2_state": ocp.PyTreeCheckpointHandler(),
}
else:
item_names = (
"unet_config",
Expand Down
64 changes: 52 additions & 12 deletions src/maxdiffusion/checkpointing/ltx2_checkpointer.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,14 @@
import json
import jax
import numpy as np
import optax
from typing import Optional, Tuple
from maxdiffusion.pipelines.ltx2.ltx2_pipeline import LTX2Pipeline
from maxdiffusion import max_logging
from maxdiffusion.checkpointing.checkpointing_utils import create_orbax_checkpoint_manager
from maxdiffusion import max_logging, max_utils
from maxdiffusion.checkpointing.checkpointing_utils import LTX2_CHECKPOINT, create_orbax_checkpoint_manager
import orbax.checkpoint as ocp
from etils import epath

LTX2_CHECKPOINT = "LTX2_CHECKPOINT"


class LTX2Checkpointer:

Expand All @@ -34,14 +33,46 @@ def __init__(self, config, checkpoint_type: str = LTX2_CHECKPOINT):
self.checkpoint_type = checkpoint_type
self.opt_state = None

self.checkpoint_manager: ocp.CheckpointManager = create_orbax_checkpoint_manager(
getattr(self.config, "checkpoint_dir", ""),
enable_checkpointing=True,
checkpoint_dir = getattr(self.config, "checkpoint_dir", "") or ""
raw_use_async = getattr(self.config, "enable_async_checkpointing", True)
use_async = raw_use_async if isinstance(raw_use_async, bool) else True

self.checkpoint_manager: Optional[ocp.CheckpointManager] = create_orbax_checkpoint_manager(
checkpoint_dir,
enable_checkpointing=bool(checkpoint_dir),
save_interval_steps=1,
checkpoint_type=checkpoint_type,
dataset_type=getattr(config, "dataset_type", None),
use_async=use_async,
)

def _create_optimizer(self, config, learning_rate: float):
schedule_type = getattr(config, "lr_schedule_type", "constant")
total_steps = int(getattr(config, "learning_rate_schedule_steps", -1))
if total_steps <= 0:
total_steps = int(config.max_train_steps)
warmup_steps = int(total_steps * float(getattr(config, "warmup_steps_fraction", 0.0)))

if schedule_type == "cosine" and total_steps > warmup_steps and total_steps > 0:
# In optax.warmup_cosine_decay_schedule, decay_steps is the total schedule length
# including warmup_steps (Optax internally passes decay_steps - warmup_steps).
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)),
)
Comment on lines +56 to +65

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.

else:
learning_rate_scheduler = max_utils.create_learning_rate_schedule(
learning_rate,
total_steps,
float(getattr(config, "warmup_steps_fraction", 0.0)),
int(config.max_train_steps),
)
tx = max_utils.create_optimizer(config, learning_rate_scheduler)
return tx, learning_rate_scheduler

def load_ltx2_configs_from_orbax(self, step: Optional[int]) -> Tuple[Optional[dict], Optional[int]]:
if self.checkpoint_manager is None:
max_logging.log("No checkpoint manager configured, skipping Orbax load.")
Expand Down Expand Up @@ -95,19 +126,28 @@ def load_checkpoint(

return pipeline, opt_state, step

def save_checkpoint(self, train_step, pipeline: LTX2Pipeline, train_states: dict):
def save_checkpoint(
self,
train_step,
pipeline: LTX2Pipeline,
train_states: dict,
transformer_config_dict: Optional[dict] = None,
):
"""Saves the training state and model configurations."""
if self.checkpoint_manager is None:
max_logging.log("No checkpoint manager configured, skipping checkpoint save.")
return

def config_to_json(model_or_config):
return json.loads(model_or_config.to_json_string())

max_logging.log(f"Saving checkpoint for step {train_step}")
cfg_payload = transformer_config_dict if transformer_config_dict is not None else config_to_json(pipeline.transformer)
items = {
"ltx2_config": ocp.args.JsonSave(config_to_json(pipeline.transformer)),
"ltx2_config": ocp.args.JsonSave(cfg_payload),
"ltx2_state": ocp.args.PyTreeSave(train_states),
}

items["ltx2_state"] = ocp.args.PyTreeSave(train_states)

# Save the checkpoint
self.checkpoint_manager.save(train_step, args=ocp.args.Composite(**items))
self.checkpoint_manager.save(int(train_step), args=ocp.args.Composite(**items))
max_logging.log(f"Checkpoint for step {train_step} saved.")
227 changes: 227 additions & 0 deletions src/maxdiffusion/configs/ltx2_train.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Run & output directories
run_name: 'ltx2_bucketed_train'
output_dir: '/tmp/ltx2_train_outputs'
base_output_directory: ''
config_path: ''
save_config_to_gcs: False

metrics_file: ''
write_metrics: True
timing_metrics_file: ''
write_timing_metrics: False
gcs_metrics: False
log_period: 10

# Hardware & distributed setup
hardware: 'tpu'
skip_jax_distributed_system: False
jax_cache_dir: ''
aot_cache_dir: ''
aot_build_revision: ''
converted_weights_dir: ''

# Model & dtype settings
pretrained_model_name_or_path: 'Lightricks/LTX-2'
model_name: 'ltx2_video'
model_type: 'T2V'
unet_checkpoint: ''
weights_dtype: 'bfloat16'
activations_dtype: 'bfloat16'
text_encoder_dtype: 'bfloat16'
precision: 'DEFAULT'
jit_initializers: True

# Offline / miniature config-only initialization (set True in CI / unit tests)
init_transformer_from_config_only: False
load_encoders_for_training: False
transformer_in_channels: 128
transformer_audio_in_channels: 128
transformer_patch_size: 1
transformer_patch_size_t: 1
transformer_num_attention_heads: 32
transformer_attention_head_dim: 128
transformer_audio_num_attention_heads: 32
transformer_audio_attention_head_dim: 64
transformer_num_layers: 48
transformer_caption_channels: 3840
transformer_cross_attn_mod: False
transformer_gated_attn: False

# Attention & rematerialization
attention: 'flash'
a2v_attention_kernel: 'dot_product'
v2a_attention_kernel: 'dot_product'
attention_sharding_uniform: True
ulysses_shards: -1
ulysses_attention_chunks: 1
use_base2_exp: False
use_experimental_scheduler: False
use_svg_attention: False
svg_spatial_density: 1.0
svg_flash_block_sizes: {}

flash_block_sizes: {
block_q: 512,
block_kv: 512,
block_kv_compute: 512,
block_q_dkv: 512,
block_kv_dkv: 512,
block_kv_dkv_compute: 512,
block_q_dq: 512,
block_kv_dq: 512,
use_fused_bwd_kernel: False,
}
flash_min_seq_length: 1024

scan_layers: True
scan_diffusion_loop: False
remat_policy: 'FULL'
names_which_can_be_saved: []
names_which_can_be_offloaded: []
enable_jax_named_scopes: False

# Parallelism & FSDP-major sharding (avoids parameter transpose remat on hybrid FSDP+CP meshes)
mesh_axes: ['data', 'fsdp', 'context', 'tensor']
logical_axis_rules: [
['batch', ['data', 'fsdp']],
['activation_batch', ['data', 'fsdp']],
['activation_self_attn_heads', ['context', 'tensor']],
['activation_cross_attn_q_length', ['context', 'tensor']],
['activation_length', 'context'],
['activation_kv_length', 'context'],
['activation_embed', null],
['activation_heads', 'tensor'],
['activation_kv', null],
['mlp', 'tensor'],
['embed', ['fsdp', 'context']],
['heads', 'tensor'],
['norm', 'tensor'],
['layers', null],
['conv_batch', ['data', 'fsdp', 'context']],
['out_channels', 'tensor'],
['conv_out', 'context'],
]
data_sharding: ['data', 'fsdp', 'context', 'tensor']

sharding:
transformer: 'default'
vae: 'default'
text_connector: 'default'

dcn_data_parallelism: 1
dcn_fsdp_parallelism: -1
dcn_context_parallelism: 1
dcn_tensor_parallelism: 1
ici_data_parallelism: 1
ici_fsdp_parallelism: -1
ici_context_parallelism: 1
ici_tensor_parallelism: 1
allow_split_physical_axes: False
compile_topology_num_slices: -1

# Quantization (disabled by default for training)
use_qwix_quantization: False
quantization: 'int8'
quantization_local_shard_count: -1
weight_quantization_calibration_method: 'absmax'
act_quantization_calibration_method: 'absmax'
bwd_quantization_calibration_method: 'absmax'
qwix_module_path: '.*'

# Dataset & 3D/1D Bucketing
dataset_name: ''
dataset_save_location: ''
train_data_dir: ''
train_split: 'train'
dataset_type: 'synthetic' # 'synthetic' | 'preencoded_npz'
cache_latents_text_encoder_outputs: True
train_text_encoder: False
per_device_batch_size: 1.0
global_batch_size: 0
max_sequence_length: 1024

ltx2_buckets: [
[1024, 256, 1024],
[2048, 512, 1024],
[4096, 1024, 1024],
]
text_padding_mode: 'post_connector'
connector_num_learnable_registers: 128
bucket_overflow_policy: 'error'
synthetic_video_only_prob: 0.0
synthetic_num_unique_batches_per_bucket: 0

# Rectified-Flow Objective & Cross-Bucket Gradient Accumulation
seed: 42
max_train_steps: 100
num_train_epochs: 1
gradient_accumulation_steps: 1
audio_loss_weight: 1.0
timestep_sampling: 'logit_normal' # 'logit_normal' | 'uniform'
logit_normal_mean: 0.0
logit_normal_std: 1.0
use_dynamic_shifting: True
disable_training_weights: True
use_cross_timestep: False # Set True for LTX-2.3

# Optimizer & LR Schedule
learning_rate: 1.0e-4
learning_rate_schedule_steps: -1
lr_schedule_type: 'cosine' # 'cosine' | 'constant'
lr_end_value: 0.0
warmup_steps_fraction: 0.05
adam_b1: 0.9
adam_b2: 0.999
adam_eps: 1.0e-8
adam_weight_decay: 0.01
opt_enable_grad_clipping: False
max_grad_value: 1.0
opt_enable_grad_global_norm_clipping: True
max_grad_norm: 1.0

# NNX LoRA Training Option
enable_lora_training: False
lora_rank: 32
lora_alpha: 32.0
lora_target_modules: [
'attn1.to_q', 'attn1.to_k', 'attn1.to_v', 'attn1.to_out',
'audio_attn1.to_q', 'audio_attn1.to_k', 'audio_attn1.to_v', 'audio_attn1.to_out',
'attn2.to_q', 'attn2.to_k', 'attn2.to_v', 'attn2.to_out',
'audio_attn2.to_q', 'audio_attn2.to_k', 'audio_attn2.to_v', 'audio_attn2.to_out',
'audio_to_video_attn.to_q', 'audio_to_video_attn.to_k', 'audio_to_video_attn.to_v', 'audio_to_video_attn.to_out',
'video_to_audio_attn.to_q', 'video_to_audio_attn.to_k', 'video_to_audio_attn.to_v', 'video_to_audio_attn.to_out',
'ff.net_0', 'ff.net_2',
'audio_ff.net_0', 'audio_ff.net_2',
]
merge_lora_on_save: False
lora_safetensors_export_dir: ''

# Checkpointing & Profiling
checkpoint_dir: ''
checkpoint_every: -1
save_optimizer: True
save_final_checkpoint: False
enable_async_checkpointing: False
enable_single_replica_ckpt_restoring: False
eval_every: -1

enable_profiler: False
skip_first_n_steps_for_profiler: 5
profiler_steps: 5
enable_ml_diagnostics: False
profiler_gcs_path: ''
enable_ondemand_xprof: False
Loading
Loading