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: MiniMax-H3 joint video and audio LoRA training (#8244)

Daniel Hanae09aa86fbda
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 5fd79ab39bd..887abeb3547 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -532,7 +532,7 @@ def _is_trusted_diffusion_repo(repo_id: str) -> bool:
return rid.startswith("unsloth/") or rid in _TRUSTED_NON_GGUF_REPOS
-def _assert_local_base_is_pipeline(base_repo: str) -> None:
+def _assert_local_base_is_pipeline(base_repo: str, *, allow_modular: bool = False) -> None:
"""A companion ``base_repo`` fed to ``from_pretrained(base)`` (or ``config=base``) must be a
diffusers PIPELINE directory (has ``model_index.json``). ``_is_trusted_diffusion_repo`` accepts
ANY existing local path, so without this a local base that is not a pipeline dir would pass the
@@ -541,7 +541,14 @@ def _assert_local_base_is_pipeline(base_repo: str) -> None:
by the trust check (it is neither an existing path nor an unsloth/*/allowlisted repo); a bare
remote id is left for the loader to resolve. Shared by the image, video, and training preflights
so their local-base shape check stays in sync. Never evicts; raises ValueError on a bad local
- base."""
+ base.
+
+ ``allow_modular`` accepts ``modular_model_index.json`` as well, for a caller whose loader is
+ ``ModularPipeline.from_pretrained``: that IS the valid on-disk layout for a Modular Diffusers
+ pipeline (MiniMax-H3 ships no ``model_index.json`` at all), and the local-model scanners
+ already count either index. Off by default -- a conventional ``DiffusionPipeline`` load still
+ needs the conventional index, and accepting a modular directory there would only move the
+ failure back into the loader."""
base = (base_repo or "").strip()
if not base:
return
@@ -552,9 +559,13 @@ def _assert_local_base_is_pipeline(base_repo: str) -> None:
return # invalid path characters -> a remote id, not a local path
if not exists:
return
- if not root.is_dir() or not (root / "model_index.json").is_file():
+ indexes = ["model_index.json"]
+ if allow_modular:
+ indexes.append("modular_model_index.json")
+ if not root.is_dir() or not any((root / name).is_file() for name in indexes):
raise ValueError(
- f"Local base_repo is not a diffusers pipeline directory (no model_index.json): {base}"
+ f"Local base_repo is not a diffusers pipeline directory "
+ f"(no {' or '.join(indexes)}): {base}"
)
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index 5f6d59f33e4..4c8753e0898 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -1084,6 +1084,21 @@ def assert_pipeline_class_available(
)
+def family_probe_class(fam: Any) -> str:
+ """The class whose presence in the installed diffusers actually proves ``fam`` is loadable.
+
+ Normally that is ``fam.pipeline_class``. ``ModularPipeline`` is the exception: it is the
+ generic entry point for every Modular Diffusers workflow, not a family, and it has existed for
+ several releases, so a diffusers that predates MiniMax-H3's own blocks still answers hasattr
+ for it. Probe the family's own transformer class there instead, which is the thing the load
+ actually needs. Shared by the listing probe and by both training gates so a family cannot be
+ hidden from the picker and simultaneously accepted by /diffusion/start."""
+ name = str(getattr(fam, "pipeline_class", "") or "")
+ if name == "ModularPipeline":
+ return str(getattr(fam, "transformer_class", None) or name)
+ return name
+
+
def family_pipeline_available(fam: Optional[DiffusionFamily]) -> bool:
"""True when the installed diffusers actually has this family's pipeline class.
@@ -1099,9 +1114,18 @@ def family_pipeline_available(fam: Optional[DiffusionFamily]) -> bool:
lookup imports that pipeline module and can raise something other than AttributeError."""
if fam is None:
return False
+ # A modular family is judged on its own transformer class, not on the generic
+ # ``ModularPipeline`` entry point -- see ``family_probe_class``.
+ name = family_probe_class(fam)
+ # No class name to probe means the record is not one this helper can judge, which is the same
+ # position as a missing diffusers: answer OPEN. ``family_probe_class`` reads the attribute with
+ # a default, so a record without ``pipeline_class`` reaches here as "" rather than raising into
+ # the guard below, and ``hasattr(diffusers, "")`` is False -- which would hide the model.
+ if not name:
+ return True
try:
import diffusers
- return hasattr(diffusers, fam.pipeline_class)
+ return hasattr(diffusers, name)
except Exception: # noqa: BLE001 -- no diffusers here: the load path reports it properly
return True
diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.py
index 84579ecc4a5..dfb3a5a91be 100644
--- a/studio/backend/core/inference/diffusion_transformer_quant.py
+++ b/studio/backend/core/inference/diffusion_transformer_quant.py
@@ -248,6 +248,11 @@ _FAMILY_SCHEME_DENY: dict[str, frozenset[str]] = {
_FAMILY_TRAIN_SCHEME_DENY: dict[str, frozenset[str]] = {
"qwen-image": frozenset({TQ_FP8}),
"qwen-image-edit": frozenset({TQ_FP8}),
+ # MiniMax-H3's packed sequence runs three modalities through one set of linears, so its
+ # activation range is not the per-family range the fp8 filter was measured against. The
+ # trainer refuses both outright; declaring it here is what keeps /diffusion/info from
+ # advertising a start that is guaranteed to 400.
+ "minimax-h3": frozenset({TQ_FP8, TQ_MXFP8}),
}
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 89101fade06..de2d897e9b9 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -1234,6 +1234,7 @@ class VideoBackend:
ltx23 = True,
te_sources = te_sources,
skip_transformer_weights = skip_transformer_weights,
+ h3_task = kwargs.get("h3_task"),
h3_te_scheme = h3_te_scheme,
)
with self._lock:
@@ -1976,17 +1977,18 @@ class VideoBackend:
meta-inits the encoder from the base repo's component config;
- the dense weight shards of the denoiser partition this load opens, under
``skip_transformer_weights``, supplied instead by a hosted PRE-QUANTIZED
- denoiser checkpoint (H3's transformer is 66.3 GB of its base repo). The
- partition, not the literal ``transformer/``: a reference load stages
- ``transformer_ref/``, so skipping the other name would skip nothing and
- leave 66.28 GB in a plan the load never opens. The partition's
- ``config.json`` is kept for the same reason the pre-cast encoders keep
- theirs: the pre-quant loader meta-inits the DiT from it, so dropping it
- would break the very load that made the skip safe.
-
- ``h3_task`` picks the H3 denoiser partition. The base repo ships two 66.28 GB partitions and
- a load brings up one: ``transformer/`` for fl2va (which also covers text-only),
- ``transformer_ref/`` for ref2va. The scoped list carries exactly one, never both."""
+ denoiser checkpoint (H3's transformer is 66.3 GB of its base repo).
+ ``transformer/config.json`` is kept for the same reason the pre-cast
+ encoders keep theirs: the pre-quant loader meta-inits the DiT from it,
+ so dropping it would break the very load that made the skip safe.
+
+ ``h3_task`` picks the H3 denoiser partition. The base repo ships two, and a load only ever
+ brings up one: ``transformer/`` for fl2va (which also covers text-only) and
+ ``transformer_ref/`` for ref2va. They are 66.28 GB each, so the scoped list carries exactly
+ one of them, never both. Substituting rather than listing both is what keeps the stage at
+ one denoiser: listing only ``transformer/`` staged the wrong 66.28 GB for a ref2va load and
+ left the right one to be fetched inline, outside the download manager's disk preflight and
+ cancellation."""
from .diffusion_te_prequant import is_prequant_covered_weight
from .video_minimax_h3 import H3_TASK_REFERENCES
@@ -2118,7 +2120,8 @@ class VideoBackend:
``h3_task`` picks which MiniMax-H3 denoiser partition is staged. It was swallowed by
``**load_kwargs`` too, so a ref2va plan staged the fl2va ``transformer/`` and left the
- 66.28 GB ``transformer_ref/`` the load needs to be pulled inline."""
+ 66.28 GB ``transformer_ref/`` the load then needs to be pulled inline, outside the
+ download manager."""
from huggingface_hub import HfApi
fam = _detect_load_family(repo_id, gguf_filename, family_override)
@@ -4219,7 +4222,11 @@ class VideoBackend:
result["mp4_bytes"],
{
"prompt": gen_kwargs["prompt"],
- "negative_prompt": gen_kwargs.get("negative_prompt"),
+ # From the RESULT, not the request, exactly like guidance below: a
+ # guidance-distilled family consumes no negative prompt on either engine, and
+ # persisting the caller's string made the restored recipe claim conditioning
+ # that never reached a sampler.
+ "negative_prompt": result.get("negative_prompt"),
"width": result["width"],
"height": result["height"],
"num_frames": result["num_frames"],
@@ -4357,11 +4364,28 @@ class VideoBackend:
)
steps = int(steps or default_steps)
guidance = float(default_guidance if guidance is None else guidance)
+ # A guidance-free family (supports_cfg=False, MiniMax-H3) forwards no CFG control
+ # to either engine: the diffusers branch below skips the kwarg entirely and the
+ # native branch pins --cfg-scale 1.0. The requested number therefore never reached
+ # a sampler, so recording it would label the clip and its gallery sidecar with a
+ # parameter that did nothing. Normalise to the family default instead of refusing:
+ # the value is inert, and a 422 would break every caller that sends the generic
+ # default. negative_prompt goes the same way and for the same reason: a negative
+ # prompt IS the unconditional branch, so a family without one consumes it on
+ # neither engine (the diffusers call adds the kwarg only when the pipeline
+ # signature has it, which a guidance-distilled workflow does not, and
+ # SdCppVideoGenParams has no field for it at all). Left as sent, it reached the
+ # gallery sidecar and the restored recipe claimed conditioning that never touched
+ # a sampler.
+ # fam.default_guidance, NOT the identifier-derived one:
+ # default_video_generation_params matches on the repo id or path, so a local
+ # H3 file whose path happens to contain another family's keyword (say
+ # /models/wan/minimax_h3_fl2va-Q4.gguf) picks up that family's 5.0. Recording
+ # it would write back the inaccurate recipe this normalisation exists to
+ # prevent, and with a number no H3 sampler can ever have seen.
if not fam.supports_cfg:
- # A CFG-free family never reads this: diffusers gets no guidance kwarg and the
- # native path pins cfg_scale to 1.0. Clamped so the recipe cannot record a
- # guidance that did not run.
guidance = float(fam.default_guidance)
+ negative_prompt = None
shift, audio_shift = self._resolve_flow_shifts(
fam, state.engine, flow_shift, audio_flow_shift
)
@@ -4664,6 +4688,10 @@ class VideoBackend:
"conditioning": conditioning,
"steps": steps,
"guidance": guidance,
+ # The EFFECTIVE negative prompt, like guidance beside it: a guidance-distilled
+ # family normalises it away above, so the sidecar records what conditioned the
+ # clip instead of what the caller happened to send.
+ "negative_prompt": negative_prompt,
"flow_shift": shift,
"audio_flow_shift": audio_shift,
# The BUILD this clip came off, read from the ENGAGED state and never from the
@@ -5040,6 +5068,10 @@ class VideoBackend:
"conditioning": conditioning,
"steps": steps,
"guidance": guidance,
+ # sd-cli's vid_gen mode has no negative-prompt input at all
+ # (SdCppVideoGenParams carries no field for one), and this path serves only
+ # MiniMax-H3, which is guidance-distilled. Recorded as the None it ran with.
+ "negative_prompt": None,
"flow_shift": flow_shift,
# sd.cpp pins the audio schedule, so the recipe records what it actually ran.
"audio_flow_shift": state.family.default_audio_flow_shift,
diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.py
index 0c69ec18c9a..5ff448dc0ae 100644
--- a/studio/backend/core/training/diffusion_dit_trainer.py
+++ b/studio/backend/core/training/diffusion_dit_trainer.py
@@ -339,8 +339,18 @@ def _int8_quantize_base(transformer, family: Optional[str] = None) -> None:
``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
+ after the whole base has been loaded.
+
+ The family's PAD list is applied for the same reason, and the same way the inference path
+ applies it: a small-M Linear is either excluded or padded, and a family that chose padding
+ (MiniMax-H3's context_embedder and token_refiner blocks) has those names in neither the
+ generic nor the family exclusions, so without this they are quantized bare and raise on the
+ first forward exactly like an unexcluded one."""
+ from core.inference.diffusion_transformer_quant import (
+ apply_small_m_padding,
+ exclude_tokens_for_scheme,
+ make_filter_fn,
+ )
from torchao.quantization import Int8WeightOnlyConfig, quantize_
quantize_(
@@ -350,6 +360,10 @@ def _int8_quantize_base(transformer, family: Optional[str] = None) -> None:
512, exclude_name_tokens = exclude_tokens_for_scheme("int8", family)
),
)
+ # After quantize_, as the helper requires: it reparents the Linears it wraps. Not
+ # best-effort -- a raise means the base is quantized but not safely runnable, which is the
+ # one state worse than either end.
+ apply_small_m_padding(transformer, "int8", family)
def _fp8_module_filter(mod, fqn: str) -> bool:
diff --git a/studio/backend/core/training/diffusion_h3_clips.py b/studio/backend/core/training/diffusion_h3_clips.py
new file mode 100644
index 00000000000..806f57da1ae
--- /dev/null
+++ b/studio/backend/core/training/diffusion_h3_clips.py
@@ -0,0 +1,482 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The clip dataset layer for MiniMax-H3 LoRA training.
+
+MiniMax-H3 is the first family Studio trains from **clips with sound** rather than stills,
+and it has no still-image shortcut: its video VAE encodes ``17 * n + 5`` pixel frames at a
+time (a 1-frame clip is not a valid input, unlike LTX-2's), and every forward carries audio
+rows in the same packed sequence as the video rows. So the dataset unit is a video file with
+a soundtrack, and this module is the part of that which needs no torch and no diffusers:
+discovery, captions, the frame/latent/row arithmetic, and the canvas rule.
+
+The decode itself (``decode_clip``) needs PyAV, which the video backend already depends on.
+Everything above it is pure filesystem + arithmetic so the geometry contract is unit-testable
+on a CPU-only box.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import os
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+# ── the model's grid ─────────────────────────────────────────────────────────
+#
+# Every constant here is a checkpoint contract, mirrored from
+# ``diffusers.modular_pipelines.minimax_h3`` (which the trainer cannot import without pulling
+# in the whole modular stack, and which a CPU-only test host may not carry at all). The
+# trainer asserts them against the live components at load, so a diffusers release that moves
+# one is caught rather than silently trained through.
+H3_FPS = 24
+# The video VAE's ``clip_length`` and ``tokens_chunk_size``: 17 pixel frames per chunk, 5 latent
+# frames kept per chunk, plus a 2-frame head.
+H3_FRAMES_PER_CHUNK = 17
+H3_LATENTS_PER_CHUNK = 5
+H3_SPATIAL_COMPRESSION = 16
+# The transformer's (t, h, w) patch. Only the spatial half is > 1.
+H3_PATCH_T, H3_PATCH_H, H3_PATCH_W = 1, 2, 2
+# Both axes have to survive the VAE's 16x spatial compression AND still be a whole number of
+# 2x2 patch rows wide, so the canvas multiple is their product.
+H3_CANVAS_MULTIPLE = H3_SPATIAL_COMPRESSION * H3_PATCH_W
+H3_AUDIO_SAMPLING_RATE = 32000
+H3_AUDIO_LATENTS_PER_SECOND = 40
+H3_AUDIO_CHANNELS = 2
+# How much of a clip's audio window may be zero-padded before the clip is refused. 1% of a 5.17s
+# window is ~52ms, which covers the few-millisecond tail a container routinely ends short by
+# while still refusing a stream that is mostly silence.
+_MAX_AUDIO_PAD_FRACTION = 0.01
+# Peak amplitude at or below which a decoded window counts as silent, on PyAV's "flt" scale where
+# full scale is 1.0. About -80 dBFS: below the noise floor of any real recording, and above the
+# rounding dust an encode/decode round trip can leave on a track that was authored as digital
+# silence, so a genuinely muted soundtrack is caught whether or not it decodes to exact zeros.
+_SILENT_AUDIO_PEAK = 1e-4
+H3_AUDIO_LATENT_CHANNELS = 32
+H3_VIDEO_LATENT_CHANNELS = 24
+# Per-row modality tags, which index the transformer's AdaLN table.
+H3_VIDEO_TAG, H3_TEXT_TAG, H3_AUDIO_TAG = 0, 1, 2
+# The canvas the released checkpoint generates on.
+H3_CANVAS_SHORT_EDGE = 768
+H3_CANVAS_MAX_PIXELS = 768 * 1344
+H3_MIN_ASPECT_RATIO = 1 / 4
+H3_MAX_ASPECT_RATIO = 4
+# ImageNet, the video VAE's pixel convention.
+H3_PIXEL_MEAN = (0.485, 0.456, 0.406)
+H3_PIXEL_STD = (0.229, 0.224, 0.225)
+
+# Pixel frames one training clip covers. ONE VAE chunk, i.e. the shortest clip the video VAE
+# can encode at all, which is 0.917 s at 24 fps.
+#
+# This is deliberately far below the 5 s floor MiniMax-H3 *generates* at, and the trade is
+# explicit: the packed sequence is quadratic in its own length through the full self-attention,
+# so at the released 768-short-edge canvas a 5 s clip is ~38k rows and a 22-frame clip is ~7k.
+# Training at the native canvas on short clips keeps the SPATIAL statistics -- which is what a
+# style LoRA learns -- exactly on distribution, and only shortens the temporal extent; training
+# a 5 s clip at a canvas small enough to fit would put every spatial statistic off distribution
+# instead. The temporal rotary grid of a 22-frame clip is a strict PREFIX of the grid of a
+# generated one (``_temporal_position_grid`` starts at the same origin with the same spacing),
+# so no row sits at a coordinate the model never visits.
+H3_TRAIN_NUM_FRAMES = H3_FRAMES_PER_CHUNK + H3_LATENTS_PER_CHUNK
+
+_VIDEO_EXTS = {".mp4", ".mov", ".mkv", ".webm", ".m4v", ".avi"}
+_CAPTION_EXTS = (".txt", ".caption")
+
+
+def h3_align_num_frames(num_frames: int) -> int:
+ """Snap a frame count UP to the next ``17 * n + 5`` the video VAE can encode."""
+ if num_frames < 1:
+ raise ValueError(f"num_frames must be positive, got {num_frames}.")
+ while num_frames % H3_FRAMES_PER_CHUNK != H3_LATENTS_PER_CHUNK:
+ num_frames += 1
+ return num_frames
+
+
+def h3_video_latent_frames(num_frames: int) -> int:
+ """Latent frames the video VAE produces for an aligned frame count: ``5 * n + 2``."""
+ if num_frames % H3_FRAMES_PER_CHUNK != H3_LATENTS_PER_CHUNK:
+ raise ValueError(
+ f"num_frames must be of the form {H3_FRAMES_PER_CHUNK} * n + {H3_LATENTS_PER_CHUNK}, "
+ f"got {num_frames}."
+ )
+ return (num_frames - H3_LATENTS_PER_CHUNK) // H3_FRAMES_PER_CHUNK * H3_LATENTS_PER_CHUNK + 2
+
+
+def h3_audio_latent_count(num_frames: int) -> int:
+ """Audio latents (per channel) covering ``num_frames`` frames at 24 fps / 40 latents per s."""
+ return int(round(num_frames / H3_FPS * H3_AUDIO_LATENTS_PER_SECOND))
+
+
+def h3_audio_sample_count(num_frames: int) -> int:
+ """Waveform samples per channel the audio VAE must be handed for ``num_frames`` frames.
+
+ The audio VAE hops 800 samples (32 kHz / 40 latents per second) and right-pads a short
+ tail, so handing it exactly ``latents * hop`` samples produces exactly the latent count the
+ packed layout reserves rows for -- no pad, no truncation."""
+ hop = H3_AUDIO_SAMPLING_RATE // H3_AUDIO_LATENTS_PER_SECOND
+ return h3_audio_latent_count(num_frames) * hop
+
+
+def h3_rows_per_latent_frame(latent_height: int, latent_width: int) -> int:
+ return (latent_height // H3_PATCH_H) * (latent_width // H3_PATCH_W)
+
+
+def h3_packed_sequence_length(
+ num_text_tokens: int, num_frames: int, height: int, width: int
+) -> int:
+ """Rows of the packed ``[text | audio | video]`` sequence for one training sample.
+
+ The trainer builds no conditioning rows (it trains the ``t2va`` layout), so this is the
+ whole sequence and the figure the attention cost is quadratic in."""
+ latent_frames = h3_video_latent_frames(num_frames)
+ rows_per_frame = h3_rows_per_latent_frame(
+ height // H3_SPATIAL_COMPRESSION, width // H3_SPATIAL_COMPRESSION
+ )
+ audio_rows = h3_audio_latent_count(num_frames) * H3_AUDIO_CHANNELS
+ return num_text_tokens + audio_rows + latent_frames * rows_per_frame
+
+
+def h3_train_canvas(
+ aspect_width: float,
+ aspect_height: float,
+ short_edge: int = H3_CANVAS_SHORT_EDGE,
+ max_pixels: Optional[int] = None,
+) -> tuple[int, int]:
+ """MiniMax-H3's canvas rule, as ``(width, height)``.
+
+ Identical arithmetic to the pipeline's ``resolve_canvas_size`` (which returns
+ ``(height, width)``), re-expressed here so the trainer can size a dataset before any
+ diffusers import. ``short_edge`` is the run's ``resolution``; the area cap scales with it
+ so a smaller training canvas keeps the released aspect budget rather than the released
+ pixel count.
+ """
+ if aspect_width <= 0 or aspect_height <= 0:
+ raise ValueError(f"The aspect ratio must be positive, got {aspect_width}:{aspect_height}.")
+ ratio = aspect_width / aspect_height
+ if not H3_MIN_ASPECT_RATIO <= ratio <= H3_MAX_ASPECT_RATIO:
+ raise ValueError(
+ f"MiniMax-H3 was trained on aspect ratios from 1:4 to 4:1; this clip is "
+ f"{aspect_width:g}x{aspect_height:g} ({ratio:.2f}:1). Crop it first."
+ )
+ if max_pixels is None:
+ # The released cap, rescaled to the requested short edge: (1344/768) * short_edge^2.
+ max_pixels = int(H3_CANVAS_MAX_PIXELS * (short_edge / H3_CANVAS_SHORT_EDGE) ** 2)
+ if ratio >= 1.0:
+ width, height = short_edge * ratio, float(short_edge)
+ else:
+ width, height = float(short_edge), short_edge / ratio
+ area = width * height
+ if area > max_pixels:
+ scale = math.sqrt(max_pixels / area)
+ width, height = width * scale, height * scale
+
+ def snap(value: float) -> int:
+ return max(H3_CANVAS_MULTIPLE, round(value / H3_CANVAS_MULTIPLE) * H3_CANVAS_MULTIPLE)
+
+ return snap(width), snap(height)
+
+
+def discover_clip_caption_pairs(
+ data_dir: str | os.PathLike[str],
+ *,
+ instance_prompt: Optional[str] = None,
+ caption_column: str = "text",
+) -> list[tuple[str, str]]:
+ """Resolve ``(clip_path, caption)`` pairs from a dataset directory.
+
+ The caption rules are exactly ``discover_image_caption_pairs``' -- a per-clip ``<stem>.txt``
+ / ``<stem>.caption`` sidecar wins, then a ``metadata.jsonl`` / ``captions.jsonl`` row keyed
+ by ``file_name`` (or ``video`` / ``image`` / ``file``) carrying ``caption_column``, then the
+ dreambooth ``instance_prompt`` -- so a user who has captioned an image dataset already knows
+ this layout. Only the file extensions differ.
+
+ An empty sidecar is the same deliberate tombstone it is for images: it suppresses the
+ metadata caption and leaves the clip uncaptioned, so the ``instance_prompt`` fallback applies.
+ """
+ root = Path(data_dir).expanduser()
+ if not root.is_dir():
+ raise FileNotFoundError(f"data_dir is not a directory: {data_dir}")
+
+ clips = sorted(p for p in root.iterdir() if p.is_file() and p.suffix.lower() in _VIDEO_EXTS)
+
+ meta_caption: dict[str, str] = {}
+ for meta_name in ("metadata.jsonl", "captions.jsonl"):
+ meta_path = root / meta_name
+ if not meta_path.is_file():
+ continue
+ try:
+ meta_lines = meta_path.read_text(encoding = "utf-8").splitlines()
+ except (OSError, UnicodeError):
+ continue
+ for line in meta_lines:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ row = json.loads(line)
+ except (json.JSONDecodeError, TypeError):
+ continue
+ if not isinstance(row, dict):
+ continue
+ key = row.get("file_name") or row.get("video") or row.get("image") or row.get("file")
+ value = row.get(caption_column)
+ if key and value is not None:
+ meta_caption[str(key)] = str(value)
+
+ pairs: list[tuple[str, str]] = []
+ for clip in clips:
+ caption: Optional[str] = None
+ sidecar_present = False
+ for ext in _CAPTION_EXTS:
+ sidecar = clip.with_suffix(ext)
+ if sidecar.is_file():
+ sidecar_present = True
+ try:
+ caption = sidecar.read_text(encoding = "utf-8").strip()
+ except (OSError, UnicodeError):
+ caption = ""
+ break
+ if not sidecar_present:
+ caption = meta_caption.get(clip.name) or meta_caption.get(
+ clip.relative_to(root).as_posix()
+ )
+ if not caption and instance_prompt:
+ caption = instance_prompt
+ if caption:
+ pairs.append((str(clip), caption))
+
+ if not pairs:
+ raise ValueError(
+ "No captioned video clips found. MiniMax-H3 trains from clips with sound, not "
+ "stills: provide .mp4 / .mov / .mkv / .webm files plus a metadata.jsonl / "
+ "captions.jsonl, per-clip .txt captions, or an instance prompt."
+ )
+ return pairs
+
+
+def decode_clip(
+ path: str | os.PathLike[str],
+ *,
+ num_frames: int,
+ width: int,
+ height: int,
+ on_note: Optional[Callable[[str], None]] = None,
+) -> tuple[Any, Any]:
+ """Decode one training clip to ``(frames, waveform)``.
+
+ ``frames`` is a uint8 numpy array of shape ``(num_frames, height, width, 3)`` resampled onto
+ MiniMax-H3's own 24 fps by whole-frame drop/duplicate -- the same selection the inference
+ reference-video decoder makes, so a clip reaches the model on the model's clock however it
+ was authored. Each frame is cover-cropped to the canvas aspect ratio and then resized, so
+ nothing is letterboxed and nothing is stretched.
+
+ The window is the FIRST ``num_frames`` of the source, and the latents are cached once for
+ the run, so a longer clip trains only its opening and its caption is paired with that. That
+ is the dataset contract -- pre-trim to the training duration -- but it used to be silent,
+ which is how a caption describing a whole scene ended up on its first second. ``on_note``
+ is called once per over-long clip with the numbers, so the run reports it.
+
+ ``waveform`` is a float32 array of shape ``(2, h3_audio_sample_count(num_frames))`` at
+ 32 kHz. A mono source is duplicated to both channels; a clip with **no** audio track is
+ refused rather than silently trained as silence, because the audio rows are in the objective
+ and a silent target teaches the model to stop generating sound.
+ """
+ import av
+ import numpy as np
+ from PIL import Image
+
+ target_samples = h3_audio_sample_count(num_frames)
+ with av.open(str(path)) as container:
+ if not container.streams.video:
+ raise ValueError(f"{Path(path).name} carries no video track.")
+ if not container.streams.audio:
+ raise ValueError(
+ f"{Path(path).name} carries no audio track. MiniMax-H3 denoises video and audio "
+ f"in one packed sequence, so its training clips must have sound."
+ )
+ stream = container.streams.video[0]
+ source_fps = float(stream.average_rate or stream.guessed_rate or H3_FPS) or float(H3_FPS)
+ # Container duration, in seconds, for the over-long note below. Best effort: an unknown
+ # duration simply means no note, never a failed decode.
+ source_duration_s = 0.0
+ try:
+ if stream.duration is not None and stream.time_base is not None:
+ source_duration_s = float(stream.duration * stream.time_base)
+ elif getattr(container, "duration", None):
+ source_duration_s = float(container.duration) / 1_000_000.0
+ except Exception: # noqa: BLE001 -- a note is not worth failing a decode over
+ source_duration_s = 0.0
+
+ frames: list[Any] = []
+ next_target = 0
+ for source_index, frame in enumerate(container.decode(video = 0)):
+ if len(frames) >= num_frames:
+ break
+ if int(next_target * source_fps / H3_FPS) > source_index:
+ continue
+ image = frame.to_image().convert("RGB")
+ # Before the crop, not after: the canvas is in display orientation, so cropping the
+ # coded frame would trim the wrong pair of edges as well as train it sideways.
+ image = apply_display_rotation(image, display_rotation_degrees(frame, stream), Image)
+ image = _cover_resize(image, width, height, Image)
+ while (
+ int(next_target * source_fps / H3_FPS) <= source_index and len(frames) < num_frames
+ ):
+ frames.append(np.asarray(image, dtype = "uint8"))
+ next_target += 1
+
+ if len(frames) < num_frames:
+ raise ValueError(
+ f"{Path(path).name} decoded to {len(frames)} frames at {H3_FPS} fps, but a training "
+ f"clip needs {num_frames} ({num_frames / H3_FPS:.2f}s). Use longer clips."
+ )
+ if on_note is not None and source_duration_s > (num_frames / H3_FPS) * 1.05:
+ on_note(
+ f"{Path(path).name} is {source_duration_s:.1f}s; MiniMax-H3 trains its first "
+ f"{num_frames / H3_FPS:.2f}s and its caption is paired with that. Trim the clip to "
+ f"the part the caption describes."
+ )
+
+ waveform = _decode_clip_audio(path, target_samples, av, np)
+ return np.stack(frames), waveform
+
+
+def display_rotation_degrees(frame: Any, stream: Any) -> int:
+ """The clip's display rotation, one of 0/90/180/270, as a PLAYER would apply it.
+
+ PyAV hands back the CODED frame: unlike the ffmpeg CLI, ``to_image()`` and ``to_ndarray()``
+ do not honour the display matrix, and PyAV declines to do so by design. A phone clip shot
+ in portrait is stored landscape with a 90 degree matrix, so without this the trainer caches
+ sideways frames, on a canvas taken from the equally sideways coded size, and cover-crops
+ away the sides of the real picture.
+
+ The angle is FFmpeg's own: ``av_display_rotation_get`` on the 16.16 fixed-point 3x3, then
+ ``theta = -round(...) mod 360``, which is what ffmpeg's autorotate applies. Returns 0 for a
+ clip with no matrix, and for any PyAV too old to expose one -- previous behaviour, never an
+ exception, since a decode must not fail over orientation metadata.
+ """
+ import math
+ import struct
+
+ matrix = None
+ try:
+ from av.sidedata.sidedata import Type
+ entry = frame.side_data.get(Type.DISPLAYMATRIX)
+ if entry is not None:
+ raw = bytes(entry)
+ if len(raw) >= 36:
+ # Native byte order: the matrix is an in-memory int32[9], not a serialised field.
+ matrix = struct.unpack("=9i", raw[:36])
+ except Exception: # noqa: BLE001 -- no side-data API, or no matrix on this frame
+ matrix = None
+ if matrix is None:
+ # Legacy MOV/MP4 tag, still what older files carry.
+ try:
+ tag = (stream.metadata or {}).get("rotate")
+ return int(float(tag)) % 360 if tag is not None else 0
+ except Exception: # noqa: BLE001 -- an unparsable tag is not a decode failure
+ return 0
+ try:
+ conv = lambda v: v / (1 << 16) # noqa: E731
+ scale_x = math.hypot(conv(matrix[0]), conv(matrix[3]))
+ scale_y = math.hypot(conv(matrix[1]), conv(matrix[4]))
+ if not scale_x or not scale_y:
+ return 0
+ degrees = -math.degrees(math.atan2(conv(matrix[1]) / scale_y, conv(matrix[0]) / scale_x))
+ except Exception: # noqa: BLE001 -- a degenerate matrix means "no rotation", not a failure
+ return 0
+ theta = int(-round(degrees)) % 360
+ # Only the four square turns; anything else cannot be applied without resampling, and no
+ # camera writes one.
+ return theta if theta in (90, 180, 270) else 0
+
+
+def apply_display_rotation(image: Any, theta: int, Image: Any) -> Any:
+ """Rotate a decoded frame into display orientation. Verified against ffmpeg's autorotate."""
+ if theta == 90:
+ return image.transpose(Image.ROTATE_270)
+ if theta == 180:
+ return image.transpose(Image.ROTATE_180)
+ if theta == 270:
+ return image.transpose(Image.ROTATE_90)
+ return image
+
+
+def _cover_resize(image: Any, width: int, height: int, Image: Any) -> Any:
+ """Center cover-crop to the canvas aspect ratio, then resize to it. Never stretches."""
+ source_w, source_h = image.size
+ scale = max(width / source_w, height / source_h)
+ crop_w = min(source_w, math.ceil(width / scale))
+ crop_h = min(source_h, math.ceil(height / scale))
+ left = (source_w - crop_w) // 2
+ top = (source_h - crop_h) // 2
+ return image.resize(
+ (width, height), Image.LANCZOS, box = (left, top, left + crop_w, top + crop_h)
+ )
+
+
+def _decode_clip_audio(path: Any, target_samples: int, av: Any, np: Any) -> Any:
+ """The clip's soundtrack as float32 ``(2, target_samples)`` at 32 kHz.
+
+ Resampled by PyAV to the audio VAE's own rate and stereo layout, then trimmed or
+ zero-padded to exactly the sample count the packed layout reserves audio rows for. A short
+ tail is padded rather than refused: the video stream is the authority on the clip's length
+ and containers routinely end their audio a few milliseconds early.
+
+ That tolerance is bounded. Padding a materially short soundtrack out to the full window
+ trains the shared adapter on a target that is mostly silence, which is the exact failure the
+ "must have sound" check above exists to prevent -- and a stream carrying a fraction of a
+ second passed it, because the check only asks whether the container declares one.
+ ``_MAX_AUDIO_PAD_FRACTION`` is the container-tail allowance, not an augmentation budget.
+ """
+ resampler = av.AudioResampler(format = "flt", layout = "stereo", rate = H3_AUDIO_SAMPLING_RATE)
+ chunks = []
+ have = 0
+ with av.open(str(path)) as container:
+ # Stops at the training window, exactly as the video loop above does. An over-long source
+ # is accepted input here -- only the first num_frames are trained and the caller is merely
+ # warned -- so decoding the rest of the soundtrack would spend a whole recording's time
+ # and memory to build a sub-second sample, and would fail on damage in a region that is
+ # never used.
+ for frame in container.decode(audio = 0):
+ for resampled in resampler.resample(frame):
+ block = resampled.to_ndarray().reshape(-1, H3_AUDIO_CHANNELS)
+ chunks.append(block)
+ have += block.shape[0]
+ if have >= target_samples:
+ break
+ if have < target_samples:
+ # Only when the stream ran out: the resampler holds a partial block back, and that
+ # tail is what the pad allowance below is measured against. After an early break
+ # there is nothing to flush for -- the window is already full.
+ for resampled in resampler.resample(None):
+ chunks.append(resampled.to_ndarray().reshape(-1, H3_AUDIO_CHANNELS))
+ if not chunks:
+ raise ValueError(f"{Path(path).name} decoded to no audio samples.")
+ samples = np.concatenate(chunks, axis = 0).astype("float32")[:target_samples]
+ if samples.shape[0] < target_samples:
+ missing = target_samples - samples.shape[0]
+ if missing > _MAX_AUDIO_PAD_FRACTION * target_samples:
+ have_s = samples.shape[0] / H3_AUDIO_SAMPLING_RATE
+ want_s = target_samples / H3_AUDIO_SAMPLING_RATE
+ raise ValueError(
+ f"{Path(path).name} carries {have_s:.2f}s of audio for a {want_s:.2f}s clip. "
+ f"MiniMax-H3 denoises video and audio together, so padding the rest with "
+ f"silence would train the adapter to stop generating sound. Use a clip whose "
+ f"soundtrack runs its full length."
+ )
+ samples = np.pad(samples, ((0, missing), (0, 0)))
+ # A muted track runs the clip's full length, so every check above passes and the window comes
+ # back all zeros -- the same target the short-audio refusal exists to keep out, arriving by a
+ # route that refusal cannot see. Measured as peak amplitude rather than mean energy so a clip
+ # that is merely quiet, or silent for most of its length with one real sound in it, is kept:
+ # only a track with nothing above the floor anywhere is turned away.
+ if float(np.max(np.abs(samples))) <= _SILENT_AUDIO_PEAK:
+ raise ValueError(
+ f"{Path(path).name} has a soundtrack that is silent all the way through. "
+ f"MiniMax-H3 denoises video and audio together, so training on it would teach the "
+ f"adapter to stop generating sound. Use a clip whose soundtrack has audio in it, or "
+ f"take this one out of the dataset."
+ )
+ return np.ascontiguousarray(samples.T)
diff --git a/studio/backend/core/training/diffusion_h3_trainer.py b/studio/backend/core/training/diffusion_h3_trainer.py
new file mode 100644
index 00000000000..d033e25a309
--- /dev/null
+++ b/studio/backend/core/training/diffusion_h3_trainer.py
@@ -0,0 +1,888 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Joint video + audio LoRA training for MiniMax-H3.
+
+MiniMax-H3 is rectified flow like every family in ``diffusion_dit_trainer``, but three things
+put it outside that trainer's ``_FamilySpec`` seams rather than inside them, so it gets its
+own loop here and shares ``diffusion_train_common`` (config, events, stop, trust gate,
+publishing, EMA, the 8-bit optimizer) with everything else:
+
+1. **One packed sequence, two modalities.** H3 runs a single block stack over one 1-D
+ sequence holding ``[text | audio | video]`` rows with full self-attention. There is no
+ cross-attention, no per-modality block weights and no ``isolate_modalities`` escape hatch
+ (LTX-2 has all three). So a LoRA on the attention/MLP projections is applied to the audio
+ rows as well as the video ones, and the audio rows are keys and values for every video
+ row. Audio therefore cannot be excluded from the adapter, and the only honest objective is
+ the model's own: regress BOTH velocities. That is why the dataset unit is a clip with
+ sound (``diffusion_h3_clips``) and why there is no still-image milestone here.
+
+2. **Two coupled schedules.** Video is noised through an exponential shift of 12.0 and audio
+ through 3.0. At inference both are indexed by the same step, so the pair
+ ``(sigma_video, sigma_audio)`` traverses one curve. Training draws ONE base ``u`` and
+ pushes it through both shifts, which reproduces that curve exactly; drawing the two
+ independently would train pairs the sampler never visits. ``MiniMaxH3Scheduler`` is also
+ not a ``FlowMatchEulerDiscreteScheduler`` (reversed velocity sign, ``t = 1 - sigma`` in
+ [0, 1], a different sigma grid), so the shared trainer's sigma table does not apply.
+
+3. **It is modular-only.** There is no ``MiniMaxH3Pipeline``; the integration is a
+ ``ModularPipeline`` plus blocks. The trainer never builds one: the two layout builders it
+ needs are ``@staticmethod``s, and the components load individually -- which is a better fit
+ for the phased load than the ``transformer = None`` trick, since ``load_components`` takes
+ the component names outright.
+
+Velocity sign: H3 predicts a DATA-ward velocity (``x0 = x_t + sigma * v``), i.e. the target is
+``latents - noise``, the negation of the convention in ``diffusion_dit_trainer``.
+
+Memory: the Qwen3-VL-32B conditioner is 63 GiB on disk, so captions are encoded once up front
+and it is freed before the VAEs encode and long before the 66 GB transformer loads -- the same
+phased load the DiT trainer uses, expressed through ``load_components``.
+"""
+
+from __future__ import annotations
+
+import gc
+import random
+import time
+from contextlib import nullcontext
+from dataclasses import replace
+from pathlib import Path
+from typing import Any, Optional
+
+from core.training.diffusion_h3_clips import (
+ H3_AUDIO_CHANNELS,
+ H3_AUDIO_LATENT_CHANNELS,
+ H3_AUDIO_TAG,
+ H3_CANVAS_MULTIPLE,
+ H3_FRAMES_PER_CHUNK,
+ H3_LATENTS_PER_CHUNK,
+ H3_PIXEL_MEAN,
+ H3_PIXEL_STD,
+ H3_SPATIAL_COMPRESSION,
+ H3_TEXT_TAG,
+ H3_TRAIN_NUM_FRAMES,
+ H3_VIDEO_LATENT_CHANNELS,
+ H3_VIDEO_TAG,
+ decode_clip,
+ discover_clip_caption_pairs,
+ display_rotation_degrees,
+ h3_audio_latent_count,
+ h3_packed_sequence_length,
+ h3_train_canvas,
+ h3_video_latent_frames,
+)
+from core.training.diffusion_train_common import (
+ DEFAULT_LORA_FILENAME,
+ DEFAULT_LORA_TARGETS,
+ DiffusionLoraConfig,
+ EventCb,
+ MODULAR_BASE_FAMILIES,
+ PermutationBatchSampler,
+ StopCb,
+ _apply_perf_flags,
+ _assert_trusted_base_model,
+ _emit,
+ _latent_cache_forced,
+ _latent_cache_over_budget,
+ _restore_perf_flags,
+ h3_train_unsupported_reason,
+ native_bf16_supported,
+ resolve_train_steps,
+ train_recipe_overrides,
+)
+from core.training.diffusion_train_extras import LoRAEMA, save_ema_adapter
+
+# The video-stream and audio-stream projections of every block, fully qualified.
+#
+# There is nothing to exclude: H3 has ONE set of block weights serving all three modalities,
+# so this is the whole adapter surface and the audio rows are trained through the same
+# matrices as the video rows. What IS excluded is deliberate:
+# - ``adaln_proj.linear`` projects the timestep embedding into the modulation table. It is
+# 40% of the checkpoint's parameters, but its input is a (num_timesteps, 2688) tensor with
+# two or three rows, so a rank-r adapter there sees a handful of samples per step and
+# learns noise.
+# - ``proj_in`` / ``audio_proj_in`` / ``proj_out`` / ``audio_proj_out`` / ``context_embedder``
+# are the patch and text projections, kept in fp32 by the checkpoint's own
+# ``_keep_in_fp32_modules``; adapting them mixes precisions for no benefit.
+# - the ``token_refiner`` blocks carry ``attn`` and ``ff`` under the SAME leaf names
+# (``token_refiner.refiner_blocks.0.attn.to_q``), so PEFT's suffix rule for a LIST of
+# target names would adapt the text refiner as well as the denoiser stack.
+#
+# That last point is why the targets are a REGEX and not a list: PEFT globs nothing, it either
+# suffix-matches a list or ``re.fullmatch``es a string, so qualifying a list entry with
+# ``transformer_blocks.*.`` matches nothing at all and the adapter silently trains zero
+# parameters (the trainer also refuses an empty adapter, so both halves of that mistake are
+# caught).
+_H3_TARGET_LEAVES = (
+ "attn.to_q",
+ "attn.to_k",
+ "attn.to_v",
+ "attn.to_out.0",
+ "ff.net.0.proj",
+ "ff.net.2",
+)
+_H3_TARGETS = (
+ r"transformer_blocks\.\d+\.(?:"
+ + "|".join(leaf.replace(".", r"\.") for leaf in _H3_TARGET_LEAVES)
+ + ")"
+)
+
+# Modules whose weights the transformer reads a DTYPE off to align an activation with
+# (``x.to(self.linear.weight.dtype)``). A bitsandbytes ``Params4bit`` reports ``uint8``, so
+# quantizing one of these casts the activation to Byte and the next norm dies with
+# ``"rms_norm" not implemented for 'Byte'``. Keeping them dense is the whole fix; it costs the
+# nf4 saving on ``adaln_proj`` (36.6 GB resident instead of ~17 GB), which is still well under
+# the 66.3 GB dense weight. torchao int8 is unaffected -- its tensor subclass reports the
+# logical bfloat16 -- so ``base_precision="int8"`` quantizes everything.
+_H3_NF4_SKIP_MODULES = ("context_embedder", "adaln_proj", "norm_out")
+
+# The exponential sigma shifts of the two schedules, from the released scheduler configs.
+_H3_VIDEO_SHIFT = 12.0
+_H3_AUDIO_SHIFT = 3.0
+
+# Which Qwen3-VL hidden state conditions the transformer. The last layer is post-norm and is
+# not what the released weights were trained against.
+_H3_TEXT_ENCODER_LAYER = 50
+
+# Components the conditioning phase needs, and the one the training phase needs. Naming them
+# is what keeps the 66 GB transformer off the device while the 63 GiB conditioner is on it.
+_H3_TEXT_COMPONENTS = ("text_encoder", "tokenizer", "processor")
+# The VAEs load in fp32: both carry modules diffusers refuses to cast (their encoders,
+# decoders and projection heads), so a bf16 load followed by a .to(float32) both warns and
+# leaves the cast half-applied.
+_H3_VAE_COMPONENTS = ("vae", "audio_vae")
+_H3_CONDITIONING_COMPONENTS = _H3_TEXT_COMPONENTS + _H3_VAE_COMPONENTS
+
+
+def _shifted_sigma(u: float, shift: float) -> float:
+ """The exponential shift both H3 schedules apply: ``s*u / (1 + (s - 1) * u)``."""
+ return shift * u / (1.0 + (shift - 1.0) * u)
+
+
+def _assert_component_grid(pipe: Any) -> None:
+ """Check the constants in ``diffusion_h3_clips`` against the loaded components.
+
+ Those constants drive the packed layout, and a wrong one produces a silently misaligned
+ sequence rather than an exception, so they are asserted against the checkpoint that is
+ actually loaded instead of trusted."""
+ vae = getattr(pipe, "vae", None)
+ audio_vae = getattr(pipe, "audio_vae", None)
+ actual = {}
+ if vae is not None:
+ actual["spatial compression"] = (vae.spatial_compression_ratio, H3_SPATIAL_COMPRESSION)
+ actual["VAE frames per chunk"] = (vae.config.clip_length, H3_FRAMES_PER_CHUNK)
+ actual["VAE latents per chunk"] = (vae.tokens_chunk_size, H3_LATENTS_PER_CHUNK)
+ actual["video latent channels"] = (vae.config.latent_channels, H3_VIDEO_LATENT_CHANNELS)
+ if audio_vae is not None:
+ actual["audio latent channels"] = (
+ audio_vae.config.latent_channels,
+ H3_AUDIO_LATENT_CHANNELS,
+ )
+ actual["audio sampling rate"] = (audio_vae.config.sampling_rate, 32000)
+ mismatched = [f"{k}: checkpoint {a}, trainer {b}" for k, (a, b) in actual.items() if a != b]
+ if mismatched:
+ raise ValueError(
+ "This MiniMax-H3 checkpoint does not match the grid the trainer builds its packed "
+ "sequence on (" + "; ".join(mismatched) + ")."
+ )
+
+
+def _load_conditioners(cfg, device):
+ """Build the modular pipeline and load ONLY the conditioning components.
+
+ ``ModularPipeline.from_pretrained`` without ``workflow=`` keeps the whole block graph (a
+ ``workflow=`` prunes it statically and cannot be undone), and ``load_components(names=...)``
+ then fetches exactly the components named -- so the transformer is never even downloaded at
+ this phase, let alone resident."""
+ import torch
+ from diffusers import ModularPipeline
+
+ from core.inference.diffusion import hub_cache_dir
+
+ # Pinned, like every loader call on the inference side. diffusers resolves an unset
+ # cache_dir through huggingface_hub's import-time constant, and the training subprocess is
+ # spawned without the cache-environment wrapper, so a cache folder changed mid-session was
+ # invisible here: components already sitting in the selected root were missed and roughly
+ # 145 GB re-downloaded into the old one.
+ cache_dir = hub_cache_dir()
+ pipe = ModularPipeline.from_pretrained(cfg.base_model, token = cfg.hf_token, cache_dir = cache_dir)
+ # The token above opens the modular INDEX only. load_components runs a separate
+ # from_pretrained per component, against the repos that index names, so it has to carry the
+ # token again -- and it swallows a component failure as a logger.warning rather than raising,
+ # so an anonymous 401 leaves the attribute unset and the first use dies on None instead of
+ # saying the base was gated. The inference H3 loader forwards it for the same reason.
+ auth = {"token": cfg.hf_token} if cfg.hf_token else {}
+ pipe.load_components(
+ names = list(_H3_TEXT_COMPONENTS),
+ torch_dtype = torch.bfloat16,
+ cache_dir = cache_dir,
+ **auth,
+ )
+ pipe.load_components(
+ names = list(_H3_VAE_COMPONENTS),
+ torch_dtype = torch.float32,
+ cache_dir = cache_dir,
+ **auth,
+ )
+ _assert_component_grid(pipe)
+ # ``load_components`` builds every component on the CPU, so place them explicitly.
+ pipe.text_encoder.to(device)
+ pipe.vae.to(device)
+ pipe.audio_vae.to(device)
+ return pipe
+
+
+def _encode_prompt(pipe, caption: str, device) -> Any:
+ """One caption -> the ``(1, num_tokens, 5120)`` hidden state H3 conditions on.
+
+ The presentation is the prompt verbatim: no chat template, no special tokens. The stack is
+ called through ``text_encoder.model`` because H3 reads ``hidden_states[50]`` and never uses
+ the language-model head, whose vocabulary-wide projection is all the top-level forward would
+ add."""
+ import torch
+
+ token_ids = pipe.tokenizer(caption, add_special_tokens = False)["input_ids"]
+ if not token_ids:
+ raise ValueError(
+ "A MiniMax-H3 caption cannot be empty: the packed sequence needs text rows."
+ )
+ input_ids = torch.tensor([token_ids], dtype = torch.long, device = device)
+ mm_token_type_ids = torch.tensor(
+ pipe.processor.create_mm_token_type_ids([token_ids]), dtype = torch.long, device = device
+ )
+ encoder = pipe.text_encoder
+ num_layers = encoder.config.text_config.num_hidden_layers
+ if num_layers <= _H3_TEXT_ENCODER_LAYER:
+ raise ValueError(
+ f"MiniMax-H3 conditions on hidden_states[{_H3_TEXT_ENCODER_LAYER}] of its Qwen3-VL "
+ f"conditioner, which needs more than {_H3_TEXT_ENCODER_LAYER} decoder layers; this "
+ f"one has {num_layers}."
+ )
+ with torch.no_grad():
+ out = encoder.model(
+ input_ids = input_ids,
+ attention_mask = torch.ones_like(input_ids),
+ mm_token_type_ids = mm_token_type_ids,
+ use_cache = False,
+ output_hidden_states = True,
+ )
+ return out.hidden_states[_H3_TEXT_ENCODER_LAYER].to("cpu", torch.float32)
+
+
+def _encode_video_stats(vae, frames, device) -> tuple[Any, Any]:
+ """Encode one clip's frames to the normalised posterior's affine ``(A, B)`` pair.
+
+ ``frames`` is the uint8 ``(F, H, W, 3)`` array ``decode_clip`` returns. The recipe is the
+ released model's: ImageNet-normalise the pixels, encode, and normalise the latent by the
+ VAE's ``latents_mean`` / ``latents_std``. Caching ``(A, B)`` rather than a sample keeps a
+ fresh posterior draw available at every step without the VAE resident, exactly as the DiT
+ trainer's latent cache does. The reference's float16 rounding of the SAMPLE is not applied:
+ it is a conditioning-anchor reproducibility device (it makes a keyframe encode
+ bit-identical), and rounding a training target only removes signal."""
+ import torch
+
+ pixels = torch.from_numpy(frames).to(device)
+ # (F, H, W, 3) uint8 -> (1, 3, F, H, W) float32
+ pixels = pixels.permute(3, 0, 1, 2).unsqueeze(0).to(torch.float32).div_(255.0)
+ pixel_mean = torch.tensor(H3_PIXEL_MEAN, device = device).view(1, -1, 1, 1, 1)
+ pixel_std = torch.tensor(H3_PIXEL_STD, device = device).view(1, -1, 1, 1, 1)
+ pixels = (pixels - pixel_mean) / pixel_std
+ with torch.no_grad():
+ posterior = vae.encode(pixels, return_dict = False)[0]
+ latents_mean = torch.tensor(vae.config.latents_mean, device = device).view(1, -1, 1, 1, 1)
+ latents_std = torch.tensor(vae.config.latents_std, device = device).view(1, -1, 1, 1, 1)
+ return (
+ ((posterior.mean - latents_mean) / latents_std).float().cpu(),
+ (posterior.std / latents_std).float().cpu(),
+ )
+
+
+def _encode_audio_latents(audio_vae, waveform, device) -> Any:
+ """Encode one clip's stereo soundtrack to normalised audio latents ``(2, 32, n)``.
+
+ The audio VAE is mono, so the two stereo channels go through as two batch items -- the same
+ boundary the decoder crosses in reverse. MiniMax-H3 consumes the posterior MEAN and never
+ evaluates the ``logs_proj`` head, so the audio target is deterministic and no affine pair is
+ cached for it."""
+ import torch
+
+ samples = torch.from_numpy(waveform).to(device).unsqueeze(1) # (2, 1, samples)
+ with torch.no_grad():
+ posterior = audio_vae.encode(samples, return_dict = False)[0]
+ latents = posterior.mode()
+ mean = torch.tensor(audio_vae.config.latents_mean, device = device).view(1, -1, 1)
+ std = torch.tensor(audio_vae.config.latents_std, device = device).view(1, -1, 1)
+ return ((latents - mean) / std).float().cpu()
+
+
+def _load_transformer(cfg, device, base_precision):
+ """Load the denoiser alone, in the resolved precision. See ``_H3_NF4_SKIP_MODULES``."""
+ import torch
+ from diffusers import MiniMaxH3Transformer3DModel
+
+ from core.inference.diffusion import hub_cache_dir
+
+ # Same pin as the conditioners above: the denoiser is the 145 GB half, so an unpinned load
+ # here is the expensive one to get wrong.
+ cache_dir = hub_cache_dir()
+ if base_precision == "nf4":
+ from diffusers import BitsAndBytesConfig as DiffusersBnb
+ quant = DiffusersBnb(
+ load_in_4bit = True,
+ bnb_4bit_quant_type = "nf4",
+ bnb_4bit_compute_dtype = torch.bfloat16,
+ bnb_4bit_use_double_quant = True,
+ llm_int8_skip_modules = list(_H3_NF4_SKIP_MODULES),
+ )
+ return MiniMaxH3Transformer3DModel.from_pretrained(
+ cfg.base_model,
+ subfolder = "transformer",
+ quantization_config = quant,
+ torch_dtype = torch.bfloat16,
+ token = cfg.hf_token,
+ cache_dir = cache_dir,
+ )
+ return MiniMaxH3Transformer3DModel.from_pretrained(
+ cfg.base_model,
+ subfolder = "transformer",
+ torch_dtype = torch.bfloat16,
+ token = cfg.hf_token,
+ cache_dir = cache_dir,
+ ).to(device)
+
+
+def _patchify(latents, patch: tuple[int, int, int]):
+ """``(1, C, F, H, W)`` video latents -> the transformer's rows, frame-major then row-major."""
+ from diffusers.modular_pipelines.minimax_h3.before_denoise import patchify_video_latents
+ return patchify_video_latents(latents, patch)
+
+
+def _build_layout(
+ num_text_tokens: int,
+ latent_frames: int,
+ latent_h: int,
+ latent_w: int,
+ num_audio_latents: int,
+ patch: tuple[int, int, int],
+ device,
+):
+ """The packed ``[text | audio | video]`` layout for one training sample.
+
+ Built by the pipeline's own ``@staticmethod`` so the trainer and the sampler cannot drift:
+ the rotary grid, the row order and the modality tags are a checkpoint contract, and a
+ reimplementation that agreed today would not stay agreeing."""
+ import torch
+ from diffusers.modular_pipelines.minimax_h3.before_denoise import MiniMaxH3PrepareLayoutStep
+
+ text_token_tags = torch.full((num_text_tokens,), H3_TEXT_TAG, dtype = torch.long)
+ (
+ position_ids,
+ token_tags,
+ video_indices,
+ audio_indices,
+ text_indices,
+ n_cond_video,
+ n_cond_audio,
+ ) = MiniMaxH3PrepareLayoutStep.build_packed_sequence(
+ text_token_tags,
+ latent_frames,
+ latent_h,
+ latent_w,
+ num_audio_latents,
+ patch,
+ H3_AUDIO_CHANNELS,
+ H3_AUDIO_TAG,
+ H3_VIDEO_TAG,
+ (), # the trainer trains the t2va layout: no keyframe conditioning rows
+ )
+ return {
+ "position_ids": position_ids.to(device),
+ "token_tags": token_tags.to(device),
+ "video_indices": video_indices.to(device),
+ "audio_indices": audio_indices.to(device),
+ "text_indices": text_indices.to(device),
+ "num_condition_video_rows": n_cond_video,
+ "num_condition_audio_rows": n_cond_audio,
+ }
+
+
+def _row_timesteps(layout, num_text_tokens: int, t_video: float, t_audio: float, device):
+ """The transformer's ``(timestep, timestep_indices)`` pair for one step.
+
+ Also the pipeline's own ``@staticmethod``: one forward serves rows at different noise
+ levels, and which row is at which level is the layout's business, not the loop's."""
+ from diffusers.modular_pipelines.minimax_h3.before_denoise import MiniMaxH3SetTimestepsStep
+
+ timestep, timestep_indices = MiniMaxH3SetTimestepsStep.build_row_timesteps(
+ layout["video_indices"],
+ layout["audio_indices"],
+ layout["num_condition_video_rows"],
+ layout["num_condition_audio_rows"],
+ num_text_tokens,
+ t_video,
+ t_audio,
+ # No conditioning rows exist in this layout, so the two condition timesteps are
+ # unreachable; pass the generated ones so no phantom value enters ``torch.unique``.
+ t_video,
+ t_audio,
+ )
+ return timestep.to(device), timestep_indices.to(device)
+
+
+def _save_lora(
+ out_dir: str,
+ layers: dict,
+ adapter_config: Optional[dict] = None,
+) -> None:
+ """Write the adapter as ``pytorch_lora_weights.safetensors``.
+
+ Diffusers ships no ``MiniMaxH3LoraLoaderMixin``, so there is no
+ ``MiniMaxH3Pipeline.save_lora_weights`` to route through and no
+ ``pipe.load_lora_weights`` to read it back. The file this writes is nonetheless the
+ ordinary diffusers single-file layout with the ``transformer.`` prefix every mixin uses, so
+ it loads with ``transformer.load_lora_adapter(path, prefix="transformer")`` today and will
+ load with ``load_lora_weights`` unchanged the day that mixin lands.
+
+ ``adapter_config`` is the PEFT config, written as safetensors metadata in the layout
+ ``_save_lora_weights`` uses: the JSON under ``lora_adapter_metadata``, every key packed with
+ the same ``transformer.`` prefix, because ``load_lora_adapter`` strips the prefix off the
+ metadata exactly as it does off the tensors. Without it the loader falls through to
+ ``get_peft_kwargs``, which reads the rank off the B matrices and then sets
+ ``lora_alpha = r`` -- so an adapter trained at rank 16 / alpha 32 came back at half the
+ strength it was trained with, silently."""
+ import json
+
+ from safetensors.torch import save_file
+
+ Path(out_dir).mkdir(parents = True, exist_ok = True)
+ state = {f"transformer.{k}": v.to("cpu").contiguous() for k, v in layers.items()}
+ metadata = {"format": "pt"}
+ if adapter_config:
+ packed = {
+ f"transformer.{key}": list(value) if isinstance(value, set) else value
+ for key, value in adapter_config.items()
+ }
+ metadata["lora_adapter_metadata"] = json.dumps(packed, indent = 2, sort_keys = True)
+ save_file(state, str(Path(out_dir) / DEFAULT_LORA_FILENAME), metadata = metadata)
+
+
+def run_h3_lora_training(
+ config: DiffusionLoraConfig,
+ *,
+ on_event: Optional[EventCb] = None,
+ should_stop: Optional[StopCb] = None,
+) -> str:
+ """Train a MiniMax-H3 joint video + audio LoRA from a clip dataset and export it."""
+ cfg = config.normalized()
+ if cfg.resolved_family != "minimax-h3":
+ raise ValueError(f"This trainer is for minimax-h3, not {cfg.resolved_family!r}.")
+ # Every config-only refusal lives in the shared preflight, which the START ROUTE also calls
+ # BEFORE it evicts the user's resident GPU models. Raised again here so a direct call to the
+ # trainer is refused too, and so the two can never disagree about what H3 accepts.
+ reason = h3_train_unsupported_reason(cfg)
+ if reason:
+ raise ValueError(reason)
+ # The two image-LoRA augmentation knobs are fixed for a clip dataset, not honoured: every
+ # frame goes through the same centre cover-crop (_cover_resize), and nothing is flipped --
+ # a per-frame flip would tear a clip, and a per-clip one has nowhere to live, since the
+ # cached tensors carry no variant axis. snr_gamma is the same shape of mismatch on the loss
+ # side: the step is a plain unweighted MSE and the field defaults to 5.0, so every default
+ # request recorded min-SNR weighting that never ran (weighting_scheme, its sibling, is
+ # refused above because it has no default to break). All three SCHEMA defaults disagree with
+ # what the loop does, so they are normalised rather than refused: refusing would 422 every
+ # default request, and leaving them would have the run record describe a recipe that did not
+ # happen. Read off the shared table, which the SERVICE also applies to the config it persists
+ # -- normalising only here fixed the run and left the history entry lying about it.
+ cfg = replace(cfg, **train_recipe_overrides(cfg))
+
+ import torch
+
+ rng = random.Random(cfg.seed)
+ torch.manual_seed(cfg.seed)
+
+ save_on_stop = True
+
+ def _check_stop() -> bool:
+ nonlocal save_on_stop
+ if should_stop is None:
+ return False
+ sig = should_stop()
+ if not sig:
+ return False
+ if isinstance(sig, dict) and sig.get("save") is False:
+ save_on_stop = False
+ return True
+
+ device = "cuda" if torch.cuda.is_available() else "cpu"
+ if device == "cuda" and not native_bf16_supported():
+ raise ValueError(
+ "This trainer requires a bfloat16-capable GPU (Ampere or newer); "
+ "this CUDA device does not support bf16."
+ )
+ weight_dtype = torch.bfloat16 if device == "cuda" else torch.float32
+
+ # allow_modular: this loop loads through ModularPipeline.from_pretrained, and a local
+ # MiniMax-H3 pipeline carries modular_model_index.json and no model_index.json, so the
+ # conventional shape check refused the only local layout the family has. Read off the shared
+ # set rather than hard-coded True, because the start route runs this same gate first and has
+ # to reach the same verdict about the same directory.
+ _assert_trusted_base_model(
+ cfg.base_model,
+ allow_modular = (cfg.resolved_family or "").strip().lower() in MODULAR_BASE_FAMILIES,
+ )
+ pairs = discover_clip_caption_pairs(
+ cfg.data_dir, instance_prompt = cfg.instance_prompt, caption_column = cfg.caption_column
+ )
+ cfg = replace(cfg, train_steps = resolve_train_steps(cfg, len(pairs)), num_epochs = 0)
+ _emit(on_event, "model_load_started", num_images = len(pairs))
+ if _check_stop():
+ out_dir = Path(cfg.output_dir).expanduser()
+ _emit(
+ on_event, "complete", output_dir = str(out_dir), lora_path = None, stopped = True, steps_run = 0
+ )
+ return str(out_dir)
+
+ perf_snap = _apply_perf_flags(cfg, device)
+ try:
+ return _train_h3(
+ cfg, pairs, rng, device, weight_dtype, on_event, _check_stop, lambda: save_on_stop
+ )
+ finally:
+ _restore_perf_flags(perf_snap)
+
+
+def _train_h3(cfg, pairs, rng, device, weight_dtype, on_event, _check_stop, _save_on_stop):
+ import torch
+ import torch.nn.functional as F
+ from diffusers.optimization import get_scheduler
+ from diffusers.training_utils import cast_training_params
+ from peft import LoraConfig
+ from peft.utils import get_peft_model_state_dict
+
+ from core.training.diffusion_dit_trainer import _int8_quantize_base, _make_optimizer
+
+ out_dir = Path(cfg.output_dir).expanduser()
+ clip_paths = [p for p, _ in pairs]
+ captions = [c for _, c in pairs]
+ num_frames = H3_TRAIN_NUM_FRAMES
+ latent_frames = h3_video_latent_frames(num_frames)
+ num_audio_latents = h3_audio_latent_count(num_frames)
+
+ to_encode = sorted(set(captions))
+
+ # ── phase 1: conditioning. The 63 GiB Qwen3-VL conditioner and both VAEs are resident
+ # here and nowhere else; the 66 GB transformer has not been fetched yet.
+ pipe = _load_conditioners(cfg, device)
+ caption_embeds = {cap: _encode_prompt(pipe, cap, device) for cap in to_encode}
+ _emit(on_event, "preparing", stage = "encode_prompts", done = len(to_encode), total = len(to_encode))
+ pipe.text_encoder = None
+ if getattr(pipe, "processor", None) is not None:
+ pipe.processor = None
+ gc.collect()
+ if device == "cuda":
+ torch.cuda.empty_cache()
+
+ # ── phase 2: the clip cache. One canvas for the run, taken from the FIRST clip's aspect
+ # ratio: every other clip is cover-cropped onto it, so a mixed-aspect dataset trains on one
+ # geometry rather than reshaping the packed sequence per step.
+ width, height = _dataset_canvas(clip_paths[0], cfg.resolution)
+ latent_h, latent_w = height // H3_SPATIAL_COMPRESSION, width // H3_SPATIAL_COMPRESSION
+ cache: list[tuple[Any, Any, Any]] = []
+ for i, path in enumerate(clip_paths):
+ frames, waveform = decode_clip(
+ path,
+ num_frames = num_frames,
+ width = width,
+ height = height,
+ # The window is the clip's opening and the latents are cached once for the run, so
+ # a longer source trains only its first seconds while its caption describes the
+ # whole thing. Reported rather than left silent.
+ on_note = lambda message: _emit(on_event, "warning", message = message),
+ )
+ video_a, video_b = _encode_video_stats(pipe.vae, frames, device)
+ audio = _encode_audio_latents(pipe.audio_vae, waveform, device)
+ if audio.shape[-1] != num_audio_latents:
+ raise ValueError(
+ f"{Path(path).name} encoded to {audio.shape[-1]} audio latents, but the packed "
+ f"layout reserves {num_audio_latents} rows per channel."
+ )
+ entry = (video_a, video_b, audio)
+ if i == 0 and not _latent_cache_forced():
+ # Size-gate off the FIRST real entry, the way the SDXL and DiT caches do, before the
+ # rest of the dataset is encoded. Those two answer an over-budget estimate by dropping
+ # the cache and encoding per step; H3 cannot, because both VAEs are freed below to
+ # make room for the 66 GB transformer. So the honest answer is to say so now, with the
+ # numbers, instead of running the whole preparation and being OOM-killed at the end of
+ # it with nothing to show.
+ from core.training import diffusion_train_common as _train_common
+ per_clip = int(sum(t.numel() * t.element_size() for t in entry))
+ if _latent_cache_over_budget(per_clip, len(clip_paths)):
+ budget = _train_common._LATENT_CACHE_BUDGET_BYTES
+ raise ValueError(
+ f"{len(clip_paths)} clips at {width}x{height} need about "
+ f"{per_clip * len(clip_paths) / 1024**3:.1f} GiB of host memory for the "
+ f"MiniMax-H3 latent cache, over the {budget / 1024**3:.0f} GiB budget. Train "
+ f"on fewer clips or at a lower resolution, or set "
+ f"UNSLOTH_DIFFUSION_FORCE_LATENT_CACHE=1 to cache them anyway."
+ )
+ cache.append(entry)
+ _emit(on_event, "preparing", stage = "cache_latents", done = i + 1, total = len(clip_paths))
+ if _check_stop():
+ _emit(
+ on_event,
+ "complete",
+ output_dir = str(out_dir),
+ lora_path = None,
+ stopped = True,
+ steps_run = 0,
+ )
+ return str(out_dir)
+ del pipe
+ gc.collect()
+ if device == "cuda":
+ torch.cuda.empty_cache()
+
+ # ── phase 3: the denoiser.
+ base_precision = cfg.base_precision if cfg.base_precision != "auto" else "nf4"
+ if base_precision in ("fp8", "mxfp8"):
+ raise ValueError(
+ "MiniMax-H3 has no fp8 training path: its packed sequence mixes three modalities "
+ "through one set of linears, so the activation range is not the per-family range "
+ "the fp8 filter was measured against. Use nf4, int8 or bf16."
+ )
+ transformer = _load_transformer(cfg, device, base_precision)
+ transformer.requires_grad_(False)
+ # ``normalized()`` fills lora_target_modules with the generic DEFAULT_LORA_TARGETS when a
+ # caller does not set it, so that value means "unset" and the family's own regex wins. Any
+ # other explicit tuple is a deliberate override and is passed through as a list.
+ targets: Any = (
+ _H3_TARGETS
+ if tuple(cfg.lora_target_modules) == DEFAULT_LORA_TARGETS
+ else list(cfg.lora_target_modules)
+ )
+ transformer.add_adapter(
+ LoraConfig(
+ r = cfg.lora_rank,
+ lora_alpha = cfg.lora_alpha,
+ lora_dropout = cfg.lora_dropout,
+ init_lora_weights = "gaussian",
+ target_modules = targets,
+ )
+ )
+ if cfg.gradient_checkpointing:
+ import functools
+ import torch.utils.checkpoint as _ckpt
+ transformer.enable_gradient_checkpointing(
+ gradient_checkpointing_func = functools.partial(_ckpt.checkpoint, use_reentrant = False)
+ )
+ cast_training_params(transformer, dtype = torch.float32)
+ lora_params = [p for p in transformer.parameters() if p.requires_grad]
+ if not lora_params:
+ raise ValueError(
+ f"No LoRA target matched the MiniMax-H3 transformer for {targets!r}; the adapter "
+ f"would train nothing."
+ )
+ if base_precision == "int8":
+ # WITH the family. H3's adaln_proj is Linear(2688 -> 96768), so it clears the 512-feature
+ # floor and gets quantized, then runs at M = 1 and raises "self.size(0) needs to be
+ # greater than 16" on the first step -- after the whole 66.3 GB base has loaded. The
+ # family also carries the pad list (context_embedder, token_refiner) the helper applies.
+ _int8_quantize_base(transformer, cfg.resolved_family)
+
+ ema = LoRAEMA(transformer, decay = cfg.ema_decay) if getattr(cfg, "ema_decay", 0.0) else None
+ optimizer = _make_optimizer(lora_params, cfg.learning_rate)
+ lr_sched = get_scheduler(
+ cfg.lr_scheduler,
+ optimizer = optimizer,
+ num_warmup_steps = cfg.lr_warmup_steps,
+ num_training_steps = cfg.train_steps,
+ )
+ video_shift = (
+ float(cfg.flow_shift) if isinstance(cfg.flow_shift, (int, float)) else _H3_VIDEO_SHIFT
+ )
+ _emit(
+ on_event,
+ "model_load_completed",
+ compiled = False,
+ base_precision = base_precision,
+ sequence_length = h3_packed_sequence_length(
+ max(e.shape[1] for e in caption_embeds.values()), num_frames, height, width
+ ),
+ )
+
+ transformer.train()
+ patch = tuple(transformer.config.patch_size)
+ index_sampler = PermutationBatchSampler(len(clip_paths), rng)
+ autocast = (
+ torch.autocast(device_type = "cuda", dtype = torch.bfloat16)
+ if device == "cuda"
+ else nullcontext()
+ )
+ stopped = False
+ running_loss = 0.0
+ peak_gb = 0.0
+ t_start = time.time()
+ t_steady = None
+ done = 0
+ for opt_step in range(cfg.train_steps):
+ optimizer.zero_grad(set_to_none = True)
+ step_loss = 0.0
+ step_video = 0.0
+ step_audio = 0.0
+ for _ in range(cfg.gradient_accumulation_steps):
+ index = index_sampler.next_batch(1)[0]
+ video_a, video_b, audio_latents = cache[index]
+ video_a = video_a.to(device)
+ video_b = video_b.to(device)
+ # A fresh posterior draw per step, exactly like encoding in the loop would give.
+ clean_video = video_a + video_b * torch.randn_like(video_a)
+ clean_audio = audio_latents.to(device)
+
+ # ONE base u through BOTH shifts: the (video, audio) sigma pair the sampler visits.
+ u = rng.random()
+ sigma_video = _shifted_sigma(u, video_shift)
+ sigma_audio = _shifted_sigma(u, _H3_AUDIO_SHIFT)
+
+ noise_video = torch.randn_like(clean_video)
+ noise_audio = torch.randn_like(clean_audio)
+ noisy_video = (1.0 - sigma_video) * clean_video + sigma_video * noise_video
+ noisy_audio = (1.0 - sigma_audio) * clean_audio + sigma_audio * noise_audio
+
+ video_rows = _patchify(noisy_video, patch)
+ audio_rows = noisy_audio.permute(0, 2, 1).reshape(-1, H3_AUDIO_LATENT_CHANNELS)
+ # DATA-ward velocity: x0 = x_t + sigma * v, so the target is latents - noise.
+ target_video = _patchify(clean_video - noise_video, patch)
+ target_audio = (
+ (clean_audio - noise_audio).permute(0, 2, 1).reshape(-1, H3_AUDIO_LATENT_CHANNELS)
+ )
+
+ embeds = caption_embeds[captions[index]].to(device, weight_dtype)
+ num_text_tokens = embeds.shape[1]
+ layout = _build_layout(
+ num_text_tokens, latent_frames, latent_h, latent_w, num_audio_latents, patch, device
+ )
+ timestep, timestep_indices = _row_timesteps(
+ layout, num_text_tokens, 1.0 - sigma_video, 1.0 - sigma_audio, device
+ )
+ with autocast:
+ pred_video, pred_audio = transformer(
+ hidden_states = video_rows[None],
+ audio_hidden_states = audio_rows[None],
+ encoder_hidden_states = embeds,
+ timestep = timestep,
+ timestep_indices = timestep_indices,
+ token_tags = layout["token_tags"],
+ position_ids = layout["position_ids"],
+ video_indices = layout["video_indices"],
+ audio_indices = layout["audio_indices"],
+ text_indices = layout["text_indices"],
+ return_dict = False,
+ )
+ loss_video = F.mse_loss(pred_video[0].float(), target_video.float())
+ loss_audio = F.mse_loss(pred_audio[0].float(), target_audio.float())
+ # Unweighted sum, the model's own objective: the two streams share every
+ # matrix the adapter touches, so down-weighting audio would not protect it, it
+ # would only stop the loss reporting that it had drifted.
+ loss = loss_video + loss_audio
+ (loss / cfg.gradient_accumulation_steps).backward()
+ step_loss += float(loss.detach()) / cfg.gradient_accumulation_steps
+ step_video += float(loss_video.detach()) / cfg.gradient_accumulation_steps
+ step_audio += float(loss_audio.detach()) / cfg.gradient_accumulation_steps
+
+ grad_norm = None
+ if cfg.max_grad_norm and cfg.max_grad_norm > 0:
+ grad_norm = float(torch.nn.utils.clip_grad_norm_(lora_params, cfg.max_grad_norm))
+ optimizer.step()
+ lr_sched.step()
+ if ema is not None:
+ ema.update(transformer)
+
+ running_loss += step_loss
+ done = opt_step + 1
+ now = time.time()
+ if done == 1:
+ t_steady = now
+ if done % cfg.log_every == 0 or done == cfg.train_steps:
+ if device == "cuda":
+ peak_gb = round(torch.cuda.max_memory_allocated() / 1e9, 2)
+ per_step = cfg.gradient_accumulation_steps
+ if t_steady is not None and done > 1:
+ sps = round((done - 1) * per_step / max(now - t_steady, 1e-6), 3)
+ else:
+ sps = round(done * per_step / max(now - t_start, 1e-6), 3)
+ _emit(
+ on_event,
+ "progress",
+ step = done,
+ total_steps = cfg.train_steps,
+ loss = round(step_loss, 5),
+ avg_loss = round(running_loss / done, 5),
+ video_loss = round(step_video, 5),
+ audio_loss = round(step_audio, 5),
+ learning_rate = lr_sched.get_last_lr()[0],
+ grad_norm = round(grad_norm, 5) if grad_norm is not None else None,
+ samples_per_second = sps,
+ peak_memory_gb = peak_gb or None,
+ )
+ if _check_stop():
+ stopped = True
+ break
+
+ lora_path: Optional[str] = None
+ ema_path: Optional[str] = None
+ if not (stopped and not _save_on_stop()):
+ layers = get_peft_model_state_dict(transformer)
+ # The trained config, so the alpha survives the round trip rather than being re-derived
+ # as the rank. ``default`` is the adapter name add_adapter used.
+ adapter_config = dict(transformer.peft_config["default"].to_dict())
+ _save_lora(str(out_dir), layers, adapter_config)
+ lora_path = str(out_dir / DEFAULT_LORA_FILENAME)
+ if ema is not None and ema.updates > 0:
+ try:
+ ema_dir = save_ema_adapter(
+ ema,
+ transformer,
+ lambda _pipe, d, l: _save_lora(d, l, adapter_config),
+ str(out_dir),
+ )
+ ema_path = str(Path(ema_dir) / DEFAULT_LORA_FILENAME)
+ except Exception as exc: # noqa: BLE001 -- the primary adapter is already saved
+ _emit(on_event, "warning", message = f"EMA adapter save failed: {exc}")
+ _emit(
+ on_event,
+ "complete",
+ output_dir = str(out_dir),
+ lora_path = lora_path,
+ ema_path = ema_path,
+ catalog_path = None,
+ family = cfg.resolved_family,
+ base_model = cfg.base_model,
+ stopped = stopped,
+ steps_run = done if cfg.train_steps else 0,
+ wall_seconds = round(time.time() - t_start, 1),
+ )
+ return str(out_dir)
+
+
+def _dataset_canvas(clip_path: str, short_edge: int) -> tuple[int, int]:
+ """The one canvas the run trains on, from the first clip's DISPLAYED aspect ratio."""
+ import av
+
+ with av.open(str(clip_path)) as container:
+ stream = container.streams.video[0]
+ source_w = int(stream.codec_context.width)
+ source_h = int(stream.codec_context.height)
+ # The coded size is not the displayed size for a rotated clip, and decode_clip rotates
+ # its frames, so a portrait phone clip would otherwise get a landscape canvas and be
+ # cover-cropped down to it. One frame is decoded because the matrix travels with the
+ # frame; the container is open either way.
+ theta = 0
+ try:
+ frame = next(container.decode(video = 0), None)
+ if frame is not None:
+ theta = display_rotation_degrees(frame, stream)
+ except Exception: # noqa: BLE001 -- an undecodable first frame is decode_clip's error to raise
+ theta = 0
+ if theta in (90, 270):
+ source_w, source_h = source_h, source_w
+ return h3_train_canvas(source_w, source_h, short_edge = short_edge)
diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.py
index 7710cd24e9b..70d5c3238ff 100644
--- a/studio/backend/core/training/diffusion_train_common.py
+++ b/studio/backend/core/training/diffusion_train_common.py
@@ -60,16 +60,17 @@ _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", "ltx-2"}
+ {"qwen-image", "z-image", "krea-2", "flux.2-klein", "flux.2-dev", "ltx-2", "minimax-h3"}
)
# 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"})
+# picker -- so the trainable set lives here, next to the trainers, and every name in it MUST
+# resolve through ``get_trainer``. Not necessarily to the DiT loop: LTX-2 is a
+# ``diffusion_dit_trainer._SPECS`` family, while MiniMax-H3 has its own trainer. 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", "minimax-h3"})
# Families whose ``flow_shift`` default is "auto" (reproduce the family's INFERENCE sigma
# distribution) rather than the historical identity 1.0. Both schedulers set
@@ -78,7 +79,14 @@ TRAINABLE_VIDEO_FAMILIES: frozenset[str] = frozenset({"ltx-2"})
# 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"})
+#
+# MiniMax-H3 is here for the same reason, reached differently: its schedules carry an explicit
+# exponential shift (12.0 video, 3.0 audio, from the released scheduler configs) rather than a
+# dynamic one, and ``run_h3_lora_training`` applies those two whenever ``flow_shift`` is not a
+# number. Without this entry an omitted flow_shift normalized to the identity 1.0, which IS a
+# number, so the trainer took it and every default H3 run trained against an unshifted
+# distribution the sampler never visits.
+AUTO_FLOW_SHIFT_FAMILIES: frozenset[str] = frozenset({"qwen-image", "ltx-2", "minimax-h3"})
# 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).
@@ -149,16 +157,21 @@ def _component_only_repos() -> dict[str, tuple[str, str, str]]:
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 hosted pre-quantized DENOISER (a video family's ``prequant_repos``) is the same shape: the
+ DiT alone, no pipeline around it. The image registry's identically-named table means the
+ opposite -- a full quantized pipeline mirror -- so the two are read separately rather than
+ together.
+
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()]
+ image_families = [detect_family("", override = n) for n in supported_family_names()]
+ video_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:
+ for fam, is_video in [(f, False) for f in image_families] + [(f, True) for f in video_families]:
if fam is None:
continue
for attr in ("base_repo", "deploy_base_repo"):
@@ -166,9 +179,23 @@ def _component_only_repos() -> dict[str, tuple[str, str, str]]:
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.
+ # (scheme, repo) and (base, scheme, repo). The two registries mean DIFFERENT things by
+ # these tables, so they cannot be read the same way. An image family's entry is a full
+ # quantized PIPELINE mirror, and so a base. A video family's is a hosted pre-quantized
+ # DENOISER -- the DiT alone, as the field's own docstring says -- which is a component in
+ # exactly the way a pre-cast text encoder is: no model_index.json, no VAE, no scheduler.
+ # Treating one as a base is what let it through the training preflight, resolve to its
+ # family by name, pass the unsloth/* trust gate, and fail inside from_pretrained only
+ # after the resident GPU workloads had been evicted.
for table in ("prequant_repos", "prequant_variant_repos"):
- bases.update(str(row[-1]).strip().lower() for row in getattr(fam, table, ()) if row)
+ for row in getattr(fam, table, ()) or ():
+ if not row:
+ continue
+ repo = str(row[-1]).strip().lower()
+ if is_video:
+ components.setdefault(repo, (fam.name, "transformer", str(fam.base_repo)))
+ else:
+ bases.add(repo)
for _scheme, component, repo in getattr(fam, "te_prequant_repos", ()):
components.setdefault(
str(repo).strip().lower(), (fam.name, str(component), str(fam.base_repo))
@@ -229,10 +256,17 @@ def _assert_family_pipeline_available(fam: Any) -> None:
called in plenty of places that never train, so making it depend on a working diffusers import
would refuse configs over an unrelated environment problem.
- Family-agnostic on purpose: it reads ``fam.pipeline_class`` off whatever spec it is handed, so
- the image registry and the separate video registry share one gate rather than one each."""
- from core.inference.diffusion_families import assert_pipeline_class_available
- assert_pipeline_class_available(fam.pipeline_class, fam.name)
+ Family-agnostic on purpose: it reads the probe class off whatever spec it is handed, so the
+ image registry and the separate video registry share one gate rather than one each. The class
+ comes from ``family_probe_class`` rather than ``fam.pipeline_class`` for the reason that
+ helper documents: a modular family's ``pipeline_class`` is the generic ``ModularPipeline``,
+ which an older diffusers exports regardless, so probing it accepted a MiniMax-H3 start that
+ the listing had already hidden and the child could only fail -- after the teardown."""
+ from core.inference.diffusion_families import (
+ assert_pipeline_class_available,
+ family_probe_class,
+ )
+ assert_pipeline_class_available(family_probe_class(fam), fam.name)
def training_pipeline_import_error(resolved_family: str) -> Optional[str]:
@@ -249,7 +283,10 @@ 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
+ from core.inference.diffusion_families import (
+ assert_pipeline_class_available,
+ family_probe_class,
+ )
# 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.
@@ -257,7 +294,7 @@ def training_pipeline_import_error(resolved_family: str) -> Optional[str]:
if fam is None:
return None
try:
- assert_pipeline_class_available(fam.pipeline_class, fam.name, strict = True)
+ assert_pipeline_class_available(family_probe_class(fam), fam.name, strict = True)
except ValueError as e:
return str(e)
return None
@@ -284,9 +321,17 @@ def resolve_trainable_family(base_model: str, model_family: Optional[str] = None
"""
name = str(base_model or "").strip().lower()
# GGUF weights (a ``.gguf`` file or ``*-GGUF`` repo) are inference-only: training needs the full diffusers pipeline.
- # Exempt a local diffusers checkout that merely has "gguf" in its path, identified by its ``model_index.json``.
+ # Exempt a local diffusers checkout that merely has "gguf" in its path, identified by its
+ # index file. ``modular_model_index.json`` counts: a MODULAR_BASE_FAMILIES checkout (MiniMax-H3)
+ # has that and no ``model_index.json``, so reading only the conventional name refused the one
+ # local form the family has, under /models/gguf/..., before model_family could even be read.
local = Path(base_model).expanduser() if base_model else None
- is_local_diffusers = bool(local and (local / "model_index.json").is_file())
+ is_local_diffusers = bool(
+ local
+ and (
+ (local / "model_index.json").is_file() or (local / "modular_model_index.json").is_file()
+ )
+ )
if name.endswith(".gguf") or ("gguf" in name and not is_local_diffusers):
raise ValueError(
f"'{base_model}' is a GGUF checkpoint/repo, which can't be a training base "
@@ -442,6 +487,11 @@ def get_trainer(family: str) -> Callable[..., str]:
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
+ # MiniMax-H3 has its own loop: it denoises video and audio jointly over one packed
+ # sequence on two coupled schedules, which is outside the DiT trainer's _FamilySpec seams.
+ if key == "minimax-h3":
+ from core.training.diffusion_h3_trainer import run_h3_lora_training
+ return run_h3_lora_training
raise ValueError(f"No trainer is registered for family {family!r}.")
@@ -481,6 +531,18 @@ FAMILY_TRAIN_DEFAULTS: dict[str, dict[str, Any]] = {
"resolution": 512,
"lr_warmup_steps": 20,
},
+ # MiniMax-H3. ``resolution`` is the canvas SHORT EDGE, and 768 is the one the released
+ # checkpoint generates on, so a training clip's spatial statistics land exactly on the
+ # distribution the sampler works in. rank 16 rather than LTX-2's 32: the adapter is applied
+ # to the audio rows as well as the video ones (one shared block stack), so a smaller
+ # adapter is the conservative default. Batch size is pinned to 1 by the trainer.
+ "minimax-h3": {
+ "lora_rank": 16,
+ "learning_rate": 1e-4,
+ "resolution": 768,
+ "lr_warmup_steps": 20,
+ "train_batch_size": 1,
+ },
}
@@ -499,6 +561,7 @@ _FAMILY_LABELS = {
"flux.2-klein": "FLUX.2 Klein",
"flux.2-dev": "FLUX.2-dev",
"ltx-2": "LTX-2",
+ "minimax-h3": "MiniMax-H3",
}
# 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.
@@ -532,6 +595,20 @@ _FAMILY_TRAIN_SPECS: dict[str, dict[str, Any]] = {
"gated": False,
"note": "Video: trains a style LoRA on still images.",
},
+ # Video + audio. Measured on a B200 at the released 768 short edge, 22-frame clips,
+ # rank 16, batch 1, gradient checkpointing: the training LOOP peaks around 44 GB (nf4 with
+ # the dtype-reading modules kept dense, see _H3_NF4_SKIP_MODULES), but the RUN peaks far
+ # higher while the 63 GiB Qwen3-VL conditioner 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: a real 20-step run on this branch peaked at
+ # 77.76 GB, so 72 was under its own measurement and sized users onto a card that OOMs
+ # only after the conditioner has loaded.
+ "minimax-h3": {
+ "params": "31B",
+ "qlora_vram_gb": 80,
+ "gated": False,
+ "note": "Video with sound: trains on clips that have a soundtrack.",
+ },
}
# Facts that differ between selectable checkpoints inside one family. Keys are canonical
# upstream ids; family_train_infos also publishes the mirror aliases so a custom mirror pick
@@ -562,6 +639,10 @@ def _family_vram_note(name: str) -> str:
_DIT_TRAIN_FAMILIES = frozenset(
{"flux.1", "qwen-image", "z-image", "krea-2", "flux.2-klein", "flux.2-dev", "ltx-2"}
)
+# Families with a flow-matching trainer that is NOT diffusion_dit_trainer, but which still
+# expose base_precision and need bf16 on CUDA. Kept separate so the DiT-specific levers
+# (compile, the shared sigma table) do not follow.
+_FLOW_TRAIN_FAMILIES = _DIT_TRAIN_FAMILIES | {"minimax-h3"}
def effective_mixed_precision(cfg: Any) -> str:
@@ -576,11 +657,15 @@ def effective_mixed_precision(cfg: Any) -> str:
import torch # noqa: PLC0415 -- keep the import list light for the training subprocess
requested = str(getattr(cfg, "mixed_precision", "") or "")
- if str(getattr(cfg, "resolved_family", "") or "").strip().lower() in _DIT_TRAIN_FAMILIES:
- # The DiT trainer does not read mixed_precision at all: weight_dtype is bf16 on CUDA and
- # fp32 otherwise. Recording the REQUEST for those families put "fp16" or "no" in the
- # identity of a run that executed in bf16, and a later bf16 resume of it was then
- # rejected as a precision mismatch between two runs that ran identically.
+ if str(getattr(cfg, "resolved_family", "") or "").strip().lower() in _FLOW_TRAIN_FAMILIES:
+ # No flow-matching trainer reads mixed_precision at all: weight_dtype is bf16 on CUDA and
+ # fp32 otherwise, in the DiT loop and in the H3 loop alike. Recording the REQUEST for those
+ # families put "fp16" or "no" in the identity of a run that executed in bf16, and a later
+ # bf16 resume of it was then rejected as a precision mismatch between two runs that ran
+ # identically. _FLOW_TRAIN_FAMILIES rather than _DIT_TRAIN_FAMILIES so the answer follows
+ # the weight dtype rather than which loop happens to own the family: H3 refuses a non-bf16
+ # request and writes no checkpoint today, so this is the same string either way for every
+ # config it accepts, but the helper stops being the odd one out the day that changes.
return "bf16" if torch.cuda.is_available() else "no"
if not torch.cuda.is_available():
return "no"
@@ -617,8 +702,12 @@ def bf16_unsupported_reason(resolved_family: str) -> Optional[str]:
live GPU cannot provide, else None. The DiT trainer requires a bf16-capable GPU (Ampere
or newer) and otherwise raises deep in model load; the start route uses this to fail fast
BEFORE evicting resident GPU workloads. CPU-only hosts (which fall back to fp32 for
- import/unit tests) and SDXL (its own mixed_precision path) are exempt. Never raises."""
- if (resolved_family or "").strip().lower() not in _DIT_TRAIN_FAMILIES:
+ import/unit tests) and SDXL (its own mixed_precision path) are exempt. Never raises.
+
+ Covers every FLOW-matching trainer, not just the DiT one: MiniMax-H3 has the same bf16
+ requirement (its checkpoint keeps the patch projections and output heads in fp32) and the
+ same eviction ordering to protect."""
+ if (resolved_family or "").strip().lower() not in _FLOW_TRAIN_FAMILIES:
return None
try:
import torch
@@ -640,8 +729,11 @@ def dit_accelerator_missing_reason(resolved_family: str) -> Optional[str]:
quantization." unless CUDA, XPU or MPS is present. Without this gate a GPU-less host
accepts the default nf4 start, evicts the resident Images pipeline, downloads the text
encoders, and only then dies in the child. SDXL keeps its own fp32-on-CPU path.
+
+ Covers MiniMax-H3 too, for the same reason: it loads its denoiser through the same 4-bit
+ quantizer.
"""
- if (resolved_family or "").strip().lower() not in _DIT_TRAIN_FAMILIES:
+ if (resolved_family or "").strip().lower() not in _FLOW_TRAIN_FAMILIES:
return None
try:
import torch
@@ -686,7 +778,7 @@ def training_precision_preflight_error(resolved_family: str, base_precision: str
return reason
fam = (resolved_family or "").strip().lower()
mode = (base_precision or "").strip().lower()
- if fam in _DIT_TRAIN_FAMILIES and mode in ("bf16", "int8", "fp8", "mxfp8"):
+ if fam in _FLOW_TRAIN_FAMILIES and mode in ("bf16", "int8", "fp8", "mxfp8"):
# The DiT trainer's dense precisions all require CUDA, and bf16_unsupported_reason exempts a CPU-only host, so without this a dense request would evict residents then raise in the child.
try:
import torch
@@ -746,8 +838,13 @@ def family_train_infos() -> list[dict[str, Any]]:
# 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
+ # base_precision applies to every flow-matching trainer, not only the shared DiT one:
+ # MiniMax-H3 has its own trainer but the same base_precision lever and the same bf16-on-
+ # CUDA requirement. Reading _DIT_TRAIN_FAMILIES here reported precision_modes = [] for it,
+ # which the Train panel reads as "this GPU cannot train this family" and disables Start
+ # with "Not supported on this GPU" -- the trainer was unreachable from Studio on every
+ # host. SDXL keeps its mixed_precision lever and is in neither set.
+ is_dit = name in _FLOW_TRAIN_FAMILIES
# On a non-bf16 CUDA GPU the start preflight rejects EVERY DiT family, so advertise no precision, else /info offers an
# nf4 DiT option that always 400s. Otherwise drop any scheme this family's DiT corrupts, plus any the TRAINING bar
# holds back even though inference passes (fp8 on Qwen-Image: rendering is validated, a training run is not).
@@ -756,6 +853,11 @@ def family_train_infos() -> list[dict[str, Any]]:
if is_dit
else None
)
+ # compile is the one DiT-only lever that does NOT follow the precision one. MiniMax-H3
+ # refuses compile_transformer="on" -- its packed sequence changes length with every
+ # caption, so each step would re-trace -- so advertising the control would offer a
+ # selection that always 400s.
+ supports_compile = bool(not dit_block) and name in _DIT_TRAIN_FAMILIES
if not is_dit or dit_block:
fam_modes: list[str] = []
else:
@@ -793,8 +895,20 @@ def family_train_infos() -> list[dict[str, Any]]:
"note": "" if dit_block else spec.get("note", ""),
"precision_modes": fam_modes,
"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),
+ # compile is offered for SDXL's regional U-Net and the shared DiT trainer, except
+ # a family the GPU cannot train in bf16, and except a trainer that cannot compile.
+ "supports_compile": supports_compile or name == "sdxl",
+ # Same reasoning one field up, for the other control a family can simply not
+ # have. save_steps is REFUSED for a checkpointless family, not ignored, so a
+ # panel that keeps offering "Checkpoint every" turns a nonzero value into a
+ # rejected Start with no way to see why from the control itself.
+ "supports_checkpoints": name not in CHECKPOINTLESS_FAMILIES,
+ # And the third one, for the same reason. A batch > 1 is REFUSED for a family
+ # whose forward covers one packed sequence, so a panel that keeps offering an
+ # unrestricted Batch turns a perfectly reasonable 2 -- or a value carried over
+ # from the family the user was on a moment ago -- into a rejected Start with
+ # nothing on the control to say why.
+ "max_train_batch_size": 1 if name in SINGLE_SEQUENCE_FAMILIES else None,
# 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),
# Families with several train/deploy pairs cannot use the scalar above.
@@ -954,6 +1068,23 @@ class DiffusionLoraConfig:
if self.resume_from_checkpoint is not None
else ""
) or None
+ # The H3 loop does not checkpoint: it neither writes a resume bundle nor restores one.
+ # Accepting these two silently was the dangerous part -- a caller handing over a resume
+ # bundle got a FRESH optimization that then overwrote the outputs it was meant to
+ # continue, and one asking for periodic saves got none, both discovered only after an
+ # expensive run. Refuse in validation, where it costs nothing, until the loop supports it.
+ if resolved_family in CHECKPOINTLESS_FAMILIES:
+ if resume_from_checkpoint:
+ raise ValueError(
+ f"resume_from_checkpoint is not supported for {resolved_family}: its trainer "
+ f"writes no checkpoint bundle, so there is nothing to continue from and the "
+ f"run would silently start over and overwrite its output. Start a fresh run."
+ )
+ if save_steps:
+ raise ValueError(
+ f"save_steps is not supported for {resolved_family}: its trainer writes no "
+ f"checkpoint bundle. Leave it at 0; the adapter is still saved at the end."
+ )
try:
ema_decay = float(self.ema_decay or 0.0)
except (TypeError, ValueError) as exc:
@@ -987,6 +1118,19 @@ class DiffusionLoraConfig:
# Refuse a scheme this family's DiT is known to corrupt, and also one the training bar holds back while
# inference allows it: qwen-image fp8 now renders inside the accuracy gate, but no one has measured whether a
# LoRA converges against fp8-frozen linears, so it fails fast here rather than silently training on faith.
+ # MiniMax-H3 runs all three modalities through one set of linears, so the
+ # per-family activation range the fp8 module filter was measured against does not
+ # describe it. Refuse the float8 modes rather than train against a clipped forward.
+ if resolved_family == "minimax-h3" and base_precision in ("fp8", "mxfp8"):
+ raise ValueError(
+ f"base_precision={base_precision!r} is not supported for minimax-h3: its "
+ f"packed sequence mixes video, audio and text through one set of linears, "
+ f"so the activation range fp8 was measured against does not apply. Use "
+ f"'nf4', 'int8', 'bf16', or 'auto'."
+ )
+ # _family_train_denied, not _family_denied: it is the strict superset (every inference
+ # deny plus the training-only ones), so importing the narrower helper here would let a
+ # scheme cleared only for rendering reach a trainer.
from core.inference.diffusion_transformer_quant import _family_train_denied
if _family_train_denied(resolved_family, base_precision):
@@ -1311,6 +1455,167 @@ def discover_image_caption_pairs(
return pairs
+# Families whose trainer has no checkpoint/resume support yet. The shared DiffusionLoraConfig
+# carries save_steps / resume_from_checkpoint for every family, so a loop that implements
+# neither has to say so rather than ignore them.
+CHECKPOINTLESS_FAMILIES: frozenset[str] = frozenset({"minimax-h3"})
+
+# Families whose forward covers ONE packed sequence, so the batch axis is a pure replication
+# axis and a second clip cannot join it: the layout, the rotary grid and the row timesteps are
+# set by that clip's geometry and its caption's length. Kept beside the refusal it explains.
+SINGLE_SEQUENCE_FAMILIES: frozenset[str] = frozenset({"minimax-h3"})
+
+# Families whose trainer loads its base through ``ModularPipeline.from_pretrained``. Their local
+# layout is ``modular_model_index.json`` and no ``model_index.json``, so the conventional shape
+# check in ``_assert_trusted_base_model`` refuses the only local form the family HAS. The trainer
+# knew this and passed allow_modular itself; the START ROUTE runs the same gate first, and
+# without the same answer a local H3 pipeline 400'd there before the trainer was ever reached.
+# One set, read by both, so the two cannot drift into disagreeing about the same directory.
+MODULAR_BASE_FAMILIES: frozenset[str] = frozenset({"minimax-h3"})
+
+# MiniMax-H3 canvas multiple: a 16x VAE compression and a 2x patch.
+_H3_CANVAS_MULTIPLE = 32
+
+
+def h3_train_unsupported_reason(cfg: Any) -> Optional[str]:
+ """Reason this config cannot run the MiniMax-H3 trainer, else None. Never raises.
+
+ Called by the START ROUTE before it frees the resident GPU models, and again by the trainer
+ itself so a direct call is refused the same way. Config-only by construction: every check
+ here reads the request, never the host, so the route can answer without importing torch or
+ touching the GPU. Host capability stays in the precision preflight next to it.
+ """
+ if (getattr(cfg, "resolved_family", "") or "").strip().lower() != "minimax-h3":
+ return None
+ if cfg.mixed_precision != "bf16":
+ return (
+ "MiniMax-H3 LoRA training requires bf16: its checkpoint keeps the patch "
+ "projections, the timestep MLP and the output heads in fp32 and fp16 overflows "
+ "them. The loop hard-codes the bf16 weight dtype and autocast either way, so any "
+ "other setting would be recorded and then not run. Set mixed precision to bf16."
+ )
+ if cfg.resolution % _H3_CANVAS_MULTIPLE:
+ return (
+ f"MiniMax-H3 trains on a canvas whose edges are multiples of {_H3_CANVAS_MULTIPLE} "
+ f"(a 16x VAE compression and a 2x patch); got resolution {cfg.resolution}."
+ )
+ if float(getattr(cfg, "cfg_dropout", 0.0) or 0.0) > 0:
+ return (
+ "MiniMax-H3 is guidance-distilled: it has no unconditional branch and no negative "
+ "prompt, so a classifier-free-guidance dropout trains a path the sampler never "
+ "takes. Set cfg_dropout to 0."
+ )
+ if str(getattr(cfg, "weighting_scheme", "none") or "none") != "none":
+ return (
+ "MiniMax-H3 has no timestep-weighted loss yet: its two schedules put video and "
+ "audio at different sigmas in the same step, so a single weight over 'the' "
+ "timestep is ambiguous. Use weighting_scheme='none'."
+ )
+ # The batch axis of an H3 forward is a pure replication axis: the layout, the rotary grid
+ # and the row timesteps describe ONE packed sequence that every batch item shares. Two
+ # clips with different captions have different text lengths and therefore different
+ # layouts, so a batch > 1 cannot be formed without padding the model has no mask for.
+ if cfg.train_batch_size != 1:
+ return (
+ "MiniMax-H3 trains at batch size 1: one forward covers one packed sequence, whose "
+ "row layout is set by the clip's own geometry and its caption's length. Use "
+ "gradient_accumulation_steps to raise the effective batch."
+ )
+ # torch.compile is never invoked here (the packed layout changes shape with every clip's
+ # caption length, so each step would recompile), and the run already reports compiled=False.
+ # "auto" means "the trainer decides", which it does; an explicit "on" is a policy that would
+ # be accepted and then ignored.
+ if str(getattr(cfg, "compile_transformer", "auto") or "auto").strip().lower() == "on":
+ return (
+ "MiniMax-H3 does not compile: its packed sequence changes length with every clip's "
+ "caption, so torch.compile would re-trace each step. Use compile_transformer "
+ "'off' or 'auto'."
+ )
+ # No conditioning cache exists on this path: the conditioner is loaded and every caption and
+ # latent recomputed each run. Accepting the directory would promise a saving that never
+ # happens, so an explicit one is refused rather than silently unused.
+ if str(getattr(cfg, "cond_cache_dir", "") or "").strip():
+ return (
+ "MiniMax-H3 has no persistent conditioning cache yet: each run loads the "
+ "conditioner and recomputes its captions and latents, so cond_cache_dir would be "
+ "recorded and never read. Leave it unset."
+ )
+ return None
+
+
+# The SCHEMA defaults the MiniMax-H3 loop cannot honour, and the value it actually runs with.
+# Unlike the fields ``h3_train_unsupported_reason`` refuses, these have a DEFAULT that the loop
+# disagrees with, so refusing them would 422 every untouched request; they are normalised
+# instead. center_crop/random_flip: every frame goes through the same centre cover-crop and
+# nothing is flipped (a per-frame flip tears a clip, and a per-clip one has nowhere to live --
+# the cached tensors carry no variant axis). snr_gamma: the step is a plain unweighted MSE.
+# cache_latents/cache_variants: the loop encodes every clip once, up front, into exactly one
+# cached (video_a, video_b, audio) tuple and then frees the VAEs, with no per-step encode path
+# to fall back to and nowhere to put a second draw. It never reads either field, so a request
+# asking for no cache, or for the schema's four variants, got one cache of one variant anyway
+# and a run record claiming otherwise.
+_H3_FIXED_RECIPE: dict[str, Any] = {
+ "center_crop": True,
+ "random_flip": False,
+ "snr_gamma": None,
+ "cache_latents": True,
+ "cache_variants": 1,
+}
+
+
+def train_recipe_overrides(cfg: Any) -> dict[str, Any]:
+ """The fields whose REQUESTED value this family's loop replaces, mapped to what it runs.
+
+ Shared for the same reason ``h3_train_unsupported_reason`` is: the trainer applies these in
+ the CHILD, while the run record is written by the PARENT from the config handed to
+ ``service.start``. Normalising in the trainer alone therefore fixed what ran and left Previous
+ Runs describing cropping, flipping and min-SNR weighting that never happened -- exactly the
+ recipe drift the normalisation exists to prevent. Both sides read this one table instead.
+
+ Empty for every other family: their loops honour all three."""
+ if (getattr(cfg, "resolved_family", "") or "").strip().lower() != "minimax-h3":
+ return {}
+ return dict(_H3_FIXED_RECIPE)
+
+
+# Families whose dataset is captioned video CLIPS rather than stills. LTX-2 is deliberately not
+# here: it trains a style LoRA FROM still images, so it keeps the image discovery.
+CLIP_TRAINED_FAMILIES: frozenset[str] = frozenset({"minimax-h3"})
+
+
+def discover_training_pairs(
+ resolved_family: str,
+ data_dir: str | os.PathLike[str],
+ *,
+ instance_prompt: Optional[str] = None,
+ caption_column: str = "text",
+ verify_images: bool = False,
+) -> list[tuple[str, str]]:
+ """The ``(path, caption)`` pairs for ``resolved_family``, from whichever discovery its
+ trainer runs.
+
+ The /diffusion/start preflight exists so a bad dataset 400s BEFORE the resident GPU models
+ are freed, which only holds while it runs the SAME discovery as the trainer. It ran the
+ image one unconditionally, so a MiniMax-H3 dataset -- captioned clips, which is the only
+ thing its trainer accepts -- was rejected at the route with "No captioned images found" and
+ the advertised H3 trainer could not be reached through /diffusion/start at all.
+
+ ``verify_images`` is image-only: the clip discovery has no cheap header probe to match it
+ (a container has to be opened to be judged), so it is ignored for a clip family rather than
+ quietly implying a check that did not happen."""
+ if str(resolved_family or "").strip().lower() in CLIP_TRAINED_FAMILIES:
+ from core.training.diffusion_h3_clips import discover_clip_caption_pairs
+ return discover_clip_caption_pairs(
+ data_dir, instance_prompt = instance_prompt, caption_column = caption_column
+ )
+ return discover_image_caption_pairs(
+ data_dir,
+ instance_prompt = instance_prompt,
+ caption_column = caption_column,
+ verify_images = verify_images,
+ )
+
+
def _emit(on_event: Optional[EventCb], type_: str, **kw: Any) -> None:
if on_event is not None:
on_event({"type": type_, "ts": time.time(), **kw})
@@ -1454,6 +1759,8 @@ _TRAIN_EXTRA_TRUSTED_REPOS = frozenset(
# 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",
+ # MiniMax-H3's official base, for the same reason: safetensors-only, no remote code.
+ "minimaxai/minimax-h3",
}
)
@@ -1478,11 +1785,15 @@ def _refuse_ltx23_training_base(base_model: str) -> None:
)
-def _assert_trusted_base_model(base_model: str) -> None:
+def _assert_trusted_base_model(base_model: str, *, allow_modular: bool = False) -> None:
"""Gate the training base model the same way the inference backend gates non-GGUF loads:
a local path or a trusted repo (``unsloth/*`` or an allowlisted official base). This runs
BEFORE ``from_pretrained`` so an untrusted remote repo (which could ship pickle weights)
- is never fetched or deserialised."""
+ is never fetched or deserialised.
+
+ ``allow_modular`` is for a trainer whose loader is ``ModularPipeline.from_pretrained``: a
+ local MiniMax-H3 pipeline carries ``modular_model_index.json`` and no ``model_index.json``,
+ so the conventional shape check rejected the one local layout that family HAS."""
from core.inference.diffusion import _assert_local_base_is_pipeline, _is_trusted_diffusion_repo
trusted = (
@@ -1494,8 +1805,8 @@ def _assert_trusted_base_model(base_model: str) -> None:
f"Refusing to train from untrusted base model '{base_model}'. Use a local path or "
f"a trusted repo (an unsloth/* repo or an official base)."
)
- # An existing LOCAL base is loaded as a full pipeline, which needs a model_index.json; reject a non-pipeline local dir before /diffusion/start frees the GPU models.
- _assert_local_base_is_pipeline(base_model)
+ # An existing LOCAL base is loaded as a full pipeline, which needs an index; reject a non-pipeline local dir before /diffusion/start frees the GPU models.
+ _assert_local_base_is_pipeline(base_model, allow_modular = allow_modular)
# ── resume checkpoints ────────────────────────────────────────────────────────
diff --git a/studio/backend/core/training/diffusion_training_service.py b/studio/backend/core/training/diffusion_training_service.py
index dbb67f86cdf..2c17219c0a8 100644
--- a/studio/backend/core/training/diffusion_training_service.py
+++ b/studio/backend/core/training/diffusion_training_service.py
@@ -299,6 +299,9 @@ def _idle_state() -> dict[str, Any]:
"avg_loss": None,
"learning_rate": None,
"grad_norm": None,
+ # The last per-modality losses of a joint run; None on families that train one modality.
+ "video_loss": None,
+ "audio_loss": None,
"num_images": None,
"in_model_load": False,
"output_dir": None,
@@ -328,23 +331,41 @@ def _idle_state() -> dict[str, Any]:
"metric_loss": [],
"metric_lr": [],
"metric_grad_norm": [],
+ # The two halves of MiniMax-H3's joint objective. Null on every other family, and null
+ # on H3 steps that reported only the combined loss, so the series stay index-aligned.
+ "metric_video_loss": [],
+ "metric_audio_loss": [],
}
+# The value series, in append order, paired index-for-index with ``metric_steps``. One list so a
+# new series cannot be added to the appends and forgotten in the decimation below, which would
+# leave the curves silently misaligned rather than failing.
+_METRIC_SERIES: tuple[str, ...] = (
+ "metric_loss",
+ "metric_lr",
+ "metric_grad_norm",
+ "metric_video_loss",
+ "metric_audio_loss",
+)
+
+
def _append_metric(
state: dict[str, Any],
step: Any,
loss: Any,
lr: Any,
grad_norm: Any = None,
+ video_loss: Any = None,
+ audio_loss: Any = None,
) -> None:
- """Append one (step, loss, lr, grad_norm) point to the bounded history arrays on
- ``state``.
+ """Append one (step, loss, lr, grad_norm, video_loss, audio_loss) point to the bounded
+ history arrays on ``state``.
Only records finite, positive-step points (mirrors the LLM trainer, which logs history
only for step > 0 with a real loss). When the arrays hit ``_METRIC_CAP`` they are
decimated in place (keep every other point) so appends stay bounded without losing the
- curve's shape. lr / grad_norm may be None (kept as None so those series can be sparse
+ curve's shape. Everything but loss may be None (kept as None so those series can be sparse
while staying index-aligned with ``steps``)."""
try:
istep = int(step)
@@ -355,28 +376,26 @@ def _append_metric(
floss = _finite_or_none(loss)
if floss is None: # non-numeric or non-finite: skip, keep the curve JSON-safe
return
- # lr / grad_norm may be None or non-finite; non-finite is nulled (not dropped) to stay index-aligned.
- flr = _finite_or_none(lr)
- fgn = _finite_or_none(grad_norm)
+ # Every series but loss may be None or non-finite; non-finite is nulled (not dropped) to
+ # stay index-aligned.
+ values = {
+ "metric_loss": floss,
+ "metric_lr": _finite_or_none(lr),
+ "metric_grad_norm": _finite_or_none(grad_norm),
+ "metric_video_loss": _finite_or_none(video_loss),
+ "metric_audio_loss": _finite_or_none(audio_loss),
+ }
steps = state["metric_steps"]
- losses = state["metric_loss"]
- lrs = state["metric_lr"]
- gns = state["metric_grad_norm"]
if len(steps) >= _METRIC_CAP:
state["metric_steps"] = steps[::2]
- state["metric_loss"] = losses[::2]
- state["metric_lr"] = lrs[::2]
- state["metric_grad_norm"] = gns[::2]
- steps, losses, lrs, gns = (
- state["metric_steps"],
- state["metric_loss"],
- state["metric_lr"],
- state["metric_grad_norm"],
- )
+ for key in _METRIC_SERIES:
+ state[key] = (state.get(key) or [])[::2]
+ steps = state["metric_steps"]
steps.append(istep)
- losses.append(floss)
- lrs.append(flr)
- gns.append(fgn)
+ for key in _METRIC_SERIES:
+ # setdefault, not [key]: a run resumed from a record written before a series existed
+ # carries a state dict without it, and losing the whole point is worse than a short tail.
+ state.setdefault(key, []).append(values[key])
def _resolved_total_steps(state: dict[str, Any], cfg: dict[str, Any]) -> int:
@@ -546,10 +565,13 @@ class DiffusionTrainingService:
Raises ValueError for an unusable config (before any spawn) and RuntimeError if a
job is already running. Returns the new job id."""
- # Validate cheaply BEFORE spawning so a bad request fails fast with a clear error.
+ # Validate cheaply BEFORE spawning so a bad request fails fast with a clear error. The
+ # normalised config is kept: it carries the resolved family the recipe overrides below
+ # are keyed on, which the raw request dict does not have to name.
from .diffusion_lora_trainer import _config_from_dict
+ from .diffusion_train_common import train_recipe_overrides
- _config_from_dict(config).normalized()
+ normalized_cfg = _config_from_dict(config).normalized()
# Join a finished job's pump OUTSIDE the lock: its final state writes take this lock, so joining under it would stall the start and let the stale pump overwrite the new state.
with self._lock:
@@ -609,8 +631,13 @@ class DiffusionTrainingService:
# against, instead of trusting the pathname and offering back whatever later
# occupies that slot.
self._seed_source_identity(config)
- # Keep the config (minus secrets) for the persisted run record.
+ # Keep the config (minus secrets) for the persisted run record, with the fields this
+ # family's loop REPLACES rather than honours set to what it will actually run. The
+ # trainer applies the same table in the child, which the record is not written from,
+ # so without this Previous runs described a recipe (cropping, flipping, min-SNR
+ # weighting) that no step of the run ever used.
self._config = {k: v for k, v in dict(config).items() if k != "hf_token"}
+ self._config.update(train_recipe_overrides(normalized_cfg))
self._pump = threading.Thread(
target = self._pump_loop, args = (event_queue, self._proc), daemon = True
)
@@ -784,6 +811,8 @@ class DiffusionTrainingService:
"avg_loss": s.get("avg_loss"),
"learning_rate": s.get("learning_rate"),
"grad_norm": s.get("grad_norm"),
+ "video_loss": s.get("video_loss"),
+ "audio_loss": s.get("audio_loss"),
"samples_per_second": s.get("samples_per_second"),
"peak_memory_gb": s.get("peak_memory_gb"),
"num_images": s.get("num_images"),
@@ -829,6 +858,8 @@ class DiffusionTrainingService:
"loss": s.get("metric_loss") or [],
"lr": s.get("metric_lr") or [],
"grad_norm": s.get("metric_grad_norm") or [],
+ "video_loss": s.get("metric_video_loss") or [],
+ "audio_loss": s.get("metric_audio_loss") or [],
},
}
path = _runs_dir() / f"{s['job_id']}.json"
@@ -933,6 +964,15 @@ class DiffusionTrainingService:
grad_norm = (
_finite_or_none(ev["grad_norm"]) if "grad_norm" in ev else s["grad_norm"]
)
+ # The two halves of a joint objective, when the trainer reports them. Folded
+ # like the rest rather than dropped: on MiniMax-H3 the combined loss can hold
+ # steady while one modality degrades, and these are the only signal that says so.
+ video_loss = (
+ _finite_or_none(ev["video_loss"]) if "video_loss" in ev else s["video_loss"]
+ )
+ audio_loss = (
+ _finite_or_none(ev["audio_loss"]) if "audio_loss" in ev else s["audio_loss"]
+ )
s.update(
status = "running",
step = ev.get("step", s["step"]),
@@ -941,6 +981,8 @@ class DiffusionTrainingService:
avg_loss = avg_loss,
learning_rate = learning_rate,
grad_norm = grad_norm,
+ video_loss = video_loss,
+ audio_loss = audio_loss,
message = "Training...",
)
# Fold optional perf fields so the UI shows throughput + peak VRAM.
@@ -948,13 +990,15 @@ class DiffusionTrainingService:
s["samples_per_second"] = ev.get("samples_per_second")
if ev.get("peak_memory_gb") is not None:
s["peak_memory_gb"] = ev.get("peak_memory_gb")
- # Retain a bounded (step, loss, lr, grad_norm) history for the live charts.
+ # Retain a bounded per-step history for the live charts.
_append_metric(
s,
ev.get("step"),
ev.get("loss"),
ev.get("learning_rate"),
ev.get("grad_norm"),
+ ev.get("video_loss"),
+ ev.get("audio_loss"),
)
elif etype == "complete":
# Reset in_model_load: a stop during model load emits complete with no preceding model_load_completed, leaving a stale indicator.
diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.py
index 627ac4cfdf9..8a6a0d76b5f 100644
--- a/studio/backend/hub/services/models/local_inventory.py
+++ b/studio/backend/hub/services/models/local_inventory.py
@@ -123,10 +123,17 @@ def _is_diffusers_pipeline_dir(path: Path) -> bool:
publisher walk descends into it and offers its components (``vae``, ``transformer``, ...) as
separate models, none of which any loader can start.
+ Either index counts. A Modular Diffusers pipeline carries ``modular_model_index.json`` and no
+ ``model_index.json``, which is the pair the video loader accepts, so recognising only the
+ conventional one hid a valid local root from the picker and left the publisher walk to offer
+ its components separately.
+
``routes.models._local_pipeline_index`` is the same test; the two scanners are separate
modules, and only that one had it."""
try:
- return (path / "model_index.json").is_file()
+ return (path / "model_index.json").is_file() or (
+ path / "modular_model_index.json"
+ ).is_file()
except OSError:
return False
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index 135da11b0be..3678078836f 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -153,6 +153,28 @@ def test_the_h3_native_repo_is_a_recognised_bundle_repo():
assert gguf.is_h3_bundle_repo(H3_GGUF_REPO)
+def test_minimax_h3_variant_labels_name_the_partition_and_build():
+ variants = [
+ gguf.GgufVariantInfo(
+ filename = "minimax_h3_fl2va_pruned-Q4_K_M.gguf",
+ quant = "minimax_h3_fl2va_pruned-Q4_K_M",
+ size_bytes = 1,
+ ),
+ gguf.GgufVariantInfo(
+ filename = "minimax_h3_ref2va-Q4_K_M.gguf",
+ quant = "minimax_h3_ref2va-Q4_K_M",
+ size_bytes = 1,
+ ),
+ ]
+
+ gguf._apply_gguf_display_labels(variants)
+
+ assert [variant.display_label for variant in variants] == [
+ "Text & frames · Q4_K_M · Pruned",
+ "References · Q4_K_M · Full",
+ ]
+
+
def test_big_endian_detection_ignores_model_name_be_token():
assert gguf.is_big_endian_gguf_path("model-Q4_K_M-be.gguf", "Q4_K_M")
assert gguf.is_big_endian_gguf_path("model-Q4_K_M_be_infill.gguf", "Q4_K_M")
@@ -6481,6 +6503,27 @@ def test_the_pipeline_test_is_safe_on_a_path_that_is_not_a_readable_directory(tm
assert local_inventory._is_diffusers_pipeline_dir(odd) is False
+def test_a_modular_pipeline_root_is_recognised(tmp_path):
+ """A Modular Diffusers pipeline carries ``modular_model_index.json`` and NO
+ ``model_index.json``, which is exactly the pair the video loader accepts. Recognising only
+ the conventional index hid such a root from the Images/Video picker and let the publisher
+ walk descend into it and offer ``transformer`` / ``vae`` as separate, unusable models."""
+ root = tmp_path / "modular"
+ root.mkdir()
+ (root / "modular_model_index.json").write_text("{}")
+ (root / "transformer").mkdir()
+ assert local_inventory._is_diffusers_pipeline_dir(root) is True
+
+ conventional = tmp_path / "conventional"
+ conventional.mkdir()
+ (conventional / "model_index.json").write_text("{}")
+ assert local_inventory._is_diffusers_pipeline_dir(conventional) is True
+
+ neither = tmp_path / "neither"
+ neither.mkdir()
+ assert local_inventory._is_diffusers_pipeline_dir(neither) is False
+
+
def test_gguf_progress_unknown_hashes_calls_a_sibling_only_dir_absent(monkeypatch, tmp_path):
"""A repo dir kept alive by a sibling quant is not evidence that THIS one is here.
diff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.py
index fc4886df4b7..cea4d6376cd 100644
--- a/studio/backend/hub/utils/gguf.py
+++ b/studio/backend/hub/utils/gguf.py
@@ -422,6 +422,11 @@ def gguf_variant_key(filename: str) -> str:
quant = quant_token_with_bpw(path)
if quant is None:
return _unknown_gguf_variant_key(path)
+ # MiniMax H3 bundles two denoiser partitions, and may publish both full and pruned
+ # builds at one quant. Each file is a different loadable checkpoint, so the bare
+ # quant cannot identify the row, download state, or file the loader should open.
+ if path.rsplit("/", 1)[-1].lower().startswith(_H3_DENOISER_PARTITIONS):
+ return _unknown_gguf_variant_key(path)
parents = path.rpartition("/")[0]
if any(segment and not _is_quant_directory(segment) for segment in parents.split("/")):
return _unknown_gguf_variant_key(path)
@@ -467,6 +472,16 @@ def _apply_gguf_display_labels(variants: list[GgufVariantInfo]) -> None:
scopes[scope] = scopes.get(scope, 0) + 1
for variant in variants:
token = extract_quant_token(variant.filename)
+ h3_name = Path(variant.filename).name.lower()
+ h3_partition = next(
+ (partition for partition in _H3_DENOISER_PARTITIONS if h3_name.startswith(partition)),
+ None,
+ )
+ if h3_partition is not None:
+ task = "References" if h3_partition.endswith("ref2va") else "Text & frames"
+ build = "Pruned" if "_pruned-" in h3_name else "Full"
+ variant.display_label = f"{task} · {token or 'GGUF'} · {build}"
+ continue
if token is None:
variant.display_label = f"GGUF · {variant.filename}" if ambiguous else "GGUF"
elif variant.quant.lower() != (_plain_key(variant) or "").lower():
diff --git a/studio/backend/models/training.py b/studio/backend/models/training.py
index 53242ee1521..d42bacaf6aa 100644
--- a/studio/backend/models/training.py
+++ b/studio/backend/models/training.py
@@ -972,14 +972,17 @@ class DiffusionTrainingStartResponse(BaseModel):
class DiffusionMetricHistory(BaseModel):
- """Paired step-indexed history arrays for the live training charts. ``lr`` and
- ``grad_norm`` entries may be null so those sparse series still align with ``steps``
- by index."""
+ """Paired step-indexed history arrays for the live training charts. Every series but
+ ``loss`` may hold nulls so the sparse ones still align with ``steps`` by index."""
steps: List[int] = Field(default_factory = list)
loss: List[float] = Field(default_factory = list)
lr: List[Optional[float]] = Field(default_factory = list)
grad_norm: List[Optional[float]] = Field(default_factory = list)
+ # The two halves of a joint video+audio objective (MiniMax-H3). All-null on every other
+ # family, which is what lets the chart decide whether to draw the split curves at all.
+ video_loss: List[Optional[float]] = Field(default_factory = list)
+ audio_loss: List[Optional[float]] = Field(default_factory = list)
class DiffusionTrainingStatusResponse(BaseModel):
@@ -996,6 +999,10 @@ class DiffusionTrainingStatusResponse(BaseModel):
learning_rate: Optional[float] = None
# Total pre-clip gradient norm from the last optimizer step (health signal the UI charts).
grad_norm: Optional[float] = None
+ # The last per-modality losses of a joint video+audio run (MiniMax-H3), None elsewhere. The
+ # combined loss can hold steady while one modality degrades, so these are reported apart.
+ video_loss: Optional[float] = None
+ audio_loss: Optional[float] = None
num_images: Optional[int] = None
in_model_load: bool = False
output_dir: Optional[str] = None
@@ -1104,6 +1111,16 @@ class DiffusionTrainableFamily(BaseModel):
precision_modes: List[str] = Field(default_factory = list)
recommended_precision: str = "nf4"
supports_compile: bool = False
+ # Whether this family's loop writes checkpoint bundles. False makes the panel drop the
+ # "Checkpoint every" control: save_steps is refused, not ignored, for such a family, so
+ # offering the control means offering a value that rejects Start. Defaults True so an older
+ # backend's payload, which has no such families in it, keeps the control.
+ supports_checkpoints: bool = True
+ # The largest batch this family's loop can form, or None for unrestricted. 1 for a family
+ # whose forward covers one packed sequence: the panel then drops the Batch control, since a
+ # value above the cap is refused rather than clamped. Declared here or Pydantic silently
+ # drops it from the response and the panel's clamp never receives its input.
+ max_train_batch_size: Optional[int] = None
# When set, a LoRA trained on this family previews on this repo instead of the training base (Krea trains on Raw, runs on Turbo).
deploy_base: Optional[str] = None
# Variant-specific training-base to inference-base pairs, including public mirror ids.
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 7d3a539b595..027c7cfe27c 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -299,10 +299,15 @@ def _has_non_gguf_weights(path: Path) -> bool:
def _local_pipeline_index(d: Path) -> bool:
- """True when *d* is a diffusers PIPELINE root (top-level ``model_index.json``, weights in
- component subdirs), which ``_is_model_directory`` (root config + loose weights) rejects."""
+ """True when *d* is a diffusers PIPELINE root (a top-level index, weights in component
+ subdirs), which ``_is_model_directory`` (root config + loose weights) rejects.
+
+ Either index counts. A Modular Diffusers pipeline carries ``modular_model_index.json`` and no
+ ``model_index.json``, and the video loader accepts exactly that pair, so recognising only the
+ conventional one hid a valid local root from the picker and let the publisher walk descend
+ into it and offer its components as separate, unusable models."""
try:
- return (d / "model_index.json").is_file()
+ return (d / "model_index.json").is_file() or (d / "modular_model_index.json").is_file()
except OSError:
return False
@@ -3897,10 +3902,24 @@ _VIDEO_GEN_TASK = "text-to-video"
_UNSUPPORTED_DIFFUSION_TASK = "image-diffusion-unsupported"
+# The two denoiser partitions, by the filename prefix the loader itself validates against
+# (``video_minimax_h3``). These GGUFs carry no architecture metadata, so the NAME is the only
+# evidence there is, and it is the same evidence the load path acts on.
+_H3_DENOISER_GGUF_PREFIXES = ("minimax_h3_fl2va", "minimax_h3_ref2va")
+
+
def _is_h3_bundle_gguf_hint(hint: Optional[str]) -> bool:
- """True when a name hint is one of the MiniMax-H3 GGUF bundle repos (video, never chat)."""
+ """True when a name hint names MiniMax-H3 GGUF weights (video, never chat).
+
+ Either a known bundle repo id, or a validated denoiser FILENAME. The filename half matters
+ for a GGUF the user copied into a custom local directory rather than leaving under one of the
+ bundle ids: with no architecture metadata to fall back on, ``_local_model_task`` returned null
+ and an otherwise loadable checkpoint was dropped from the Video On Device picker."""
if not hint:
return False
+ name = str(hint).strip().lower().rsplit("/", 1)[-1].rsplit("\\", 1)[-1]
+ if name.endswith(".gguf") and name.startswith(_H3_DENOISER_GGUF_PREFIXES):
+ return True
try:
from hub.utils.gguf import is_h3_bundle_repo
return is_h3_bundle_repo(hint)
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index fe358d241ad..2649783a9d3 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -2775,6 +2775,16 @@ async def start_diffusion_training(
),
)
+ # Same rule for the MiniMax-H3 trainer's own restrictions, which are config-only and so
+ # answerable here: a batch > 1, a non-bf16 precision, a weighting scheme, a compile
+ # request or a conditioning-cache directory used to reach the worker and 400 there, with
+ # the user's resident models already evicted for a run that never started.
+ from core.training.diffusion_train_common import h3_train_unsupported_reason
+
+ _h3_reason = h3_train_unsupported_reason(normalized_cfg)
+ if _h3_reason:
+ raise HTTPException(status_code = 400, detail = _h3_reason)
+
# Preflight the requested DiT precision BEFORE freeing GPU residents: the trainer's own
# checks fire only in the child, AFTER eviction. Fail fast (400).
from core.training.diffusion_train_common import training_precision_preflight_error
@@ -2837,10 +2847,19 @@ async def start_diffusion_training(
raise HTTPException(status_code = 400, detail = str(e))
# Run the trainers' trust gate here too, so an untrusted/typoed base 400s BEFORE freeing GPU residents rather than failing in the child.
- from core.training.diffusion_train_common import _assert_trusted_base_model
+ from core.training.diffusion_train_common import (
+ MODULAR_BASE_FAMILIES,
+ _assert_trusted_base_model,
+ )
try:
- _assert_trusted_base_model(config.get("base_model", ""))
+ # Same answer the trainer's own call reaches. A local MiniMax-H3 pipeline is a modular
+ # directory (modular_model_index.json, no model_index.json); without this the gate here
+ # rejected it and returned 400 before the trainer that CAN load it ever ran.
+ _assert_trusted_base_model(
+ config.get("base_model", ""),
+ allow_modular = normalized_cfg.resolved_family in MODULAR_BASE_FAMILIES,
+ )
except ValueError as e:
raise HTTPException(status_code = 400, detail = str(e))
@@ -2865,16 +2884,24 @@ async def start_diffusion_training(
# Fail closed on clips BEFORE that discovery, which cannot see them: clip-only it
# reports the folder as uncaptioned, and mixed it succeeds on the images and trains on
# that subset without saying so.
+ # For the IMAGE-trained families only. A clip-trained family is the case this refusal
+ # was written to protect against, so leaving it unconditional rejected every valid
+ # MiniMax-H3 request with "training from clips is not supported yet" -- the trainer this
+ # branch adds, unreachable through its own route. discover_training_pairs below already
+ # branches on the family; this is the same question asked one step earlier.
# In a worker thread like the discovery below it, and for the same reason: the scan stats
# every file and reads the caption sidecars, which on a large or network-mounted dataset
# would hold the event loop and stall status/stop alongside it.
- clip_refusal = await asyncio.to_thread(_clip_dataset_refusal, config["data_dir"])
- if clip_refusal is not None:
- raise HTTPException(status_code = 400, detail = clip_refusal)
+ mixed_refusal = await asyncio.to_thread(
+ _mixed_media_refusal, config["data_dir"], normalized_cfg.resolved_family
+ )
+ if mixed_refusal is not None:
+ raise HTTPException(status_code = 400, detail = mixed_refusal)
# Preflight the dataset: a missing/empty/uncaptionable data_dir otherwise fails inside the trainer AFTER eviction. Same discovery the trainer runs, so the two cannot disagree.
try:
pairs = await asyncio.to_thread(
- _dtc.discover_image_caption_pairs,
+ _dtc.discover_training_pairs,
+ normalized_cfg.resolved_family,
config["data_dir"],
instance_prompt = config.get("instance_prompt") or None,
caption_column = config.get("caption_column") or "text",
@@ -2947,6 +2974,8 @@ async def diffusion_training_status(current_subject: str = Depends(get_current_s
loss = snap.pop("metric_loss", []),
lr = snap.pop("metric_lr", []),
grad_norm = snap.pop("metric_grad_norm", []),
+ video_loss = snap.pop("metric_video_loss", []),
+ audio_loss = snap.pop("metric_audio_loss", []),
)
return DiffusionTrainingStatusResponse(**snap, metric_history = metric_history)
@@ -3106,6 +3135,41 @@ def _diffusion_dataset_summary(folder: Path) -> DiffusionDatasetSummary:
)
+def _mixed_media_refusal(data_dir: str, resolved_family: str) -> Optional[str]:
+ """Why ``resolved_family`` cannot train on this folder as it stands, or None.
+
+ Both discoveries read one medium and ignore the other, so a mixed folder trains on a
+ subset the picker counted as trainable and says nothing. The rule is the same in both
+ directions, only the medium that is out of place changes: refuse the folder rather than
+ quietly train part of it.
+ """
+ from core.training.diffusion_train_common import CLIP_TRAINED_FAMILIES
+
+ if str(resolved_family or "").strip().lower() in CLIP_TRAINED_FAMILIES:
+ return _image_dataset_refusal(data_dir)
+ return _clip_dataset_refusal(data_dir)
+
+
+def _image_dataset_refusal(data_dir: str) -> Optional[str]:
+ """The converse of ``_clip_dataset_refusal``, for a family that trains from clips.
+
+ ``discover_clip_caption_pairs`` enumerates video extensions only, so a still sitting in a
+ clip folder is dropped from the run while /diffusion/info and the picker both count it as
+ a training item. Same failure as the mixed case below, same answer."""
+ try:
+ summary = _diffusion_dataset_summary(Path(data_dir).expanduser())
+ except OSError:
+ return None
+ if summary.image_count <= 0:
+ return None
+ images = f"{summary.image_count} still image" + ("" if summary.image_count == 1 else "s")
+ return (
+ f"'{Path(data_dir).expanduser().name}' holds {images} alongside its clips. This model "
+ "trains from clips, so a run started here would leave the stills out. Take the images "
+ "out of this folder, or choose a dataset of clips."
+ )
+
+
def _clip_dataset_refusal(data_dir: str) -> Optional[str]:
"""Why a folder holding clips cannot be trained on yet, or None when it can.
@@ -3133,13 +3197,79 @@ def _clip_dataset_refusal(data_dir: str) -> Optional[str]:
)
+def _listed_dataset_clip_count(summary: DiffusionDatasetSummary) -> int:
+ """How many trainable CLIPS a listed dataset folder holds, as the dataset layer reports it.
+
+ Read off the summary with a 0 default rather than recounted here. Counting clips is the
+ dataset layer's job, and while that layer is still image-only the summary carries no clip
+ count at all, so every folder answers 0 -- which is precisely the state
+ ``_ui_trainable_families`` below has to detect. When the layer starts reporting clips this
+ starts returning them, with no edit here."""
+ try:
+ return int(getattr(summary, "clip_count", 0) or 0)
+ except (TypeError, ValueError): # a non-numeric count is no evidence of a clip dataset
+ return 0
+
+
+def _listed_dataset_trains_clips(summary: DiffusionDatasetSummary) -> bool:
+ """Whether a listed folder could actually start a clip run, not merely whether it holds clips.
+
+ The same two conditions ``_image_dataset_refusal`` applies at Start, read off the summary the
+ listing already built: clips present, and no stills mixed in with them. Kept beside the count
+ helper above so the advertisement and the refusal cannot drift into disagreeing about which
+ folders a clip family can use."""
+ if _listed_dataset_clip_count(summary) <= 0:
+ return False
+ try:
+ return int(getattr(summary, "image_count", 0) or 0) <= 0
+ except (TypeError, ValueError): # a non-numeric count is no evidence either way; be strict
+ return False
+
+
+def _ui_trainable_families(datasets: list[DiffusionDatasetSummary]) -> list[dict]:
+ """The trainable families to ADVERTISE in the Train picker, given the datasets this same
+ response lists as selectable.
+
+ ``family_train_infos()`` describes every family that has a trainer, which is the right
+ answer for the API: ``/diffusion/start`` accepts any of them and must keep doing so. It is
+ the wrong answer for the picker, because the picker offers a family and a dataset together.
+ The families in ``CLIP_TRAINED_FAMILIES`` train from captioned video clips and from nothing
+ else, so while every selectable dataset is stills, choosing one of them can only end in
+ Start failing with "No captioned video clips found" -- an option that cannot be completed
+ from the UI it is offered in.
+
+ Gated on the LISTED datasets rather than on a family name or a feature flag, so this needs
+ no follow-up edit: the moment the dataset layer lists a folder of clips, the family that
+ trains on clips is advertised alongside it, and if the clip listing were ever withdrawn the
+ advertisement withdraws with it. Nothing here decides whether clips are listable; it only
+ reads what the listing already said.
+
+ "Has clips" is not enough on its own. ``_image_dataset_refusal`` turns a MIXED folder away
+ from a clip family, so counting clips alone advertises the family on the strength of a
+ folder Start will then refuse -- an option that still cannot be completed, just one that
+ fails later and with a different message. The qualifying folder is one that would survive
+ that refusal: clips and no stills."""
+ from core.training.diffusion_train_common import CLIP_TRAINED_FAMILIES, family_train_infos
+
+ infos = family_train_infos()
+ if any(_listed_dataset_trains_clips(s) for s in datasets):
+ return infos
+ return [
+ i for i in infos if str(i.get("name") or "").strip().lower() not in CLIP_TRAINED_FAMILIES
+ ]
+
+
@router.get("/diffusion/info", response_model = DiffusionTrainingInfoResponse)
async def diffusion_training_info(current_subject: str = Depends(get_current_subject)):
"""Describe where diffusion training reads/writes, and list usable dataset folders.
A dataset folder is any direct child of the datasets root that contains at least one
trainable item: an image, or a clip for the families that train from video. The UI uses
- this to offer a picker instead of a blind free-text path."""
+ this to offer a picker instead of a blind free-text path.
+
+ The family list is the trainable set NARROWED to what these datasets can feed: see
+ ``_ui_trainable_families``. Only the advertisement narrows -- ``/diffusion/start`` still
+ accepts every family that has a trainer."""
from utils.paths import datasets_root, outputs_root
def scan() -> DiffusionTrainingInfoResponse:
@@ -3163,9 +3293,7 @@ async def diffusion_training_info(current_subject: str = Depends(get_current_sub
# A clip-only folder is a real dataset for the video families, so admit on either count.
if summary.image_count > 0 or summary.clip_count > 0:
found.append(summary)
- from core.training.diffusion_train_common import family_train_infos
-
- families = [DiffusionTrainableFamily(**info) for info in family_train_infos()]
+ families = [DiffusionTrainableFamily(**info) for info in _ui_trainable_families(found)]
return DiffusionTrainingInfoResponse(
datasets_root = str(root),
outputs_root = str(outputs_root()),
@@ -3543,7 +3671,7 @@ def _safe_dataset_image_path(folder: Path, filename: str) -> Path:
def _load_metadata_captions(folder: Path) -> dict[str, str]:
"""Read metadata.jsonl / captions.jsonl into {file_name: caption}, mirroring the
- trainer's discovery (keys file_name/image/file; caption in the ``text`` column)."""
+ trainer's discovery (keys file_name/video/image/file; caption in the ``text`` column)."""
import json
out: dict[str, str] = {}
@@ -3566,7 +3694,10 @@ def _load_metadata_captions(folder: Path) -> dict[str, str]:
continue
if not isinstance(row, dict):
continue
- key = row.get("file_name") or row.get("image") or row.get("file")
+ # "video" too: the clip discovery accepts it, so without it a clip dataset whose
+ # metadata.jsonl uses that key reports caption_count 0 and the panel demands a
+ # trigger prompt the trainer does not need.
+ key = row.get("file_name") or row.get("video") or row.get("image") or row.get("file")
value = row.get("text")
# A JSON null is "no caption", not the string "None".
if key and value is not None:
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index e1b5bdb2e3d..02f9aeadc7b 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -4367,3 +4367,21 @@ def test_a_cancelled_quant_beside_a_scope_still_answers_from_state(monkeypatch,
)
)
assert [(v.quant, v.partial) for v in response.variants] == [("Q6_K", True)]
+
+
+def test_a_standalone_h3_denoiser_gguf_is_recognised_by_its_filename():
+ """H3's GGUFs carry no metadata keys at all (kv_count 0), so ``general.architecture`` is
+ absent and the NAME is the only evidence there is. Keying only on the two bundle repo ids
+ meant a denoiser copied into a custom local directory returned a null task and was dropped
+ from the Video On Device picker, even though the loader validates exactly these prefixes.
+ """
+ for name in (
+ "minimax_h3_fl2va-Q4_K_M.gguf",
+ "minimax_h3_ref2va-Q8_0.gguf",
+ "/home/me/models/h3/minimax_h3_fl2va-Q4_K_M.gguf",
+ ):
+ assert models_route._arch_to_task(None, (name,)) == models_route._VIDEO_GEN_TASK, name
+
+ # The conditioner and unrelated GGUFs in the same folder must NOT be claimed as video.
+ for name in ("qwen3vl-Q8_0.gguf", "minimax_h3_notes.txt", "llama-Q4_K_M.gguf"):
+ assert models_route._arch_to_task(None, (name,)) is None, name
diff --git a/studio/backend/tests/test_diffusion_dataset_clips.py b/studio/backend/tests/test_diffusion_dataset_clips.py
index 1daafa40fd6..a5462816795 100644
--- a/studio/backend/tests/test_diffusion_dataset_clips.py
+++ b/studio/backend/tests/test_diffusion_dataset_clips.py
@@ -390,6 +390,36 @@ def test_start_refuses_a_mixed_folder_rather_than_training_the_images_alone(tmp_
assert "1 video clip" in detail and "1 video clips" not in detail
+def test_the_summary_reads_a_video_keyed_metadata_caption(tmp_path):
+ """The clip discovery accepts {"video": ..., "text": ...}; the summary loader must too.
+
+ It knew only file_name/image/file, so a clip dataset written with the video key reported
+ caption_count 0 while the trainer had a caption for every clip, and the panel blocked Start
+ on a trigger prompt that was not needed.
+ """
+ import json
+
+ folder = tmp_path / "video-keyed"
+ folder.mkdir()
+ for stem in ("a", "b"):
+ (folder / f"{stem}.mp4").write_bytes(_MP4_BYTES)
+ (folder / "metadata.jsonl").write_text(
+ "\n".join(
+ json.dumps({"video": f"{stem}.mp4", "text": f"clip {stem}"}) for stem in ("a", "b")
+ ),
+ encoding = "utf-8",
+ )
+
+ summary = _diffusion_dataset_summary(folder)
+ assert summary.clip_count == 2
+ assert summary.caption_count == 2
+
+ # And the trainer agrees, which is the disagreement this closes.
+ from core.training.diffusion_h3_clips import discover_clip_caption_pairs
+
+ assert len(discover_clip_caption_pairs(folder)) == 2
+
+
def test_start_leaves_an_image_only_folder_alone(tmp_path):
"""No clips, no refusal: the ordinary uncaptioned-folder error still speaks for itself."""
from routes.training import _clip_dataset_refusal
diff --git a/studio/backend/tests/test_diffusion_dit_trainer_ltx2.py b/studio/backend/tests/test_diffusion_dit_trainer_ltx2.py
index 0f20b16c107..f2e06f4c4ec 100644
--- a/studio/backend/tests/test_diffusion_dit_trainer_ltx2.py
+++ b/studio/backend/tests/test_diffusion_dit_trainer_ltx2.py
@@ -153,11 +153,16 @@ def test_ltx2_spec_is_registered_and_bf16_only():
assert spec.lora_targets == _LTX2_TARGETS
-def test_every_trainable_video_family_has_a_spec():
+def test_every_trainable_video_family_has_a_trainer():
# 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
+ # that get_trainer cannot resolve would pass resolve_trainable_family and then raise after
+ # /diffusion/start had already evicted the resident GPU models. Not every trainable video
+ # family is a _SPECS family any more -- MiniMax-H3 has its own loop -- so the invariant is
+ # "has a trainer", checked one name at a time.
+ for name in TRAINABLE_VIDEO_FAMILIES:
+ assert callable(get_trainer(name)), name
+ assert "ltx-2" in _SPECS
+ assert "ltx-2" in _DIT_TRAIN_FAMILIES
assert get_trainer("ltx-2") is dit.run_dit_lora_training
diff --git a/studio/backend/tests/test_diffusion_h3_trainer.py b/studio/backend/tests/test_diffusion_h3_trainer.py
new file mode 100644
index 00000000000..a8d79c76c88
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_h3_trainer.py
@@ -0,0 +1,1869 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""MiniMax-H3 LoRA training: the clip dataset layer, the packed-sequence geometry, the
+two-schedule sigma coupling, the LoRA target surface, the routing, and the forward contract.
+
+CPU-only and free of a diffusers import wherever the contract allows it: the two places that
+genuinely need the pipeline's own layout builders are exercised against a fake transformer, so
+the forward contract is checkable without the 66 GB checkpoint.
+"""
+
+from __future__ import annotations
+
+import importlib
+import json
+import random
+import sys
+import types
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.training.diffusion_h3_clips import ( # noqa: E402
+ H3_AUDIO_CHANNELS,
+ H3_AUDIO_LATENTS_PER_SECOND,
+ H3_AUDIO_SAMPLING_RATE,
+ H3_CANVAS_MULTIPLE,
+ H3_FPS,
+ H3_FRAMES_PER_CHUNK,
+ H3_LATENTS_PER_CHUNK,
+ H3_SPATIAL_COMPRESSION,
+ H3_TRAIN_NUM_FRAMES,
+ discover_clip_caption_pairs,
+ h3_align_num_frames,
+ h3_audio_latent_count,
+ h3_audio_sample_count,
+ h3_packed_sequence_length,
+ h3_rows_per_latent_frame,
+ h3_train_canvas,
+ h3_video_latent_frames,
+)
+from core.training.diffusion_train_common import ( # noqa: E402
+ TRAINABLE_VIDEO_FAMILIES,
+ DiffusionLoraConfig,
+ _FLOW_TRAIN_FAMILIES,
+ bf16_unsupported_reason,
+ dit_accelerator_missing_reason,
+ get_trainer,
+ resolve_trainable_family,
+ train_defaults,
+)
+
+
+# ── frame / latent arithmetic ────────────────────────────────────────────────
+def test_align_num_frames_snaps_up_to_the_vae_grid():
+ # The video VAE encodes 17 * n + 5 frames; anything else is not encodable at all.
+ assert h3_align_num_frames(22) == 22
+ assert h3_align_num_frames(1) == 5
+ assert h3_align_num_frames(6) == 22
+ assert h3_align_num_frames(124) == 124
+ assert h3_align_num_frames(125) == 141
+ for n in range(1, 400):
+ aligned = h3_align_num_frames(n)
+ assert aligned >= n
+ assert aligned % H3_FRAMES_PER_CHUNK == H3_LATENTS_PER_CHUNK
+
+
+def test_align_num_frames_refuses_a_non_positive_count():
+ with pytest.raises(ValueError):
+ h3_align_num_frames(0)
+
+
+def test_video_latent_frames_is_five_per_chunk_plus_two():
+ assert h3_video_latent_frames(5) == 2
+ assert h3_video_latent_frames(22) == 7
+ assert h3_video_latent_frames(124) == 37
+ assert h3_video_latent_frames(345) == 102
+
+
+def test_video_latent_frames_refuses_an_unaligned_count():
+ # Silently accepting one would reserve the wrong number of video rows in the layout.
+ with pytest.raises(ValueError):
+ h3_video_latent_frames(24)
+
+
+def test_the_training_clip_is_exactly_one_vae_chunk():
+ assert H3_TRAIN_NUM_FRAMES == H3_FRAMES_PER_CHUNK + H3_LATENTS_PER_CHUNK
+ assert h3_align_num_frames(H3_TRAIN_NUM_FRAMES) == H3_TRAIN_NUM_FRAMES
+ # ... and is the SHORTEST encodable clip above the VAE's 5-frame head.
+ assert h3_align_num_frames(H3_LATENTS_PER_CHUNK + 1) == H3_TRAIN_NUM_FRAMES
+
+
+# ── audio arithmetic ─────────────────────────────────────────────────────────
+def test_audio_latent_count_follows_the_forty_per_second_grid():
+ assert h3_audio_latent_count(H3_FPS) == H3_AUDIO_LATENTS_PER_SECOND
+ assert h3_audio_latent_count(124) == 207
+ assert h3_audio_latent_count(22) == 37
+
+
+def test_audio_sample_count_is_a_whole_number_of_hops():
+ # The audio VAE hops 800 samples and right-pads a short tail, so handing it exactly
+ # latents * hop is what makes the encode produce the row count the layout reserves.
+ hop = H3_AUDIO_SAMPLING_RATE // H3_AUDIO_LATENTS_PER_SECOND
+ assert hop == 800
+ for frames in (22, 124, 345):
+ samples = h3_audio_sample_count(frames)
+ assert samples % hop == 0
+ assert samples // hop == h3_audio_latent_count(frames)
+
+
+# ── the packed sequence ──────────────────────────────────────────────────────
+def test_rows_per_latent_frame_applies_the_two_by_two_patch():
+ assert h3_rows_per_latent_frame(48, 84) == 24 * 42
+
+
+def test_packed_sequence_length_counts_text_audio_and_video_rows():
+ text, frames, height, width = 48, 22, 768, 1344
+ latent_h, latent_w = height // H3_SPATIAL_COMPRESSION, width // H3_SPATIAL_COMPRESSION
+ expected = (
+ text
+ + h3_audio_latent_count(frames) * H3_AUDIO_CHANNELS
+ + h3_video_latent_frames(frames) * h3_rows_per_latent_frame(latent_h, latent_w)
+ )
+ assert h3_packed_sequence_length(text, frames, height, width) == expected
+ # The figure the attention cost is quadratic in, at the released canvas.
+ assert expected == 7178
+
+
+def test_a_five_second_clip_is_five_times_the_sequence_of_a_training_clip():
+ # The reason the trainer uses 22-frame clips rather than the 5 s floor H3 generates at.
+ short = h3_packed_sequence_length(48, 22, 768, 1344)
+ full = h3_packed_sequence_length(48, 124, 768, 1344)
+ assert full > 5 * short
+
+
+# ── the canvas rule ──────────────────────────────────────────────────────────
+def test_train_canvas_reproduces_the_released_sixteen_by_nine_canvas():
+ assert h3_train_canvas(16, 9) == (1344, 768)
+
+
+def test_train_canvas_snaps_both_axes_to_the_multiple():
+ for aspect in ((16, 9), (4, 3), (1, 1), (3, 4), (9, 16), (2048, 872)):
+ width, height = h3_train_canvas(*aspect)
+ assert width % H3_CANVAS_MULTIPLE == 0
+ assert height % H3_CANVAS_MULTIPLE == 0
+
+
+def test_train_canvas_scales_its_area_cap_with_the_short_edge():
+ # A smaller training canvas must keep the released AREA budget in units of the short edge,
+ # not the released pixel count: with a fixed cap a 384-edge canvas never reaches the cap at
+ # all, so a wide clip trains at a completely different area-to-edge ratio than it would at
+ # 768 and the geometry stops being a scaled-down version of the released one.
+ def area_ratio(short_edge: int) -> float:
+ width, height = h3_train_canvas(21, 9, short_edge = short_edge)
+ return width * height / short_edge**2
+
+ assert area_ratio(384) == pytest.approx(area_ratio(768), rel = 0.10)
+ assert area_ratio(192) == pytest.approx(area_ratio(768), rel = 0.10)
+
+
+def test_train_canvas_refuses_an_untrained_aspect_ratio():
+ with pytest.raises(ValueError, match = "1:4 to 4:1"):
+ h3_train_canvas(10, 1)
+
+
+def test_train_canvas_names_a_degenerate_size_as_such():
+ # A zero-sized source has no aspect ratio at all. Folding it into the trained-range message
+ # would tell the user to "crop it first", which cannot help.
+ with pytest.raises(ValueError, match = "must be positive"):
+ h3_train_canvas(0, 9)
+ with pytest.raises(ValueError, match = "must be positive"):
+ h3_train_canvas(16, -1)
+
+
+# ── clip discovery ───────────────────────────────────────────────────────────
+def _clip(tmp_path: Path, name: str) -> Path:
+ path = tmp_path / name
+ path.write_bytes(b"not a real container")
+ return path
+
+
+def test_discover_clip_pairs_reads_a_sidecar_caption(tmp_path):
+ _clip(tmp_path, "a.mp4")
+ (tmp_path / "a.txt").write_text("a rabbit in a meadow")
+ assert discover_clip_caption_pairs(tmp_path) == [
+ (str(tmp_path / "a.mp4"), "a rabbit in a meadow")
+ ]
+
+
+def test_discover_clip_pairs_reads_metadata_jsonl(tmp_path):
+ _clip(tmp_path, "a.mov")
+ (tmp_path / "metadata.jsonl").write_text(
+ json.dumps({"file_name": "a.mov", "text": "from metadata"}) + "\n"
+ )
+ assert discover_clip_caption_pairs(tmp_path)[0][1] == "from metadata"
+
+
+def test_discover_clip_pairs_accepts_a_video_key_in_metadata(tmp_path):
+ _clip(tmp_path, "a.webm")
+ (tmp_path / "metadata.jsonl").write_text(
+ json.dumps({"video": "a.webm", "text": "keyed by video"}) + "\n"
+ )
+ assert discover_clip_caption_pairs(tmp_path)[0][1] == "keyed by video"
+
+
+def test_a_sidecar_beats_a_metadata_row(tmp_path):
+ _clip(tmp_path, "a.mp4")
+ (tmp_path / "a.txt").write_text("the explicit edit")
+ (tmp_path / "metadata.jsonl").write_text(
+ json.dumps({"file_name": "a.mp4", "text": "the bulk caption"}) + "\n"
+ )
+ assert discover_clip_caption_pairs(tmp_path)[0][1] == "the explicit edit"
+
+
+def test_an_empty_sidecar_is_a_tombstone_that_falls_back_to_the_instance_prompt(tmp_path):
+ _clip(tmp_path, "a.mp4")
+ (tmp_path / "a.txt").write_text(" ")
+ (tmp_path / "metadata.jsonl").write_text(
+ json.dumps({"file_name": "a.mp4", "text": "suppressed"}) + "\n"
+ )
+ pairs = discover_clip_caption_pairs(tmp_path, instance_prompt = "fallback")
+ assert pairs[0][1] == "fallback"
+
+
+def test_discover_clip_pairs_ignores_still_images(tmp_path):
+ # H3 has no still-image milestone: a 1-frame clip is not a valid video VAE input.
+ (tmp_path / "a.png").write_bytes(b"x")
+ (tmp_path / "a.txt").write_text("a still")
+ with pytest.raises(ValueError, match = "clips with sound"):
+ discover_clip_caption_pairs(tmp_path)
+
+
+def test_discover_clip_pairs_raises_for_a_missing_directory(tmp_path):
+ with pytest.raises(FileNotFoundError):
+ discover_clip_caption_pairs(tmp_path / "nope")
+
+
+def test_discover_clip_pairs_is_sorted_and_stable(tmp_path):
+ for name in ("c.mp4", "a.mp4", "b.mp4"):
+ _clip(tmp_path, name)
+ pairs = discover_clip_caption_pairs(tmp_path, instance_prompt = "p")
+ assert [Path(p).name for p, _ in pairs] == ["a.mp4", "b.mp4", "c.mp4"]
+
+
+# ── the preflight has to run the trainer's own discovery ─────────────────────
+
+
+def test_discover_training_pairs_routes_h3_to_the_clip_discovery(tmp_path):
+ """The gap this closes: /diffusion/start preflights the dataset BEFORE freeing the resident
+ GPU models, and it ran the IMAGE discovery unconditionally. An H3 dataset is captioned clips
+ -- the only thing its trainer accepts -- so a perfectly valid one was rejected at the route
+ with "No captioned images found" and the advertised H3 trainer could not be reached at all.
+ """
+ from core.training.diffusion_train_common import discover_training_pairs
+
+ _clip(tmp_path, "a.mp4")
+ (tmp_path / "a.txt").write_text("a rabbit in a meadow")
+ pairs = discover_training_pairs("minimax-h3", tmp_path, verify_images = True)
+ assert [Path(p).name for p, _ in pairs] == ["a.mp4"]
+ assert pairs[0][1] == "a rabbit in a meadow"
+
+
+def test_discover_training_pairs_leaves_an_image_family_on_the_image_discovery(tmp_path):
+ """The other half: nothing about an existing image family moves, verify_images included."""
+ from PIL import Image
+
+ from core.training.diffusion_train_common import discover_training_pairs
+
+ Image.new("RGB", (8, 8)).save(tmp_path / "a.png")
+ _clip(tmp_path, "b.mp4") # present, and must be ignored for an image family
+ pairs = discover_training_pairs("sdxl", tmp_path, instance_prompt = "p", verify_images = True)
+ assert [Path(p).name for p, _ in pairs] == ["a.png"]
+
+
+def test_the_clip_families_are_exactly_the_ones_whose_trainer_takes_clips():
+ """LTX-2 trains a style LoRA FROM STILLS, so it must keep the image discovery even though it
+ is a video family -- the split is by what the TRAINER reads, not by output modality."""
+ from core.training.diffusion_train_common import (
+ CLIP_TRAINED_FAMILIES,
+ TRAINABLE_VIDEO_FAMILIES,
+ )
+
+ assert CLIP_TRAINED_FAMILIES == {"minimax-h3"}
+ assert CLIP_TRAINED_FAMILIES <= TRAINABLE_VIDEO_FAMILIES
+ assert "ltx-2" not in CLIP_TRAINED_FAMILIES
+
+
+# ── the two coupled schedules ────────────────────────────────────────────────
+def test_the_two_shifts_come_from_the_released_scheduler_configs():
+ from core.training.diffusion_h3_trainer import _H3_AUDIO_SHIFT, _H3_VIDEO_SHIFT
+ assert _H3_VIDEO_SHIFT == 12.0
+ assert _H3_AUDIO_SHIFT == 3.0
+
+
+def test_an_omitted_flow_shift_reaches_the_trainer_as_the_released_video_shift():
+ """The gap this closes: ``normalized()`` resolved an omitted flow_shift to the identity 1.0
+ for every family outside AUTO_FLOW_SHIFT_FAMILIES, and the H3 loop only falls back to
+ _H3_VIDEO_SHIFT when the value is NOT a number. 1.0 is a number, so it won over the 12.0 the
+ released scheduler uses and every default run trained against an unshifted video-noise
+ distribution the sampler never visits -- silently, at full cost."""
+ from core.training.diffusion_train_common import AUTO_FLOW_SHIFT_FAMILIES, DiffusionLoraConfig
+
+ assert "minimax-h3" in AUTO_FLOW_SHIFT_FAMILIES
+ cfg = DiffusionLoraConfig(
+ base_model = "MiniMaxAI/MiniMax-H3",
+ data_dir = "/tmp/d",
+ output_dir = "/tmp/o",
+ instance_prompt = "p",
+ ).normalized()
+ assert cfg.resolved_family == "minimax-h3"
+ # Not a number, which is exactly what routes the trainer to its own pair of shifts.
+ assert cfg.flow_shift == "auto"
+ assert not isinstance(cfg.flow_shift, (int, float))
+
+
+def test_an_explicit_flow_shift_still_overrides_the_video_default():
+ """The escape hatch stays: a caller who names a shift gets it, not 12.0."""
+ from core.training.diffusion_train_common import DiffusionLoraConfig
+
+ cfg = DiffusionLoraConfig(
+ base_model = "MiniMaxAI/MiniMax-H3",
+ data_dir = "/tmp/d",
+ output_dir = "/tmp/o",
+ instance_prompt = "p",
+ flow_shift = 7.0,
+ ).normalized()
+ assert cfg.flow_shift == 7.0
+
+
+def test_shifted_sigma_matches_the_schedulers_exponential_shift():
+ from core.training.diffusion_h3_trainer import _shifted_sigma
+ for shift in (3.0, 12.0):
+ # The endpoints are fixed points of the shift, which is what keeps t = 0 clean and
+ # t = 1 pure noise.
+ assert _shifted_sigma(0.0, shift) == 0.0
+ assert _shifted_sigma(1.0, shift) == 1.0
+ for u in (0.1, 0.25, 0.5, 0.9):
+ assert _shifted_sigma(u, shift) == pytest.approx(shift * u / (1 + (shift - 1) * u))
+
+
+def test_a_larger_shift_pushes_sigma_higher_so_video_is_always_noisier_than_audio():
+ # Both streams are indexed by the SAME step at inference, so the pair (video, audio) walks
+ # one curve. Drawing one u and pushing it through both shifts is what reproduces it.
+ from core.training.diffusion_h3_trainer import (
+ _H3_AUDIO_SHIFT,
+ _H3_VIDEO_SHIFT,
+ _shifted_sigma,
+ )
+ for u in (0.05, 0.2, 0.5, 0.8, 0.95):
+ assert _shifted_sigma(u, _H3_VIDEO_SHIFT) > _shifted_sigma(u, _H3_AUDIO_SHIFT)
+
+
+def test_shifted_sigma_is_monotonic_in_u():
+ from core.training.diffusion_h3_trainer import _shifted_sigma
+ previous = -1.0
+ for i in range(101):
+ value = _shifted_sigma(i / 100, 12.0)
+ assert value > previous
+ previous = value
+
+
+# ── LoRA targets ─────────────────────────────────────────────────────────────
+# Every Linear of the released checkpoint, by name (num_layers and num_refiner_layers cut
+# down; the names are otherwise exactly what MiniMaxH3Transformer3DModel builds).
+_H3_LINEARS = (
+ "proj_in",
+ "audio_proj_in",
+ "context_embedder",
+ "time_embedder.linear_1",
+ "time_embedder.linear_2",
+ "token_refiner.refiner_blocks.0.attn.to_q",
+ "token_refiner.refiner_blocks.0.attn.to_k",
+ "token_refiner.refiner_blocks.0.attn.to_v",
+ "token_refiner.refiner_blocks.0.attn.to_out.0",
+ "token_refiner.refiner_blocks.0.ff.net.0.proj",
+ "token_refiner.refiner_blocks.0.ff.net.2",
+ "token_refiner.refiner_blocks.1.attn.to_q",
+ "transformer_blocks.0.attn.to_q",
+ "transformer_blocks.0.attn.to_k",
+ "transformer_blocks.0.attn.to_v",
+ "transformer_blocks.0.attn.to_out.0",
+ "transformer_blocks.0.ff.net.0.proj",
+ "transformer_blocks.0.ff.net.2",
+ "transformer_blocks.0.adaln_proj.linear",
+ "transformer_blocks.49.attn.to_q",
+ "transformer_blocks.49.ff.net.2",
+ "norm_out.linear",
+ "proj_out",
+ "audio_proj_out",
+)
+
+
+def _selected(target_regex: str) -> set:
+ """PEFT's own rule for a STRING target_modules: re.fullmatch on the module name."""
+ import re
+ return {name for name in _H3_LINEARS if re.fullmatch(target_regex, name)}
+
+
+def test_h3_targets_are_a_regex_because_peft_does_not_glob():
+ # PEFT either suffix-matches a LIST of names or re.fullmatch-es a STRING. A list entry
+ # written "transformer_blocks.*.attn.to_q" matches nothing at all, so the adapter would
+ # train zero parameters while every step still reported a loss.
+ from core.training.diffusion_h3_trainer import _H3_TARGETS
+ assert isinstance(_H3_TARGETS, str)
+ assert "*" not in _H3_TARGETS
+
+
+def test_h3_targets_never_adapt_the_text_refiner():
+ # MiniMaxH3TokenRefinerBlock carries `attn` and `ff` under the SAME leaf names as a
+ # transformer block, so a bare "to_q" would also adapt the two refiner blocks, i.e. the
+ # text stream rather than the denoiser.
+ from core.training.diffusion_h3_trainer import _H3_TARGETS
+ assert not any(name.startswith("token_refiner") for name in _selected(_H3_TARGETS))
+
+
+def test_h3_targets_cover_attention_and_the_feed_forward_and_nothing_else():
+ from core.training.diffusion_h3_trainer import _H3_TARGET_LEAVES, _H3_TARGETS
+
+ assert set(_H3_TARGET_LEAVES) == {
+ "attn.to_q",
+ "attn.to_k",
+ "attn.to_v",
+ "attn.to_out.0",
+ "ff.net.0.proj",
+ "ff.net.2",
+ }
+ selected = _selected(_H3_TARGETS)
+ assert selected == {
+ f"transformer_blocks.{index}.{leaf}"
+ for index in (0, 49)
+ for leaf in _H3_TARGET_LEAVES
+ if f"transformer_blocks.{index}.{leaf}" in _H3_LINEARS
+ }
+ # adaln_proj is 40% of the checkpoint but its input carries two or three rows per step.
+ assert not any("adaln" in name for name in selected)
+ # The patch and text projections are fp32 in the checkpoint's own _keep_in_fp32_modules.
+ assert not any(
+ "proj_in" in name or "proj_out" in name or "context_embedder" in name for name in selected
+ )
+ # The final norm's modulation projection is a dtype-reading module, not an adapter site.
+ assert "norm_out.linear" not in selected
+
+
+def test_the_nf4_skip_list_covers_every_dtype_reading_module():
+ # The transformer aligns activations with `x.to(self.<m>.weight.dtype)` in five places. A
+ # bitsandbytes Params4bit reports uint8, so quantizing one of those casts the activation
+ # to Byte and the next RMSNorm raises. proj_in / audio_proj_in / proj_out /
+ # audio_proj_out / time_embedder are already excluded by _keep_in_fp32_modules; the three
+ # here are not.
+ from core.training.diffusion_h3_trainer import _H3_NF4_SKIP_MODULES
+ assert set(_H3_NF4_SKIP_MODULES) == {"context_embedder", "adaln_proj", "norm_out"}
+
+
+# ── routing ──────────────────────────────────────────────────────────────────
+def test_minimax_h3_is_a_trainable_video_family():
+ assert "minimax-h3" in TRAINABLE_VIDEO_FAMILIES
+
+
+def test_minimax_h3_routes_to_its_own_trainer():
+ from core.training import diffusion_h3_trainer
+ assert get_trainer("minimax-h3") is diffusion_h3_trainer.run_h3_lora_training
+
+
+def test_minimax_h3_does_not_route_to_the_dit_trainer():
+ # Its objective is a two-schedule joint loss over one packed sequence, which the DiT
+ # loop's single sigma and single target cannot express.
+ from core.training import diffusion_dit_trainer
+ assert get_trainer("minimax-h3") is not diffusion_dit_trainer.run_dit_lora_training
+
+
+def test_the_official_h3_base_resolves_to_the_h3_family():
+ assert resolve_trainable_family("MiniMaxAI/MiniMax-H3") == "minimax-h3"
+
+
+def test_minimax_h3_is_a_flow_family_for_the_preflight_gates():
+ # Without this the start route skips the bf16 / accelerator checks for H3, evicts the
+ # resident GPU models, and only then fails inside the child.
+ assert "minimax-h3" in _FLOW_TRAIN_FAMILIES
+ assert bf16_unsupported_reason("minimax-h3") is None or isinstance(
+ bf16_unsupported_reason("minimax-h3"), str
+ )
+ assert dit_accelerator_missing_reason("minimax-h3") is None or isinstance(
+ dit_accelerator_missing_reason("minimax-h3"), str
+ )
+
+
+def test_the_official_h3_base_is_trusted_for_training():
+ # The image-side inference allowlist never covered a video family, so without the training
+ # allowlist entry the official repo is refused as untrusted and only a local path trains.
+ from core.training.diffusion_train_common import _assert_trusted_base_model
+ _assert_trusted_base_model("MiniMaxAI/MiniMax-H3")
+ with pytest.raises(ValueError, match = "untrusted"):
+ _assert_trusted_base_model("some-random-user/minimax-h3-repack")
+
+
+def test_h3_defaults_train_at_the_released_short_edge():
+ defaults = train_defaults("minimax-h3")
+ assert defaults["resolution"] == 768
+ assert defaults["train_batch_size"] == 1
+ assert defaults["lora_rank"] == 16
+
+
+# ── config validation ────────────────────────────────────────────────────────
+def _cfg(**kw) -> DiffusionLoraConfig:
+ base = {
+ "base_model": "MiniMaxAI/MiniMax-H3",
+ "data_dir": "/tmp/clips",
+ "output_dir": "/tmp/out",
+ "mixed_precision": "bf16",
+ "resolution": 768,
+ }
+ base.update(kw)
+ return DiffusionLoraConfig(**base)
+
+
+def test_h3_refuses_fp16():
+ with pytest.raises(ValueError, match = "bf16"):
+ _cfg(mixed_precision = "fp16").normalized()
+
+
+def test_h3_refuses_an_off_grid_resolution():
+ with pytest.raises(ValueError, match = "multiple of 32"):
+ _cfg(resolution = 760).normalized()
+
+
+def test_h3_refuses_the_float8_precisions():
+ for mode in ("fp8", "mxfp8"):
+ with pytest.raises(ValueError, match = "minimax-h3"):
+ _cfg(base_precision = mode).normalized()
+
+
+def test_h3_accepts_the_precisions_it_supports():
+ for mode in ("nf4", "auto"):
+ assert _cfg(base_precision = mode).normalized().base_precision == mode
+
+
+def test_h3_resolves_to_its_family_through_normalized():
+ assert _cfg().normalized().resolved_family == "minimax-h3"
+
+
+# ── entrypoint refusals, all of which must fire BEFORE anything loads ─────────
+def _run(**kw):
+ from core.training.diffusion_h3_trainer import run_h3_lora_training
+ return run_h3_lora_training(_cfg(**kw))
+
+
+def test_h3_refuses_a_batch_larger_than_one():
+ # The batch axis of an H3 forward is a pure replication axis: the row layout is set by the
+ # clip's geometry AND its caption's length, so two clips cannot share one packed sequence.
+ with pytest.raises(ValueError, match = "batch size 1"):
+ _run(train_batch_size = 2)
+
+
+def test_h3_refuses_a_cfg_dropout():
+ # The checkpoint is guidance-distilled: there is no unconditional branch to train.
+ with pytest.raises(ValueError, match = "guidance-distilled"):
+ _run(cfg_dropout = 0.1)
+
+
+def test_h3_refuses_a_weighted_loss():
+ # Two schedules put video and audio at different sigmas in the same step, so a single
+ # weight over "the" timestep is ambiguous.
+ with pytest.raises(ValueError, match = "weighting_scheme"):
+ _run(weighting_scheme = "bell")
+
+
+def test_the_entrypoint_refusals_fire_before_the_data_directory_is_read():
+ # _cfg points data_dir at a path that does not exist, so any of these reaching discovery
+ # would raise FileNotFoundError instead -- and in a real run would have already evicted the
+ # resident GPU models.
+ with pytest.raises(ValueError):
+ _run(train_batch_size = 4)
+
+
+# ── the forward contract, against a fake transformer ─────────────────────────
+torch = pytest.importorskip("torch")
+
+try:
+ # diffusers' lazy module machinery makes a bare importorskip on the PACKAGE succeed even
+ # when the real module cannot import, so pull the symbol these tests actually use. Only
+ # the handful of tests below need it; the rest of this file stays runnable on a host
+ # without the MiniMax-H3 diffusers revision.
+ from diffusers.modular_pipelines.minimax_h3.before_denoise import ( # noqa: F401
+ MiniMaxH3PrepareLayoutStep,
+ )
+ _H3_BLOCKS = True
+ _H3_BLOCKS_WHY = ""
+except Exception as _exc: # noqa: BLE001 -- a host without the H3 diffusers revision
+ _H3_BLOCKS = False
+ _H3_BLOCKS_WHY = f"diffusers MiniMax-H3 blocks unavailable: {_exc}"
+
+needs_h3_blocks = pytest.mark.skipif(not _H3_BLOCKS, reason = _H3_BLOCKS_WHY)
+
+
+def _layout(
+ text_tokens = 6,
+ latent_frames = 2,
+ latent_h = 4,
+ latent_w = 6,
+ audio_latents = 3,
+):
+ from core.training.diffusion_h3_trainer import _build_layout
+ return _build_layout(
+ text_tokens, latent_frames, latent_h, latent_w, audio_latents, (1, 2, 2), "cpu"
+ )
+
+
+@needs_h3_blocks
+def test_the_layout_reserves_one_row_per_token_of_every_modality():
+ layout = _layout()
+ rows = h3_rows_per_latent_frame(4, 6)
+ assert layout["text_indices"].numel() == 6
+ assert layout["audio_indices"].numel() == 3 * H3_AUDIO_CHANNELS
+ assert layout["video_indices"].numel() == 2 * rows
+ assert layout["position_ids"].shape == (6 + 3 * H3_AUDIO_CHANNELS + 2 * rows, 3)
+
+
+@needs_h3_blocks
+def test_the_layout_has_no_conditioning_rows():
+ # The trainer trains the t2va layout: every media row is a generated row, so nothing is
+ # pinned at the keyframe noise-augmentation level.
+ layout = _layout()
+ assert layout["num_condition_video_rows"] == 0
+ assert layout["num_condition_audio_rows"] == 0
+
+
+@needs_h3_blocks
+def test_every_row_of_the_layout_is_claimed_by_exactly_one_modality():
+ layout = _layout()
+ claimed = torch.cat([layout["text_indices"], layout["audio_indices"], layout["video_indices"]])
+ assert claimed.numel() == layout["position_ids"].shape[0]
+ assert torch.equal(claimed.sort().values, torch.arange(claimed.numel()))
+
+
+@needs_h3_blocks
+def test_the_row_timestep_plan_carries_exactly_the_two_generated_timesteps():
+ from core.training.diffusion_h3_trainer import _row_timesteps
+
+ layout = _layout()
+ timestep, indices = _row_timesteps(layout, 6, 0.25, 0.75, "cpu")
+ # Two distinct noise levels in one forward: the video rows and the audio rows.
+ assert sorted(round(float(t), 6) for t in timestep) == [0.25, 0.75]
+ assert indices.shape == (layout["position_ids"].shape[0],)
+ video_t = timestep[indices[layout["video_indices"]]]
+ audio_t = timestep[indices[layout["audio_indices"]]]
+ assert torch.allclose(video_t, torch.full_like(video_t, 0.25))
+ assert torch.allclose(audio_t, torch.full_like(audio_t, 0.75))
+
+
+@needs_h3_blocks
+def test_the_text_rows_inherit_the_video_timestep():
+ # Text rows never reach an output head; the reference gives them the video level.
+ from core.training.diffusion_h3_trainer import _row_timesteps
+
+ layout = _layout()
+ timestep, indices = _row_timesteps(layout, 6, 0.25, 0.75, "cpu")
+ text_t = timestep[indices[layout["text_indices"]]]
+ assert torch.allclose(text_t, torch.full_like(text_t, 0.25))
+
+
+@needs_h3_blocks
+def test_patchify_round_trips_through_the_decoder_unpack():
+ # The trainer packs the target the same way the sampler packs its noise, so the loss is
+ # taken in the transformer's own row order.
+ from core.training.diffusion_h3_trainer import _patchify
+
+ latents = torch.randn(1, 24, 2, 4, 6)
+ rows = _patchify(latents, (1, 2, 2))
+ assert rows.shape == (2 * h3_rows_per_latent_frame(4, 6), 24 * 4)
+ back = rows.reshape(-1, 2, 2, 3, 24, 1, 2, 2).permute(0, 4, 1, 5, 2, 6, 3, 7)
+ assert torch.allclose(back.reshape(1, 24, 2, 4, 6), latents)
+
+
+def test_audio_rows_are_channel_major_like_the_decoder_expects():
+ # (channels, latent_channels, n) -> rows, one block per stereo channel.
+ audio = torch.randn(H3_AUDIO_CHANNELS, 32, 3)
+ rows = audio.permute(0, 2, 1).reshape(-1, 32)
+ assert rows.shape == (H3_AUDIO_CHANNELS * 3, 32)
+ assert torch.allclose(rows[0], audio[0, :, 0])
+ assert torch.allclose(rows[3], audio[1, :, 0])
+
+
+def test_the_velocity_target_is_data_ward():
+ # MiniMax-H3 predicts x0 = x_t + sigma * v, so v = latents - noise: the NEGATION of the
+ # convention in diffusion_dit_trainer. Getting this backwards trains a model that
+ # reliably converges and then generates noise.
+ import inspect
+
+ from core.training import diffusion_h3_trainer
+
+ source = inspect.getsource(diffusion_h3_trainer._train_h3)
+ assert "clean_video - noise_video" in source
+ assert "noise_video - clean_video" not in source
+ assert "clean_audio - noise_audio" in source
+
+
+def test_the_loss_includes_both_modalities():
+ # A LoRA on the shared block stack changes the audio prediction whether or not audio is in
+ # the loss, so leaving audio out would degrade it silently.
+ import inspect
+
+ from core.training import diffusion_h3_trainer
+
+ source = inspect.getsource(diffusion_h3_trainer._train_h3)
+ assert "loss_video + loss_audio" in source
+
+
+def test_the_row_timestep_plan_is_built_video_first():
+ # build_row_timesteps takes (video_timestep, audio_timestep) in that order, and both are
+ # plain floats, so swapping them is silent: the video rows would be conditioned at the
+ # audio schedule's noise level and vice versa.
+ import inspect
+
+ from core.training import diffusion_h3_trainer
+
+ source = inspect.getsource(diffusion_h3_trainer._train_h3)
+ assert "1.0 - sigma_video, 1.0 - sigma_audio" in source
+ assert "1.0 - sigma_audio, 1.0 - sigma_video" not in source
+
+
+def test_one_base_u_drives_both_sigmas():
+ import inspect
+
+ from core.training import diffusion_h3_trainer
+
+ source = inspect.getsource(diffusion_h3_trainer._train_h3)
+ assert "u = rng.random()" in source
+ assert "_shifted_sigma(u, video_shift)" in source
+ assert "_shifted_sigma(u, _H3_AUDIO_SHIFT)" in source
+
+
+def test_the_conditioning_phase_never_names_the_transformer():
+ # Naming it in load_components would put the 66 GB denoiser on the device alongside the
+ # 63 GiB conditioner, which is the whole point of the phased load.
+ from core.training.diffusion_h3_trainer import _H3_CONDITIONING_COMPONENTS
+
+ assert "transformer" not in _H3_CONDITIONING_COMPONENTS
+ assert "transformer_ref" not in _H3_CONDITIONING_COMPONENTS
+ assert set(_H3_CONDITIONING_COMPONENTS) == {
+ "text_encoder",
+ "tokenizer",
+ "processor",
+ "vae",
+ "audio_vae",
+ }
+
+
+def test_the_component_grid_assertion_catches_a_moved_constant():
+ from core.training.diffusion_h3_trainer import _assert_component_grid
+
+ class _Cfg:
+ def __init__(self, **kw):
+ self.__dict__.update(kw)
+
+ good_vae = types.SimpleNamespace(
+ spatial_compression_ratio = H3_SPATIAL_COMPRESSION,
+ tokens_chunk_size = H3_LATENTS_PER_CHUNK,
+ config = _Cfg(clip_length = H3_FRAMES_PER_CHUNK, latent_channels = 24),
+ )
+ good_audio = types.SimpleNamespace(config = _Cfg(latent_channels = 32, sampling_rate = 32000))
+ _assert_component_grid(types.SimpleNamespace(vae = good_vae, audio_vae = good_audio))
+
+ bad_vae = types.SimpleNamespace(
+ spatial_compression_ratio = 8,
+ tokens_chunk_size = H3_LATENTS_PER_CHUNK,
+ config = _Cfg(clip_length = H3_FRAMES_PER_CHUNK, latent_channels = 24),
+ )
+ with pytest.raises(ValueError, match = "spatial compression"):
+ _assert_component_grid(types.SimpleNamespace(vae = bad_vae, audio_vae = good_audio))
+
+
+def test_the_saved_adapter_carries_the_diffusers_transformer_prefix(tmp_path):
+ # Diffusers ships no MiniMaxH3LoraLoaderMixin, so the file is written directly. It must
+ # still be the ordinary single-file layout, or nothing can load it.
+ from safetensors.torch import load_file
+
+ from core.training.diffusion_h3_trainer import _save_lora
+
+ _save_lora(str(tmp_path), {"transformer_blocks.0.attn.to_q.lora_A.weight": torch.zeros(2, 2)})
+ saved = load_file(str(tmp_path / "pytorch_lora_weights.safetensors"))
+ assert list(saved) == ["transformer.transformer_blocks.0.attn.to_q.lora_A.weight"]
+
+
+# ── the hosted denoiser is a component, not a base ───────────────────────────
+
+
+def test_the_hosted_prequant_denoiser_is_refused_as_a_training_base():
+ """The two registries mean opposite things by ``prequant_repos``: an image family's entry is a
+ full quantized PIPELINE mirror, a video family's is the pre-quantized DENOISER alone. Reading
+ both as bases let the H3 denoiser repo through the preflight -- its name resolves to the
+ family, the unsloth/* trust gate passes it -- so the run evicted the resident GPU workloads
+ and only then failed inside ModularPipeline.from_pretrained."""
+ from core.inference.video_families import detect_video_family
+ from core.training.diffusion_train_common import (
+ _component_only_repos,
+ resolve_trainable_family,
+ )
+
+ fam = detect_video_family("", override = "minimax-h3")
+ denoiser_repo = fam.prequant_repos[0][1]
+ assert _component_only_repos()[denoiser_repo.lower()][:2] == ("minimax-h3", "transformer")
+ with pytest.raises(ValueError) as exc:
+ resolve_trainable_family(denoiser_repo)
+ detail = str(exc.value)
+ assert "not a full model" in detail
+ assert fam.base_repo in detail # and names what to train instead
+
+
+def test_the_real_h3_base_is_still_trainable():
+ """The other side of the same coin: the base itself must not be caught by the refusal."""
+ from core.inference.video_families import detect_video_family
+ from core.training.diffusion_train_common import resolve_trainable_family
+
+ fam = detect_video_family("", override = "minimax-h3")
+ assert resolve_trainable_family(fam.base_repo) == "minimax-h3"
+
+
+# ── the checkpoint contract the H3 loop does not implement ───────────────────
+
+
+def _h3_cfg(**kw):
+ from core.training.diffusion_train_common import DiffusionLoraConfig
+ return DiffusionLoraConfig(
+ base_model = "MiniMaxAI/MiniMax-H3",
+ data_dir = "/tmp/d",
+ output_dir = "/tmp/o",
+ instance_prompt = "p",
+ **kw,
+ )
+
+
+def test_resume_is_refused_rather_than_silently_starting_over():
+ """The dangerous half: run_h3_lora_training neither writes a resume bundle nor restores one,
+ so a caller handing one over got a FRESH optimization that then overwrote the outputs it was
+ meant to continue -- discovered only after an expensive run."""
+ with pytest.raises(ValueError, match = "resume_from_checkpoint is not supported"):
+ _h3_cfg(resume_from_checkpoint = "/tmp/o/checkpoint-100").normalized()
+
+
+def test_save_steps_is_refused_rather_than_silently_ignored():
+ """The quieter half: periodic saves were accepted and never happened, so a stopped run had
+ nothing to go back to."""
+ with pytest.raises(ValueError, match = "save_steps is not supported"):
+ _h3_cfg(save_steps = 50).normalized()
+
+
+def test_the_defaults_are_untouched():
+ """Neither knob set is the normal case and must stay valid, or the family becomes untrainable."""
+ cfg = _h3_cfg().normalized()
+ assert cfg.save_steps == 0
+ assert cfg.resume_from_checkpoint is None
+
+
+def test_an_image_family_keeps_its_checkpointing():
+ """The refusal is scoped to the loop that lacks the support, not to training at large."""
+ from core.training.diffusion_train_common import DiffusionLoraConfig
+
+ cfg = DiffusionLoraConfig(
+ base_model = "stabilityai/stable-diffusion-xl-base-1.0",
+ data_dir = "/tmp/d",
+ output_dir = "/tmp/o",
+ instance_prompt = "p",
+ save_steps = 50,
+ ).normalized()
+ assert cfg.save_steps == 50
+
+
+# ── the four review fixes ────────────────────────────────────────────────────
+
+
+def test_int8_training_applies_h3s_small_m_guards():
+ """Without the family, ``adaln_proj`` (Linear(2688 -> 96768) on the dense checkpoint) clears
+ the 512-feature floor, gets quantized, then runs at M = 1 and raises
+ ``self.size(0) needs to be greater than 16`` on the first step -- after the whole 66.3 GB
+ base has loaded. The family also carries the PAD list, which is the other half of the same
+ contract: context_embedder and the two token_refiner blocks are in neither exclusion list
+ precisely because they are meant to be padded instead."""
+ from core.inference.diffusion_transformer_quant import (
+ exclude_tokens_for_scheme,
+ pad_tokens_for_scheme,
+ )
+ from core.training import diffusion_dit_trainer as dit
+ from core.training import diffusion_h3_trainer as h3
+
+ assert "adaln_proj" in exclude_tokens_for_scheme("int8", "minimax-h3")
+ assert "adaln_proj" not in exclude_tokens_for_scheme("int8", None)
+ assert pad_tokens_for_scheme("int8", "minimax-h3")
+
+ # The trainer hands the family down, and the shared helper reads BOTH lists off it.
+ src = Path(h3.__file__).read_text()
+ assert "_int8_quantize_base(transformer, cfg.resolved_family)" in src
+ dit_src = Path(dit.__file__).read_text()
+ body = dit_src.split("def _int8_quantize_base", 1)[1].split("\ndef ", 1)[0]
+ assert 'exclude_tokens_for_scheme("int8", family)' in body
+ assert 'apply_small_m_padding(transformer, "int8", family)' in body
+
+
+def test_int8_quantize_base_pads_the_families_small_m_linears(monkeypatch):
+ # The behavioural half: the helper must call the padding pass, with the family, AFTER
+ # quantize_ (which is what reparents the Linears the pass wraps).
+ import torch.nn as nn
+
+ from core.training import diffusion_dit_trainer as dit
+
+ order: list = []
+ fake_ao = types.ModuleType("torchao.quantization")
+ fake_ao.Int8WeightOnlyConfig = lambda: "int8cfg"
+ fake_ao.quantize_ = lambda model, cfg, filter_fn = None: order.append("quantize")
+ monkeypatch.setitem(sys.modules, "torchao", types.ModuleType("torchao"))
+ monkeypatch.setitem(sys.modules, "torchao.quantization", fake_ao)
+ monkeypatch.setattr(
+ "core.inference.diffusion_transformer_quant.apply_small_m_padding",
+ lambda transformer, scheme, family, **kw: order.append(("pad", scheme, family)),
+ )
+
+ dit._int8_quantize_base(nn.Linear(4, 4), "minimax-h3")
+ assert order == ["quantize", ("pad", "int8", "minimax-h3")]
+
+
+def test_a_non_default_lora_alpha_survives_the_export(tmp_path):
+ """``load_lora_adapter`` reads the rank off the B matrices and then sets
+ ``lora_alpha = r`` unless the file carries adapter metadata, so an adapter trained at
+ rank 16 / alpha 32 used to come back at half its trained strength. The metadata layout is
+ diffusers' own: JSON under ``lora_adapter_metadata``, every key packed with the same
+ ``transformer.`` prefix the tensors carry, because the loader strips it off both."""
+ from safetensors import safe_open
+
+ from core.training.diffusion_h3_trainer import _save_lora
+
+ _save_lora(
+ str(tmp_path),
+ {"transformer_blocks.0.attn.to_q.lora_A.weight": torch.zeros(2, 2)},
+ {"r": 16, "lora_alpha": 32, "target_modules": {"to_q"}},
+ )
+ with safe_open(str(tmp_path / "pytorch_lora_weights.safetensors"), framework = "pt") as f:
+ meta = f.metadata()
+ assert meta["format"] == "pt"
+ recorded = json.loads(meta["lora_adapter_metadata"])
+ assert recorded["transformer.lora_alpha"] == 32
+ assert recorded["transformer.r"] == 16
+ # A set is not JSON-serialisable; diffusers lists them, and so must this.
+ assert recorded["transformer.target_modules"] == ["to_q"]
+
+
+def test_the_export_without_a_config_still_writes_a_plain_file(tmp_path):
+ # The EMA path and the existing callers pass no config; that must stay a valid file.
+ from safetensors.torch import load_file
+
+ from core.training.diffusion_h3_trainer import _save_lora
+
+ _save_lora(str(tmp_path), {"transformer_blocks.0.attn.to_q.lora_A.weight": torch.zeros(2, 2)})
+ assert list(load_file(str(tmp_path / "pytorch_lora_weights.safetensors"))) == [
+ "transformer.transformer_blocks.0.attn.to_q.lora_A.weight"
+ ]
+
+
+def test_a_mostly_silent_soundtrack_is_refused_rather_than_padded(tmp_path):
+ """The mandatory-audio check only asks whether the container declares an audio stream, and
+ the pad had no ceiling, so a clip carrying a fraction of a second of sound was accepted and
+ zero-padded out to the whole window -- training the shared adapter on the silence the check
+ exists to keep out."""
+ import numpy as np
+
+ from core.training import diffusion_h3_clips as clips
+
+ target = clips.h3_audio_sample_count(clips.H3_FRAMES_PER_CHUNK)
+
+ class _Resampler:
+ def resample(self, frame):
+ return [] if frame is None else [frame]
+
+ class _Container:
+ def __init__(self, n):
+ self._n = n
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def decode(self, audio = 0):
+ block = types.SimpleNamespace(
+ # A real signal, not zeros: this test is about DURATION, and an all-zero window
+ # is separately refused for being silent, which would mask what it checks.
+ to_ndarray = lambda: np.full(
+ (self._n * clips.H3_AUDIO_CHANNELS,), 0.25, dtype = "float32"
+ )
+ )
+ return [block]
+
+ def fake_av(n):
+ return types.SimpleNamespace(
+ AudioResampler = lambda **kw: _Resampler(),
+ open = lambda path: _Container(n),
+ )
+
+ # A tail a few milliseconds short is still padded, as the comment promises.
+ short_tail = target - int(0.002 * clips.H3_AUDIO_SAMPLING_RATE)
+ out = clips._decode_clip_audio(tmp_path / "a.mp4", target, fake_av(short_tail), np)
+ assert out.shape == (clips.H3_AUDIO_CHANNELS, target)
+
+ # A soundtrack that is materially shorter is refused instead.
+ with pytest.raises(ValueError, match = "of audio for a"):
+ clips._decode_clip_audio(tmp_path / "a.mp4", target, fake_av(target // 10), np)
+
+
+def test_a_soundtrack_that_is_silent_throughout_is_refused(tmp_path):
+ """A muted track is full length, so the duration checks above all pass and the window comes
+ back all zeros -- the very target the short-audio refusal exists to keep out, arriving by a
+ route that refusal cannot see. Training on it teaches the shared adapter to stop making
+ sound, so it is refused with the rest of the audio validation rather than accepted.
+
+ The control matters as much as the refusal: a track that is quiet, or silent for almost all
+ of its length with one real sound in it, is still a usable soundtrack and must be kept."""
+ import types
+
+ import numpy as np
+
+ from core.training import diffusion_h3_clips as clips
+
+ target = clips.h3_audio_sample_count(41)
+
+ class _Resampler:
+ def resample(self, frame):
+ return [] if frame is None else [frame]
+
+ def container_of(fill):
+ class _Container:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def decode(self, audio = 0):
+ buf = fill(target)
+ return [types.SimpleNamespace(to_ndarray = lambda b = buf: b)]
+
+ return _Container()
+
+ def fake_av(fill):
+ return types.SimpleNamespace(
+ AudioResampler = lambda **kw: _Resampler(),
+ open = lambda path, _f = fill: container_of(_f),
+ )
+
+ def silent(n):
+ return np.zeros((n * clips.H3_AUDIO_CHANNELS,), dtype = "float32")
+
+ def dithered(n):
+ # Not exact zeros: an encode/decode round trip leaves rounding dust on digital silence,
+ # and a threshold that only caught 0.0 would wave that through.
+ return (silent(n) + 1e-7).astype("float32")
+
+ def one_real_sound(n):
+ buf = silent(n)
+ buf[: 64 * clips.H3_AUDIO_CHANNELS] = 0.4
+ return buf
+
+ def quiet(n):
+ return (silent(n) + 0.01).astype("float32")
+
+ for fill in (silent, dithered):
+ with pytest.raises(ValueError, match = "silent all the way through"):
+ clips._decode_clip_audio(tmp_path / "a.mp4", target, fake_av(fill), np)
+
+ for fill in (one_real_sound, quiet):
+ out = clips._decode_clip_audio(tmp_path / "a.mp4", target, fake_av(fill), np)
+ assert out.shape == (clips.H3_AUDIO_CHANNELS, target)
+
+
+def test_the_knobs_h3_cannot_honour_are_refused_or_normalised():
+ """Same rule as the other pins this trainer applies: a setting the loop does not implement
+ must not be accepted and then silently dropped. Refused where the value can only be an
+ explicit non-default, normalised where the SCHEMA DEFAULT is the one the loop disagrees with
+ -- refusing there would 422 every untouched request.
+
+ Read off the shared preflight, which is also what the START ROUTE calls before it evicts the
+ user's resident models."""
+ from dataclasses import replace as _replace
+
+ from core.training.diffusion_train_common import h3_train_unsupported_reason
+
+ base = _h3_cfg().normalized()
+ assert h3_train_unsupported_reason(base) is None, "a default H3 request must start"
+
+ refused = {
+ "mixed_precision": ("no", "requires bf16"),
+ "train_batch_size": (2, "batch size 1"),
+ "compile_transformer": ("on", "does not compile"),
+ "cond_cache_dir": ("/tmp/cond", "conditioning cache"),
+ "cfg_dropout": (0.1, "guidance-distilled"),
+ "weighting_scheme": ("bell", "timestep-weighted"),
+ "resolution": (700, "multiples of"),
+ }
+ for field, (value, fragment) in refused.items():
+ reason = h3_train_unsupported_reason(_replace(base, **{field: value}))
+ assert reason and fragment in reason, f"{field} was accepted: {reason!r}"
+
+ # Config-only, so it never answers for another family and never touches the host.
+ from core.training.diffusion_train_common import DiffusionLoraConfig
+
+ other = DiffusionLoraConfig(
+ base_model = "black-forest-labs/FLUX.1-dev",
+ data_dir = "/tmp/d",
+ output_dir = "/tmp/o",
+ instance_prompt = "p",
+ mixed_precision = "no",
+ )
+ assert h3_train_unsupported_reason(other.normalized()) is None
+
+
+def test_the_h3_preflight_runs_before_the_start_route_evicts_anything():
+ # The whole point of the shared helper: these used to reach the worker and 400 there, with
+ # the resident models already freed for a run that never began.
+ import inspect
+
+ import routes.training as tr
+
+ src = inspect.getsource(tr.start_diffusion_training)
+ # The CALL, not the docstring's mention of it.
+ assert src.index("h3_train_unsupported_reason") < src.index(
+ "asyncio.to_thread(_free_gpu_for_diffusion_training)"
+ )
+
+
+def test_the_augmentation_knobs_record_what_h3_actually_does():
+ """Every frame goes through the same centre cover-crop and nothing is flipped, but the
+ schema defaults say the opposite (center_crop=False, random_flip=True), so an untouched
+ request described augmentation that never happened. Normalised rather than refused: a
+ refusal would 422 every default request."""
+ from dataclasses import replace as _replace
+
+ from core.training import diffusion_h3_trainer as h3
+ from core.training.diffusion_train_common import train_recipe_overrides
+
+ src = Path(h3.__file__).read_text()
+ # Applied from the shared table, which the service also reads for the persisted run record.
+ assert "replace(cfg, **train_recipe_overrides(cfg))" in src
+ overrides = train_recipe_overrides(_h3_cfg().normalized())
+ assert overrides["center_crop"] is True and overrides["random_flip"] is False
+ # And the two fields really are settable on the config the trainer normalises.
+ cfg = _replace(_h3_cfg(), center_crop = True, random_flip = False)
+ assert cfg.center_crop is True and cfg.random_flip is False
+
+
+def test_h3_is_advertised_as_trainable_with_the_precisions_it_has():
+ """The Train panel reads an EMPTY precision_modes on a non-SDXL family as "this GPU cannot
+ train this family" and disables Start with "Not supported on this GPU". MiniMax-H3 was only
+ in _FLOW_TRAIN_FAMILIES, while the info builder keyed the precision branch on
+ _DIT_TRAIN_FAMILIES, so it reported [] even on a host that can train, and the trainer this
+ PR adds was unreachable from Studio.
+
+ Judged against a reference DiT family rather than against a hardcoded list, so the test
+ describes the host it runs on: on a GPU-less runner BOTH are legitimately empty, and the
+ invariant under test is that H3 is never the only one that is. fp8/mxfp8 stay out either
+ way -- the trainer refuses both outright."""
+ from core.training.diffusion_train_common import family_train_infos
+
+ infos = {i["name"]: i for i in family_train_infos()}
+ h3 = infos.get("minimax-h3")
+ reference = next((infos[n] for n in ("flux.1", "ltx-2", "qwen-image") if n in infos), None)
+ if h3 is None or reference is None:
+ pytest.skip("this diffusers carries neither H3 nor a reference DiT family")
+
+ expected = [m for m in reference["precision_modes"] if m not in ("fp8", "mxfp8")]
+ assert h3["precision_modes"] == expected
+ # The case the bug was: a host that CAN train the DiT families must be able to train H3.
+ if reference["precision_modes"]:
+ assert h3["precision_modes"], "an empty list disables Start in the Train panel"
+ # compile is the one DiT lever that must NOT follow: "on" is refused by the trainer.
+ assert h3["supports_compile"] is False
+ assert infos["sdxl"]["supports_compile"] is True
+ if reference["precision_modes"]:
+ assert reference["supports_compile"] is True
+
+
+def test_an_over_long_clip_says_that_only_its_opening_trains(tmp_path, monkeypatch):
+ """The window is the clip's FIRST num_frames and the latents are cached once for the run, so
+ a longer source trains only its opening while its caption describes the whole scene. That is
+ the dataset contract, but it was silent, which is how the mismatch went unnoticed."""
+ import numpy as np
+
+ from core.training import diffusion_h3_clips as clips
+
+ notes: list = []
+
+ class _Frame:
+ def to_image(self):
+ from PIL import Image
+ return Image.new("RGB", (64, 64))
+
+ class _Stream:
+ average_rate = clips.H3_FPS
+ guessed_rate = clips.H3_FPS
+ duration = 10 * clips.H3_FPS
+ time_base = 1 / clips.H3_FPS
+
+ class _Container:
+ streams = types.SimpleNamespace(video = [_Stream()], audio = [object()])
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def decode(self, video = 0):
+ return [_Frame() for _ in range(10 * clips.H3_FPS)]
+
+ monkeypatch.setattr(
+ clips, "av", types.SimpleNamespace(open = lambda p: _Container()), raising = False
+ )
+ monkeypatch.setitem(sys.modules, "av", types.SimpleNamespace(open = lambda p: _Container()))
+ monkeypatch.setattr(
+ clips,
+ "_decode_clip_audio",
+ lambda path, target, av, np_: np.zeros((clips.H3_AUDIO_CHANNELS, target), "float32"),
+ )
+
+ clips.decode_clip(
+ tmp_path / "a.mp4",
+ num_frames = clips.H3_FRAMES_PER_CHUNK,
+ width = 64,
+ height = 64,
+ on_note = notes.append,
+ )
+ assert notes and "trains its first" in notes[0]
+
+ # A clip already at the training duration says nothing.
+ notes.clear()
+ _Stream.duration = clips.H3_FRAMES_PER_CHUNK
+ clips.decode_clip(
+ tmp_path / "a.mp4",
+ num_frames = clips.H3_FRAMES_PER_CHUNK,
+ width = 64,
+ height = 64,
+ on_note = notes.append,
+ )
+ assert notes == []
+
+
+# ── what the run RECORDS vs what the loop RUNS ───────────────────────────────
+def test_the_precision_recorded_for_h3_is_the_one_its_loop_runs_in():
+ """``identity_for_config`` records the EFFECTIVE mixed precision, and the helper it reads it
+ from keyed the "this loop ignores the knob" branch on _DIT_TRAIN_FAMILIES, which H3 is not in.
+
+ H3's loop is byte-identical to the DiT loop here -- bf16 on CUDA, fp32 otherwise, and the
+ string "mixed_precision" appears nowhere in it -- so the two families must resolve to the same
+ answer. Judged against a reference DiT family rather than a hardcoded value, so the test
+ describes the host it runs on (a CPU runner legitimately answers "no" for both).
+
+ Not reachable as a live mismatch today: an H3 request may only be bf16 (two independent gates
+ below), and H3 writes no checkpoint at all, so nothing consults the identity. Pinned anyway
+ because both of those are documented as temporary."""
+ import inspect
+
+ from core.training import diffusion_dit_trainer, diffusion_h3_trainer
+ from core.training.diffusion_train_common import effective_mixed_precision
+
+ h3 = _cfg().normalized()
+ reference = DiffusionLoraConfig(
+ base_model = "black-forest-labs/FLUX.1-dev",
+ data_dir = "/tmp/d",
+ output_dir = "/tmp/o",
+ instance_prompt = "p",
+ mixed_precision = "bf16",
+ ).normalized()
+ assert effective_mixed_precision(h3) == effective_mixed_precision(reference)
+
+ # The claim the equality rests on: the same weight-dtype rule in both loops, and no reader of
+ # mixed_precision in the H3 one.
+ dtype_rule = 'weight_dtype = torch.bfloat16 if device == "cuda" else torch.float32'
+ h3_src = inspect.getsource(diffusion_h3_trainer)
+ assert dtype_rule in h3_src
+ assert dtype_rule in inspect.getsource(diffusion_dit_trainer)
+ assert "mixed_precision" not in h3_src
+
+
+def test_an_h3_run_can_never_record_a_precision_it_did_not_use():
+ """The three gates that keep the identity honest today, so a change to any of them fails here
+ rather than in a resume refusal: fp16 is refused in validation, any other non-bf16 value is
+ refused by the shared start preflight, and the family writes no checkpoint to record into."""
+ from dataclasses import replace as _replace
+
+ from core.training.diffusion_train_common import h3_train_unsupported_reason
+
+ with pytest.raises(ValueError, match = "bf16"):
+ _cfg(mixed_precision = "fp16").normalized()
+ reason = h3_train_unsupported_reason(_replace(_cfg().normalized(), mixed_precision = "no"))
+ assert reason and "requires bf16" in reason
+ with pytest.raises(ValueError, match = "resume_from_checkpoint"):
+ _cfg(resume_from_checkpoint = "/tmp/out").normalized()
+ with pytest.raises(ValueError, match = "save_steps"):
+ _cfg(save_steps = 100).normalized()
+
+
+def test_the_persisted_h3_recipe_is_the_one_the_loop_runs():
+ """The loop replaces center_crop / random_flip / snr_gamma, but the run record is written by
+ the PARENT from the config handed to ``service.start`` -- the child's ``replace`` never
+ reached it, so Previous runs described cropping, flipping and min-SNR weighting that no step
+ used. Both sides read one shared table now."""
+ import inspect
+
+ from core.training.diffusion_training_service import DiffusionTrainingService
+ from core.training.diffusion_train_common import train_recipe_overrides
+
+ assert train_recipe_overrides(_cfg().normalized()) == {
+ "center_crop": True,
+ "random_flip": False,
+ "snr_gamma": None,
+ # The loop encodes each clip once into one cached tuple and frees the VAEs; it reads
+ # neither field, so a request for no cache, or for the schema's four variants, ran
+ # cached-with-one anyway and the record said otherwise.
+ "cache_latents": True,
+ "cache_variants": 1,
+ }
+ # Config-only, and no other family's loop disagrees with its request.
+ other = DiffusionLoraConfig(
+ base_model = "black-forest-labs/FLUX.1-dev",
+ data_dir = "/tmp/d",
+ output_dir = "/tmp/o",
+ instance_prompt = "p",
+ ).normalized()
+ assert train_recipe_overrides(other) == {}
+
+ # The two appliers: the trainer for what runs, the service for what is recorded.
+ from core.training import diffusion_h3_trainer
+
+ assert "train_recipe_overrides" in inspect.getsource(diffusion_h3_trainer)
+ start_src = inspect.getsource(DiffusionTrainingService.start)
+ assert "train_recipe_overrides" in start_src
+ assert "self._config.update(" in start_src
+
+
+# ── start-route gates ────────────────────────────────────────────────────────
+def test_the_strict_start_gate_probes_the_h3_transformer_not_modular_pipeline(monkeypatch):
+ """A diffusers old enough to predate H3's blocks still exports the generic ``ModularPipeline``,
+ so the listing probe (which reads the family's own transformer class) hid H3 while a direct
+ POST /diffusion/start sailed through both training gates, evicted the resident GPU models and
+ failed in the child. Both gates read the same probe class now."""
+ from core.inference.diffusion_families import family_pipeline_available, family_probe_class
+ from core.training.diffusion_train_common import (
+ _trainable_family_spec,
+ training_pipeline_import_error,
+ )
+
+ fam = _trainable_family_spec("minimax-h3")
+ assert fam is not None and fam.pipeline_class == "ModularPipeline"
+ assert family_probe_class(fam) == "MiniMaxH3Transformer3DModel"
+
+ old = types.ModuleType("diffusers")
+ old.__version__ = "0.36.0"
+ old.ModularPipeline = object # the generic entry point, present for several releases
+ old.FluxPipeline = object
+ monkeypatch.setitem(sys.modules, "diffusers", old)
+
+ assert family_pipeline_available(fam) is False
+ reason = training_pipeline_import_error("minimax-h3")
+ assert reason and "MiniMaxH3Transformer3DModel" in reason
+ # A conventional family on the same install is untouched.
+ assert training_pipeline_import_error("flux.1") is None
+
+ # And the trainer-side half refuses before it can reach a download.
+ with pytest.raises(ValueError, match = "MiniMaxH3Transformer3DModel"):
+ _cfg().normalized()
+
+
+def test_the_probe_still_fails_open_for_a_record_that_names_no_pipeline_class():
+ """``family_pipeline_available`` hides nothing it cannot judge. The probe helper reads
+ ``pipeline_class`` with a default, so a record without one arrives as the empty string, and
+ ``hasattr(diffusers, "")`` is False -- which would drop a usable repo out of a picker over a
+ stand-in family object rather than over a real missing class."""
+ from core.inference.diffusion_families import family_pipeline_available, family_probe_class
+
+ assert family_probe_class(object()) == ""
+ assert family_pipeline_available(object()) is True
+
+
+def test_a_local_modular_h3_pipeline_is_an_acceptable_training_base(tmp_path):
+ """A local MiniMax-H3 pipeline carries ``modular_model_index.json`` and NO
+ ``model_index.json`` -- that is the layout ``ModularPipeline.from_pretrained`` reads and the
+ one the local-model scanners already count. The shared shape check knew only the conventional
+ index, so it rejected the only local layout the family has."""
+ from core.training.diffusion_train_common import _assert_trusted_base_model
+
+ modular = tmp_path / "MiniMax-H3"
+ modular.mkdir()
+ (modular / "modular_model_index.json").write_text("{}")
+
+ _assert_trusted_base_model(str(modular), allow_modular = True)
+ # Off by default: a conventional DiffusionPipeline load still needs the conventional index.
+ with pytest.raises(ValueError, match = "model_index.json"):
+ _assert_trusted_base_model(str(modular))
+ # And a directory that is neither is still refused on both paths.
+ empty = tmp_path / "not-a-pipeline"
+ empty.mkdir()
+ for allow in (True, False):
+ with pytest.raises(ValueError, match = "not a diffusers pipeline directory"):
+ _assert_trusted_base_model(str(empty), allow_modular = allow)
+
+
+def test_the_start_route_reaches_the_same_modular_verdict_as_the_trainer():
+ """The route runs the trainers' trust gate first, so an untrusted base 400s before the
+ resident GPU models are freed. It called it with the default conventional-only shape check,
+ while the H3 loop called it with allow_modular -- so a local modular pipeline, the only local
+ layout the family HAS, was rejected at the route and the loop that can load it never ran.
+ Both sides now select off one set, which is the only way they cannot disagree again."""
+ import inspect
+
+ from core.training import diffusion_h3_trainer
+ from core.training.diffusion_train_common import MODULAR_BASE_FAMILIES
+ from routes import training as training_routes
+
+ assert "minimax-h3" in MODULAR_BASE_FAMILIES
+ # A family whose trainer loads a conventional pipeline must NOT be in it, or the shape check
+ # would start accepting a modular directory its loader cannot read.
+ assert MODULAR_BASE_FAMILIES.isdisjoint({"flux.1", "qwen-image", "sdxl", "ltx-2"})
+
+ # Neither call site may hard-code its answer: that is what let them drift apart.
+ route_src = inspect.getsource(training_routes.start_diffusion_training)
+ assert "MODULAR_BASE_FAMILIES" in route_src
+ assert "_assert_trusted_base_model(\n config.get" in route_src
+ trainer_src = inspect.getsource(diffusion_h3_trainer)
+ assert "MODULAR_BASE_FAMILIES" in trainer_src
+ assert "allow_modular = True" not in trainer_src
+
+
+def test_h3_advertises_that_it_cannot_checkpoint():
+ """save_steps is REFUSED for a checkpointless family, not ignored, so a panel that keeps
+ offering "Checkpoint every" offers a value that rejects Start with nothing on the control
+ saying why. The family metadata already carries supports_compile for the same reason."""
+ from core.training.diffusion_train_common import CHECKPOINTLESS_FAMILIES, family_train_infos
+
+ infos = {info["name"]: info for info in family_train_infos()}
+ assert "minimax-h3" in CHECKPOINTLESS_FAMILIES
+ for name, info in infos.items():
+ assert info["supports_checkpoints"] == (name not in CHECKPOINTLESS_FAMILIES), name
+ # The flag has to agree with the validation, or the panel hides a control that works or
+ # offers one that does not.
+ with pytest.raises(ValueError, match = "save_steps is not supported"):
+ _cfg(save_steps = 50).normalized()
+ _cfg(save_steps = 0).normalized()
+
+
+def test_the_batch_cap_survives_the_response_model():
+ """family_train_infos emitting it is not enough: the route builds a DiffusionTrainableFamily
+ from that dict, and Pydantic drops any field the model does not declare. Undeclared, the
+ panel reads the cap as undefined, keeps rendering Batch, and sends a carried-over value the
+ validation refuses -- the clamp exists but never receives its input."""
+ from core.training.diffusion_train_common import (
+ SINGLE_SEQUENCE_FAMILIES,
+ family_train_infos,
+ )
+ from models.training import DiffusionTrainableFamily
+
+ infos = {info["name"]: info for info in family_train_infos()}
+ assert "minimax-h3" in SINGLE_SEQUENCE_FAMILIES
+ for name, info in infos.items():
+ expected = 1 if name in SINGLE_SEQUENCE_FAMILIES else None
+ assert info["max_train_batch_size"] == expected, name
+ # Through the wire model, which is where it was being dropped.
+ assert DiffusionTrainableFamily(**info).max_train_batch_size == expected, name
+ # And the cap has to agree with the validation, or the panel hides a control that works.
+ from core.training.diffusion_train_common import h3_train_unsupported_reason
+
+ assert "batch size 1" in (
+ h3_train_unsupported_reason(_cfg(train_batch_size = 2).normalized()) or ""
+ )
+ assert h3_train_unsupported_reason(_cfg(train_batch_size = 1).normalized()) is None
+
+
+def test_the_h3_conditioner_load_carries_the_hub_token(monkeypatch):
+ """``ModularPipeline.from_pretrained``'s token opens the modular INDEX only: every component
+ is fetched by its own ``from_pretrained`` inside ``load_components``, which swallows a failure
+ as a logger.warning and leaves the attribute unset. A gated or private base therefore loaded
+ its components anonymously and died on a None, after the route's authenticated preflight had
+ passed. The inference H3 loader forwards it again for exactly this reason."""
+ from core.training import diffusion_h3_trainer as h3
+
+ seen: list[dict] = []
+
+ class _Placed:
+ def to(self, device):
+ return self
+
+ class _Pipe:
+ text_encoder = _Placed()
+ vae = _Placed()
+ audio_vae = _Placed()
+
+ def load_components(self, **kwargs):
+ seen.append(kwargs)
+
+ class _Modular:
+ @staticmethod
+ def from_pretrained(
+ path,
+ token = None,
+ **kw,
+ ):
+ seen.append({"index_token": token, **kw})
+ return _Pipe()
+
+ monkeypatch.setitem(sys.modules, "diffusers", types.SimpleNamespace(ModularPipeline = _Modular))
+ monkeypatch.setattr(h3, "_assert_component_grid", lambda pipe: None)
+ monkeypatch.setattr("core.inference.diffusion.hub_cache_dir", lambda: "/live/hub")
+
+ cfg = types.SimpleNamespace(base_model = "unsloth/private-h3", hf_token = "hf_secret")
+ h3._load_conditioners(cfg, "cpu")
+
+ assert seen[0] == {"index_token": "hf_secret", "cache_dir": "/live/hub"}
+ component_loads = seen[1:]
+ assert len(component_loads) == 2
+ assert all(call.get("token") == "hf_secret" for call in component_loads), component_loads
+ # And every one of them pinned to the LIVE cache root. An unset cache_dir resolves through
+ # huggingface_hub's import-time constant, which a mid-session cache-folder change does not
+ # update, and the training subprocess is spawned without the cache-environment wrapper: the
+ # components already in the selected root would be missed and re-downloaded into the old one.
+ assert all(call.get("cache_dir") == "/live/hub" for call in component_loads), component_loads
+
+ # No token configured -> the kwarg is omitted entirely rather than sent as None.
+ seen.clear()
+ h3._load_conditioners(
+ types.SimpleNamespace(base_model = "MiniMaxAI/MiniMax-H3", hf_token = None), "cpu"
+ )
+ assert all("token" not in call for call in seen[1:]), seen
+
+
[email protected]("base_precision", ["bf16", "nf4"])
+def test_the_h3_denoiser_load_is_pinned_to_the_live_cache(monkeypatch, base_precision):
+ """The denoiser is the 145 GB half, so this is the expensive one to leave unpinned."""
+ from core.training import diffusion_h3_trainer as h3
+
+ seen: list[dict] = []
+
+ class _Model:
+ def to(self, device):
+ return self
+
+ class _Transformer:
+ @staticmethod
+ def from_pretrained(path, **kw):
+ seen.append(kw)
+ return _Model()
+
+ monkeypatch.setitem(
+ sys.modules,
+ "diffusers",
+ types.SimpleNamespace(
+ MiniMaxH3Transformer3DModel = _Transformer,
+ BitsAndBytesConfig = lambda **kw: kw,
+ ),
+ )
+ monkeypatch.setattr("core.inference.diffusion.hub_cache_dir", lambda: "/live/hub")
+
+ cfg = types.SimpleNamespace(base_model = "MiniMaxAI/MiniMax-H3", hf_token = None)
+ h3._load_transformer(cfg, "cpu", base_precision)
+
+ assert len(seen) == 1
+ assert seen[0]["cache_dir"] == "/live/hub"
+ assert seen[0]["subfolder"] == "transformer"
+
+
+def test_the_audio_decode_stops_at_the_training_window(tmp_path):
+ """An over-long source is accepted input -- only its first num_frames train, and the caller is
+ warned -- so the soundtrack past that window is never used. The video loop already breaks at
+ the window; the audio one decoded and resampled the whole recording and kept every chunk
+ before truncating, so a long clip cost a recording's worth of time and memory to build a
+ sub-second sample (and failed on damage in a region that is never read)."""
+ import numpy as np
+
+ from core.training import diffusion_h3_clips as clips
+
+ target = clips.h3_audio_sample_count(clips.H3_FRAMES_PER_CHUNK)
+ decoded = 0
+
+ class _Resampler:
+ def resample(self, frame):
+ return [] if frame is None else [frame]
+
+ class _Container:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def decode(self, audio = 0):
+ nonlocal decoded
+ for _ in range(4000): # an hour of audio behind a one-second window
+ decoded += 1
+ yield types.SimpleNamespace(
+ # Nonzero for the same reason as above: the subject here is where decoding
+ # STOPS, and a silent window is refused before that can be asserted.
+ to_ndarray = lambda: np.full(
+ (target * clips.H3_AUDIO_CHANNELS,), 0.25, dtype = "float32"
+ )
+ )
+
+ av = types.SimpleNamespace(
+ AudioResampler = lambda **_kw: _Resampler(), open = lambda _p: _Container()
+ )
+ out = clips._decode_clip_audio(tmp_path / "a.mp4", target, av, np)
+
+ assert out.shape == (clips.H3_AUDIO_CHANNELS, target)
+ assert decoded == 1, f"decoded {decoded} blocks for a window one block wide"
+
+
+def _stub_training_stack(monkeypatch):
+ """Satisfy the four training-stack names ``_train_h3`` binds on entry.
+
+ The backend CI image installs neither diffusers nor peft, so the function-level
+ ``from diffusers.optimization import get_scheduler`` aborted the cache-gate tests before they
+ reached the gate. None of the four is called on the path under test -- the gate raises, or
+ the faked ``_load_transformer`` does -- so binding them to placeholders keeps the tests
+ running everywhere rather than skipping them on the only host that runs them in CI."""
+ scheduler = types.ModuleType("diffusers.optimization")
+ scheduler.get_scheduler = lambda *_a, **_k: None
+ training_utils = types.ModuleType("diffusers.training_utils")
+ training_utils.cast_training_params = lambda *_a, **_k: None
+ peft_utils = types.ModuleType("peft.utils")
+ peft_utils.get_peft_model_state_dict = lambda *_a, **_k: {}
+ peft = types.ModuleType("peft")
+ peft.LoraConfig = object
+ peft.utils = peft_utils
+ for name, module in (
+ # The SUBMODULES only, never a bare ``diffusers`` parent. ``from a.b import c`` is
+ # satisfied straight from ``sys.modules["a.b"]`` without importing ``a``, and a stub
+ # parent would be worse than none here: ``resolve_trainable_family`` absorbs an
+ # unimportable diffusers but REFUSES one that imports and lacks
+ # MiniMaxH3Transformer3DModel, so faking the package turns a skipped probe into a raise.
+ ("diffusers.optimization", scheduler),
+ ("diffusers.training_utils", training_utils),
+ ("peft", peft),
+ ("peft.utils", peft_utils),
+ ):
+ # Only where the real one is absent, so a developer host keeps running the real imports.
+ try:
+ importlib.import_module(name)
+ except Exception: # noqa: BLE001 -- absent or broken both mean "use the placeholder"
+ monkeypatch.setitem(sys.modules, name, module)
+
+
+def _h3_cache_run(monkeypatch, *, num_clips: int):
+ """Drive ``_train_h3`` through phase 2 only, with every model call faked.
+
+ ``_load_transformer`` raises a sentinel, so "got past the cache gate" is observable without
+ the 66 GB base."""
+ import torch
+
+ from core.training import diffusion_h3_trainer as h3
+
+ _stub_training_stack(monkeypatch)
+
+ class _Placed:
+ def to(self, _device):
+ return self
+
+ pipe = types.SimpleNamespace(
+ text_encoder = _Placed(), processor = None, vae = _Placed(), audio_vae = _Placed()
+ )
+ monkeypatch.setattr(h3, "_load_conditioners", lambda cfg, device: pipe)
+ monkeypatch.setattr(h3, "_encode_prompt", lambda *_a, **_k: torch.zeros(1, 8, 16))
+ monkeypatch.setattr(h3, "_dataset_canvas", lambda _path, _short_edge: (64, 64))
+ monkeypatch.setattr(h3, "decode_clip", lambda *_a, **_k: (None, None))
+ monkeypatch.setattr(
+ h3,
+ "_encode_video_stats",
+ lambda *_a: (torch.zeros(1, 4, 2, 8, 8), torch.zeros(1, 4, 2, 8, 8)),
+ )
+ num_audio = h3.h3_audio_latent_count(h3.H3_TRAIN_NUM_FRAMES)
+ monkeypatch.setattr(
+ h3,
+ "_encode_audio_latents",
+ lambda *_a: torch.zeros(1, h3.H3_AUDIO_LATENT_CHANNELS, num_audio),
+ )
+
+ def _no_transformer(*_a, **_k):
+ raise RuntimeError("reached phase 3")
+
+ monkeypatch.setattr(h3, "_load_transformer", _no_transformer)
+
+ cfg = _cfg(output_dir = "/tmp/h3-out").normalized()
+ pairs = [(f"/clips/{i}.mp4", "a caption") for i in range(num_clips)]
+ return lambda: h3._train_h3(
+ cfg,
+ pairs,
+ random.Random(0),
+ "cpu",
+ torch.float32,
+ lambda *_a, **_k: None,
+ lambda: False,
+ lambda: True,
+ )
+
+
+def test_the_h3_latent_cache_is_size_gated_like_the_image_trainers(monkeypatch):
+ """Both shared image trainers measure the FIRST real entry and refuse to build a latent cache
+ over the host-memory budget. H3 built one entry per discovered clip unconditionally, so a
+ large clip dataset was OOM-killed at the end of the whole preparation with nothing saved.
+
+ It cannot answer the way they do -- they drop the cache and encode per step, and H3 frees both
+ VAEs to make room for the 66 GB transformer -- so it says so up front instead, with the
+ numbers and the same explicit override the size gate already has."""
+ from core.training import diffusion_train_common as common
+
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_FORCE_LATENT_CACHE", raising = False)
+ monkeypatch.setattr(common, "_LATENT_CACHE_BUDGET_BYTES", 1)
+
+ with pytest.raises(ValueError, match = "latent cache") as exc:
+ _h3_cache_run(monkeypatch, num_clips = 4)()
+ assert "UNSLOTH_DIFFUSION_FORCE_LATENT_CACHE" in str(exc.value)
+
+
+def test_the_h3_latent_cache_gate_honours_the_explicit_override(monkeypatch):
+ """The gate is the AUTOMATIC default only, exactly as it is for the image trainers: a user who
+ has the RAM and says so gets the cache, and the run carries on into phase 3."""
+ from core.training import diffusion_train_common as common
+
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_FORCE_LATENT_CACHE", "1")
+ monkeypatch.setattr(common, "_LATENT_CACHE_BUDGET_BYTES", 1)
+
+ with pytest.raises(RuntimeError, match = "reached phase 3"):
+ _h3_cache_run(monkeypatch, num_clips = 4)()
+
+
+def _write_rotated_clip(
+ path,
+ *,
+ theta: int,
+ width: int = 640,
+ height: int = 360,
+ seconds: int = 2,
+):
+ """A real H.264+AAC clip whose display matrix says ``theta``, coded ``width`` x ``height``."""
+ av = pytest.importorskip("av")
+ np = pytest.importorskip("numpy")
+
+ with av.open(str(path), "w") as out:
+ video = out.add_stream("libx264", rate = H3_FPS)
+ video.width, video.height = width, height
+ video.pix_fmt = "yuv420p"
+ audio = out.add_stream("aac", rate = 48000)
+ if theta:
+ video.set_display_rotation(theta)
+ for i in range(H3_FPS * seconds):
+ # An asymmetric picture, so a wrong rotation cannot look like a right one.
+ img = np.zeros((height, width, 3), dtype = "uint8")
+ img[: height // 3, :, 0] = 255
+ img[:, : max(1, i * 4), 1] = 255
+ for packet in video.encode(av.VideoFrame.from_ndarray(img, format = "rgb24")):
+ out.mux(packet)
+ # An audible tone, not silence: these clips go through the real decode, which refuses a
+ # soundtrack that is silent end to end. A rotation test must not depend on that refusal
+ # being absent, and a clip with a working soundtrack is the realistic input anyway.
+ t = np.arange(48000 * seconds, dtype = "float32") / 48000.0
+ tone = (0.3 * np.sin(2 * np.pi * 440.0 * t)).astype("float32").reshape(1, -1)
+ frame = av.AudioFrame.from_ndarray(tone, format = "fltp", layout = "mono")
+ frame.sample_rate = 48000
+ for packet in audio.encode(frame):
+ out.mux(packet)
+ for packet in video.encode():
+ out.mux(packet)
+ for packet in audio.encode():
+ out.mux(packet)
+
+
+def test_a_rotated_clip_reports_its_display_rotation(tmp_path):
+ """PyAV hands back the CODED frame: unlike the ffmpeg CLI it does not apply the display
+ matrix. A portrait phone clip is stored landscape with a 90 degree matrix, so the rotation
+ has to be read off the frame or every target trains sideways."""
+ av = pytest.importorskip("av")
+ from core.training.diffusion_h3_clips import display_rotation_degrees
+
+ clip = tmp_path / "portrait.mp4"
+ _write_rotated_clip(clip, theta = 90)
+ with av.open(str(clip)) as container:
+ stream = container.streams.video[0]
+ frame = next(container.decode(video = 0))
+ assert (frame.width, frame.height) == (640, 360), "the coded frame is still landscape"
+ assert display_rotation_degrees(frame, stream) == 270
+
+
+def test_an_unrotated_clip_reports_no_rotation(tmp_path):
+ """The common case must stay exactly as it was, matrix or no matrix."""
+ av = pytest.importorskip("av")
+ from core.training.diffusion_h3_clips import display_rotation_degrees
+
+ clip = tmp_path / "landscape.mp4"
+ _write_rotated_clip(clip, theta = 0)
+ with av.open(str(clip)) as container:
+ frame = next(container.decode(video = 0))
+ assert display_rotation_degrees(frame, container.streams.video[0]) == 0
+
+
+def test_the_canvas_follows_the_displayed_orientation_not_the_coded_one(tmp_path):
+ """``_dataset_canvas`` used to read ``codec_context`` alone, so a portrait clip picked a
+ LANDSCAPE canvas and every frame was then cover-cropped down to it -- the sides of the real
+ picture thrown away, on top of training it sideways."""
+ pytest.importorskip("av")
+ from core.training.diffusion_h3_trainer import _dataset_canvas
+
+ landscape = tmp_path / "landscape.mp4"
+ portrait = tmp_path / "portrait.mp4"
+ _write_rotated_clip(landscape, theta = 0)
+ _write_rotated_clip(portrait, theta = 90)
+
+ wide_w, wide_h = _dataset_canvas(str(landscape), 512)
+ tall_w, tall_h = _dataset_canvas(str(portrait), 512)
+ assert wide_w > wide_h, (wide_w, wide_h)
+ assert tall_h > tall_w, "a rotated clip must train on a portrait canvas"
+ assert (tall_w, tall_h) == (wide_h, wide_w)
+
+
+def test_decode_clip_returns_the_rotated_picture(tmp_path):
+ """End to end: the cached frames are the picture a player shows, not the coded one."""
+ np = pytest.importorskip("numpy")
+ pytest.importorskip("av")
+ from core.training.diffusion_h3_clips import decode_clip
+
+ clip = tmp_path / "portrait.mp4"
+ _write_rotated_clip(clip, theta = 90, seconds = 3)
+ frames, _waveform = decode_clip(clip, num_frames = 8, width = 64, height = 128)
+
+ assert frames.shape == (8, 128, 64, 3)
+ # The red band occupies the top third of the CODED frame. Rotated 90 CCW for display it
+ # moves to the left third, so the rotation is observable in the pixels rather than assumed.
+ first = frames[0].astype("int32")
+ left = first[:, : 64 // 3, 0].mean()
+ right = first[:, -(64 // 3) :, 0].mean()
+ assert left > right + 40, f"red band did not move to the left edge (left {left}, right {right})"
+ top = first[: 128 // 3, :, 0].mean()
+ assert left > top + 40, "the band is still along the top, so no rotation was applied"
+
+
+def test_a_local_modular_pipeline_under_a_gguf_path_is_not_refused_as_gguf(tmp_path):
+ """``resolve_trainable_family`` exempted a local checkout by ``model_index.json`` only. A
+ MODULAR_BASE_FAMILIES base has ``modular_model_index.json`` and no ``model_index.json``, so
+ the one local layout MiniMax-H3 HAS was refused as a GGUF repo whenever its path contained
+ 'gguf', before model_family was even consulted."""
+ from core.training.diffusion_train_common import resolve_trainable_family
+
+ base = tmp_path / "gguf" / "MiniMax-H3"
+ base.mkdir(parents = True)
+ (base / "modular_model_index.json").write_text("{}", encoding = "utf-8")
+
+ assert resolve_trainable_family(str(base), model_family = "minimax-h3") == "minimax-h3"
+
+
+def test_a_real_gguf_path_without_a_pipeline_is_still_refused(tmp_path):
+ """The exemption is the index file, not the word: an actual GGUF pick must still be refused."""
+ from core.training.diffusion_train_common import resolve_trainable_family
+
+ base = tmp_path / "gguf" / "MiniMax-H3-GGUF"
+ base.mkdir(parents = True)
+ with pytest.raises(ValueError, match = "GGUF"):
+ resolve_trainable_family(str(base), model_family = "minimax-h3")
+
+
+def test_the_advertised_h3_vram_floor_covers_the_measured_run_peak():
+ """The field's own contract is the WHOLE-RUN peak, because that is what a card has to hold.
+ A real run on this branch peaked at 77.76 GB, so the advertised floor may not sit under it:
+ the chip is what a user sizes a host from."""
+ from core.training.diffusion_train_common import _FAMILY_TRAIN_SPECS
+ assert _FAMILY_TRAIN_SPECS["minimax-h3"]["qlora_vram_gb"] >= 78
diff --git a/studio/backend/tests/test_diffusion_lora_trainer.py b/studio/backend/tests/test_diffusion_lora_trainer.py
index ad8c8f4136b..5644bcc8fa9 100644
--- a/studio/backend/tests/test_diffusion_lora_trainer.py
+++ b/studio/backend/tests/test_diffusion_lora_trainer.py
@@ -260,11 +260,16 @@ def test_config_normalized_krea2_requires_bf16_compute():
def test_force_bf16_families_matches_trainer_specs():
- # The route-level bf16-only preflight set must list exactly the DiT families whose trainer spec sets force_bf16. A missing
+ # The route-level bf16-only preflight set must list every family whose trainer refuses fp16. A missing
# one lets an fp16 start pass the preflight, reserve training and evict residents, with only the child trainer raising.
+ # The DiT families declare it on their spec; MiniMax-H3 has its own trainer and declares it there, so the set is
+ # the union rather than the _SPECS projection alone.
from core.training.diffusion_dit_trainer import _SPECS
from core.training.diffusion_train_common import _FORCE_BF16_FAMILIES
- assert _FORCE_BF16_FAMILIES == {fam for fam, spec in _SPECS.items() if spec.force_bf16}
+
+ dit_bf16_only = {fam for fam, spec in _SPECS.items() if spec.force_bf16}
+ assert dit_bf16_only <= _FORCE_BF16_FAMILIES
+ assert _FORCE_BF16_FAMILIES - dit_bf16_only == {"minimax-h3"}
def _cfg(**kw):
diff --git a/studio/backend/tests/test_diffusion_train_picker_clip_families.py b/studio/backend/tests/test_diffusion_train_picker_clip_families.py
new file mode 100644
index 00000000000..903fcfeb071
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_train_picker_clip_families.py
@@ -0,0 +1,298 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""What the Train picker is allowed to ADVERTISE, versus what the API accepts.
+
+MiniMax-H3 trains from captioned video clips and from nothing else. ``/diffusion/info`` is
+what fills the Train tab's family dropdown, and the same response lists the datasets that
+dropdown can pick from. While every listed dataset is stills, offering H3 there offers a
+combination that cannot be completed: whichever dataset the user picks, Start comes back with
+"No captioned video clips found".
+
+So the family list in that response is narrowed to the families its own dataset list can feed.
+The narrowing is derived, not hardcoded: it reads the clip count the dataset layer reports for
+the folders it just listed, so the day that layer starts listing folders of clips, H3 is
+offered next to them with no edit here and no flag to flip.
+
+The API is deliberately NOT narrowed. ``family_train_infos()`` still describes H3 and
+``/diffusion/start`` still routes it through the clip discovery, in both dataset states. Only
+the advertisement moves.
+"""
+
+from __future__ import annotations
+
+import inspect
+import io
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from PIL import Image
+
+from auth.authentication import get_current_subject
+from models.training import DiffusionDatasetSummary
+from routes.training import router as training_router
+
+
+def client():
+ app = FastAPI()
+ app.include_router(training_router, prefix = "/api/train")
+ app.dependency_overrides[get_current_subject] = lambda: "test-user"
+ return TestClient(app)
+
+
+def ds_root(monkeypatch, tmp_path):
+ import utils.paths as up
+
+ root = tmp_path / "assets" / "datasets"
+ root.mkdir(parents = True)
+ out = tmp_path / "outputs"
+ out.mkdir()
+ monkeypatch.setattr(up, "datasets_root", lambda: root)
+ monkeypatch.setattr(up, "outputs_root", lambda: out)
+ return root
+
+
+def _stills_dataset(root: Path, name: str = "cat-photos") -> Path:
+ folder = root / name
+ folder.mkdir()
+ buf = io.BytesIO()
+ Image.new("RGB", (8, 8)).save(buf, format = "PNG")
+ (folder / "a.png").write_bytes(buf.getvalue())
+ (folder / "a.txt").write_text("a cat", encoding = "utf-8")
+ return folder
+
+
+def _clip_families() -> set[str]:
+ from core.training.diffusion_train_common import CLIP_TRAINED_FAMILIES
+ return set(CLIP_TRAINED_FAMILIES)
+
+
+def _trainable_here() -> set[str]:
+ """The families this install can actually train. A diffusers without H3's transformer drops
+ it from ``family_train_infos()`` for an unrelated reason, and these tests are about the
+ picker gate, not about that probe."""
+ from core.training.diffusion_train_common import family_train_infos
+ return {i["name"] for i in family_train_infos()}
+
+
+def _report_clips(
+ monkeypatch,
+ count: int,
+ images: int | None = None,
+) -> None:
+ """Make the dataset layer report ``count`` clips for every folder it summarises.
+
+ ``images`` overrides the still count the real summariser found. The folders here are built
+ out of PNGs because there is no helper that writes a decodable clip, so a folder standing in
+ for a folder of CLIPS has to say ``images = 0`` -- otherwise it reports as a MIXED folder,
+ which is a different case with a different answer. Left as None it keeps the real count,
+ which is what an image dataset should report.
+
+ Written to survive the dataset layer growing a real clip count: if
+ ``DiffusionDatasetSummary`` already carries the field, the genuine model is used and this is
+ exactly the payload the layer will produce; if it does not yet, a subclass supplies it, which
+ is the same thing the gate sees. Either way the gate is exercised through the summary object
+ the route builds, never through a stub of the gate itself."""
+ import routes.training as tr
+
+ has_field = "clip_count" in getattr(DiffusionDatasetSummary, "model_fields", {})
+
+ class _WithClips(DiffusionDatasetSummary):
+ clip_count: int = 0
+
+ model = DiffusionDatasetSummary if has_field else _WithClips
+ real = tr._diffusion_dataset_summary
+
+ def fake(folder: Path):
+ base = real(folder)
+ return model(
+ name = base.name,
+ path = base.path,
+ image_count = base.image_count if images is None else images,
+ caption_count = base.caption_count,
+ clip_count = count,
+ )
+
+ monkeypatch.setattr(tr, "_diffusion_dataset_summary", fake)
+
+
+# ── the picker ───────────────────────────────────────────────────────────────
+def test_a_clip_family_is_not_offered_while_every_listed_dataset_is_stills(client, ds_root):
+ """The bug: H3 was advertised in the Train tab while the only datasets that tab can list are
+ folders of images. Every pick was a dead end -- Start rejected the dataset the picker had
+ just offered for it."""
+ clip_families = _clip_families() & _trainable_here()
+ if not clip_families:
+ pytest.skip("this install trains no clip family")
+ _stills_dataset(ds_root)
+
+ body = client.get("/api/train/diffusion/info").json()
+ assert [d["name"] for d in body["datasets"]] == ["cat-photos"]
+ offered = {f["name"] for f in body["families"]}
+ assert not (
+ offered & clip_families
+ ), "a family that trains only on clips must not be offered while no clip dataset is listable"
+ # The narrowing is surgical: everything else the API offers is still in the picker.
+ assert offered == _trainable_here() - clip_families
+ assert "sdxl" in offered
+
+
+def test_a_clip_family_is_offered_as_soon_as_a_clip_dataset_is_listable(
+ client, ds_root, monkeypatch
+):
+ """The other half, and the reason the gate reads a count rather than naming a family: nothing
+ below has to be edited for H3 to light up. The dataset layer reporting a clip is the whole
+ trigger."""
+ clip_families = _clip_families() & _trainable_here()
+ if not clip_families:
+ pytest.skip("this install trains no clip family")
+ _stills_dataset(ds_root, "video-clips")
+ # A folder of clips, so images = 0: with stills left in it this is the mixed case, which
+ # test_a_mixed_folder_does_not_advertise_a_clip_family covers and which Start refuses.
+ _report_clips(monkeypatch, 3, images = 0)
+
+ body = client.get("/api/train/diffusion/info").json()
+ assert [d["name"] for d in body["datasets"]] == ["video-clips"]
+ offered = {f["name"] for f in body["families"]}
+ assert clip_families <= offered
+ # And now the picker is the full trainable set again: the gate withheld nothing else.
+ assert offered == _trainable_here()
+
+
+def test_a_zero_clip_report_is_not_a_clip_dataset(client, ds_root, monkeypatch):
+ """The layer reporting the field but counting none is the image-only case, not the clip one.
+ Asserted separately because it is the state every existing image dataset will be in once the
+ field exists."""
+ clip_families = _clip_families() & _trainable_here()
+ if not clip_families:
+ pytest.skip("this install trains no clip family")
+ _stills_dataset(ds_root)
+ _report_clips(monkeypatch, 0)
+
+ offered = {f["name"] for f in client.get("/api/train/diffusion/info").json()["families"]}
+ assert not (offered & clip_families)
+
+
+def test_the_gate_withholds_exactly_the_clip_trained_families():
+ """Named from ``CLIP_TRAINED_FAMILIES`` -- the set that already says which families read
+ clips instead of stills -- so the gate cannot drift from the discovery split it mirrors, and
+ a family that trains from stills is never withheld for being video."""
+ import routes.training as tr
+ from core.training.diffusion_train_common import CLIP_TRAINED_FAMILIES, family_train_infos
+
+ every = {i["name"] for i in family_train_infos()}
+ withheld = every - {i["name"] for i in tr._ui_trainable_families([])}
+ assert withheld == CLIP_TRAINED_FAMILIES & every
+ # LTX-2 is video and trains from stills, so a still dataset feeds it and it stays offered.
+ if "ltx-2" in every:
+ assert "ltx-2" not in withheld
+
+ # Derived from the dataset layer's own report, not from a hardcoded name or a flag someone
+ # has to remember to flip: the source of the gate mentions no family at all.
+ src = (
+ inspect.getsource(tr._ui_trainable_families)
+ + inspect.getsource(tr._listed_dataset_clip_count)
+ + inspect.getsource(tr._listed_dataset_trains_clips)
+ )
+ assert "minimax" not in src.lower()
+
+
+def test_a_mixed_folder_does_not_advertise_a_clip_family():
+ """The advertisement has to agree with the refusal that runs at Start, not merely with the
+ clip count.
+
+ ``_image_dataset_refusal`` turns a folder holding stills away from a clip family, so a mixed
+ folder that advertises H3 offers an option Start then rejects. That is the same dead end the
+ narrowing exists to close, reached one click later. A clip-only folder alongside it is enough
+ to bring the family back, because that folder really can start a run."""
+ import routes.training as tr
+ from core.training.diffusion_train_common import CLIP_TRAINED_FAMILIES, family_train_infos
+
+ every = {i["name"] for i in family_train_infos()}
+ clip_families = CLIP_TRAINED_FAMILIES & every
+ assert clip_families, "nothing to assert about if no family trains from clips"
+
+ def summary(name, images, clips_):
+ return DiffusionDatasetSummary(
+ name = name,
+ path = f"/ds/{name}",
+ image_count = images,
+ clip_count = clips_,
+ caption_count = clips_ + images,
+ )
+
+ mixed_only = {i["name"] for i in tr._ui_trainable_families([summary("mixed", 4, 6)])}
+ assert not (mixed_only & clip_families)
+
+ # And the converse, so this cannot pass by withholding the family unconditionally.
+ with_clean = {
+ i["name"]
+ for i in tr._ui_trainable_families([summary("mixed", 4, 6), summary("clips", 0, 6)])
+ }
+ assert clip_families <= with_clean
+
+
+def test_a_summary_with_an_unreadable_clip_count_is_treated_as_no_clips():
+ """The count is read off whatever the layer hands over, so a junk value must not raise out of
+ the info route. No clips is the safe reading: it withholds an option rather than offering one
+ that cannot run."""
+ import routes.training as tr
+
+ class _Junk:
+ clip_count = "lots"
+
+ class _None:
+ clip_count = None
+
+ assert tr._listed_dataset_clip_count(_Junk()) == 0
+ assert tr._listed_dataset_clip_count(_None()) == 0
+ assert tr._listed_dataset_clip_count(object()) == 0
+
+
+# ── the API is not narrowed ──────────────────────────────────────────────────
+def test_the_api_still_carries_the_family_the_picker_withholds(client, ds_root):
+ """The review item asked for the routing to be KEPT: only the advertisement changes. So on a
+ stills-only host, where the picker withholds H3, the trainable set the start route resolves
+ against still has it."""
+ import routes.training as tr
+ from core.training.diffusion_train_common import (
+ TRAINABLE_VIDEO_FAMILIES,
+ family_train_infos,
+ )
+
+ clip_families = _clip_families()
+ assert clip_families <= TRAINABLE_VIDEO_FAMILIES
+ trainable = clip_families & _trainable_here()
+ if not trainable:
+ pytest.skip("this install trains no clip family")
+ _stills_dataset(ds_root)
+
+ offered = {f["name"] for f in client.get("/api/train/diffusion/info").json()["families"]}
+ assert not (offered & trainable)
+ # Same request, the unnarrowed source: the API still describes the family in full.
+ assert trainable <= {i["name"] for i in family_train_infos()}
+
+ # And the gate lives on the info route alone: the start route never consults it.
+ start = inspect.getsource(tr.start_diffusion_training)
+ assert "_ui_trainable_families" not in start
+ assert "_listed_dataset_clip_count" not in start
+
+
+def test_the_start_preflight_still_takes_a_clip_dataset_for_the_withheld_family(tmp_path):
+ """The concrete thing the picker gate must not have broken: the dataset preflight
+ ``/diffusion/start`` runs (``discover_training_pairs``, the same call the route makes) still
+ accepts a folder of captioned clips for a clip family. Nothing about a direct API start
+ depends on what the picker chose to show."""
+ from core.training.diffusion_train_common import discover_training_pairs
+ for family in sorted(_clip_families()):
+ (tmp_path / f"{family}.mp4").write_bytes(b"\x00" * 16)
+ (tmp_path / f"{family}.txt").write_text("a rabbit in a meadow", encoding = "utf-8")
+ pairs = discover_training_pairs(family, tmp_path, verify_images = True)
+ assert [Path(p).name for p, _ in pairs] == [f"{family}.mp4"]
+ assert pairs[0][1] == "a rabbit in a meadow"
+ for p in tmp_path.iterdir():
+ p.unlink()
diff --git a/studio/backend/tests/test_diffusion_training.py b/studio/backend/tests/test_diffusion_training.py
index 635e09bf772..8f81411cd06 100644
--- a/studio/backend/tests/test_diffusion_training.py
+++ b/studio/backend/tests/test_diffusion_training.py
@@ -252,6 +252,46 @@ def test_apply_event_transitions():
assert svc.status()["status"] == "error" and svc.status()["message"] == "boom"
+def test_the_joint_losses_reach_status_and_history():
+ """MiniMax-H3 trains video and audio against one objective, and the combined loss can hold
+ steady while one half degrades. The trainer emits ``video_loss`` / ``audio_loss`` per step
+ for exactly that, so the service has to carry them: an emission the queue drops is a
+ diagnostic that silently does not exist.
+
+ Also pinned here: they stay index-aligned with ``steps``. A family that reports only the
+ combined loss contributes nulls rather than short arrays, so the two curves can be drawn
+ against the same x axis as the loss."""
+ svc = DiffusionTrainingService(ctx = _FakeCtx(), target = _happy_target)
+ svc._apply_event(
+ {
+ "type": "progress",
+ "step": 1,
+ "total_steps": 2,
+ "loss": 0.5,
+ "video_loss": 0.4,
+ "audio_loss": 0.1,
+ }
+ )
+ st = svc.status()
+ assert st["video_loss"] == 0.4 and st["audio_loss"] == 0.1
+ assert st["metric_video_loss"] == [0.4] and st["metric_audio_loss"] == [0.1]
+
+ # A step that reports only the combined loss keeps the series aligned rather than short.
+ svc._apply_event({"type": "progress", "step": 2, "total_steps": 2, "loss": 0.4})
+ st = svc.status()
+ assert st["metric_steps"] == [1, 2]
+ assert len(st["metric_video_loss"]) == len(st["metric_steps"])
+ assert len(st["metric_audio_loss"]) == len(st["metric_steps"])
+
+ # And a single-modality family reports neither, so the whole series is null and the chart
+ # can tell "not a joint run" from "a joint run whose audio loss was zero".
+ solo = DiffusionTrainingService(ctx = _FakeCtx(), target = _happy_target)
+ solo._apply_event({"type": "progress", "step": 1, "total_steps": 1, "loss": 0.5})
+ st = solo.status()
+ assert st["video_loss"] is None and st["audio_loss"] is None
+ assert st["metric_video_loss"] == [None] and st["metric_audio_loss"] == [None]
+
+
def test_progress_nulls_non_finite_floats_for_strict_json():
# A divergent step can push loss / avg_loss / learning_rate to NaN or Infinity, which strict JSON forbids, so the service must null them.
import json
@@ -589,6 +629,75 @@ def test_route_start_preflights_gated_base_off_the_coroutine_thread(client, monk
assert threads["preflight"] is not threads["inline"] # offloaded to a worker, not run inline
+def test_a_clip_trained_family_is_not_turned_away_by_the_clip_refusal(client, monkeypatch):
+ """The refusal exists to protect the IMAGE discovery, so it must not outrank a clip family.
+
+ It ran unconditionally and fires on any folder with a clip in it, above the discovery that
+ was already taught to branch on the family. So every valid MiniMax-H3 request, whose dataset
+ is captioned clips and nothing else, came back 400 "training from clips is not supported
+ yet": the trainer this branch adds, unreachable through its own route.
+ """
+ import routes.training as tr
+ from core.training import diffusion_train_common as _dtc
+
+ consulted: list[str] = []
+
+ def _refusal(data_dir):
+ consulted.append(str(data_dir))
+ return "'clips' holds 2 video clips. Training from clips is not supported yet."
+
+ monkeypatch.setattr(tr, "_clip_dataset_refusal", _refusal)
+ monkeypatch.setattr(
+ _dtc, "discover_training_pairs", lambda family, data_dir, **kw: [("a.mp4", "a rabbit")]
+ )
+
+ r = client.post(
+ "/api/train/diffusion/start",
+ json = {**_BODY, "base_model": "MiniMaxAI/MiniMax-H3", "instance_prompt": "p"},
+ )
+ assert r.status_code == 200, r.text
+ assert consulted == [], "the clip refusal was consulted for a clip-trained family"
+
+ # Control: an image family with the same dataset is still turned away, and by this refusal.
+ r = client.post("/api/train/diffusion/start", json = _BODY)
+ assert r.status_code == 400
+ assert "not supported yet" in r.json()["detail"]
+ assert len(consulted) == 1
+
+
+def test_a_clip_family_still_refuses_a_folder_holding_stills(client, monkeypatch):
+ """Exempting a clip family from the clip refusal must not exempt it from the mixed case.
+
+ discover_clip_caption_pairs enumerates video extensions only, so a still in a clip folder
+ is dropped from the run while /diffusion/info and the picker both count it as a training
+ item: the same silent partial dataset the clip refusal exists to prevent, in the other
+ direction.
+ """
+ import routes.training as tr
+ from core.training import diffusion_train_common as _dtc
+
+ monkeypatch.setattr(
+ tr,
+ "_image_dataset_refusal",
+ lambda data_dir: "'d' holds 3 still images alongside its clips.",
+ )
+ monkeypatch.setattr(tr, "_clip_dataset_refusal", lambda data_dir: None)
+ monkeypatch.setattr(
+ _dtc, "discover_training_pairs", lambda family, data_dir, **kw: [("a.mp4", "a rabbit")]
+ )
+
+ r = client.post(
+ "/api/train/diffusion/start",
+ json = {**_BODY, "base_model": "MiniMaxAI/MiniMax-H3", "instance_prompt": "p"},
+ )
+ assert r.status_code == 400
+ assert "alongside its clips" in r.json()["detail"]
+
+ # And an image family never sees that one: its stills are exactly what it trains on.
+ r = client.post("/api/train/diffusion/start", json = _BODY)
+ assert r.status_code == 200, r.text
+
+
@pytest.mark.parametrize(
("hf_token", "authorization"),
[(None, None), (" hf_test ", "Bearer hf_test")],
diff --git a/studio/backend/tests/test_gguf_variant_rows.py b/studio/backend/tests/test_gguf_variant_rows.py
index 8c7bda6537b..2dbd72eb7fc 100644
--- a/studio/backend/tests/test_gguf_variant_rows.py
+++ b/studio/backend/tests/test_gguf_variant_rows.py
@@ -166,6 +166,38 @@ def test_one_quant_shipped_twice_is_not_advertised_twice():
assert rows["BF16"] == ("BF16/QwQ-32B-BF16-00001-of-00002.gguf", 65)
+def test_h3_partitions_and_builds_at_one_quant_are_separate_rows():
+ files = [
+ ("minimax_h3_fl2va-Q4_K_M.gguf", 18),
+ ("minimax_h3_fl2va_pruned-Q4_K_M.gguf", 11),
+ ("minimax_h3_ref2va-Q4_K_M.gguf", 18),
+ ("minimax_h3_ref2va_pruned-Q4_K_M.gguf", 11),
+ ("minimax_h3_ref2va_pruned-Q2_K_M.gguf", 6),
+ ]
+ rows = group_gguf_variant_files(files)
+ assert list(rows) == [
+ "minimax_h3_fl2va-Q4_K_M",
+ "minimax_h3_fl2va_pruned-Q4_K_M",
+ "minimax_h3_ref2va-Q4_K_M",
+ "minimax_h3_ref2va_pruned-Q4_K_M",
+ "minimax_h3_ref2va_pruned-Q2_K_M",
+ ]
+ assert [filename for filename, _size in rows.values()] == [
+ filename for filename, _size in files
+ ]
+
+
+def test_h3_variant_keys_match_the_loader_copy():
+ for filename in (
+ "minimax_h3_fl2va-Q4_K_M.gguf",
+ "minimax_h3_fl2va_pruned-Q4_K_M.gguf",
+ "minimax_h3_ref2va-Q4_K_M.gguf",
+ "minimax_h3_ref2va_pruned-Q2_K_M.gguf",
+ "minimax_h3_ref2va_pruned-Q4_K_M.gguf",
+ ):
+ assert _gguf_variant_key(filename) == gguf_variant_key(filename)
+
+
def test_local_lister_matches_the_remote_shape(tmp_path):
snapshot = tmp_path / "snap"
for path, _ in LTX_FILES:
diff --git a/studio/backend/tests/test_local_model_format.py b/studio/backend/tests/test_local_model_format.py
index f0dc1ed516e..c88b32a8e5e 100644
--- a/studio/backend/tests/test_local_model_format.py
+++ b/studio/backend/tests/test_local_model_format.py
@@ -342,3 +342,26 @@ def test_local_task_ignores_family_token_in_parent_path(tmp_path):
_touch(d2 / "model.safetensors")
m2 = _local(d2, id = str(d2), display_name = "z-image-turbo")
assert models_route._local_is_diffusers(m2) is True
+
+
+def test_a_modular_pipeline_root_counts_as_a_pipeline_index(tmp_path):
+ """A Modular Diffusers pipeline carries ``modular_model_index.json`` and NO
+ ``model_index.json``, which is the pair the video loader accepts. Recognising only the
+ conventional index hid such a root from the picker and let the publisher walk descend into it
+ and offer its components as separate, unusable models. The hub scanner
+ (``local_inventory._is_diffusers_pipeline_dir``) makes the same test and has its own case."""
+ from routes.models import _local_pipeline_index
+
+ modular = tmp_path / "modular"
+ (modular / "transformer").mkdir(parents = True)
+ (modular / "modular_model_index.json").write_text("{}")
+ assert _local_pipeline_index(modular) is True
+
+ conventional = tmp_path / "conventional"
+ conventional.mkdir()
+ (conventional / "model_index.json").write_text("{}")
+ assert _local_pipeline_index(conventional) is True
+
+ neither = tmp_path / "neither"
+ neither.mkdir()
+ assert _local_pipeline_index(neither) is False
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 61c2466ce81..b20207cf11c 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -4820,6 +4820,26 @@ def test_h3_native_generate_stages_both_keyframes_on_the_canvas(monkeypatch):
assert result["conditioning"] == "fl2va"
+def test_h3_native_generate_records_the_build_it_ran_on(monkeypatch):
+ """_run_generate persists these with result.get(...), so a field the native path omits lands
+ in the gallery sidecar as null. Clips generated from different GGUF quantizations of the same
+ repo then cannot be told apart or reproduced from their saved recipe, unlike the diffusers
+ path, which records the same set off the engaged state."""
+ pytest.importorskip("PIL.Image")
+ calls: list = []
+ backend = _h3_native_backend(monkeypatch, calls)
+
+ result = backend.generate(prompt = "a fox runs through snow", width = 960, height = 544)
+
+ state = backend._state
+ assert result["model_kind"] == state.kind == "gguf"
+ assert result["gguf_filename"] == state.gguf_filename
+ assert result["memory_mode"] == state.memory_mode
+ assert result["offload_policy"] == state.offload_policy
+ assert result["transformer_quant"] == state.transformer_quant
+ assert result["text_encoder_quant"] == state.text_encoder_quant
+
+
def test_h3_native_generate_names_each_keyframe_combination(monkeypatch):
calls: list = []
backend = _h3_native_backend(monkeypatch, calls)
@@ -6235,6 +6255,7 @@ def test_plan_keeps_the_bf16_budget_without_a_hosted_pre_cast_encoder(fake_runti
def test_plan_is_unchanged_when_no_text_encoder_quant_is_requested(fake_runtime, monkeypatch):
# The whole change is inert on a default load: every family keeps its bf16-table budget, so no
# existing decision on any device moves.
+ from core.inference.diffusion_families import family_pipeline_available
from core.inference.video_families import _FAMILIES
_allow_te_prequant(monkeypatch)
@@ -6298,6 +6319,182 @@ def test_dense_quant_replan_uses_the_scaled_text_encoder(fake_runtime, monkeypat
)
+# ── MiniMax-H3: the denoiser partition a ref2va load actually needs ──────────
+
+
+_H3_TWO_PARTITION_SIBLINGS = [
+ _sibling("model_index.json", 1),
+ _sibling("modular_model_index.json", 1),
+ _sibling("scheduler/scheduler_config.json", 1),
+ _sibling("audio_scheduler/scheduler_config.json", 1),
+ _sibling("vae/diffusion_pytorch_model.safetensors", 10),
+ _sibling("audio_vae/diffusion_pytorch_model.safetensors", 1),
+ _sibling("text_encoder/model-00001-of-00002.safetensors", 66),
+ _sibling("tokenizer/tokenizer.json", 1),
+ _sibling("processor/preprocessor_config.json", 1),
+ _sibling("transformer/config.json", 1),
+ _sibling("transformer/diffusion_pytorch_model-00001-of-00002.safetensors", 66),
+ _sibling("transformer_ref/config.json", 1),
+ _sibling("transformer_ref/diffusion_pytorch_model-00001-of-00002.safetensors", 66),
+ _sibling("FL2VA/single_file.safetensors", 144),
+ _sibling("Ref2VA/single_file.safetensors", 144),
+]
+
+
+def test_a_ref2va_pick_stages_the_reference_denoiser_and_only_that_one():
+ """MiniMaxAI/MiniMax-H3 ships two 66.28 GB denoisers, and the modular load builds exactly
+ one: diffusers' ref2va denoise step is constructed with transformer_name="transformer_ref".
+ Staging only transformer/ therefore downloaded the keyframe partition for a References load
+ and left the one it opens to be fetched inline, outside the download manager."""
+ info = types.SimpleNamespace(siblings = _H3_TWO_PARTITION_SIBLINGS)
+
+ ref = [n for n, _ in VideoBackend._base_download_files(info, "pipeline", h3_task = "ref2va")]
+ assert any(n.startswith("transformer_ref/") for n in ref)
+ assert not any(n.startswith("transformer/") for n in ref)
+
+ # The default (and an explicit keyframe task) keeps the fl2va partition and drops the other.
+ for task in (None, "fl2va"):
+ keyframes = [
+ n for n, _ in VideoBackend._base_download_files(info, "pipeline", h3_task = task)
+ ]
+ assert any(n.startswith("transformer/") for n in keyframes)
+ assert not any(n.startswith("transformer_ref/") for n in keyframes)
+
+ # Neither partition doubles the stage, and the packaged single-file dirs stay excluded.
+ assert not any(n.startswith(("FL2VA/", "Ref2VA/")) for n in ref)
+
+
+def test_download_plan_keys_the_h3_denoiser_on_the_requested_task(monkeypatch):
+ # The plan is what the Hub download manager stages, so the task has to reach it: without it
+ # a References pick paid for 66.28 GB of keyframe denoiser it never opens.
+ _cuda_bf16_target(monkeypatch)
+ _plan_api(monkeypatch, {"MiniMaxAI/MiniMax-H3": _H3_TWO_PARTITION_SIBLINGS})
+
+ def files_for(task):
+ plan = VideoBackend().download_plan(
+ "MiniMaxAI/MiniMax-H3",
+ family_override = "minimax-h3",
+ model_kind = "pipeline",
+ h3_task = task,
+ )
+ by_repo = {entry["repo_id"]: entry for entry in plan["entries"]}
+ return by_repo["MiniMaxAI/MiniMax-H3"]["files"]
+
+ assert any(n.startswith("transformer_ref/") for n in files_for("ref2va"))
+ assert not any(n.startswith("transformer/") for n in files_for("ref2va"))
+ assert any(n.startswith("transformer/") for n in files_for(None))
+
+
+def test_h3_records_the_guidance_that_actually_ran(monkeypatch):
+ """MiniMax-H3 declares supports_cfg=False: the diffusers branch forwards no CFG kwarg and
+ the native branch pins --cfg-scale 1.0, so a requested guidance reaches no sampler. Keeping
+ the request in the result labelled the clip and its gallery sidecar with a number that did
+ nothing, and two clips run at 1.0 read back as different recipes."""
+ pytest.importorskip("PIL.Image")
+ calls: list = []
+ backend = _h3_native_backend(monkeypatch, calls)
+
+ result = backend.generate(prompt = "a fox runs through snow", width = 960, height = 544, guidance = 7.5)
+
+ assert result["guidance"] == backend._state.family.default_guidance == 1.0
+ # And that default is exactly what the engine was told to run.
+ assert calls[-1]["params"].cfg_scale == 1.0
+
+
+def test_h3_guidance_normalises_to_its_own_default_not_a_neighbours(monkeypatch):
+ """The normalisation above has to use the FAMILY default, not the identifier-derived one.
+
+ ``default_video_generation_params`` matches on the repo id or path, so a local H3 file under
+ a folder named after another family picks up that family's guidance. Recording it writes back
+ exactly the inaccurate recipe this normalisation exists to prevent, and with a number no H3
+ sampler can have produced.
+ """
+ import dataclasses
+
+ pytest.importorskip("PIL.Image")
+ calls: list = []
+ backend = _h3_native_backend(monkeypatch, calls)
+ local = "/models/wan/minimax_h3_fl2va-Q4_K_M.gguf"
+ backend._state = dataclasses.replace(backend._state, repo_id = local)
+
+ # Precondition: the identifier really does resolve to a different family's guidance, so the
+ # test cannot pass by that lookup happening to agree with H3.
+ from core.inference.video import default_video_generation_params
+
+ fam = backend._state.family
+ _steps, derived = default_video_generation_params(
+ local, fallback = (fam.default_steps, fam.default_guidance)
+ )
+ assert derived != fam.default_guidance
+
+ result = backend.generate(prompt = "a fox runs through snow", width = 960, height = 544)
+ assert result["guidance"] == fam.default_guidance == 1.0
+ assert calls[-1]["params"].cfg_scale == 1.0
+
+
+def test_h3_records_no_negative_prompt_because_neither_engine_takes_one(monkeypatch):
+ """The same rule as the guidance above, for the other half of the unconditional branch. A
+ negative prompt IS the unconditional branch, so a guidance-distilled family consumes none:
+ the diffusers call adds the kwarg only when the pipeline signature has it (H3's modular
+ workflow does not) and ``SdCppVideoGenParams`` carries no field for one at all. Persisting the
+ caller's string left the gallery sidecar and its restored recipe claiming conditioning that
+ never reached a sampler."""
+ pytest.importorskip("PIL.Image")
+ calls: list = []
+ backend = _h3_native_backend(monkeypatch, calls)
+
+ result = backend.generate(
+ prompt = "a fox runs through snow",
+ negative_prompt = "blurry, watermark",
+ width = 960,
+ height = 544,
+ )
+
+ assert result["negative_prompt"] is None
+ assert not hasattr(calls[-1]["params"], "negative_prompt")
+
+
+def test_the_video_sidecar_records_the_negative_prompt_that_ran(monkeypatch, tmp_path):
+ """The recipe the gallery reads back comes from the RESULT, like guidance beside it, not from
+ the request the worker was handed: normalising inside generate() alone would have left
+ _run_generate persisting the caller's original string."""
+ from core.inference import video as video_mod
+ from core.inference import video_gallery
+
+ saved: list = []
+ monkeypatch.setattr(
+ video_gallery, "save", lambda data, meta: (saved.append(meta), {"id": "v1"})[1]
+ )
+
+ backend = VideoBackend()
+ result = {
+ "mp4_bytes": b"MP4",
+ "seed": 7,
+ "repo_id": "unsloth/MiniMax-H3-GGUF",
+ "width": 960,
+ "height": 544,
+ "num_frames": 124,
+ "fps": 24,
+ "duration_s": 5.0,
+ "has_audio": True,
+ "conditioning": "t2va",
+ "steps": 30,
+ "guidance": 1.0,
+ "negative_prompt": None,
+ }
+ monkeypatch.setattr(backend, "generate", lambda **kw: result)
+ monkeypatch.setattr(backend, "_finish_generate_job", lambda **kw: None)
+
+ backend._run_generate(
+ cancel_event = threading.Event(),
+ prompt = "a fox runs through snow",
+ negative_prompt = "blurry, watermark",
+ )
+
+ assert saved and saved[-1]["negative_prompt"] is None
+ assert saved[-1]["prompt"] == "a fox runs through snow"
+
+
def test_a_managed_h3_native_run_holds_the_install_off(monkeypatch, tmp_path):
"""An H3 native run is an sd-cli run out of the managed tree, so it takes the same reader claim
the one-shot image path takes. Without it an image-engine request sees no readers, starts an
diff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.py
index 8abd0528be7..7dedf02812b 100644
--- a/studio/backend/tests/test_video_routes.py
+++ b/studio/backend/tests/test_video_routes.py
@@ -122,7 +122,8 @@ class _FakeBackend(video_module.VideoBackend):
if kind in ("gguf", "single_file") and not gguf_filename:
raise ValueError("A gguf/single_file load needs the checkpoint filename.")
# Non-GGUF loads are gated to unsloth/* repos, the official bases, and existing local paths.
- trusted = model_path.lower().startswith(("unsloth/", "lightricks/")) or (
+ # minimaxai/: the real gate trusts MiniMaxAI/MiniMax-H3 as an official family base repo.
+ trusted = model_path.lower().startswith(("unsloth/", "lightricks/", "minimaxai/")) or (
Path(model_path).expanduser().exists()
)
if kind != "gguf" and not trusted:
@@ -1263,6 +1264,59 @@ def test_video_download_plan_forwards_the_h3_partition(client, monkeypatch):
assert seen["h3_task"] == "ref2va"
+def test_video_download_plan_judges_a_quantized_reference_pick_per_partition(client, monkeypatch):
+ # The plan route asks the same (scheme, PARTITION) question the load does, so a pick it
+ # answers 200 is one the load will honour. Both halves matter and they are one test because
+ # either alone passes for the wrong reason: refusing everything, or accepting everything.
+ #
+ # ref2va now has its own hosted int8 and fp8 denoisers, so the reference partition is a real
+ # pick rather than a keyframe checkpoint wearing the wrong name. A scheme with no checkpoint
+ # at all is still refused BEFORE staging, which is the failure this route check was added for
+ # -- a 200 plan carrying 20 GB for a request the load then answered with a 400.
+ backend = video_module.get_video_backend()
+ monkeypatch.setattr(
+ backend,
+ "validate_load_request",
+ video_module.VideoBackend.validate_load_request.__get__(backend),
+ raising = False,
+ )
+ seen: dict = {}
+
+ def _plan(model_path, **kwargs):
+ seen.update(kwargs)
+ return {"entries": [], "total_bytes": 0}
+
+ monkeypatch.setattr(backend, "download_plan", _plan, raising = False)
+
+ def _ask(scheme):
+ return client.post(
+ "/api/inference/video/download-plan",
+ json = {
+ "model_path": "MiniMaxAI/MiniMax-H3",
+ "family_override": "minimax-h3",
+ "model_kind": "pipeline",
+ "transformer_quant": scheme,
+ "h3_task": "ref2va",
+ },
+ )
+
+ served = _ask("int8")
+ assert served.status_code == 200, served.json()
+ # Planned for the partition that was asked for, not the keyframe one it used to fall back to.
+ assert seen["h3_task"] == "ref2va"
+ assert seen["transformer_quant"] == "int8"
+
+ seen.clear()
+ refused = _ask("nvfp4")
+ assert refused.status_code == 400
+ detail = refused.json()["detail"]
+ # Named per task: "unavailable" here is a claim about ref2va, not about the whole family.
+ assert "ref2va" in detail
+ # A refusal that does not name the alternative just moves the dead end earlier.
+ assert "int8" in detail and "fp8" in detail
+ assert not seen, "download_plan must not be reached for a refused pick"
+
+
def test_video_download_plan_refuses_an_unsupported_combination_before_staging(client, monkeypatch):
# The whole point of moving the refusal into validation: this pick used to return a 200 plan,
# stage ~98.7 GB, and only then fail inside the loader. Runs the REAL validation rather than
diff --git a/studio/backend/tests/test_video_shape_validation.py b/studio/backend/tests/test_video_shape_validation.py
index 9a595df613f..0eb952c523c 100644
--- a/studio/backend/tests/test_video_shape_validation.py
+++ b/studio/backend/tests/test_video_shape_validation.py
@@ -512,3 +512,47 @@ def test_both_axes_and_neither_stay_valid_with_a_keyframe():
VideoGenerateRequest(prompt = "a cat", first_frame = frame, width = 768, height = 512).width == 768
)
assert VideoGenerateRequest(prompt = "a cat", first_frame = frame).width is None
+
+
+# ── on-lattice but out of the family's range ─────────────────────────────────
+
+
[email protected]("count", [107, 362])
+def test_an_on_lattice_count_outside_the_family_range_is_refused(count):
+ """The hole this closes: the gate judged the LATTICE only, while snap_num_frames also CLAMPS
+ to min/max_num_frames. MiniMax-H3 is 17k + 5 over 124..345, so 107 and 362 both sit exactly
+ on the lattice, passed validation, and were then rendered as 124 and 345 -- the API
+ accepting one recipe and drawing another, which is the whole reason this check exists."""
+ from core.inference.video_families import (
+ VideoShapeError,
+ detect_video_family,
+ snap_num_frames,
+ validate_video_request_shape,
+ )
+
+ fam = detect_video_family("", override = "minimax-h3")
+ assert (count - fam.frame_offset) % fam.frame_step == 0, "the point of the case is on-lattice"
+ assert snap_num_frames(fam, count) != count, "and that the snap would have moved it"
+ with pytest.raises(VideoShapeError, match = "not a supported frame count"):
+ validate_video_request_shape(fam, num_frames = count)
+
+
[email protected]("count", [124, 141, 345])
+def test_in_range_lattice_counts_still_pass(count):
+ """The endpoints and one interior point stay valid, so the range check did not narrow the
+ family to less than it actually offers."""
+ from core.inference.video_families import detect_video_family, validate_video_request_shape
+
+ fam = detect_video_family("", override = "minimax-h3")
+ validate_video_request_shape(fam, num_frames = count)
+
+
+def test_a_family_without_a_declared_range_is_unaffected():
+ """Every pre-existing family declares min 1 and no max, so the added bound must be inert for
+ them: the request model's own ceiling stays the only upper limit."""
+ from core.inference.video_families import detect_video_family, validate_video_request_shape
+
+ fam = detect_video_family("", override = "ltx-2")
+ assert fam.min_num_frames == 1 and fam.max_num_frames is None
+ for k in (0, 1, 5, 20):
+ validate_video_request_shape(fam, num_frames = k * fam.frame_step + fam.frame_offset)
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index d46cddfed9e..a53d2eec808 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -2407,6 +2407,8 @@ def _gguf_variant_key(filename: str) -> str:
quant = _quant_token_with_bpw(path)
if quant is None:
return _gguf_variant_family(path)
+ if path.rsplit("/", 1)[-1].lower().startswith(("minimax_h3_fl2va", "minimax_h3_ref2va")):
+ return _gguf_variant_family(path)
for segment in path.rpartition("/")[0].split("/"):
# A quant-named directory adds nothing the basename does not already say; a
# directory naming something else is a different checkpoint and qualifies.
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index e152a0e1f8d..a522d64697c 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -641,6 +641,11 @@ export interface DiffusionTrainableFamily {
recommended_precision?: string;
// Whether the family's transformer can be torch.compile'd (gates the Speed > Compile row).
supports_compile?: boolean;
+ // Whether the family's loop writes checkpoint bundles (gates the "Checkpoint every" field).
+ // Undefined on an older backend, which has no checkpointless family, so it reads as true.
+ supports_checkpoints?: boolean;
+ /** 1 for a family whose forward covers one packed sequence; null/absent means unrestricted. */
+ max_train_batch_size?: number | null;
// When set, deploying a LoRA trained on this family previews it on this repo instead of the checkpoint it trained on (Krea trains on Raw, runs on Turbo).
deploy_base?: string | null;
// Variant-specific training-base to inference-base pairs, including public mirror ids.
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 ec32fb47476..d6959bd9394 100644
--- a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
+++ b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
@@ -422,6 +422,17 @@ export function DiffusionTrainPanel({
}, [reportedFamily?.precision_modes, familyUntrainable]);
// Whether to show the torch.compile control. The backend advertises it per family; default on for DiT families on an older backend.
const supportsCompile = reportedFamily?.supports_compile ?? isDiT;
+ // Same idea for checkpoints. MiniMax-H3's loop writes no resume bundle and its validation
+ // REFUSES a nonzero save_steps rather than ignoring it, so leaving the field on offer meant a
+ // user could set it and get a rejected Start with nothing on the control saying why.
+ const supportsCheckpoints = reportedFamily?.supports_checkpoints ?? true;
+ // And the batch axis, third of the same kind. MiniMax-H3's forward covers ONE packed
+ // sequence, so its validation REFUSES a batch above 1 rather than clamping. The field was
+ // rendered unrestricted and always sent, so a 2 typed here -- or simply carried over from the
+ // family the user was on a moment ago -- rejected Start with nothing on the control to say
+ // why. Hidden when the family caps it at 1, and the cap is what gets sent.
+ const maxBatchSize = reportedFamily?.max_train_batch_size ?? null;
+ const batchIsFixed = maxBatchSize != null && maxBatchSize <= 1;
const setBaseChoice = onBaseChoiceChange;
const [customBase, setCustomBase] = useState("");
@@ -454,6 +465,7 @@ export function DiffusionTrainPanel({
const [rank, setRank] = useState(family?.defaults.rank ?? 16);
const [resolution, setResolution] = useState(family?.defaults.resolution ?? 768);
const [batchSize, setBatchSize] = useState(1);
+ const effectiveBatchSize = maxBatchSize == null ? batchSize : Math.min(batchSize, maxBatchSize);
const [gradAccum, setGradAccum] = useState(1);
const [seed, setSeed] = useState(42);
// Periodic resume points. 0 (off) keeps the default behaviour: only a stop-and-save writes one,
@@ -1064,14 +1076,19 @@ export function DiffusionTrainPanel({
train_steps: durationUnit === "epochs" ? undefined : steps,
num_epochs: durationUnit === "epochs" ? epochs : undefined,
learning_rate: learningRate,
- train_batch_size: batchSize,
+ // The family cap, not the field: it is only hidden, not reset, so a value typed for
+ // another family would otherwise still be sent and refused.
+ train_batch_size: effectiveBatchSize,
gradient_accumulation_steps: gradAccum,
seed,
gradient_checkpointing: gradCheckpoint,
lr_scheduler: lrScheduler,
lr_warmup_steps: lrScheduler === "constant" ? 0 : lrWarmupSteps,
lora_rank: rank,
- save_steps: Math.max(0, Math.floor(saveSteps)),
+ // Zero rather than the field's value when the family has none, because the field is
+ // only hidden, not reset: a value typed for one family would otherwise still be sent
+ // after switching to a checkpointless one, and refused.
+ save_steps: supportsCheckpoints ? Math.max(0, Math.floor(saveSteps)) : 0,
mixed_precision: precision,
// DiT families quantise the base weights; sdxl uses mixed_precision above and ignores this. Only send compile where supported.
base_precision: isDiT ? basePrecision : undefined,
@@ -1111,6 +1128,8 @@ export function DiffusionTrainPanel({
isDiT,
basePrecision,
supportsCompile,
+ supportsCheckpoints,
+ effectiveBatchSize,
compileTransformer,
poll,
]);
@@ -1303,20 +1322,24 @@ export function DiffusionTrainPanel({
step: 64,
hint: "The pixel size images train at, in multiples of 64. Higher is sharper and costs noticeably more VRAM.",
})}
- {numberField("Batch", batchSize, setBatchSize, 1, {
- hint: "Images trained on per step. Higher is faster per image and needs more VRAM.",
- })}
+ {!batchIsFixed &&
+ numberField("Batch", batchSize, setBatchSize, 1, {
+ hint: "Images trained on per step. Higher is faster per image and needs more VRAM.",
+ })}
{numberField("Grad accumulation", gradAccum, setGradAccum, 1, {
- hint: "Collects this many batches before each update, for the effect of a larger batch without the VRAM. Effective batch = Batch x Grad accumulation.",
+ hint: batchIsFixed
+ ? "Collects this many clips before each update. This model trains one clip at a time, so this is the only way to raise the effective batch."
+ : "Collects this many batches before each update, for the effect of a larger batch without the VRAM. Effective batch = Batch x Grad accumulation.",
})}
{numberField("Seed", seed, setSeed, 42, {
min: 0,
hint: "Fixes the run's randomness, so the same settings and images reproduce the same LoRA.",
})}
- {numberField("Checkpoint every", saveSteps, setSaveSteps, 0, {
- min: 0,
- hint: "Saves a resume point every this many steps, so a crash or a shutdown can be picked up where it left off. 0 turns it off; stopping and saving always leaves one either way.",
- })}
+ {supportsCheckpoints &&
+ numberField("Checkpoint every", saveSteps, setSaveSteps, 0, {
+ min: 0,
+ hint: "Saves a resume point every this many steps, so a crash or a shutdown can be picked up where it left off. 0 turns it off; stopping and saving always leaves one either way.",
+ })}
</div>
<div className="grid grid-cols-1 items-start gap-x-6 gap-y-5 @min-[324px]:grid-cols-2 @min-[498px]:grid-cols-3">
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts
index 3d12c86ff64..de9dd7842a0 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.check.ts
@@ -15,10 +15,12 @@ import type { CatalogGroup, ModelArtifact } from "./model-catalog.ts";
import {
IMAGE_CATALOG,
VIDEO_CATALOG,
+ artifactForRepoId,
canonicalKeyFor,
catalogGroupFitsDevice,
catalogToModelOptions,
classifyGgufFit,
+ curatedDisplayNameFor,
groupForRepoId,
groupMatchesQuery,
loadSpecFor,
@@ -216,10 +218,36 @@ for (const id of [
assert.ok(imageOptionIds.has(id), `image option missing: ${id}`);
}
const videoOptionIds = new Set(catalogToModelOptions(VIDEO_CATALOG).map((o) => o.id));
-for (const id of ["unsloth/LTX-2.3-GGUF", ...OLD_PIPELINE_MODELS]) {
+for (const id of [
+ "unsloth/LTX-2.3-GGUF",
+ "unsloth/MiniMax-H3-GGUF",
+ "leejet/MiniMax-H3-GGUF",
+ ...OLD_PIPELINE_MODELS,
+]) {
assert.ok(videoOptionIds.has(id), `video option missing: ${id}`);
}
+// H3 publishes the ordinary and reference denoisers as separately loadable GGUFs.
+// Curating both repos must keep their bundled file menus on the matching partition.
+assert.equal(
+ artifactForRepoId("unsloth/MiniMax-H3-GGUF", VIDEO_CATALOG)?.artifact
+ .ggufFilenamePrefix,
+ "minimax_h3_fl2va",
+);
+assert.equal(
+ artifactForRepoId("leejet/MiniMax-H3-GGUF", VIDEO_CATALOG)?.artifact
+ .ggufFilenamePrefix,
+ "minimax_h3_ref2va",
+);
+assert.equal(
+ curatedDisplayNameFor("unsloth/MiniMax-H3-GGUF", VIDEO_CATALOG),
+ "MiniMax H3 (GGUF - Text and frames)",
+);
+assert.equal(
+ curatedDisplayNameFor("leejet/MiniMax-H3-GGUF", VIDEO_CATALOG),
+ "MiniMax H3 (GGUF - References)",
+);
+
// ── classifyGgufFit ────────────────────────────────────────────────────────────
const GB = 1024 ** 3;
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
index 9c5dfbb42fd..f69d61bb039 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-catalog.ts
@@ -26,6 +26,9 @@ export interface ModelArtifact {
offloadFitTiers?: readonly { gpuGb: number; systemRamGb: number }[];
/** Extra search tokens beyond the id/label ("4bit", "nf4", ...). */
keywords?: readonly string[];
+ /** Restrict a bundled GGUF repo's variant menu to filenames for this artifact.
+ * Used when one repo publishes several independently loadable model partitions. */
+ ggufFilenamePrefix?: string;
/** Parameter count of THIS artifact's checkpoint, for the row's size chip.
* Only a fallback: the Hub listing's own `expand=gguf` total wins wherever it
* reports one. Rows the listing never returns (a repo it does not index, a
@@ -363,7 +366,21 @@ export const VIDEO_CATALOG: CatalogGroup[] = [
],
}),
// The FL2VA denoiser this repo publishes, summed off its GGUF tensor shapes.
- gguf("unsloth/MiniMax-H3-GGUF", { totalParams: 20_111_438_744 }),
+ gguf("unsloth/MiniMax-H3-GGUF", {
+ label: "GGUF - Text and frames",
+ keywords: ["gguf", "quantized", "fl2va", "keyframes"],
+ totalParams: 20_111_438_744,
+ ggufFilenamePrefix: "minimax_h3_fl2va",
+ }),
+ // The community bundle currently publishing the Ref2VA quants. Its repo also contains
+ // FL2VA files and Qwen companions, so the filename prefix keeps this artifact's menu on
+ // the reference partition while the backend's bundle filter keeps companions out.
+ gguf("leejet/MiniMax-H3-GGUF", {
+ label: "GGUF - References",
+ keywords: ["gguf", "quantized", "ref2va", "references"],
+ totalParams: 20_111_438_744,
+ ggufFilenamePrefix: "minimax_h3_ref2va",
+ }),
],
},
{
@@ -591,6 +608,19 @@ export function curatedCapabilitiesFor(
};
}
+/** Human-facing name of an exact curated artifact, including the artifact label
+ * when its model has more than one selectable representation. */
+export function curatedDisplayNameFor(
+ repoId: string,
+ catalog: CatalogGroup[],
+): string | null {
+ const hit = artifactForRepoId(repoId, catalog);
+ if (!hit) return null;
+ return hit.group.artifacts.length > 1
+ ? `${hit.group.displayName} (${hit.artifact.label})`
+ : hit.group.displayName;
+}
+
/** Back-compat: the flat ModelOption list the ModelSelector `models` prop expects, one option per ARTIFACT. */
export function catalogToModelOptions(catalog: CatalogGroup[]): ModelOption[] {
const options: ModelOption[] = [];
@@ -598,10 +628,7 @@ export function catalogToModelOptions(catalog: CatalogGroup[]): ModelOption[] {
for (const artifact of group.artifacts) {
options.push({
id: artifact.repoId,
- name:
- group.artifacts.length > 1
- ? `${group.displayName} (${artifact.label})`
- : group.displayName,
+ name: curatedDisplayNameFor(artifact.repoId, catalog) ?? group.displayName,
description: `${group.description} - ${artifact.label}`,
isGguf: artifact.format === "gguf",
});
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index e60be6704b0..632d9821034 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -166,6 +166,7 @@ import {
type CatalogGroup,
artifactForRepoId,
curatedCapabilitiesFor,
+ curatedDisplayNameFor,
curatedSizeBytesFor,
curatedTotalParamsFor,
} from "./model-catalog";
@@ -1178,6 +1179,7 @@ function GgufVariantExpander({
onDevice = false,
allowPin = false,
onHasVision,
+ filenamePrefix,
}: {
repoId: string;
/** Snapshot the cached listing pinned this repo to, if any. */
@@ -1219,6 +1221,8 @@ function GgufVariantExpander({
allowPin?: boolean;
/** Report GGUF vision support up so the parent row can badge it. */
onHasVision?: (hasVision: boolean) => void;
+ /** A curated artifact may expose one partition of a bundled GGUF repo. */
+ filenamePrefix?: string;
}) {
const pinnedKeys = usePinnedModelsStore((s) => s.pinned);
const togglePinnedQuant = usePinnedModelsStore((s) => s.togglePinned);
@@ -1272,8 +1276,41 @@ function GgufVariantExpander({
.then((res) => {
if (canceled) return;
const normalized = normalizeGgufVariantsResponse(res);
- setVariants(normalized.variants);
- setDefaultVariant(normalized.defaultVariant);
+ setVariants(
+ filenamePrefix
+ ? normalized.variants.filter((variant) =>
+ variant.filename
+ .replace(/\\/g, "/")
+ .split("/")
+ .at(-1)
+ ?.toLowerCase()
+ .startsWith(filenamePrefix.toLowerCase()),
+ )
+ : normalized.variants,
+ );
+ // Only if it survived the filter. defaultVariant is a QUANT key chosen across the
+ // WHOLE repo, and a prefix subset need not contain it: the H3 catalog's ref2va group
+ // offers 6 quants against fl2va's 8. Kept as-is, effectiveRecommended's
+ // budget-unavailable branch returns a key with no visible row, so nothing reads as
+ // recommended and the sorter falls through to largest-first. Null says "no
+ // recommendation for this subset", which is the truth; inventing one is
+ // pick_best_gguf's job and it never saw the subset.
+ setDefaultVariant(
+ filenamePrefix &&
+ normalized.defaultVariant != null &&
+ !normalized.variants.some(
+ (variant) =>
+ variant.quant === normalized.defaultVariant &&
+ variant.filename
+ .replace(/\\/g, "/")
+ .split("/")
+ .at(-1)
+ ?.toLowerCase()
+ .startsWith(filenamePrefix.toLowerCase()),
+ )
+ ? null
+ : normalized.defaultVariant,
+ );
setHasVision(normalized.hasVision);
onHasVision?.(normalized.hasVision);
setNativeContext(normalized.contextLength);
@@ -1291,7 +1328,7 @@ function GgufVariantExpander({
canceled = true;
controller.abort();
};
- }, [repoId, localSource, refreshKey, hfToken]);
+ }, [repoId, localSource, refreshKey, hfToken, filenamePrefix]);
// Covers Unix absolute (/), Windows drive (C:\, D:/), UNC (\\server), relative (./, ../), tilde (~/)
const isLocalPath = /^(\/|\.{1,2}[\\/]|~[\\/]|[A-Za-z]:[\\/]|\\\\)/.test(
@@ -2109,6 +2146,13 @@ export function HubModelPicker({
}) {
const gpu = useGpuInfo();
const inferenceGpu = useInferenceGpuInfo();
+ const curatedGgufFilenamePrefix = useCallback(
+ (repoId: string) =>
+ catalog
+ ? artifactForRepoId(repoId, catalog)?.artifact.ggufFilenamePrefix
+ : undefined,
+ [catalog],
+ );
// What the backend actually holds, not the dropdown highlight, which can be a
// staged pick. The selection alone was wrong: an image or video load evicts
// the chat model and leaves the pick untouched, so its rows kept the "Loaded"
@@ -3943,6 +3987,7 @@ export function HubModelPicker({
{expanderOpen && (
<GgufVariantExpander
repoId={c.repo_id}
+ filenamePrefix={curatedGgufFilenamePrefix(c.repo_id)}
loadId={c.load_id}
cachePath={c.cache_path}
onDevice={true}
@@ -5037,7 +5082,9 @@ export function HubModelPicker({
return (
<div key={id}>
<ModelRow
- label={id}
+ label={
+ (catalog && curatedDisplayNameFor(id, catalog)) || id
+ }
hubUrl={hubRepoUrl(id)}
alignMeta="hub"
showSize={hubRowsShowSize}
@@ -5082,6 +5129,7 @@ export function HubModelPicker({
{expandedGguf === id && (
<GgufVariantExpander
repoId={id}
+ filenamePrefix={curatedGgufFilenamePrefix(id)}
onSelect={onSelect}
resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
@@ -5142,7 +5190,9 @@ export function HubModelPicker({
return (
<div key={id}>
<ModelRow
- label={id}
+ label={
+ (catalog && curatedDisplayNameFor(id, catalog)) || id
+ }
hubUrl={hubRepoUrl(id)}
alignMeta="hub"
showSize={hubRowsShowSize}
@@ -5200,6 +5250,7 @@ export function HubModelPicker({
{expandedGguf === id && (
<GgufVariantExpander
repoId={id}
+ filenamePrefix={curatedGgufFilenamePrefix(id)}
onSelect={onSelect}
resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
@@ -5251,7 +5302,9 @@ export function HubModelPicker({
return (
<div key={id}>
<ModelRow
- label={id}
+ label={
+ (catalog && curatedDisplayNameFor(id, catalog)) || id
+ }
hubUrl={hubRepoUrl(id)}
alignMeta="hub"
showSize={hubRowsShowSize}
@@ -5307,6 +5360,7 @@ export function HubModelPicker({
{expandedGguf === id && (
<GgufVariantExpander
repoId={id}
+ filenamePrefix={curatedGgufFilenamePrefix(id)}
onSelect={onSelect}
resolveDownloadFootprint={resolveDownloadFootprint}
onConfigure={onConfigure}
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 5c9343e611d..fb9639ff112 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -18,6 +18,13 @@ import { MediaPageLink } from "@/components/media-page-link";
import { useHardwareInfo } from "@/hooks/use-hardware-info";
import { usePersistedToggle } from "@/hooks/use-persisted-toggle";
import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
@@ -94,8 +101,8 @@ import {
type VideoGenerateProgress,
type VideoReferenceVideo,
type VideoLoadProgress,
- type VideoStatus,
type VideoLoadRequest,
+ type VideoStatus,
cancelVideoGeneration,
clearVideoGallery,
deleteGalleryVideo,
@@ -660,6 +667,42 @@ function RecipeRow({
}
type Busy = "loading" | "unloading" | "generating" | null;
+type H3Task = NonNullable<VideoLoadRequest["h3_task"]>;
+type VideoLoadOptions = {
+ kind: "gguf" | "single_file" | "pipeline";
+ filename?: string;
+ h3Task?: H3Task;
+};
+/** A pick held back while the user chooses the H3 partition. It carries what the deferred
+ * loadOrStage call would otherwise have been given inline, so the choice only adds `h3Task`:
+ * `source` decides whether the pick is preflighted against the Hub download plan or loaded
+ * straight off disk, and a dialog must not silently change that for the pick it is holding. */
+type PendingH3Load = {
+ repoId: string;
+ opts: VideoLoadOptions;
+ source: ModelSelectorChangeMeta["source"];
+ token: number;
+};
+
+const H3_BF16_REPO = "MiniMaxAI/MiniMax-H3";
+
+/** Whether a pick is the H3 base pipeline, whose denoiser partition the user must choose.
+ * Shared by both entry points: a chat-picker pick arrives as ?model= and reaches loadOrStage
+ * without passing through handleModelSelect, so checking it in one place staged the default
+ * fl2va partition, tens of GB, with no way to ask for References.
+ *
+ * An on-device copy counts. The same pipeline added as a directory reaches the generic
+ * local-pipeline branch, which a Hub-id equality test never recognises, so an omitted h3_task
+ * pinned it to fl2va and its transformer_ref partition was unreachable even with the weights
+ * sitting on disk. Matched on the final path segment, the same way a local checkpoint's family
+ * is read off its filename elsewhere. */
+function isH3PipelinePick(repoId: string, kind: VideoLoadOptions["kind"]): boolean {
+ if (kind !== "pipeline") return false;
+ const id = repoId.toLowerCase();
+ if (id === H3_BF16_REPO.toLowerCase()) return true;
+ const leaf = id.replace(/\\/g, "/").replace(/\/+$/, "").split("/").at(-1) ?? "";
+ return leaf === H3_BF16_REPO.split("/")[1].toLowerCase();
+}
// What a pick optimistically replaced, so a load that never takes can put all of it back. The quant
// label and the generation recipe move together at pick time, so they have to roll back together too.
@@ -779,9 +822,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
"auto" | "none" | "fp8" | "int8" | "nvfp4" | "mxfp8"
>("auto");
// The last load descriptor, so "Reapply" can reload the same model with new advanced options.
- const lastLoad = useRef<{ repoId: string; kind: "gguf" | "single_file" | "pipeline"; filename?: string } | null>(
- null,
- );
+ const lastLoad = useRef<({ repoId: string } & VideoLoadOptions) | null>(null);
// Whether this session holds a reapply descriptor: with a model already resident, lastLoad is null, so hide the button rather than offer a dead control.
const [canReapply, setCanReapply] = useState(false);
@@ -794,6 +835,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const [status, setStatus] = useState<VideoStatus | null>(null);
// Controlled so the body-portaled model selector force-closes when this page is mounted but off-tab.
const [selectorOpen, setSelectorOpen] = useState(false);
+ const [pendingH3Load, setPendingH3Load] = useState<PendingH3Load | null>(null);
const {
attach: attachSettingsScroll,
onScroll: onSettingsScroll,
@@ -1628,10 +1670,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// Resolves true when the background load STARTED (callers may revert optimistic picker state on false).
async (
repoId: string,
- opts: {
- kind: "gguf" | "single_file" | "pipeline";
- filename?: string;
- },
+ opts: VideoLoadOptions,
// Staged loads use the controls their preflight validated.
pinned?: VideoLoadAdvanced,
): Promise<boolean> => {
@@ -1662,7 +1701,8 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const prevLastLoad = lastLoad.current;
const prevCanReapply = canReapply;
const advanced = pinned ?? currentLoadAdvanced(opts.kind);
- lastLoad.current = { repoId, kind: opts.kind, filename: opts.filename };
+ // Spread, so the H3 partition rides along: Reapply reloads the same denoiser, not the default one.
+ lastLoad.current = { repoId, ...opts };
setCanReapply(true);
// Carry the prior target so the async poll can restore it if the background load fails after starting.
lastLoadRevert.current = { prev: prevLastLoad, canReapply: prevCanReapply };
@@ -1678,6 +1718,9 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
attention_backend: advanced.attention_backend,
transformer_cache: advanced.transformer_cache,
transformer_quant: advanced.transformer_quant,
+ // Not an Advanced control: the partition is chosen per pick, so it stays on opts rather
+ // than joining the pinned set.
+ h3_task: opts.h3Task,
});
await startRequest;
} catch (err) {
@@ -1727,7 +1770,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// Downloads go through the Hub download manager like every other model, sharing its panel, progress, cancel and preflight. Mirrors Images.
const pendingStagedLoad = useRef<{
repoId: string;
- opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string };
+ opts: VideoLoadOptions;
advanced: VideoLoadAdvanced;
// The pick that staged it: a download outlives its pick, so it must not evict a newer one when it lands.
token: number;
@@ -1797,7 +1840,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const loadOrStage = useCallback(
async (
repoId: string,
- opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string },
+ opts: VideoLoadOptions,
source: ModelSelectorChangeMeta["source"] = "hub",
token?: number,
): Promise<boolean> => {
@@ -1834,6 +1877,9 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// The route preflights the same values used by the eventual load.
transformer_quant: advanced.transformer_quant,
memory_mode: advanced.memory_mode,
+ // And the partition, for the same reason: the two H3 denoisers are separate downloads,
+ // so a plan asked without it stages the default fl2va weights for a References pick.
+ h3_task: opts.h3Task,
});
// Superseded. Report started so this pick's `.then` leaves the newer label alone.
if (pick !== pickSeq.current || !owns()) return true;
@@ -1935,10 +1981,31 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
[guidance, loadOrStage, pickGuard, quant, revertPick, steps],
);
+ // A pick that is rejected after beginPick() has already retired the staged pick it replaced, so
+ // nothing will load and nothing else will restore the label. Hand the resident state back here or
+ // the selector keeps showing the abandoned pick's quant and recipe for good.
+ const abandonPick = useCallback(() => {
+ if (quantRevert.current) {
+ revertPick(quantRevert.current);
+ quantRevert.current = null;
+ }
+ }, [revertPick]);
+
// A hidden page owns nothing: both stay mounted, so a resolution started here must not load after the user switched.
useEffect(() => {
- if (!active) pickGuard.release();
- }, [active, pickGuard]);
+ if (!active) {
+ pickGuard.release();
+ // Through the SAME ending as pressing Cancel. The pick that opened this dialog already
+ // replaced the quant label, steps and guidance and parked their rollback in quantRevert,
+ // and the load it was deferring never ran. Clearing the dialog alone leaves the controls
+ // describing H3 over whatever model is still resident, and leaves a stale rollback for the
+ // next pick to trip over.
+ setPendingH3Load((pending) => {
+ if (pending) abandonPick();
+ return null;
+ });
+ }
+ }, [abandonPick, active, pickGuard]);
// A diffusion model picked from the chat picker arrives as ?model= on this route. Load it once, then clear the params.
const routeSearch = useSearch({ strict: false }) as {
@@ -1989,6 +2056,16 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, "hub"));
return;
}
+ // A routed pick owns the page exactly like a direct one, so it has to offer the same choice.
+ if (isH3PipelinePick(pick.repoId, pick.opts.kind)) {
+ setPendingH3Load({
+ repoId: pick.repoId,
+ opts: pick.opts,
+ source: "hub",
+ token,
+ });
+ return;
+ }
void loadOrStage(pick.repoId, pick.opts, "hub", token);
}, [
active,
@@ -2001,10 +2078,48 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
pickGuard,
]);
+
+ // The task dialog defers the load out of the branch that snapshotted the rollback, so the two
+ // ways out of it carry that branch's two endings: choosing runs the load and reverts if it never
+ // starts, cancelling abandons the pick outright.
+ const chooseH3Task = useCallback(
+ (task: H3Task) => {
+ const pending = pendingH3Load;
+ setPendingH3Load(null);
+ if (!pending || !pickGuard.holds(pending.token)) return;
+ const revert = quantRevert.current;
+ void loadOrStage(
+ pending.repoId,
+ { ...pending.opts, h3Task: task },
+ pending.source,
+ pending.token,
+ ).then((started) => {
+ // One slot, so only the pick that set the label may take it back.
+ if (!started && revert && quantRevert.current === revert && pickGuard.holds(pending.token)) {
+ revertPick(revert);
+ quantRevert.current = null;
+ }
+ });
+ },
+ [loadOrStage, pendingH3Load, pickGuard, revertPick],
+ );
+
+ const cancelH3TaskChoice = useCallback(() => {
+ setPendingH3Load(null);
+ abandonPick();
+ pickGuard.cancel();
+ }, [abandonPick, pickGuard]);
+
// Reload the current model with the current advanced options.
const handleReapply = useCallback(() => {
const l = lastLoad.current;
- if (l) void handleLoad(l.repoId, { kind: l.kind, filename: l.filename });
+ if (l) {
+ void handleLoad(l.repoId, {
+ kind: l.kind,
+ filename: l.filename,
+ h3Task: l.h3Task,
+ });
+ }
}, [handleLoad]);
// The chat picker emits (modelId, quant + filename) for a GGUF, or just (modelId) for a curated pipeline pick.
@@ -2012,16 +2127,6 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// its pick, and the direct-local branches call handleLoad rather than loadOrStage, so clearing
// only inside loadOrStage left the old job's onReady free to load the abandoned model over the
// one just chosen. Bumping the sequence here also invalidates any plan still in flight.
- // A pick that is rejected after beginPick() has already retired the staged pick it replaced, so
- // nothing will load and nothing else will restore the label. Hand the resident state back here or
- // the selector keeps showing the abandoned pick's quant and recipe for good.
- const abandonPick = useCallback(() => {
- if (quantRevert.current) {
- revertPick(quantRevert.current);
- quantRevert.current = null;
- }
- }, [revertPick]);
-
const beginPick = useCallback(() => {
pickSeq.current += 1;
pendingStagedLoad.current = null;
@@ -2054,6 +2159,15 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const d = defaultsFor(spec.filename ? `${id}/${spec.filename}` : id);
setSteps(d.steps);
setGuidance(d.guidance);
+ if (isH3PipelinePick(id, spec.kind)) {
+ setPendingH3Load({
+ repoId: id,
+ opts: { kind: spec.kind, filename: spec.filename },
+ source: meta.source,
+ token,
+ });
+ return;
+ }
void loadOrStage(
id,
{ kind: spec.kind, filename: spec.filename },
@@ -2167,6 +2281,17 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
const d = defaultsFor(id);
setSteps(d.steps);
setGuidance(d.guidance);
+ // The on-device copy of the H3 pipeline lands here rather than in the curated branch, and
+ // it needs the same partition question: without it the load silently takes fl2va.
+ if (isH3PipelinePick(id, "pipeline")) {
+ setPendingH3Load({
+ repoId: id,
+ opts: { kind: "pipeline" },
+ source: meta.source,
+ token,
+ });
+ return;
+ }
void loadOrStage(id, { kind: "pipeline" }, meta.source, token).then((started) => {
if (!started && pickGuard.holds(token)) {
revertPick(revert);
@@ -2474,6 +2599,50 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
// The chat-style layout gives this page no outer top inset, so clear the custom
// titlebar here (34px on win/linux, 0 under macOS's native one) as chat does.
<div className="diffusion-surface flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden pt-[var(--studio-content-top-inset,0px)]">
+ <Dialog
+ open={pendingH3Load !== null}
+ onOpenChange={(open) => {
+ if (!open) cancelH3TaskChoice();
+ }}
+ >
+ <DialogContent className="max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Choose how MiniMax H3 should generate</DialogTitle>
+ <DialogDescription>
+ MiniMax H3 uses a separate denoiser for reference generation. Choose the mode you
+ want to load now. Shared components already on disk are reused.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-3 sm:grid-cols-2">
+ <Button
+ type="button"
+ variant="outline"
+ className="h-auto items-start justify-start whitespace-normal p-4 text-left"
+ onClick={() => chooseH3Task("fl2va")}
+ >
+ <span className="grid gap-1">
+ <span className="font-medium">Text and frames</span>
+ <span className="text-ui-11 font-normal leading-snug text-muted-foreground">
+ Generate from text, with optional first and last frame images.
+ </span>
+ </span>
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ className="h-auto items-start justify-start whitespace-normal p-4 text-left"
+ onClick={() => chooseH3Task("ref2va")}
+ >
+ <span className="grid gap-1">
+ <span className="font-medium">References</span>
+ <span className="text-ui-11 font-normal leading-snug text-muted-foreground">
+ Generate from reference pictures, videos and audio tracks.
+ </span>
+ </span>
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
{/* Top: the model selector, sitting clear of the sidebar and level with the controls column below. Load progress shows in a toast. */}
<div className="@container pointer-events-none relative z-40 flex h-[48px] shrink-0 items-start justify-between pl-[var(--studio-media-header-left-inset,1.5rem)] pr-2 pt-[var(--studio-chat-header-padding-top,11px)]">
{/* min-w-0: without it a long resident model name pushes the Images link off a phone screen. */}
diff --git a/studio/frontend/tests/diffusion-train-batch-cap.test.ts b/studio/frontend/tests/diffusion-train-batch-cap.test.ts
new file mode 100644
index 00000000000..bfab7d36431
--- /dev/null
+++ b/studio/frontend/tests/diffusion-train-batch-cap.test.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// MiniMax-H3's forward covers ONE packed sequence, so its backend validation REFUSES a batch
+// above 1 rather than clamping. The Train panel rendered Batch unrestricted and always sent the
+// field's state, so a 2 typed here -- or simply carried over from the family the user was on a
+// moment ago -- came back as a rejected Start with nothing on the control to say why. The panel
+// builds its payload inline, so the contract is asserted against the source, the same way the
+// labeling-grid gate is in dataset-file-selection.test.ts.
+
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+
+const source = await readFile(
+ new URL("../src/features/images/train/diffusion-train-panel.tsx", import.meta.url),
+ "utf8",
+);
+
+test("the batch cap comes from the family the backend reported", () => {
+ assert.match(source, /max_train_batch_size/);
+ assert.match(source, /const batchIsFixed = maxBatchSize != null && maxBatchSize <= 1;/);
+ // Clamped, not merely compared: the field is hidden rather than reset, so the cap has to be
+ // applied on the way out too.
+ assert.match(
+ source,
+ /const effectiveBatchSize = maxBatchSize == null \? batchSize : Math\.min\(batchSize, maxBatchSize\);/,
+ );
+});
+
+test("the hidden Batch field cannot still be sent", () => {
+ assert.match(source, /train_batch_size: effectiveBatchSize,/);
+ assert.doesNotMatch(source, /train_batch_size: batchSize,/);
+ // And the control itself is gone for a capped family rather than left offering a value the
+ // backend will refuse.
+ assert.match(source, /\{!batchIsFixed &&\s*\n\s*numberField\("Batch"/);
+});
+
+test("an uncapped family is untouched", () => {
+ // max_train_batch_size is null for every other family, and the ?? null / == null pair is what
+ // keeps those on the field's own value. An older backend reports nothing, which reads the same.
+ assert.match(source, /reportedFamily\?\.max_train_batch_size \?\? null/);
+});
diff --git a/studio/frontend/tests/gguf-variant-default-subset.test.ts b/studio/frontend/tests/gguf-variant-default-subset.test.ts
new file mode 100644
index 00000000000..07c10c531f0
--- /dev/null
+++ b/studio/frontend/tests/gguf-variant-default-subset.test.ts
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * defaultVariant is a QUANT key picked across the WHOLE repo, and a filenamePrefix subset need
+ * not contain it: the H3 catalog offers 6 ref2va quants against 8 fl2va ones. Stored unchanged,
+ * effectiveRecommended's budget-unavailable branch returns a key with no visible row, so nothing
+ * reads as recommended and the sorter falls through to largest-first.
+ */
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+
+const source = readFileSync(
+ fileURLToPath(
+ new URL(
+ "../src/features/model-picker/components/model-selector/pickers.tsx",
+ import.meta.url,
+ ),
+ ),
+ "utf8",
+);
+
+test("the stored default is dropped when the prefix filters it out", () => {
+ const call = source.slice(
+ source.indexOf("setDefaultVariant("),
+ source.indexOf("setHasVision(normalized.hasVision);"),
+ );
+ // Conditional on the prefix, and on the default surviving it.
+ assert.match(call, /filenamePrefix &&/);
+ assert.match(call, /variant\.quant === normalized\.defaultVariant/);
+ assert.match(call, /\?\s*null/);
+ // Unfiltered listings keep the repo-wide default exactly as before.
+ assert.match(call, /:\s*normalized\.defaultVariant/);
+});
+
+test("the recommendation still reads the stored default, so clearing it is what takes effect", () => {
+ const recommended = source.slice(
+ source.indexOf("const effectiveRecommended = useMemo("),
+ source.indexOf("const sortedVariants = useMemo("),
+ );
+ // The branch the bug showed up in: no budget, so the stored key is returned unchecked.
+ assert.match(recommended, /\(totalBudgetGb <= 0 && !budgetKnown\)\s*\)\s*\{\s*return defaultVariant;/);
+});
diff --git a/studio/frontend/tests/recommended-curated-row-metadata.test.ts b/studio/frontend/tests/recommended-curated-row-metadata.test.ts
index 26ae9d24451..34c68b301cd 100644
--- a/studio/frontend/tests/recommended-curated-row-metadata.test.ts
+++ b/studio/frontend/tests/recommended-curated-row-metadata.test.ts
@@ -27,6 +27,7 @@ import {
} from "../src/features/model-picker/components/model-selector/recommended-fit.ts";
const H3_GGUF = "unsloth/MiniMax-H3-GGUF";
+const H3_REF_GGUF = "leejet/MiniMax-H3-GGUF";
const H3_BF16 = "MiniMaxAI/MiniMax-H3";
const LTX_GGUF = "unsloth/LTX-2.3-GGUF";
const WAN_BF16 = "Wan-AI/Wan2.2-TI2V-5B-Diffusers";
@@ -74,6 +75,11 @@ test("a curated GGUF carries the param count its id cannot spell", () => {
// without the catalog the row has no size chip at all.
assert.equal(paramsFromId(H3_GGUF), undefined);
assert.equal(curatedTotalParamsFor(H3_GGUF, VIDEO_CATALOG), 20_111_438_744);
+ assert.equal(paramsFromId(H3_REF_GGUF), undefined);
+ assert.equal(
+ curatedTotalParamsFor(H3_REF_GGUF, VIDEO_CATALOG),
+ 20_111_438_744,
+ );
});
test("the curated param count is the artifact's own, not the group's", () => {
@@ -86,6 +92,7 @@ test("the curated param count is the artifact's own, not the group's", () => {
test("a curated audio family reports audio the repo name never mentions", () => {
assert.equal(detectCapabilities({ id: H3_GGUF }).audio, false);
assert.equal(curatedCapabilitiesFor(H3_GGUF, VIDEO_CATALOG)?.audio, true);
+ assert.equal(curatedCapabilitiesFor(H3_REF_GGUF, VIDEO_CATALOG)?.audio, true);
// Group-level, so every artifact of the model agrees.
assert.equal(curatedCapabilitiesFor(H3_BF16, VIDEO_CATALOG)?.audio, true);
assert.equal(curatedCapabilitiesFor(LTX_GGUF, VIDEO_CATALOG)?.audio, true);
diff --git a/studio/frontend/tests/video-download-plan-payload.test.ts b/studio/frontend/tests/video-download-plan-payload.test.ts
index 4c2ac86f13c..cc08b54989a 100644
--- a/studio/frontend/tests/video-download-plan-payload.test.ts
+++ b/studio/frontend/tests/video-download-plan-payload.test.ts
@@ -62,3 +62,58 @@ test("the video picker resolves the full GGUF footprint", () => {
test("the staged plan carries the memory request too", () => {
assert.equal(source.match(/memory_mode: advanced\.memory_mode/g)?.length, 3);
});
+
+test("the selected H3 task reaches both the plan and the load", () => {
+ // The STAGING plan, sliced out of loadOrStage rather than found by the first
+ // `getVideoDownloadPlan` in the file: the row-sizing footprint probe calls it earlier and only
+ // ever for a named GGUF file, where the partition is the filename, not a task flag.
+ const flow = source.slice(
+ source.indexOf("const loadOrStage = useCallback("),
+ source.indexOf("// A GGUF pick can arrive"),
+ );
+ const planAt = flow.indexOf("await getVideoDownloadPlan({");
+ assert.ok(planAt >= 0, "the staged flow must request the download plan");
+ const planCall = flow.slice(planAt, planAt + 1500);
+ const loadCall = source.slice(
+ source.indexOf("const startRequest = loadVideoModel({"),
+ source.indexOf("const startRequest = loadVideoModel({") + 1500,
+ );
+ assert.ok(planCall.includes("h3_task: opts.h3Task"));
+ assert.ok(loadCall.includes("h3_task: opts.h3Task"));
+ assert.ok(source.includes('chooseH3Task("fl2va")'));
+ assert.ok(source.includes('chooseH3Task("ref2va")'));
+});
+
+test("a routed H3 pipeline pick asks for the task instead of loading a default", () => {
+ // The chat picker cannot load a diffusion model, so a pick there arrives on this page as
+ // ?model=. That route calls loadOrStage directly: without the same interception the direct
+ // pick makes, a cached MiniMax H3 silently staged the fl2va denoiser, tens of GB, and left no
+ // way to ask for References.
+ const routeEffect = source.slice(
+ source.indexOf("const pick = diffusionRoutePick("),
+ source.indexOf("const chooseH3Task = useCallback"),
+ );
+ assert.ok(routeEffect.length > 0, "the routed pick branch must exist");
+ assert.ok(
+ routeEffect.includes("isH3PipelinePick(pick.repoId, pick.opts.kind)"),
+ "the routed branch must intercept an H3 pipeline pick",
+ );
+ const intercept = routeEffect.indexOf("isH3PipelinePick(");
+ const load = routeEffect.indexOf("void loadOrStage(pick.repoId");
+ assert.ok(
+ intercept >= 0 && load > intercept,
+ "the interception must come before the unconditional load",
+ );
+ assert.ok(routeEffect.includes("setPendingH3Load({"));
+ // One predicate, so the two entry points cannot drift apart again.
+ assert.ok(source.includes("function isH3PipelinePick("));
+ assert.ok(source.includes("isH3PipelinePick(id, spec.kind)"));
+});
+
+test("reapply preserves the loaded H3 task", () => {
+ const reapply = source.slice(
+ source.indexOf("const handleReapply = useCallback"),
+ source.indexOf("const handleReapply = useCallback") + 600,
+ );
+ assert.ok(reapply.includes("h3Task: l.h3Task"));
+});
diff --git a/studio/frontend/tests/video-h3-task-dialog.test.ts b/studio/frontend/tests/video-h3-task-dialog.test.ts
new file mode 100644
index 00000000000..cdddab1def8
--- /dev/null
+++ b/studio/frontend/tests/video-h3-task-dialog.test.ts
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Three contracts around the H3 denoiser-partition dialog, asserted against the page source the
+ * way video-download-plan-payload.test.ts does, since the page builds this flow inline.
+ *
+ * 1. The task choice must not skip the staged plan. Choosing the other partition can need the
+ * ~66 GB of shards the cache does not hold, and only the plan gives that a disk preflight,
+ * progress and a cancel. The plan is cache-aware, so a fully cached pick still costs nothing.
+ * 2. An on-device copy of the pipeline has to reach the dialog too, or its transformer_ref
+ * partition is unreachable with the weights sitting on disk.
+ * 3. Hiding the page has to take the dialog's cancellation path, not just close it.
+ */
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+
+const source = readFileSync(
+ fileURLToPath(new URL("../src/features/video/video-page.tsx", import.meta.url)),
+ "utf8",
+);
+
+test("only a non-hub pick skips the plan, so a cached hub pick still gets one", () => {
+ // The bypass is keyed on the pick's SOURCE. A curated artifact already on disk is still
+ // source "hub" (localModelMeta is the only thing that emits "local"), so it keeps the plan:
+ // "downloaded" is a property of the repo, and an H3 repo can be half downloaded.
+ assert.match(source, /if \(source !== "hub"\) return handleLoadRef\.current\(repoId, opts\);/);
+ assert.doesNotMatch(source, /if \(isDownloaded !== false\) return handleLoadRef\.current/);
+ // And the deferred choice re-enters loadOrStage rather than loading directly, so the plan
+ // decision is made again with the chosen partition in hand.
+ const choose = source.slice(
+ source.indexOf("const chooseH3Task = useCallback("),
+ source.indexOf("const cancelH3TaskChoice = useCallback("),
+ );
+ assert.match(choose, /loadOrStage\(/);
+ assert.match(choose, /h3Task: task/);
+ assert.doesNotMatch(choose, /handleLoadRef\.current\(/);
+});
+
+test("an on-device copy of the pipeline reaches the same dialog", () => {
+ const predicate = source.slice(
+ source.indexOf("function isH3PipelinePick("),
+ source.indexOf("// What a pick optimistically replaced"),
+ );
+ // Not a Hub-id equality test any more: the local directory never matches one.
+ assert.match(predicate, /split\("\/"\)\.at\(-1\)/);
+ assert.match(predicate, /H3_BF16_REPO\.split\("\/"\)\[1\]\.toLowerCase\(\)/);
+ // And the generic local-pipeline branch consults it, not only the curated branch.
+ assert.equal(
+ source.split('isH3PipelinePick(id, "pipeline")').length - 1,
+ 1,
+ "the local-pipeline branch must intercept an H3 pick exactly once",
+ );
+});
+
+test("hiding the page cancels the pending pick rather than dropping it", () => {
+ const hide = source.slice(
+ source.indexOf("// A hidden page owns nothing"),
+ source.indexOf("// A diffusion model picked from the chat picker"),
+ );
+ assert.match(hide, /abandonPick\(\)/);
+ // Guarded on there actually being one, so hiding an idle page reverts nothing.
+ assert.match(hide, /setPendingH3Load\(\(pending\) => \{/);
+ assert.match(hide, /if \(pending\) abandonPick\(\);/);
+});