Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: LTX-2 video LoRA training from still images (#8196)

Daniel Hanf02e49fc27da
diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.py
index 42ffc54a2e3..8aa02ee7a97 100644
--- a/studio/backend/core/inference/diffusion_transformer_quant.py
+++ b/studio/backend/core/inference/diffusion_transformer_quant.py
@@ -91,11 +91,27 @@ _HUNYUAN15_INT8_EXCLUDES = (
"to_add_out",
"ff_context",
)
+# LTX-2 is audiovisual: every block carries an audio-side stream (audio_attn1 / audio_attn2 /
+# audio_ff, fed by audio_proj_in) plus the a2v / v2a cross attentions. A video-only run feeds a
+# MINIMAL audio stream -- one token for a still -- so those linears run at M = 1, under the same
+# _int_mm floor of 16 as the cases above. The audio stream is deliberately inert on a video-only
+# run (isolated modalities, out of the loss, out of the LoRA targets), so leaving it in bf16 costs
+# nothing while the video-stream linears keep full int8 coverage. One token covers every audio-side
+# name, including video_to_audio_attn, whose keys/values are that same one-token stream.
+#
+# The audio token alone is not enough. LTX-2 also carries LTX2AdaLayerNormSingle projections whose
+# names say nothing about audio -- av_cross_attn_video_scale_shift / av_cross_attn_video_a2v_gate
+# (the cross-modality modulation, computed unconditionally in forward, isolate_modalities or not)
+# and prompt_adaln / audio_prompt_adaln. Each is a Linear over a BATCH-sized input, so M = batch =
+# 1 for a default training run: the same _int_mm floor, reached whatever the audio stream does.
+_LTX2_INT8_EXCLUDES = ("audio", "av_cross_attn", "adaln")
_INT8_FAMILY_EXCLUDE_NAME_TOKENS: dict[str, tuple[str, ...]] = {
"qwen-image": _QWENIMAGE_INT8_EXCLUDES,
"qwen-image-edit": _QWENIMAGE_INT8_EXCLUDES, # same DiT class + unpadded text stream
"hunyuanvideo-1.5": _HUNYUAN15_INT8_EXCLUDES,
"hunyuanvideo-1.5-720p": _HUNYUAN15_INT8_EXCLUDES,
+ "ltx-2": _LTX2_INT8_EXCLUDES,
+ "ltx-2.3": _LTX2_INT8_EXCLUDES, # same audiovisual DiT
}
diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.py
index b85937bfc6e..6a4ba26cea3 100644
--- a/studio/backend/core/training/diffusion_dit_trainer.py
+++ b/studio/backend/core/training/diffusion_dit_trainer.py
@@ -1,7 +1,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Flow-matching LoRA training for the DiT image families (FLUX.1-dev, Qwen-Image, Z-Image).
+"""Flow-matching LoRA training for the rectified-flow DiT families.
+
+Image: FLUX.1-dev, FLUX.2 (dev + Klein), Qwen-Image, Z-Image, Krea 2. Video: LTX-2 (from a
+still-image dataset; see the ``_LTX2_TARGETS`` block for what a video family adds).
These are rectified-flow transformers, not the SDXL U-Net, so they share only the plumbing
in ``diffusion_train_common`` (config, dataset discovery, events, stop, publishing). The
@@ -38,6 +41,7 @@ from typing import Any, Callable, Optional
from core._torchao_stub import is_stubbed
from core.training.diffusion_train_common import (
+ AUTO_FLOW_SHIFT_FAMILIES,
DEFAULT_LORA_FILENAME,
DEFAULT_LORA_TARGETS,
DiffusionLoraConfig,
@@ -325,19 +329,26 @@ def _load_dit_transformer(transformer_cls, cfg, device, base_precision):
).to(device)
-def _int8_quantize_base(transformer) -> None:
+def _int8_quantize_base(transformer, family: Optional[str] = None) -> None:
"""torchao weight-only int8 on the big frozen linears, applied after add_adapter so
the base_layer inside each LoRA wrapper quantizes while the adapters stay high
precision. ``make_filter_fn`` (shared with the inference quant layer) keeps only
Linears with >= 512 features -- which also naturally skips the rank-sized LoRA
- matrices -- and drops the M=1 modulation projections int8 kernels reject."""
+ matrices -- and drops the M=1 modulation projections int8 kernels reject.
+
+ ``family`` selects the per-family small-M exclusions on top of those. Passing it is what
+ keeps training and inference on the same list: without it LTX-2's one-token audio stream
+ (and Qwen-Image's unpadded text stream) is quantized here and the first forward raises,
+ after the whole base has been loaded."""
from core.inference.diffusion_transformer_quant import exclude_tokens_for_scheme, make_filter_fn
from torchao.quantization import Int8WeightOnlyConfig, quantize_
quantize_(
transformer,
Int8WeightOnlyConfig(),
- filter_fn = make_filter_fn(512, exclude_name_tokens = exclude_tokens_for_scheme("int8")),
+ filter_fn = make_filter_fn(
+ 512, exclude_name_tokens = exclude_tokens_for_scheme("int8", family)
+ ),
)
@@ -1105,6 +1116,241 @@ def _flux2_klein_save(pipe_cls, out_dir, transformer_lora_layers):
)
+# ── LTX-2 (video) ─────────────────────────────────────────────────────────────
+# The first VIDEO family. Milestone one trains from STILL IMAGES: a 1-frame clip is a valid
+# LTX-2 input (its VAE compresses time by 8, so (1 - 1) // 8 + 1 = 1 latent frame), and the
+# community consensus is that style / character LoRAs converge on 20-50 stills while only
+# motion LoRAs need coherent clips. So this spec reuses the shared image dataset layer
+# verbatim and never decodes a video; clip datasets are a follow-up.
+#
+# Two things make LTX-2 unlike the image DiTs:
+#
+# 1. It is AUDIOVISUAL. Every block carries a second, audio-side stream (audio_attn1 /
+# audio_attn2 / audio_ff) plus two cross-modality attentions (audio_to_video_attn,
+# video_to_audio_attn), and ``forward`` takes ``audio_hidden_states`` /
+# ``audio_encoder_hidden_states`` as REQUIRED arguments. Lightricks' own trainer handles a
+# video-only run by passing ``audio=None``, which their transformer short-circuits so the
+# audio and cross-modality branches never execute. diffusers has no such escape hatch, so
+# the equivalent here is: feed a minimal audio token stream, pass
+# ``isolate_modalities=True`` (which turns off the a2v/v2a cross attention for every
+# block, so the audio stream cannot influence the video prediction), keep audio out of the
+# loss, and keep the audio-side modules out of the LoRA targets. The audio stream is one
+# token for a still, so the wasted compute is negligible. This is a deliberate divergence
+# from upstream and is the reason ``_LTX2_TARGETS`` names its modules in full.
+#
+# 2. Conditioning is a TWO-STAGE stack: a Gemma3-12B encoder whose hidden states are
+# [batch, 1024, 3840 * num_layers] (~370 MB per caption in bf16), followed by a small
+# ``connectors`` module that reduces them to the [batch, 1024, 3840] the transformer
+# actually consumes. Caching the raw encoder output would be ~50x larger than caching the
+# connector output for no benefit, so ``encode_prompts`` runs BOTH stages and caches only
+# the connector result, then the loop frees the encoder and the connectors together.
+#
+# Targets: the video-stream attention projections ONLY. Fully qualified on purpose -- a bare
+# "to_q" would also match audio_attn1/audio_attn2/audio_to_video_attn/video_to_audio_attn.
+# This is exactly the split Lightricks document for a video-only run and ship in their
+# video_inpainting / video_outpainting LoRA configs.
+_LTX2_TARGETS = (
+ "attn1.to_q",
+ "attn1.to_k",
+ "attn1.to_v",
+ "attn1.to_out.0",
+ "attn2.to_q",
+ "attn2.to_k",
+ "attn2.to_v",
+ "attn2.to_out.0",
+)
+
+# Frame rate the still is placed at on the temporal RoPE axis. LTX-2's rotary temporal
+# coordinate is measured in SECONDS (pixel-frame index / fps), so a 1-frame clip at the
+# family's native 24 fps lands exactly where the first latent frame of a generated 24 fps
+# clip lands -- the position every rendered video contains. Lightricks' preprocessor instead
+# pins images to fps = 1.0, which places them at a temporal coordinate no 24 fps clip ever
+# visits; we take the inference-matching choice and note the divergence.
+_LTX2_TRAIN_FPS = 24.0
+
+
+def _ltx2_load_conditioners(cfg, device, weight_dtype):
+ from diffusers import LTX2Pipeline
+
+ pipe, vae = _load_pipe_without_transformer(LTX2Pipeline, cfg, device)
+ # The connectors are the second half of the conditioning stack and are NOT a text_encoder
+ # attribute, so ``_encoders_to_device`` never reaches them; place them explicitly.
+ if getattr(pipe, "connectors", None) is not None:
+ pipe.connectors.to(device)
+ return pipe, vae
+
+
+def _ltx2_load_transformer(cfg, device, weight_dtype, base_precision):
+ from diffusers import LTX2VideoTransformer3DModel
+ return _load_dit_transformer(LTX2VideoTransformer3DModel, cfg, device, base_precision)
+
+
+def _ltx2_encode_prompts(pipe, captions, device):
+ import torch
+
+ _encoders_to_device(pipe, device)
+ # The Gemma3 hidden states are per-LAYER stacked ([1, 1024, 3840 * layers]); only the
+ # connector output reaches the transformer, so that is what gets cached.
+ out = []
+ with torch.no_grad():
+ for cap in captions:
+ pe, mask, _neg, _neg_mask = pipe.encode_prompt(
+ prompt = cap,
+ do_classifier_free_guidance = False,
+ num_videos_per_prompt = 1,
+ max_sequence_length = 1024,
+ device = device,
+ )
+ # Read AFTER encode_prompt, exactly where the pipeline reads it. encode_prompt
+ # sets ``tokenizer.padding_side = "left"`` itself (Gemma wants left padding for
+ # chat-style prompts), so a tokenizer that loaded reporting "right" would have had
+ # that stale value baked in here -- and the connectors build the valid-token mask
+ # from this, so every caption shorter than the 1024 pad length would be masked on
+ # the wrong end and the cached conditioning would not match what inference builds.
+ padding_side = getattr(getattr(pipe, "tokenizer", None), "padding_side", "left")
+ video_emb, audio_emb, conn_mask = pipe.connectors(pe, mask, padding_side = padding_side)
+ out.append((video_emb.cpu(), audio_emb.cpu(), conn_mask.cpu()))
+ return out
+
+
+def _ltx2_latent_affine(vae, ref):
+ import torch
+
+ mean = vae.latents_mean.to(device = ref.device, dtype = ref.dtype).view(1, -1, 1, 1, 1)
+ std = vae.latents_std.to(device = ref.device, dtype = ref.dtype).view(1, -1, 1, 1, 1)
+ # scaling_factor is 1.0 on the shipped checkpoint but is applied for fidelity to _normalize_latents.
+ return mean, std / float(vae.config.scaling_factor or 1.0)
+
+
+def _ltx2_encode_latents(vae, pixel_values):
+ import torch
+
+ # A still is a 1-frame clip: [B,3,H,W] -> [B,3,1,H,W]. The VAE compresses 32x spatially
+ # and 8x temporally, so a 512px still becomes [B,128,1,16,16].
+ px = pixel_values.to(torch.float32).unsqueeze(2)
+ with torch.no_grad():
+ lat = vae.encode(px).latent_dist.sample()
+ mean, std = _ltx2_latent_affine(vae, lat)
+ return (lat - mean) / std
+
+
+def _ltx2_encode_latent_stats(vae, pixel_values):
+ import torch
+
+ px = pixel_values.to(torch.float32).unsqueeze(2)
+ with torch.no_grad():
+ dist = vae.encode(px).latent_dist
+ mean, std = _ltx2_latent_affine(vae, dist.mean)
+ return (dist.mean - mean) / std, dist.std / std
+
+
+def _ltx2_collate(
+ entries,
+ device,
+ weight_dtype,
+ pad_to = None,
+):
+ import torch
+
+ # encode_prompt pads to max_sequence_length, so every connector embed is [1, 1024, 3840]
+ # and a plain concat batches them; ``pad_to`` is moot.
+ video = torch.cat([e[0] for e in entries]).to(device = device, dtype = weight_dtype)
+ audio = torch.cat([e[1] for e in entries]).to(device = device, dtype = weight_dtype)
+ mask = torch.cat([e[2] for e in entries]).to(device)
+ return (video, audio, mask)
+
+
+def _ltx2_audio_token_count(config, num_pixel_frames: int, fps: float) -> int:
+ """Audio latent tokens accompanying ``num_pixel_frames`` at ``fps``.
+
+ The pipeline derives this as ``round(duration_s * sampling_rate / hop_length /
+ temporal_compression)``; every term is on the transformer config, so the trainer does not
+ need the audio VAE resident (it never encodes audio -- see the spec comment). Floored at
+ one token: the transformer indexes the audio stream unconditionally, so an empty one
+ would trip its RoPE."""
+ per_second = (
+ float(config.audio_sampling_rate)
+ / float(config.audio_hop_length)
+ / float(config.audio_scale_factor)
+ )
+ return max(1, round((num_pixel_frames / float(fps)) * per_second))
+
+
+def _ltx2_pack(latents, conf):
+ """[B,C,F,H,W] -> [B, F*H*W, C] via the pipeline's own patchifier."""
+ from diffusers import LTX2Pipeline
+ return LTX2Pipeline._pack_latents(latents, conf.patch_size, conf.patch_size_t)
+
+
+def _ltx2_unpack(pred, f, h, w, conf):
+ """The inverse of ``_ltx2_pack``, back to the 5-D shape ``target = noise - latents`` has."""
+ from diffusers import LTX2Pipeline
+ return LTX2Pipeline._unpack_latents(pred, f, h, w, conf.patch_size, conf.patch_size_t)
+
+
+def _ltx2_audio_state(sigmas, bsz, audio_len, channels, device, dtype):
+ """The audio-stream input for a step at ``sigmas``.
+
+ A still-image dataset carries no audio ground truth, so the placeholder stream rides the
+ SAME flow-matching state a zero clean latent would produce: ``(1 - sigma) * 0 + sigma *
+ noise``. Zero is the mean of the normalised audio latent distribution, so this keeps the
+ stream at the right SCALE for every sigma instead of feeding unit noise at a timestep the
+ model expects nearly-clean latents at. With ``isolate_modalities = True`` it cannot reach
+ the video prediction at all; it exists only because ``forward`` requires the argument."""
+ import torch
+
+ noise = torch.randn((bsz, audio_len, channels), device = device, dtype = dtype)
+ # sigmas arrives broadcast to the 5-D video latent; the audio stream is 3-D.
+ return sigmas.reshape(bsz, 1, 1) * noise
+
+
+def _ltx2_forward(transformer, noisy, timesteps, sigmas, embeds_batch, cfg, device, weight_dtype):
+ video_emb, audio_emb, mask = embeds_batch
+ bsz, _c, f, h, w = noisy.shape
+ conf = transformer.config
+ packed = _ltx2_pack(noisy, conf)
+
+ # vae_scale_factors is (temporal, height, width), so [0] is the 8x temporal compression.
+ num_pixel_frames = (f - 1) * int(conf.vae_scale_factors[0]) + 1
+ audio_len = _ltx2_audio_token_count(conf, num_pixel_frames, _LTX2_TRAIN_FPS)
+ audio_noisy = _ltx2_audio_state(
+ sigmas, bsz, audio_len, conf.audio_in_channels, packed.device, packed.dtype
+ )
+
+ pred, _audio_pred = transformer(
+ hidden_states = packed,
+ audio_hidden_states = audio_noisy,
+ encoder_hidden_states = video_emb,
+ audio_encoder_hidden_states = audio_emb,
+ # LTX-2 conditions on the UNSCALED timestep (its config carries
+ # timestep_scale_multiplier = 1000 and the pipeline passes scheduler timesteps
+ # through as-is), unlike the FLUX / Qwen families' timestep / 1000.
+ timestep = timesteps,
+ sigma = timesteps,
+ encoder_attention_mask = mask,
+ audio_encoder_attention_mask = mask,
+ num_frames = f,
+ height = h,
+ width = w,
+ fps = _LTX2_TRAIN_FPS,
+ audio_num_frames = audio_len,
+ # Disable the audio-to-video / video-to-audio cross attention so the placeholder
+ # audio stream cannot perturb the video prediction the LoRA is regressing.
+ isolate_modalities = True,
+ return_dict = False,
+ )
+ return _ltx2_unpack(pred, f, h, w, conf)
+
+
+def _ltx2_save(pipe_cls, out_dir, transformer_lora_layers):
+ from diffusers import LTX2Pipeline
+ LTX2Pipeline.save_lora_weights(
+ save_directory = out_dir,
+ transformer_lora_layers = transformer_lora_layers,
+ weight_name = DEFAULT_LORA_FILENAME,
+ )
+
+
_SPECS: dict[str, _FamilySpec] = {
"flux.1": _FamilySpec(
family = "flux.1",
@@ -1192,6 +1438,23 @@ _SPECS: dict[str, _FamilySpec] = {
forward = _flux2_forward,
save = _flux2_save,
),
+ "ltx-2": _FamilySpec(
+ family = "ltx-2",
+ lora_targets = _LTX2_TARGETS,
+ force_bf16 = True,
+ # 19B audiovisual DiT; the transformer index reports 37.76 GB bf16. The Gemma3-12B
+ # conditioning stack (~24 GB resident) is loaded, encoded and freed BEFORE this lands
+ # on the device, via the shared phased load.
+ dense_bf16_gb = 37.8,
+ load_conditioners = _ltx2_load_conditioners,
+ load_transformer = _ltx2_load_transformer,
+ encode_prompts = _ltx2_encode_prompts,
+ encode_latents = _ltx2_encode_latents,
+ encode_latent_stats = _ltx2_encode_latent_stats,
+ collate = _ltx2_collate,
+ forward = _ltx2_forward,
+ save = _ltx2_save,
+ ),
}
@@ -1529,7 +1792,7 @@ def run_dit_lora_training(
on_event: Optional[EventCb] = None,
should_stop: Optional[StopCb] = None,
) -> str:
- """Train a flow-matching DiT LoRA (FLUX.1 / FLUX.2 / Qwen-Image / Z-Image / Krea 2) and export it.
+ """Train a flow-matching DiT LoRA (FLUX.1 / FLUX.2 / Qwen-Image / Z-Image / Krea 2 / LTX-2) and export it.
Resumable: ``cfg.resume_from_checkpoint`` restores the adapter, optimizer moments, LR
position, EMA shadow, sampler cycle and RNG streams from a ``checkpoint-<N>`` bundle,
@@ -1770,7 +2033,7 @@ def _train_dit(
# int8 / fp8 / mxfp8 convert the frozen base linears AFTER the LoRA attaches, so the adapter modules are excluded and stay high precision.
if base_precision == "int8":
- _int8_quantize_base(transformer)
+ _int8_quantize_base(transformer, cfg.resolved_family)
if base_precision == "fp8" and not _apply_fp8_training(transformer, on_event):
base_precision = "bf16"
if base_precision == "mxfp8" and not _apply_mxfp8_training(transformer, on_event):
@@ -1794,7 +2057,7 @@ def _train_dit(
# Timestep-shift + loss-weighting setup (see _training_sigma_table). getattr defaults keep an un-normalized config on the historical behavior.
flow_shift = getattr(cfg, "flow_shift", None)
if flow_shift is None:
- flow_shift = "auto" if spec.family == "qwen-image" else 1.0
+ flow_shift = "auto" if spec.family in AUTO_FLOW_SHIFT_FAMILIES else 1.0
sigma_table = _training_sigma_table(scheduler, flow_shift)
shift_active = sigma_table is not scheduler.sigmas
num_train_ts = scheduler.config.num_train_timesteps
@@ -2118,8 +2381,11 @@ def _make_optimizer(params, lr):
def _free_text_encoders(pipe) -> None:
- """Drop every text-encoder / tokenizer the pipeline holds, so the (large) encoders do
- not sit in VRAM during training. The embeddings are already precomputed."""
+ """Drop every conditioning module the pipeline holds once the embeddings are
+ precomputed, so they do not sit in VRAM during training. ``connectors`` is LTX-2's
+ second conditioning stage (~2.7 GB) and belongs here for the same reason as the text
+ encoders; ``audio_vae`` / ``vocoder`` are LTX-2 decode-side modules the trainer never
+ touches. Absent attributes are skipped, so this is a no-op for the image families."""
for attr in (
"text_encoder",
"text_encoder_2",
@@ -2127,6 +2393,9 @@ def _free_text_encoders(pipe) -> None:
"tokenizer",
"tokenizer_2",
"tokenizer_3",
+ "connectors",
+ "audio_vae",
+ "vocoder",
):
if getattr(pipe, attr, None) is not None:
try:
diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.py
index 6335818213e..8c9cbe81ff4 100644
--- a/studio/backend/core/training/diffusion_train_common.py
+++ b/studio/backend/core/training/diffusion_train_common.py
@@ -36,6 +36,7 @@ from core.inference.diffusion_families import (
supported_family_names,
trainable_family_names,
)
+from core.inference.video_families import detect_video_family, supported_video_family_names
# The trainers run in a spawned child that imports diffusers itself, so the inference-side install does not carry over. Both import this module first.
install_xformers_windows_rocm_stub()
@@ -59,9 +60,31 @@ _LR_SCHEDULERS: frozenset[str] = frozenset(
# DiT families whose fp32 RoPE/embedder overflow fp16, so they train in bf16 only. Keep in sync with the DiT trainer's own specs.
_FORCE_BF16_FAMILIES: frozenset[str] = frozenset(
- {"qwen-image", "z-image", "krea-2", "flux.2-klein", "flux.2-dev"}
+ {"qwen-image", "z-image", "krea-2", "flux.2-klein", "flux.2-dev", "ltx-2"}
)
+# VIDEO families (from the separate ``video_families`` registry) Studio can train a LoRA on.
+# The video registry has no ``trainable`` flag of its own -- it exists for the inference
+# picker -- so the trainable set lives here, next to the trainers, and MUST hold exactly the
+# families ``diffusion_dit_trainer._SPECS`` implements. A video base outside this set is
+# refused by name in ``resolve_trainable_family`` rather than falling through to a trainer
+# that cannot run it.
+TRAINABLE_VIDEO_FAMILIES: frozenset[str] = frozenset({"ltx-2"})
+
+# Families whose ``flow_shift`` default is "auto" (reproduce the family's INFERENCE sigma
+# distribution) rather than the historical identity 1.0. Both schedulers set
+# ``use_dynamic_shifting``, so their static ``shift`` is skipped at init and ``scheduler.sigmas``
+# is the unshifted uniform table; training on it would draw a distribution the model never sees
+# at inference. Qwen-Image pins base_shift = max_shift = log 3 and LTX-2 evaluates its shift at
+# ``max_image_seq_len`` (so mu = max_shift = 2.05 at every resolution): in both cases the
+# inference mu is a constant the "auto" branch can reproduce exactly.
+AUTO_FLOW_SHIFT_FAMILIES: frozenset[str] = frozenset({"qwen-image", "ltx-2"})
+
+# Video latents are allocated on the family's spatial compression grid, so a training
+# resolution off that grid silently changes the latent geometry (or trips a reshape).
+# LTX-2's VAE compresses 32x spatially, matching its ``resolution_multiple``.
+_VIDEO_RESOLUTION_MULTIPLE = 32
+
_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}
_CAPTION_EXTS = (".txt", ".caption")
# diffusers' canonical single-file LoRA name, so load_lora_weights(dir) finds it.
@@ -76,10 +99,106 @@ EventCb = Callable[[dict[str, Any]], None]
StopCb = Callable[[], Any]
+def _all_trainable_family_names() -> tuple[str, ...]:
+ """Every family with a trainer: the image registry's ``trainable`` families plus the
+ video families listed in ``TRAINABLE_VIDEO_FAMILIES``. The two registries are separate
+ by design (a video checkpoint must never route to an image pipeline), so the trainable
+ view has to union them."""
+ video = tuple(n for n in supported_video_family_names() if n in TRAINABLE_VIDEO_FAMILIES)
+ return tuple(trainable_family_names()) + video
+
+
+def _trainable_family_spec(name: str) -> Any:
+ """The registry entry for a trainable family name, from EITHER registry, or None.
+
+ Every consumer that starts from a resolved family NAME (rather than from a repo id) needs
+ this: the image registry does not know a video family, so a plain ``detect_family`` returns
+ None for one and the caller silently skips it. That is how ``ltx-2`` stayed out of
+ ``/diffusion/info`` and out of the strict pipeline gate."""
+ from core.inference.diffusion_families import detect_family
+
+ key = str(name or "").strip().lower()
+ fam = detect_family("", override = key)
+ if fam is not None:
+ return fam
+ return detect_video_family("", override = key)
+
+
+def _refuse_untrainable_video_family(name: str) -> None:
+ """Raise for a video family Studio has no trainer for.
+
+ Video bases are invisible to the image registry, so before this gate existed every video
+ checkpoint fell through ``resolve_trainable_family``'s unknown-name fallback and was
+ handed to the SDXL trainer, which then failed somewhere inside from_pretrained. Refuse by
+ name instead, with the list of video families that do train."""
+ trainable = ", ".join(sorted(TRAINABLE_VIDEO_FAMILIES))
+ raise ValueError(
+ f"'{name}' is a video model Studio can't train yet. Video LoRA training currently "
+ f"supports: {trainable}. {_trainable_hint()}"
+ )
+
+
+def _component_only_repos() -> dict[str, tuple[str, str, str]]:
+ """Every repo the family registries list only as a COMPONENT source, keyed by lowercased
+ repo id -> (family name, component, that family's base repo).
+
+ A pre-cast text-encoder repo (``te_prequant_repos``, present in both the image and the video
+ registry) ships a single component archive: no ``model_index.json``, no VAE, no scheduler, no
+ pipeline. ``from_pretrained`` on one can only fail. Nothing in the NAME says so, which is the
+ whole problem: ``unsloth/LTX-2-FP8`` carries the ``ltx-2`` token, so the family detectors
+ claim it and the ``unsloth/*`` trust gate passes it. The registries' own tables are the only
+ authority on what a repo actually holds, so read them rather than special-casing repo ids.
+
+ A repo that is ALSO registered as a base somewhere (a full quantized pipeline mirror, a
+ deploy base, a train base) is a base and never appears here."""
+ from core.inference.diffusion_families import detect_family
+ from core.inference.video_families import detect_video_family
+
+ families = [detect_family("", override = n) for n in supported_family_names()]
+ families += [detect_video_family("", override = n) for n in supported_video_family_names()]
+ components: dict[str, tuple[str, str, str]] = {}
+ bases: set[str] = set()
+ for fam in families:
+ if fam is None:
+ continue
+ for attr in ("base_repo", "deploy_base_repo"):
+ repo = getattr(fam, attr, None)
+ if repo:
+ bases.add(str(repo).strip().lower())
+ bases.update(str(r).strip().lower() for r in getattr(fam, "train_base_repos", ()) if r)
+ # (scheme, repo) and (base, scheme, repo): both name a FULL pipeline mirror, so both are bases.
+ for table in ("prequant_repos", "prequant_variant_repos"):
+ bases.update(str(row[-1]).strip().lower() for row in getattr(fam, table, ()) if row)
+ for _scheme, component, repo in getattr(fam, "te_prequant_repos", ()):
+ components.setdefault(
+ str(repo).strip().lower(), (fam.name, str(component), str(fam.base_repo))
+ )
+ return {repo: hit for repo, hit in components.items() if repo not in bases}
+
+
+def _refuse_component_only_repo(base_model: str) -> None:
+ """Raise for a base model that is a family's component checkpoint rather than a model.
+
+ Runs from ``resolve_trainable_family``, so it fires in the ``/diffusion/start`` preflight
+ BEFORE the resident GPU workloads are freed. Without it the name match resolved a real
+ family, the trust gate passed the ``unsloth/*`` repo, the gated-access probe ignored the
+ resulting ``model_index.json`` 404 (a 404 is not an access problem), and the run evicted the
+ user's loaded model before failing inside ``from_pretrained`` in the child."""
+ hit = _component_only_repos().get(str(base_model or "").strip().lower())
+ if hit is None:
+ return
+ family, component, base_repo = hit
+ raise ValueError(
+ f"'{base_model}' is the pre-cast {component} checkpoint for the '{family}' family, not a "
+ f"full model: it ships no model_index.json and no pipeline, so it cannot be a training "
+ f"base. Train from '{base_repo}' instead."
+ )
+
+
def _trainable_hint() -> str:
"""A user-facing hint listing the families Studio can train today. Always names SDXL
explicitly so the message is actionable even as more families become trainable."""
- names = ", ".join(trainable_family_names()) or "sdxl"
+ names = ", ".join(_all_trainable_family_names()) or "sdxl"
return (
f"Trainable families right now: {names} "
f"(for example the SDXL base stabilityai/stable-diffusion-xl-base-1.0). "
@@ -130,9 +249,11 @@ def training_pipeline_import_error(resolved_family: str) -> Optional[str]:
Returns the message instead of raising, matching ``training_precision_preflight_error``, so the
route maps it to its own 400."""
- from core.inference.diffusion_families import assert_pipeline_class_available, detect_family
+ from core.inference.diffusion_families import assert_pipeline_class_available
- fam = detect_family("", override = str(resolved_family or "").strip().lower())
+ # Either registry: a video family is invisible to detect_family, and returning None for one
+ # would hand the strict half of the gate back to the spawned child, after the teardown.
+ fam = _trainable_family_spec(resolved_family)
if fam is None:
return None
try:
@@ -171,11 +292,26 @@ def resolve_trainable_family(base_model: str, model_family: Optional[str] = None
f"'{base_model}' is a GGUF checkpoint/repo, which can't be a training base "
f"(training needs the full diffusers model). {_trainable_hint()}"
)
+ # A component checkpoint is not a base whatever family the name matches, so this precedes
+ # every family branch below (including an explicit model_family override, which names the
+ # family but says nothing about what the repo holds).
+ _refuse_component_only_repo(base_model)
+ # Same shape as the component-only refusal: the name resolves to a real, trainable family, but
+ # the repo is not something the training loader can open.
+ _refuse_ltx23_training_base(base_model)
if model_family and str(model_family).strip():
key = str(model_family).strip().lower()
fam = detect_family("", override = key)
if fam is None:
- known = ", ".join(supported_family_names())
+ # Not an image family: it may still name a VIDEO family, which lives in its own
+ # registry. Resolve there before declaring the name unknown.
+ vid = detect_video_family("", override = key)
+ if vid is not None:
+ if vid.name not in TRAINABLE_VIDEO_FAMILIES:
+ _refuse_untrainable_video_family(vid.name)
+ _assert_family_pipeline_available(vid)
+ return vid.name
+ known = ", ".join(supported_family_names() + supported_video_family_names())
raise ValueError(f"Unknown model_family {model_family!r}. Known families: {known}.")
if not fam.trainable:
raise ValueError(f"'{fam.name}' models can't be trained yet. {_trainable_hint()}")
@@ -192,6 +328,15 @@ def resolve_trainable_family(base_model: str, model_family: Optional[str] = None
_assert_family_pipeline_available(fam)
return fam.name
+ # Only once the image registry has declined the name: a video checkpoint. Checked here
+ # rather than first so an image repo the picker already claims keeps its existing route.
+ vid = detect_video_family(base_model)
+ if vid is not None:
+ if vid.name not in TRAINABLE_VIDEO_FAMILIES:
+ _refuse_untrainable_video_family(vid.name)
+ _assert_family_pipeline_available(vid)
+ return vid.name
+
condensed = re.sub(r"[^a-z0-9]+", "-", name)
hit = next(
(p for p in _NON_TRAINABLE_RESIDUAL_PHRASES if p in condensed),
@@ -294,7 +439,7 @@ def get_trainer(family: str) -> Callable[..., str]:
if key == "sdxl":
from core.training.diffusion_lora_trainer import run_diffusion_lora_training
return run_diffusion_lora_training
- if key in ("flux.1", "qwen-image", "z-image", "krea-2", "flux.2-klein", "flux.2-dev"):
+ if key in ("flux.1", "qwen-image", "z-image", "krea-2", "flux.2-klein", "flux.2-dev", "ltx-2"):
from core.training.diffusion_dit_trainer import run_dit_lora_training
return run_dit_lora_training
raise ValueError(f"No trainer is registered for family {family!r}.")
@@ -327,6 +472,15 @@ FAMILY_TRAIN_DEFAULTS: dict[str, dict[str, Any]] = {
"resolution": 512,
"lr_warmup_steps": 20,
},
+ # LTX-2, from Lightricks' own ltx-trainer LoRA configs: rank/alpha 32, lr 1e-4. The
+ # resolution must be a multiple of 32 (its VAE's spatial compression), and 512 keeps a
+ # still at 16x16x1 latents / 256 video tokens, which trains comfortably at batch 1.
+ "ltx-2": {
+ "lora_rank": 32,
+ "learning_rate": 1e-4,
+ "resolution": 512,
+ "lr_warmup_steps": 20,
+ },
}
@@ -344,6 +498,7 @@ _FAMILY_LABELS = {
"krea-2": "Krea 2",
"flux.2-klein": "FLUX.2 Klein",
"flux.2-dev": "FLUX.2-dev",
+ "ltx-2": "LTX-2",
}
# Per-family training facts as fields, so the UI can chip them instead of parsing prose.
# ``params`` is the transformer size (SDXL is not quoted that way), ``note`` is the rest.
@@ -365,6 +520,18 @@ _FAMILY_TRAIN_SPECS: dict[str, dict[str, Any]] = {
},
"flux.2-klein": {"params": "4B", "qlora_vram_gb": 10, "gated": False, "note": ""},
"flux.2-dev": {"params": "32B", "qlora_vram_gb": 28, "gated": True, "note": ""},
+ # Video. Measured on a B200: the training LOOP peaks at 11.2 GB (nf4, rank 32, 512px
+ # stills, batch 1, gradient checkpointing), but the RUN peaks at 34.8 GB earlier, while
+ # the Gemma3-12B conditioning stack is resident and captions are encoded -- before it is
+ # freed and the transformer loads. The quoted figure covers the whole run, since that is
+ # what a card has to hold. Lightricks quote 80 GB recommended / 32 GB with their int8
+ # low-VRAM config for their own trainer.
+ "ltx-2": {
+ "params": "19B",
+ "qlora_vram_gb": 36,
+ "gated": False,
+ "note": "Video: trains a style LoRA on still images.",
+ },
}
_GATED_NOTE = "Gated: needs its license and your HF token."
@@ -382,7 +549,7 @@ def _family_vram_note(name: str) -> str:
# The flow-matching DiT families (run by diffusion_dit_trainer): they expose base_precision / compile and need bf16 on CUDA. SDXL is absent (own mixed_precision path).
_DIT_TRAIN_FAMILIES = frozenset(
- {"flux.1", "qwen-image", "z-image", "krea-2", "flux.2-klein", "flux.2-dev"}
+ {"flux.1", "qwen-image", "z-image", "krea-2", "flux.2-klein", "flux.2-dev", "ltx-2"}
)
@@ -549,17 +716,25 @@ def training_precision_preflight_error(resolved_family: str, base_precision: str
def family_train_infos() -> list[dict[str, Any]]:
"""Describe every trainable family for the Train UI: name, label, the default + allowed
base repos, the recommended starting hyperparameters, and a VRAM/access note. Built from
- the family registry so it stays in sync with what the trainers actually support."""
- from core.inference.diffusion_families import detect_family
+ the family registry so it stays in sync with what the trainers actually support.
+
+ Both registries: a video family with a trainer is as trainable as an image one, and reading
+ only the image registry is what kept ``ltx-2`` out of the Train tab entirely -- the trainer,
+ the preflight and the start route all accepted it, but nothing ever offered it. A family whose
+ pipeline class the installed diffusers lacks is dropped rather than advertised, since the start
+ route refuses it (``training_pipeline_import_error``) and no choice in the UI can fix that."""
+ from core.inference.diffusion_families import family_pipeline_available
from core.inference.diffusion_transformer_quant import _family_train_denied
dit_modes, dit_recommended = train_precision_modes()
infos: list[dict[str, Any]] = []
- for name in trainable_family_names():
- fam = detect_family("", override = name)
- if fam is None:
+ for name in _all_trainable_family_names():
+ fam = _trainable_family_spec(name)
+ if fam is None or not family_pipeline_available(fam):
continue
- repos = list(fam.train_base_repos) or [fam.base_repo]
+ # A video family carries no train_base_repos/deploy_base_repo: its own base repo is the
+ # one training base, and a video LoRA has no image catalog to deploy into.
+ repos = list(getattr(fam, "train_base_repos", ()) or ()) or [fam.base_repo]
# base_precision applies to the DiT trainer only; SDXL keeps its mixed_precision lever. compile applies everywhere.
is_dit = name in _DIT_TRAIN_FAMILIES
# On a non-bf16 CUDA GPU the start preflight rejects EVERY DiT family, so advertise no precision, else /info offers an
@@ -592,8 +767,8 @@ def family_train_infos() -> list[dict[str, Any]]:
"recommended_precision": "nf4" if (not is_dit or dit_block) else dit_recommended,
# compile is offered everywhere (SDXL regional U-Net + DiT), except a DiT family the GPU cannot train in bf16.
"supports_compile": bool(not dit_block),
- # Krea trains on Raw but previews adapters on Turbo; None elsewhere.
- "deploy_base": fam.deploy_base_repo,
+ # Krea trains on Raw but previews adapters on Turbo; None elsewhere (and never for a video family).
+ "deploy_base": getattr(fam, "deploy_base_repo", None),
}
)
return infos
@@ -691,6 +866,17 @@ class DiffusionLoraConfig:
)
if self.resolution < 64 or self.resolution % 8 != 0:
raise ValueError("resolution must be a multiple of 8 and >= 64")
+ # A video family's VAE compresses space by 32, so an off-grid resolution changes the
+ # latent geometry silently. Refuse it here, before the GPU models are evicted.
+ if (
+ resolved_family in TRAINABLE_VIDEO_FAMILIES
+ and self.resolution % _VIDEO_RESOLUTION_MULTIPLE != 0
+ ):
+ raise ValueError(
+ f"'{resolved_family}' trains at a resolution that is a multiple of "
+ f"{_VIDEO_RESOLUTION_MULTIPLE} (its VAE compresses space by that factor); "
+ f"got {self.resolution}."
+ )
if self.mixed_precision not in ("bf16", "fp16", "no"):
raise ValueError("mixed_precision must be one of bf16 / fp16 / no")
# torch.manual_seed unpacks int64/uint64, so anything wider raises inside the trainer, after eviction. Catch it here.
@@ -771,7 +957,7 @@ class DiffusionLoraConfig:
# flow_shift: None resolves to the family default ("auto" only for qwen-image, whose scheduler skips its static shift under use_dynamic_shifting); an explicit value is validated and kept.
flow_shift = self.flow_shift
if flow_shift is None:
- flow_shift = "auto" if resolved_family == "qwen-image" else 1.0
+ flow_shift = "auto" if resolved_family in AUTO_FLOW_SHIFT_FAMILIES else 1.0
if isinstance(flow_shift, str):
flow_shift = flow_shift.strip().lower()
if flow_shift != "auto":
@@ -1183,9 +1369,32 @@ _TRAIN_EXTRA_TRUSTED_REPOS = frozenset(
{
"black-forest-labs/flux.2-dev",
"black-forest-labs/flux.2-klein-4b",
+ # LTX-2's official base. It is a video family, so the image-side inference allowlist
+ # (_is_trusted_diffusion_repo) never covered it; safetensors-only, no remote code.
+ "lightricks/ltx-2",
}
)
+# LTX-2.3 repos hold SINGLE-FILE checkpoints (ltx-2.3-22b-*.safetensors) and no diffusers layout:
+# no model_index.json, no transformer/ or scheduler/ subfolder. Inference assembles them with
+# from_single_file plus 2.3 config overrides and components borrowed from the 2.0 base (see
+# core/inference/video_ltx2.py); the trainer only knows LTX2Pipeline.from_pretrained, which cannot
+# read that layout. The name still resolves to the ``ltx-2`` family, so without an explicit refusal
+# the run passes preflight, evicts the user's resident models, and only then fails in the child.
+_LTX23_TRAIN_UNSUPPORTED = ("lightricks/ltx-2.3", "lightricks/ltx-2.3-fp8")
+
+
+def _refuse_ltx23_training_base(base_model: str) -> None:
+ """Raise for an LTX-2.3 base: the family routing accepts it, the training loader cannot."""
+ if str(base_model or "").strip().lower() not in _LTX23_TRAIN_UNSUPPORTED:
+ return
+ raise ValueError(
+ f"'{base_model}' ships LTX-2.3 as single-file checkpoints with no diffusers layout, so it "
+ f"cannot be a training base yet: the trainer loads a base with from_pretrained, while 2.3 "
+ f"has to be assembled with from_single_file plus components from the 2.0 base. Train from "
+ f"'Lightricks/LTX-2' instead."
+ )
+
def _assert_trusted_base_model(base_model: str) -> None:
"""Gate the training base model the same way the inference backend gates non-GGUF loads:
@@ -1538,7 +1747,16 @@ def _publish_to_lora_catalog(
``steps`` is the step count the run actually REACHED, which is what the sidecar must
record: a run stopped at step 11 of 500 published an adapter claiming 500 steps. None
- keeps the old behaviour for callers that do not know the reached step."""
+ keeps the old behaviour for callers that do not know the reached step.
+
+ A VIDEO family publishes nothing. ``loras/diffusion`` is read by the Images LoRA picker
+ alone, and ``core/inference/video.py`` has no LoRA surface at all, so mirroring a video
+ adapter there would copy a large file into a catalog nothing can load and hand the UI a
+ deployment path Studio cannot honour. The run still reports ``lora_path`` (and ``ema_path``),
+ which is the adapter a caller loads directly. Giving video its own catalog and a load path
+ on the Video tab is a separate, larger piece of work."""
+ if detect_video_family("", override = cfg.resolved_family) is not None:
+ return None
try:
import shutil
diff --git a/studio/backend/core/training/diffusion_train_extras.py b/studio/backend/core/training/diffusion_train_extras.py
index dea080f5c25..124ec45ef2e 100644
--- a/studio/backend/core/training/diffusion_train_extras.py
+++ b/studio/backend/core/training/diffusion_train_extras.py
@@ -256,6 +256,15 @@ def _hub_cache_roots() -> list[str]:
return roots
+# Pipeline subdirectories whose weights decide what the conditioning cache holds, so an in-place
+# edit of any of them must change the fingerprint. text_encoder*/tokenizer* produce the embeddings
+# and vae* the latents, for every family. "connectors" is LTX-2's: the Gemma3 hidden states are
+# per-layer stacked and only the connector output reaches the transformer, so that projection --
+# not the raw encoder state -- is what gets cached. No other supported family runs a module between
+# encode_prompt and the DiT; the rest go straight from the text encoders to the cached tensors.
+_CACHE_SOURCE_SUBDIRS = ("text_encoder", "tokenizer", "vae", "connectors")
+
+
def source_revision(ref: Any) -> str:
"""Revision/content marker for a checkpoint reference, resolved without loading it.
@@ -276,10 +285,7 @@ def source_revision(ref: Any) -> str:
roots = [name]
with os.scandir(name) as it:
roots += [
- e.path
- for e in it
- # vae too: cached latents come from it, so an in-place VAE swap must invalidate them just like an encoder change.
- if e.is_dir() and e.name.startswith(("text_encoder", "tokenizer", "vae"))
+ e.path for e in it if e.is_dir() and e.name.startswith(_CACHE_SOURCE_SUBDIRS)
]
for root in roots:
with os.scandir(root) as it:
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 64fa82bf564..dcf64fba13b 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -3316,7 +3316,8 @@ def test_pipeline_class_guard_is_silent_when_a_lazy_submodule_cannot_import(monk
# unsatisfiable it raises RuntimeError ("Failed to import diffusers.pipelines..."). hasattr
# absorbs AttributeError only, so the RuntimeError escaped this guard exactly the way a
# missing diffusers used to: not the ValueError the routes map to 400, so a bare 500 with the
- # message lost.
+ # message lost -- and, now that the training preflight calls this too, a refusal that arrives
+ # as a 500 instead of the actionable 400. There is no version to judge here either.
import types
from core.inference.diffusion_families import assert_pipeline_class_available
diff --git a/studio/backend/tests/test_diffusion_dit_trainer.py b/studio/backend/tests/test_diffusion_dit_trainer.py
index 1d096e2a89b..5e1efe6a6f0 100644
--- a/studio/backend/tests/test_diffusion_dit_trainer.py
+++ b/studio/backend/tests/test_diffusion_dit_trainer.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Unit tests for the flow-matching DiT LoRA trainer (FLUX.1 / FLUX.2 / Qwen-Image / Z-Image).
+"""Unit tests for the flow-matching DiT LoRA trainer (FLUX.1 / FLUX.2 / Qwen-Image / Z-Image / LTX-2).
CPU-only: cover family resolution, the per-family spec table, the QLoRA prequant
heuristic, the bf16-only guard, and the gated-repo name check. The full training loop is
@@ -46,6 +46,8 @@ def test_specs_cover_the_dit_families():
"krea-2",
"flux.2-klein",
"flux.2-dev",
+ # The first VIDEO family; its own assertions live in test_diffusion_dit_trainer_ltx2.
+ "ltx-2",
}
# FLUX / Qwen share the added-kv attention target set; Z-Image and Krea 2 are single-stream.
assert "add_q_proj" in _SPECS["flux.1"].lora_targets
diff --git a/studio/backend/tests/test_diffusion_dit_trainer_ltx2.py b/studio/backend/tests/test_diffusion_dit_trainer_ltx2.py
new file mode 100644
index 00000000000..0f20b16c107
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_dit_trainer_ltx2.py
@@ -0,0 +1,883 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unit tests for the LTX-2 (video) family of the flow-matching DiT LoRA trainer.
+
+CPU-only, and deliberately free of a ``diffusers`` import: the two places that need the
+pipeline's patchifier are isolated behind ``_ltx2_pack`` / ``_ltx2_unpack`` so the forward
+contract can be checked against a fake transformer. What matters here is everything a video
+family gets WRONG by default: the LoRA targets leaking into the audio stream, the audio
+placeholder being fed at the wrong scale, the timestep being divided by 1000 as the image
+families do, the cross-modality attention staying on, and a video base silently routing to
+the SDXL trainer. The training loop itself is exercised by the live GPU run."""
+
+from __future__ import annotations
+
+import sys
+import types
+
+import pytest
+import torch
+
+from core.training import diffusion_dit_trainer as dit
+from core.training.diffusion_dit_trainer import (
+ _LTX2_TARGETS,
+ _LTX2_TRAIN_FPS,
+ _SPECS,
+ _free_text_encoders,
+ _ltx2_audio_state,
+ _ltx2_audio_token_count,
+ _ltx2_collate,
+ _ltx2_encode_latent_stats,
+ _ltx2_encode_latents,
+ _ltx2_forward,
+ _select_lora_targets,
+)
+from core.training.diffusion_train_common import (
+ AUTO_FLOW_SHIFT_FAMILIES,
+ DEFAULT_LORA_FILENAME,
+ DEFAULT_LORA_TARGETS,
+ DiffusionLoraConfig,
+ TRAINABLE_VIDEO_FAMILIES,
+ _assert_trusted_base_model,
+ _component_only_repos,
+ _DIT_TRAIN_FAMILIES,
+ _family_vram_note,
+ get_trainer,
+ _publish_to_lora_catalog,
+ resolve_trainable_family,
+ train_defaults,
+)
+
+# The real LTX-2 checkpoint's transformer config values the trainer reads (from
+# Lightricks/LTX-2 transformer/config.json), so the fakes below are not invented numbers.
+LTX2_CONF = dict(
+ patch_size = 1,
+ patch_size_t = 1,
+ audio_in_channels = 128,
+ audio_sampling_rate = 16000,
+ audio_hop_length = 160,
+ audio_scale_factor = 4,
+ vae_scale_factors = (8, 32, 32),
+)
+
+# Every Linear inside one real LTX-2 transformer block, as reported by named_modules() on
+# LTX2VideoTransformer3DModel. Split into the video stream (adaptable) and everything else.
+_BLOCK = "transformer_blocks.0."
+VIDEO_STREAM_LINEARS = tuple(
+ _BLOCK + n
+ for n in (
+ "attn1.to_q",
+ "attn1.to_k",
+ "attn1.to_v",
+ "attn1.to_out.0",
+ "attn2.to_q",
+ "attn2.to_k",
+ "attn2.to_v",
+ "attn2.to_out.0",
+ )
+)
+NON_VIDEO_STREAM_LINEARS = tuple(
+ _BLOCK + n
+ for n in (
+ "audio_attn1.to_q",
+ "audio_attn1.to_k",
+ "audio_attn1.to_v",
+ "audio_attn1.to_out.0",
+ "audio_attn2.to_q",
+ "audio_attn2.to_k",
+ "audio_attn2.to_v",
+ "audio_attn2.to_out.0",
+ "audio_to_video_attn.to_q",
+ "audio_to_video_attn.to_k",
+ "audio_to_video_attn.to_v",
+ "audio_to_video_attn.to_out.0",
+ "video_to_audio_attn.to_q",
+ "video_to_audio_attn.to_k",
+ "video_to_audio_attn.to_v",
+ "video_to_audio_attn.to_out.0",
+ "audio_ff.net.0.proj",
+ "audio_ff.net.2",
+ # Video-stream feed-forward: real, but deliberately NOT a target (Lightricks' own
+ # video inpainting/outpainting LoRA configs stop at the attention projections).
+ "ff.net.0.proj",
+ "ff.net.2",
+ )
+)
+
+
+def _fake_config():
+ return types.SimpleNamespace(**LTX2_CONF)
+
+
+class _RecordingTransformer:
+ """Stands in for LTX2VideoTransformer3DModel: records the kwargs and returns
+ correctly-shaped (video, audio) predictions."""
+
+ def __init__(self):
+ self.config = _fake_config()
+ self.kwargs = None
+
+ def __call__(self, **kwargs):
+ self.kwargs = kwargs
+ hs = kwargs["hidden_states"]
+ audio = kwargs["audio_hidden_states"]
+ return hs.clone(), audio.clone()
+
+
+def patched_pack(monkeypatch):
+ """Replace the two diffusers-backed helpers with the identity-shaped equivalents, so the
+ forward contract is testable without importing LTX2Pipeline."""
+
+ def pack(latents, conf):
+ b, c, f, h, w = latents.shape
+ return latents.permute(0, 2, 3, 4, 1).reshape(b, f * h * w, c)
+
+ def unpack(pred, f, h, w, conf):
+ b = pred.shape[0]
+ return pred.reshape(b, f, h, w, -1).permute(0, 4, 1, 2, 3)
+
+ monkeypatch.setattr(dit, "_ltx2_pack", pack)
+ monkeypatch.setattr(dit, "_ltx2_unpack", unpack)
+
+
+# ── the spec ─────────────────────────────────────────────────────────────────
+def test_ltx2_spec_is_registered_and_bf16_only():
+ spec = _SPECS["ltx-2"]
+ assert spec.family == "ltx-2"
+ # LTX-2's RoPE runs in double precision and the reference stack is bf16 throughout.
+ assert spec.force_bf16 is True
+ # The 19B transformer index reports 37.76 GB bf16; "auto" sizes the dense modes off this.
+ assert 30.0 < spec.dense_bf16_gb < 45.0
+ assert spec.lora_targets == _LTX2_TARGETS
+
+
+def test_every_trainable_video_family_has_a_spec():
+ # The video registry has no trainable flag, so this set is the only gate; a name in it
+ # without a spec would pass resolve_trainable_family and then die in run_dit_lora_training.
+ assert TRAINABLE_VIDEO_FAMILIES <= set(_SPECS)
+ assert TRAINABLE_VIDEO_FAMILIES <= _DIT_TRAIN_FAMILIES
+ assert get_trainer("ltx-2") is dit.run_dit_lora_training
+
+
+# ── LoRA targets: the audio-stream leak ──────────────────────────────────────
+def test_ltx2_targets_are_fully_qualified():
+ # A bare "to_q" would also match audio_attn1 / audio_attn2 / audio_to_video_attn /
+ # video_to_audio_attn, which is exactly the mistake Lightricks warn about in their docs.
+ for target in _LTX2_TARGETS:
+ assert target.startswith(("attn1.", "attn2.")), target
+ assert "to_q" not in _LTX2_TARGETS
+ assert "to_out.0" not in _LTX2_TARGETS
+
+
+def _peft_selects(targets, module_name: str) -> bool:
+ """PEFT's own rule for a LIST of target_modules, from
+ ``peft.tuners.tuners_utils.check_target_module_exists``: a module is adapted when its
+ fully-qualified name equals a target or ends with "." + target. Reimplemented here
+ because importing peft pulls in transformers, which some environments cannot import;
+ ``test_our_peft_rule_matches_peft`` pins it to the real thing wherever peft loads."""
+ return any(module_name == t or module_name.endswith("." + t) for t in targets)
+
+
+def test_our_peft_rule_matches_peft():
+ try:
+ from peft import LoraConfig
+ from peft.tuners import tuners_utils as peft_utils
+ except Exception as exc: # noqa: BLE001 -- peft drags in transformers; skip where it cannot load
+ pytest.skip(f"peft unavailable: {exc}")
+
+ cfg = LoraConfig(target_modules = list(_LTX2_TARGETS))
+ for name in VIDEO_STREAM_LINEARS + NON_VIDEO_STREAM_LINEARS:
+ assert peft_utils.check_target_module_exists(cfg, name) == _peft_selects(
+ _LTX2_TARGETS, name
+ ), name
+
+
[email protected]("name", VIDEO_STREAM_LINEARS)
+def test_ltx2_targets_select_every_video_attention_projection(name):
+ assert _peft_selects(_LTX2_TARGETS, name), name
+
+
[email protected]("name", NON_VIDEO_STREAM_LINEARS)
+def test_ltx2_targets_never_select_the_audio_or_cross_modality_streams(name):
+ assert not _peft_selects(_LTX2_TARGETS, name), name
+
+
[email protected]("name", NON_VIDEO_STREAM_LINEARS[:16])
+def test_the_generic_default_targets_would_leak_into_the_audio_stream(name):
+ """Why _LTX2_TARGETS is fully qualified: the shared DEFAULT_LORA_TARGETS suffixes match
+ the audio and cross-modality attentions too. If this ever stops being true the
+ qualification is no longer load-bearing and the comment above it is wrong."""
+ assert _peft_selects(DEFAULT_LORA_TARGETS, name), name
+
+
+def test_generic_default_targets_resolve_to_the_ltx2_set():
+ # normalized() fills the generic DEFAULT_LORA_TARGETS, and those bare suffixes WOULD hit
+ # the audio stream, so the spec's fully-qualified set must win.
+ cfg = DiffusionLoraConfig(
+ base_model = "Lightricks/LTX-2", data_dir = "d", output_dir = "o"
+ ).normalized()
+ assert cfg.lora_target_modules == DEFAULT_LORA_TARGETS
+ assert (
+ _select_lora_targets(cfg.lora_target_modules, _SPECS["ltx-2"].lora_targets) == _LTX2_TARGETS
+ )
+
+
+# ── the audio placeholder ────────────────────────────────────────────────────
+ "num_pixel_frames, fps, expected",
+ [
+ # 16000 / 160 / 4 = 25 audio latent tokens per second.
+ (1, 24.0, 1), # a still: 1/24 s -> round(1.04) -> 1
+ (25, 24.0, 26),
+ (121, 24.0, 126), # the family default clip
+ (1, 1.0, 25),
+ ],
+)
+def test_audio_token_count_matches_the_pipeline_formula(num_pixel_frames, fps, expected):
+ assert _ltx2_audio_token_count(_fake_config(), num_pixel_frames, fps) == expected
+
+
+def test_audio_token_count_never_returns_zero():
+ # round() would give 0 for a very short duration, and the transformer indexes the audio
+ # stream unconditionally, so an empty one trips its RoPE.
+ conf = types.SimpleNamespace(**{**LTX2_CONF, "audio_sampling_rate": 1})
+ assert _ltx2_audio_token_count(conf, 1, 24.0) == 1
+
+
+def test_audio_state_is_scaled_by_sigma():
+ torch.manual_seed(0)
+ sigmas = torch.tensor([0.25, 0.75]).view(2, 1, 1, 1, 1)
+ state = _ltx2_audio_state(sigmas, 2, 4, 128, torch.device("cpu"), torch.float32)
+ assert state.shape == (2, 4, 128)
+ # (1 - sigma) * 0 + sigma * noise: each row's scale must track its own sigma, so the
+ # 0.75 row is ~3x the 0.25 row. A version that fed unit noise regardless would be ~1:1.
+ ratio = float(state[1].std() / state[0].std())
+ assert 2.0 < ratio < 4.5
+
+
+def test_audio_state_is_zero_at_sigma_zero():
+ sigmas = torch.zeros(1).view(1, 1, 1, 1, 1)
+ state = _ltx2_audio_state(sigmas, 1, 3, 128, torch.device("cpu"), torch.float32)
+ assert torch.equal(state, torch.zeros_like(state))
+
+
+# ── the forward contract ─────────────────────────────────────────────────────
+def _run_forward(
+ transformer,
+ bsz = 1,
+ f = 1,
+ h = 4,
+ w = 4,
+ c = 8,
+ sigma = 0.5,
+):
+ noisy = torch.randn(bsz, c, f, h, w)
+ sigmas = torch.full((bsz,), sigma).view(bsz, 1, 1, 1, 1)
+ timesteps = torch.full((bsz,), sigma * 1000.0)
+ embeds = (
+ torch.randn(bsz, 6, 3840),
+ torch.randn(bsz, 6, 3840),
+ torch.ones(bsz, 6, dtype = torch.int64),
+ )
+ out = _ltx2_forward(transformer, noisy, timesteps, sigmas, embeds, None, "cpu", torch.float32)
+ return noisy, out
+
+
+def test_forward_returns_the_target_shape(patched_pack):
+ tr = _RecordingTransformer()
+ noisy, out = _run_forward(tr, bsz = 2, f = 1, h = 4, w = 4, c = 8)
+ # target = noise - latents is the 5-D latent, so the prediction must be unpacked back.
+ assert out.shape == noisy.shape
+
+
+def test_forward_isolates_the_cross_modality_attention(patched_pack):
+ tr = _RecordingTransformer()
+ _run_forward(tr)
+ # Without this the placeholder audio stream reaches the video prediction through
+ # audio_to_video_attn and the LoRA regresses against noise-contaminated targets.
+ assert tr.kwargs["isolate_modalities"] is True
+
+
+def test_forward_passes_the_unscaled_timestep(patched_pack):
+ # LTX-2's config carries timestep_scale_multiplier = 1000 and its pipeline feeds the
+ # scheduler timestep through as-is, unlike the FLUX / Qwen families' timestep / 1000.
+ tr = _RecordingTransformer()
+ _run_forward(tr, sigma = 0.5)
+ assert float(tr.kwargs["timestep"][0]) == pytest.approx(500.0)
+ # sigma rides the same tensor (what LTX-2.3 uses for prompt cross-attn modulation).
+ assert torch.equal(tr.kwargs["sigma"], tr.kwargs["timestep"])
+
+
+def test_forward_sizes_the_audio_stream_from_the_latent_frames(patched_pack):
+ tr = _RecordingTransformer()
+ # 1 latent frame -> 1 pixel frame at temporal compression 8 -> 1 audio token.
+ _run_forward(tr, f = 1)
+ assert tr.kwargs["audio_hidden_states"].shape == (1, 1, 128)
+ assert tr.kwargs["audio_num_frames"] == 1
+ # 4 latent frames -> (4 - 1) * 8 + 1 = 25 pixel frames -> 26 audio tokens.
+ _run_forward(tr, f = 4)
+ assert tr.kwargs["audio_hidden_states"].shape == (1, 26, 128)
+ assert tr.kwargs["audio_num_frames"] == 26
+
+
+def test_forward_reports_the_latent_geometry_and_fps(patched_pack):
+ tr = _RecordingTransformer()
+ _run_forward(tr, f = 1, h = 4, w = 6)
+ assert (tr.kwargs["num_frames"], tr.kwargs["height"], tr.kwargs["width"]) == (1, 4, 6)
+ # LTX-2's temporal RoPE coordinate is in SECONDS (frame index / fps), so the fps a still
+ # is trained at decides where on the temporal axis it lands.
+ assert tr.kwargs["fps"] == _LTX2_TRAIN_FPS == 24.0
+
+
+def test_forward_feeds_the_separate_video_and_audio_text_streams(patched_pack):
+ tr = _RecordingTransformer()
+ noisy = torch.randn(1, 8, 1, 4, 4)
+ sigmas = torch.full((1,), 0.5).view(1, 1, 1, 1, 1)
+ video_emb, audio_emb = torch.randn(1, 6, 3840), torch.randn(1, 6, 3840)
+ mask = torch.ones(1, 6, dtype = torch.int64)
+ _ltx2_forward(
+ tr,
+ noisy,
+ torch.full((1,), 500.0),
+ sigmas,
+ (video_emb, audio_emb, mask),
+ None,
+ "cpu",
+ torch.float32,
+ )
+ # The connector emits a DIFFERENT projection per modality; swapping them silently
+ # conditions the video stream on the audio caption embedding.
+ assert torch.equal(tr.kwargs["encoder_hidden_states"], video_emb)
+ assert torch.equal(tr.kwargs["audio_encoder_hidden_states"], audio_emb)
+ assert torch.equal(tr.kwargs["encoder_attention_mask"], mask)
+
+
+# ── latents + collation ──────────────────────────────────────────────────────
+class _FakeDist:
+ def __init__(self, mean, std):
+ self.mean, self.std = mean, std
+
+ def sample(self):
+ return self.mean
+
+
+class _FakeVae:
+ """Mimics AutoencoderKLLTX2Video: per-channel latents_mean / latents_std buffers plus a
+ scaling_factor, and a 5-D encode."""
+
+ def __init__(
+ self,
+ channels = 4,
+ scaling_factor = 1.0,
+ ):
+ self.latents_mean = torch.arange(channels, dtype = torch.float32)
+ self.latents_std = torch.full((channels,), 2.0)
+ self.config = types.SimpleNamespace(scaling_factor = scaling_factor)
+ self.seen = None
+
+ def encode(self, px):
+ self.seen = px.shape
+ b, _c, f, h, w = px.shape
+ ch = self.latents_mean.numel()
+ mean = torch.ones(b, ch, f, h // 2, w // 2) * 3.0
+ std = torch.ones(b, ch, f, h // 2, w // 2) * 5.0
+ return types.SimpleNamespace(latent_dist = _FakeDist(mean, std))
+
+
+def test_encode_latents_adds_a_temporal_axis_and_normalises_per_channel():
+ vae = _FakeVae()
+ out = _ltx2_encode_latents(vae, torch.zeros(1, 3, 8, 8))
+ # A still must reach the video VAE as a 1-frame clip, not as a 4-D image tensor.
+ assert vae.seen == (1, 3, 1, 8, 8)
+ expected = (3.0 - torch.arange(4, dtype = torch.float32)) / 2.0
+ assert torch.allclose(out[0, :, 0, 0, 0], expected)
+
+
+def test_encode_latent_stats_returns_the_posterior_affine_pair():
+ vae = _FakeVae()
+ a, b = _ltx2_encode_latent_stats(vae, torch.zeros(1, 3, 8, 8))
+ # The cache holds (A, B) so a per-step draw is A + B * randn; B must be the SCALED std,
+ # not the raw one, or every cached sample is drawn at the wrong width.
+ assert torch.allclose(a[0, :, 0, 0, 0], (3.0 - torch.arange(4, dtype = torch.float32)) / 2.0)
+ assert torch.allclose(b[0, :, 0, 0, 0], torch.full((4,), 5.0 / 2.0))
+
+
+def test_latent_normalisation_honours_the_scaling_factor():
+ # scaling_factor is 1.0 on the shipped checkpoint, so a version that dropped it would
+ # still pass every other test here.
+ plain = _ltx2_encode_latents(_FakeVae(scaling_factor = 1.0), torch.zeros(1, 3, 8, 8))
+ scaled = _ltx2_encode_latents(_FakeVae(scaling_factor = 2.0), torch.zeros(1, 3, 8, 8))
+ assert torch.allclose(scaled, plain * 2.0)
+
+
+def test_collate_batches_the_three_connector_tensors():
+ entries = [
+ (torch.zeros(1, 4, 8), torch.ones(1, 4, 8), torch.ones(1, 4, dtype = torch.int64)),
+ (torch.ones(1, 4, 8), torch.zeros(1, 4, 8), torch.zeros(1, 4, dtype = torch.int64)),
+ ]
+ video, audio, mask = _ltx2_collate(entries, "cpu", torch.float32)
+ assert video.shape == audio.shape == (2, 4, 8)
+ assert mask.shape == (2, 4)
+ # Order matters: entry 0's VIDEO embed is zeros and its AUDIO embed is ones.
+ assert float(video[0].sum()) == 0.0 and float(audio[0].sum()) == 32.0
+ assert float(video[1].sum()) == 32.0 and float(audio[1].sum()) == 0.0
+
+
+# ── memory: the LTX-2-only conditioning modules ──────────────────────────────
+def test_free_text_encoders_drops_the_ltx2_conditioning_stack():
+ pipe = types.SimpleNamespace(
+ text_encoder = object(),
+ tokenizer = object(),
+ # ~2.7 GB of connectors plus the decode-side audio modules the trainer never uses.
+ connectors = object(),
+ audio_vae = object(),
+ vocoder = object(),
+ transformer = object(),
+ vae = object(),
+ )
+ _free_text_encoders(pipe)
+ assert pipe.text_encoder is None and pipe.tokenizer is None
+ assert pipe.connectors is None and pipe.audio_vae is None and pipe.vocoder is None
+ # The VAE is freed separately (only once the latent cache is built), and the transformer
+ # is the thing being trained.
+ assert pipe.vae is not None and pipe.transformer is not None
+
+
+# ── routing, defaults, validation ────────────────────────────────────────────
+ "base",
+ ["Lightricks/LTX-2", "lightricks/ltx-2", "/data/models/ltx-2"],
+)
+def test_ltx2_bases_route_to_the_ltx2_trainer(base):
+ assert resolve_trainable_family(base) == "ltx-2"
+
+
+ "base, family",
+ [
+ ("Wan-AI/Wan2.2-TI2V-5B-Diffusers", "wan2.2-ti2v-5b"),
+ ("Wan-AI/Wan2.2-T2V-A14B-Diffusers", "wan2.2-t2v-a14b"),
+ ("hunyuanvideo-community/HunyuanVideo-1.5-Diffusers-480p_t2v", "hunyuanvideo-1.5"),
+ ],
+)
+def test_video_families_without_a_spec_are_refused_by_name(base, family):
+ # Before this gate these fell through to the unknown-name fallback and were handed to
+ # the SDXL trainer, which then failed deep inside from_pretrained.
+ with pytest.raises(ValueError) as exc:
+ resolve_trainable_family(base)
+ message = str(exc.value)
+ assert family in message
+ assert "video" in message.lower()
+ # The refusal must name what DOES work, or it is a dead end.
+ assert "ltx-2" in message
+
+
+def test_explicit_video_model_family_override_is_honoured_and_gated():
+ # An opaque local path plus an explicit family is the documented way to train from a
+ # local checkout, so the override path needs the same video routing as detection.
+ assert resolve_trainable_family("/tmp/some-local-checkout", "ltx-2") == "ltx-2"
+ with pytest.raises(ValueError, match = "wan2.2-ti2v-5b"):
+ resolve_trainable_family("/tmp/some-local-checkout", "wan2.2-ti2v-5b")
+
+
+def test_unknown_model_family_lists_the_video_families_too():
+ with pytest.raises(ValueError) as exc:
+ resolve_trainable_family("x", "not-a-real-family")
+ assert "ltx-2" in str(exc.value)
+
+
+def test_ltx2_official_base_passes_the_trusted_base_gate():
+ # It is a VIDEO base, so the image-side inference allowlist never covered it.
+ _assert_trusted_base_model("Lightricks/LTX-2")
+ with pytest.raises(ValueError, match = "untrusted"):
+ _assert_trusted_base_model("random-user/ltx-2-finetune")
+
+
+def test_ltx2_defaults_follow_the_upstream_lora_configs():
+ defaults = train_defaults("ltx-2")
+ # Lightricks ship rank/alpha 32 at lr 1e-4 in every LTX-2 LoRA config.
+ assert defaults["lora_rank"] == 32
+ assert defaults["learning_rate"] == pytest.approx(1e-4)
+ # The VAE compresses space by 32, so the default resolution must sit on that grid.
+ assert defaults["resolution"] % 32 == 0
+
+
+def test_ltx2_has_a_vram_row():
+ note = _family_vram_note("ltx-2")
+ assert "19B" in note and "GB" in note
+
+
[email protected]("resolution, ok", [(512, True), (768, True), (520, False), (528, False)])
+def test_video_resolution_must_sit_on_the_vae_grid(resolution, ok):
+ def build():
+ return DiffusionLoraConfig(
+ base_model = "Lightricks/LTX-2",
+ data_dir = "d",
+ output_dir = "o",
+ resolution = resolution,
+ ).normalized()
+
+ if ok:
+ assert build().resolution == resolution
+ else:
+ with pytest.raises(ValueError, match = "multiple of 32"):
+ build()
+
+
+def test_image_families_keep_the_multiple_of_8_rule():
+ # The /32 rule is video-only; an image family at 520px must still be accepted.
+ cfg = DiffusionLoraConfig(
+ base_model = "Tongyi-MAI/Z-Image-Turbo",
+ data_dir = "d",
+ output_dir = "o",
+ resolution = 520,
+ ).normalized()
+ assert cfg.resolution == 520
+
+
+def test_ltx2_flow_shift_defaults_to_auto():
+ # LTX-2's scheduler sets use_dynamic_shifting, so scheduler.sigmas is the UNSHIFTED
+ # uniform table; training on it would draw a sigma distribution inference never uses.
+ assert "ltx-2" in AUTO_FLOW_SHIFT_FAMILIES
+ cfg = DiffusionLoraConfig(
+ base_model = "Lightricks/LTX-2", data_dir = "d", output_dir = "o"
+ ).normalized()
+ assert cfg.flow_shift == "auto"
+ # ...while the identity families are untouched.
+ flux = DiffusionLoraConfig(
+ base_model = "black-forest-labs/FLUX.1-dev", data_dir = "d", output_dir = "o"
+ ).normalized()
+ assert flux.flow_shift == 1.0
+
+
+def test_ltx2_rejects_fp16_before_loading():
+ with pytest.raises(ValueError, match = "bf16"):
+ DiffusionLoraConfig(
+ base_model = "Lightricks/LTX-2",
+ data_dir = "d",
+ output_dir = "o",
+ mixed_precision = "fp16",
+ ).normalized()
+
+
+# ── deployment surface, environment + component-repo preflight ───────────────
+def _run_cfg(base_model: str, tmp_path) -> DiffusionLoraConfig:
+ return DiffusionLoraConfig(
+ base_model = base_model,
+ data_dir = str(tmp_path / "data"),
+ output_dir = str(tmp_path / "run"),
+ adapter_name = "myrun",
+ ).normalized()
+
+
+def test_a_video_run_publishes_no_adapter_into_the_image_lora_catalog(tmp_path, monkeypatch):
+ # loras/diffusion is scanned by the Images LoRA picker alone, and core/inference/video.py has
+ # no LoRA surface at all, so mirroring a video adapter there copies a large file into a
+ # catalog nothing can load and reports a catalog_path Studio cannot deploy.
+ from pathlib import Path
+
+ catalog = tmp_path / "loras" / "diffusion"
+ catalog.mkdir(parents = True)
+ monkeypatch.setattr("core.inference.diffusion_lora.loras_dir", lambda: catalog)
+ adapter = tmp_path / "run" / DEFAULT_LORA_FILENAME
+ adapter.parent.mkdir(parents = True, exist_ok = True)
+ adapter.write_bytes(b"adapter-bytes")
+
+ video = _run_cfg("Lightricks/LTX-2", tmp_path)
+ assert video.resolved_family == "ltx-2"
+ assert _publish_to_lora_catalog(str(adapter), video) is None
+ assert list(catalog.iterdir()) == [] # not even the metadata sidecar
+
+ # The image families are untouched: an SDXL run still mirrors + reports its catalog path.
+ image = _run_cfg("stabilityai/stable-diffusion-xl-base-1.0", tmp_path)
+ published = _publish_to_lora_catalog(str(adapter), image)
+ assert published is not None
+ assert Path(published).is_file() and Path(published).parent == catalog
+
+
+def test_ltx2_preflight_refuses_a_diffusers_without_the_pipeline(monkeypatch):
+ # LTX2Pipeline is a diffusers 0.37.0 export, and pyproject deliberately keeps an older
+ # diffusers installable on the Python 3.9 hosts this project still supports (0.36.0 is the
+ # newest one such a host can resolve). The inference paths assert this before a load; the
+ # training preflight has to as well, or the family resolves, /diffusion/start frees the
+ # resident GPU workloads, and only the child finds out. Same refusal whether the family is
+ # detected or named.
+ monkeypatch.setitem(sys.modules, "diffusers", types.SimpleNamespace(__version__ = "0.36.0"))
+ for base, family in (("Lightricks/LTX-2", None), ("/data/models/anything", "ltx-2")):
+ with pytest.raises(ValueError) as exc:
+ resolve_trainable_family(base, family)
+ message = str(exc.value)
+ assert "LTX2Pipeline" in message
+ # The floor LTX-2 actually needs, not the packaging floor, and what is installed.
+ assert "0.37.0" in message and "0.36.0" in message
+
+ # A diffusers that HAS the pipeline resolves as before, so the gate is the class, not the stub.
+ monkeypatch.setitem(
+ sys.modules,
+ "diffusers",
+ types.SimpleNamespace(__version__ = "0.39.0", LTX2Pipeline = object()),
+ )
+ assert resolve_trainable_family("Lightricks/LTX-2") == "ltx-2"
+
+
+def test_a_component_repo_is_refused_as_a_training_base():
+ # unsloth/LTX-2-FP8 holds pre-cast component archives: no model_index.json, no VAE, no
+ # pipeline. It still carries the "ltx-2" token, so the family detector claimed it and the
+ # unsloth/* trust gate passed it, and the gated-access probe ignores the model_index.json 404
+ # because a 404 is not an access problem -- so the run evicted the resident models and only
+ # then failed inside LTX2Pipeline.from_pretrained.
+ catalogued = _component_only_repos()
+ assert catalogued["unsloth/ltx-2-fp8"] == ("ltx-2", "text_encoder", "Lightricks/LTX-2")
+ for base, family in (("unsloth/LTX-2-FP8", None), ("unsloth/LTX-2-FP8", "ltx-2")):
+ with pytest.raises(ValueError) as exc:
+ resolve_trainable_family(base, family)
+ message = str(exc.value)
+ assert "model_index.json" in message # says WHY it cannot be a base
+ assert "Lightricks/LTX-2" in message # and names what to train instead
+
+
+def test_the_component_rule_reads_the_registry_rather_than_a_repo_blocklist():
+ # The rule is "registered only as a component, never as a base". The image FP8 repos are
+ # listed in prequant_repos (a full-model mirror) as well as te_prequant_repos, so they are
+ # bases and must keep resolving exactly as before.
+ assert "unsloth/qwen-image-fp8" not in _component_only_repos()
+ assert resolve_trainable_family("unsloth/Qwen-Image-FP8") == "qwen-image"
+ # An official base is never a component, whichever registry it comes from.
+ assert "lightricks/ltx-2" not in _component_only_repos()
+
+
+def test_the_preflight_survives_a_diffusers_that_cannot_import_its_pipeline(monkeypatch):
+ # The pipeline gate must refuse an OLD diffusers and stay silent on a BROKEN one. diffusers'
+ # top level is lazy, so the attribute probe is what imports the pipeline's submodule, and an
+ # install whose own dependencies are unsatisfiable raises RuntimeError from there rather than
+ # reporting the class missing. That is not the ValueError the start route maps to 400, so it
+ # would leave the preflight as a bare 500. Nothing here is a version judgement: let the load
+ # fail later with its own message.
+ class _LazyModule(types.ModuleType):
+ __version__ = "0.40.0"
+
+ def __getattr__(self, name):
+ raise RuntimeError(f"Failed to import diffusers.pipelines.{name.lower()}")
+
+ monkeypatch.setitem(sys.modules, "diffusers", _LazyModule("diffusers"))
+ assert resolve_trainable_family("Lightricks/LTX-2") == "ltx-2"
+
+
+# -- int8, the trust gate, and the connector padding side ---------------------
+
+
+def test_int8_excludes_the_one_token_audio_stream():
+ """A still feeds a ONE-token audio stream, and torch._int_mm needs M > 16. Without an
+ LTX-2 entry the generic int8 path quantized audio_proj_in / audio_attn* / audio_ff and the
+ first forward raised, after the whole base had been loaded."""
+ from core.inference.diffusion_transformer_quant import exclude_tokens_for_scheme
+
+ tokens = exclude_tokens_for_scheme("int8", "ltx-2")
+ assert "audio" in tokens and "av_cross_attn" in tokens and "adaln" in tokens
+ # The generic list is still there (the M=1 modulation projections).
+ assert "norm" in tokens and "time_embed" in tokens
+ # 2.3 is the same audiovisual DiT.
+ assert "audio" in exclude_tokens_for_scheme("int8", "ltx-2.3")
+ # An image family is unchanged, and a non-int8 scheme still excludes nothing.
+ assert "audio" not in exclude_tokens_for_scheme("int8", "flux.1")
+ assert exclude_tokens_for_scheme("fp8", "ltx-2") == ()
+
+
+def test_the_int8_filter_actually_skips_every_audio_side_linear():
+ """The token list is only useful if the shared filter drops these modules."""
+ from core.inference.diffusion_transformer_quant import exclude_tokens_for_scheme, make_filter_fn
+
+ fn = make_filter_fn(512, exclude_name_tokens = exclude_tokens_for_scheme("int8", "ltx-2"))
+ big = torch.nn.Linear(2048, 2048)
+ audio_names = (
+ "transformer_blocks.0.audio_proj_in",
+ "transformer_blocks.0.audio_attn1.to_q",
+ "transformer_blocks.0.audio_attn2.to_k",
+ "transformer_blocks.0.audio_ff.net.0.proj",
+ "transformer_blocks.0.audio_to_video_attn.to_q",
+ "transformer_blocks.0.video_to_audio_attn.to_k",
+ )
+ modulation_names = (
+ # LTX2AdaLayerNormSingle projections: Linear over a BATCH-sized input, so M = batch = 1.
+ # Nothing in these names says "audio", and none matches a generic token.
+ "av_cross_attn_video_scale_shift.linear",
+ "av_cross_attn_video_a2v_gate.linear",
+ "av_cross_attn_audio_scale_shift.linear",
+ "av_cross_attn_audio_v2a_gate.linear",
+ "prompt_adaln.linear",
+ "audio_prompt_adaln.linear",
+ )
+ for name in audio_names + modulation_names:
+ assert fn(big, name) is False, f"{name} must stay dense"
+ # The video stream keeps full int8 coverage.
+ assert fn(big, "transformer_blocks.0.attn1.to_q") is True
+ assert fn(big, "transformer_blocks.0.ff.net.0.proj") is True
+
+
+def test_the_int8_trainer_path_passes_the_family_through(monkeypatch):
+ """The exclusions only apply if the trainer asks for them by family."""
+ seen: dict = {}
+
+ def _fake_quantize(
+ model,
+ config,
+ filter_fn = None,
+ ):
+ seen["filter_fn"] = filter_fn
+
+ fake = types.ModuleType("torchao.quantization")
+ fake.Int8WeightOnlyConfig = lambda: object()
+ fake.quantize_ = _fake_quantize
+ monkeypatch.setitem(sys.modules, "torchao", types.ModuleType("torchao"))
+ monkeypatch.setitem(sys.modules, "torchao.quantization", fake)
+
+ dit._int8_quantize_base(torch.nn.Linear(8, 8), "ltx-2")
+ big = torch.nn.Linear(2048, 2048)
+ assert seen["filter_fn"](big, "transformer_blocks.0.audio_attn1.to_q") is False
+
+
+def test_ltx23_is_refused_as_a_training_base_with_the_real_reason():
+ """Lightricks/LTX-2.3 ships single-file checkpoints and no diffusers layout (no
+ model_index.json, no transformer/ subfolder), so LTX2Pipeline.from_pretrained cannot open it.
+ The name still resolves to the ltx-2 family, so it has to be refused explicitly -- in preflight,
+ before the run evicts the user's resident models."""
+ from core.training.diffusion_train_common import _assert_trusted_base_model
+
+ _assert_trusted_base_model("Lightricks/LTX-2")
+ for repo in ("Lightricks/LTX-2.3", "lightricks/ltx-2.3", "Lightricks/LTX-2.3-fp8"):
+ with pytest.raises(ValueError) as exc:
+ resolve_trainable_family(repo)
+ message = str(exc.value)
+ assert "single-file" in message and "Lightricks/LTX-2" in message
+ assert "untrusted" not in message
+ # An unrelated repo is still refused by the trust gate.
+ with pytest.raises(ValueError):
+ _assert_trusted_base_model("some-random-user/ltx-2-clone")
+
+
+def test_the_connector_padding_side_is_read_after_encode_prompt():
+ """diffusers' own encode_prompt sets tokenizer.padding_side = "left" (Gemma wants left
+ padding), and the pipeline reads the value AFTER calling it. Reading it before baked in a
+ stale "right", and the connectors build the valid-token mask from it, so every caption
+ shorter than the 1024 pad length would have been masked on the wrong end."""
+ seen: list = []
+
+ class _Tok:
+ padding_side = "right" # what the tokenizer reports before encode_prompt runs
+
+ class _Pipe:
+ tokenizer = _Tok()
+
+ def encode_prompt(self, **_kwargs):
+ # Exactly what diffusers does inside _get_gemma_prompt_embeds.
+ self.tokenizer.padding_side = "left"
+ return torch.zeros(1, 4, 8), torch.ones(1, 4), None, None
+
+ def connectors(
+ self,
+ pe,
+ mask,
+ padding_side = "left",
+ ):
+ seen.append(padding_side)
+ return torch.zeros(1, 4, 8), torch.zeros(1, 4, 8), torch.ones(1, 4)
+
+ dit._ltx2_encode_prompts(_Pipe(), ["a sloth", "a second caption"], "cpu")
+ assert seen == ["left", "left"], "the connectors must get the side encode_prompt actually used"
+
+
+# ── the Train tab has to be able to OFFER the family ──────────────────────────
+
+
+def test_family_train_infos_offers_the_video_family(dit_train_host):
+ """The gap this closes: everything below the API accepted ltx-2 -- the trainer, the preflight,
+ /diffusion/start -- but ``/api/train/diffusion/info`` is built from the IMAGE registry alone,
+ so the family never appeared in the Train tab and the whole path was unreachable from the UI.
+ """
+ from core.training.diffusion_train_common import family_train_infos
+
+ infos = {i["name"]: i for i in family_train_infos()}
+ assert "ltx-2" in infos, "a trainable video family must be offered by /diffusion/info"
+ info = infos["ltx-2"]
+ # A video family has no train_base_repos, so its own base repo is the training base.
+ assert info["default_base"] == "Lightricks/LTX-2"
+ assert info["base_repos"] == ["Lightricks/LTX-2"]
+ assert info["label"] == "LTX-2"
+ assert info["defaults"]["resolution"] % 32 == 0 # the VAE's spatial grid
+ # No image LoRA catalog entry for a video run, so nothing to deploy to Create.
+ assert info["deploy_base"] is None
+ # Still a DiT, so it keeps the base_precision selector every other DiT family has.
+ assert "nf4" in info["precision_modes"]
+ # The image families must be untouched by the union.
+ assert "sdxl" in infos and "flux.1" in infos
+
+
+def test_family_train_infos_drops_a_family_this_diffusers_cannot_run(monkeypatch, dit_train_host):
+ """A family whose pipeline class is missing can only 400 at /diffusion/start, and no choice in
+ the UI fixes it, so it must not be offered at all."""
+ import core.training.diffusion_train_common as dtc
+
+ monkeypatch.setattr(
+ dtc, "family_pipeline_available", lambda fam: fam.name != "ltx-2", raising = False
+ )
+ monkeypatch.setattr(
+ "core.inference.diffusion_families.family_pipeline_available",
+ lambda fam: getattr(fam, "name", "") != "ltx-2",
+ )
+ names = {i["name"] for i in dtc.family_train_infos()}
+ assert "ltx-2" not in names
+ assert "sdxl" in names # only the unavailable one goes
+
+
+def test_the_strict_pipeline_gate_resolves_a_video_family_too(monkeypatch):
+ """``training_pipeline_import_error`` resolved the family name through the image registry only,
+ so it returned None for ltx-2 and the strict half of the preflight was skipped: the failure
+ then landed in the spawned child, after the resident GPU models were already freed."""
+ from core.training.diffusion_train_common import training_pipeline_import_error
+
+ monkeypatch.setitem(sys.modules, "diffusers", types.SimpleNamespace(__version__ = "0.36.0"))
+ reason = training_pipeline_import_error("ltx-2")
+ assert reason and "LTX2Pipeline" in reason
+
+ healthy = types.SimpleNamespace(__version__ = "0.39.0", LTX2Pipeline = object)
+ monkeypatch.setitem(sys.modules, "diffusers", healthy)
+ assert training_pipeline_import_error("ltx-2") is None
+
+
+def test_editing_the_connectors_invalidates_the_conditioning_cache(tmp_path):
+ """Only the connector OUTPUT is cached (the Gemma3 hidden states are per-layer stacked and
+ never reach the transformer), so replacing the connector weights in place changes what a warm
+ run should encode. The fingerprint scanned text_encoder*/tokenizer*/vae* only, so it did not
+ move and the warm run trained on embeddings from the old connectors."""
+ from core.training.diffusion_train_extras import source_revision
+
+ root = tmp_path / "LTX-2"
+ for sub in ("text_encoder", "tokenizer", "vae", "connectors"):
+ (root / sub).mkdir(parents = True)
+ (root / sub / "model.safetensors").write_bytes(b"v1")
+ (root / "model_index.json").write_text("{}")
+
+ before = source_revision(str(root))
+ assert source_revision(str(root)) == before # stable while nothing changes
+
+ (root / "connectors" / "model.safetensors").write_bytes(b"v2-different-size")
+ assert source_revision(str(root)) != before
+
+
+def test_an_unrelated_subdirectory_is_still_ignored(tmp_path):
+ """The fingerprint stays cheap: only the components the cached tensors come from are hashed,
+ so a scheduler or transformer edit (which the cache does not depend on) must not invalidate it.
+ """
+ from core.training.diffusion_train_extras import source_revision
+
+ root = tmp_path / "LTX-2"
+ (root / "connectors").mkdir(parents = True)
+ (root / "connectors" / "model.safetensors").write_bytes(b"v1")
+ (root / "transformer").mkdir()
+ (root / "transformer" / "model.safetensors").write_bytes(b"dit")
+
+ before = source_revision(str(root))
+ (root / "transformer" / "model.safetensors").write_bytes(b"a-different-dit-entirely")
+ assert source_revision(str(root)) == before
diff --git a/studio/backend/tests/test_diffusion_training.py b/studio/backend/tests/test_diffusion_training.py
index 24c9cee9fc5..a4b0c518384 100644
--- a/studio/backend/tests/test_diffusion_training.py
+++ b/studio/backend/tests/test_diffusion_training.py
@@ -1708,6 +1708,50 @@ def test_a_dummy_pipeline_export_is_not_treated_as_importable():
assert "missing: torch" not in msg and "pip install -U torch" not in msg
+def test_route_start_refuses_ltx2_without_the_pipeline_before_freeing_gpu(client, monkeypatch):
+ # The video half of the same gate: LTX2Pipeline is a diffusers 0.37 export, and the packaging
+ # deliberately leaves an older diffusers installable on the Python 3.9 hosts this project still
+ # supports. Without the pipeline-class assert in the training preflight the family resolved as
+ # trainable, the start freed the resident GPU workloads, and only the spawned child failed.
+ # LTX-2 lives in the VIDEO registry, so it reaches the gate by a different branch of
+ # resolve_trainable_family than any image family above.
+ import sys
+
+ import routes.training as tr
+
+ freed = []
+ monkeypatch.setattr(tr, "_free_gpu_for_diffusion_training", lambda: freed.append(1))
+ monkeypatch.setitem(sys.modules, "diffusers", _fake_diffusers("0.36.0"))
+
+ r = client.post("/api/train/diffusion/start", json = {**_BODY, "base_model": "Lightricks/LTX-2"})
+ assert r.status_code == 400, r.text
+ assert "LTX2Pipeline" in r.json()["detail"]
+ assert freed == []
+ assert client._fake.calls == [] # the slot was never even reserved
+ assert client._fake.started_with is None
+
+
+def test_route_start_refuses_a_component_repo_before_freeing_gpu(client, monkeypatch):
+ # unsloth/LTX-2-FP8 holds pre-cast component archives, not a pipeline: no model_index.json,
+ # no VAE. The name still carries the "ltx-2" token so the family detector claimed it, the
+ # unsloth/* trust gate passed it, and the gated-access probe ignores the model_index.json 404
+ # (a 404 is not an access problem) -- so the start evicted the resident models and only then
+ # failed inside from_pretrained.
+ import routes.training as tr
+
+ freed = []
+ monkeypatch.setattr(tr, "_free_gpu_for_diffusion_training", lambda: freed.append(1))
+
+ r = client.post("/api/train/diffusion/start", json = {**_BODY, "base_model": "unsloth/LTX-2-FP8"})
+ assert r.status_code == 400, r.text
+ detail = r.json()["detail"]
+ assert "model_index.json" in detail # says why it cannot be a base
+ assert "Lightricks/LTX-2" in detail # and names what to train instead
+ assert freed == []
+ assert client._fake.calls == []
+ assert client._fake.started_with is None
+
+
def test_route_start_refuses_non_bf16_gpu_without_freeing_gpu(client, monkeypatch):
# A DiT precision the host cannot run must 400 BEFORE the GPU residents are freed. The route imports the helper locally, so patch its home module.
import routes.training as tr
diff --git a/studio/backend/tests/test_diffusion_transformer_quant.py b/studio/backend/tests/test_diffusion_transformer_quant.py
index c5f8cbbc96f..203e3c08621 100644
--- a/studio/backend/tests/test_diffusion_transformer_quant.py
+++ b/studio/backend/tests/test_diffusion_transformer_quant.py
@@ -836,7 +836,11 @@ def test_the_attention_trim_families_exclude_their_small_m_text_streams():
from core.inference.diffusion_transformer_quant import _INT8_EXCLUDE_NAME_TOKENS
assert exclude_tokens_for_scheme("fp8", "hunyuanvideo-1.5") == ()
- assert exclude_tokens_for_scheme(TQ_INT8, "ltx-2") == _INT8_EXCLUDE_NAME_TOKENS
+ # flux.1 stands in for the unrelated family here. ltx-2 no longer can: it is audiovisual, and
+ # a video-only run feeds a one-token audio stream that hits the same M floor, so it now carries
+ # its own audio exclusions.
+ assert exclude_tokens_for_scheme(TQ_INT8, "flux.1") == _INT8_EXCLUDE_NAME_TOKENS
+ assert exclude_tokens_for_scheme(TQ_INT8, None) == _INT8_EXCLUDE_NAME_TOKENS
def test_the_training_deny_is_a_superset_of_the_inference_deny():
diff --git a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
index c0e5e80e452..c5fd1f88438 100644
--- a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
+++ b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
@@ -2042,7 +2042,14 @@ export function DiffusionTrainPanel({
{completed
? "Trained"
: "Stopped early; the adapter as of the last finished step was saved"}
- {status?.family ? ` (${status.family})` : ""} and added to the LoRA picker.
+ {status?.family ? ` (${status.family})` : ""}
+ {/* The LoRA picker and Deploy to Create are the Images surface, and only an
+ adapter published into the diffusion LoRA catalog reaches them. A family
+ trained here without that catalog (video) still saves a loadable adapter,
+ so report the file and claim nothing more. */}
+ {status?.catalog_path
+ ? " and added to the LoRA picker."
+ : ". Load it from the path below."}
{status?.lora_path && (
<span className="mt-1 block break-all">Saved: {status.lora_path}</span>
)}
@@ -2051,9 +2058,12 @@ export function DiffusionTrainPanel({
)}
</p>
<div className="mt-1 flex flex-wrap gap-2">
- <Button type="button" size="sm" onClick={onDeployClick}>
- Deploy to Create
- </Button>
+ {/* A video run publishes no catalog entry, so there is nothing to deploy. */}
+ {status?.catalog_path && (
+ <Button type="button" size="sm" onClick={onDeployClick}>
+ Deploy to Create
+ </Button>
+ )}
{/* Only a run stopped short can be continued; a completed one is already at its
target. Disabled until the run record lands (and enabled only if its
checkpoint really is on disk), with the backend's reason as the tooltip. */}