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: give the MiniMax-H3 reference denoiser an int8 and fp8 rung (#8329)

Daniel Hand20f3e8a2eb4
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index 327d671842d..a98bdbd7d7e 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -75,7 +75,9 @@ class DiffusionFamily:
# that asks for it by name and the old one to every build that does not. That is what lets a
# rotated (v2) checkpoint ship without regressing an already-installed Studio, which would
# otherwise refuse the v2 tag and fall all the way back to the dense download.
- prequant_filenames: tuple[tuple[str, str], ...] = field(default_factory = tuple)
+ # A row may also be (scheme, task, filename), which names the artifact for ONE task and beats
+ # the task-agnostic row; see ``family_prequant_filename``.
+ prequant_filenames: tuple[tuple[str, ...], ...] = field(default_factory = tuple)
# Hosted PRE-CAST text-encoder checkpoints as (scheme, component, repo_id). Layerwise-fp8 only: the cast is deterministic, so the artifact is bit-identical while skipping the dense TE download.
te_prequant_repos: tuple[tuple[str, str, str], ...] = field(default_factory = tuple)
# Native (sd.cpp) single-file assets, used only on the no-GPU sd.cpp engine. The transformer GGUF is shared with
@@ -814,16 +816,46 @@ def family_prequant_repo(
return None
-def family_prequant_filename(fam: DiffusionFamily, scheme: str) -> Optional[str]:
+def family_prequant_filename(
+ fam: DiffusionFamily,
+ scheme: str,
+ task: Optional[str] = None,
+) -> Optional[str]:
"""The preferred checkpoint filename this family declares for ``scheme``, or None.
``None`` means "use the derived ``<Model>-<SCHEME>.pt`` name", which is every family but the
ones shipping a second artifact under the same repo and scheme. Not variant-keyed: the
- filename says WHICH artifact, the repo says which base."""
- for entry_scheme, filename in getattr(fam, "prequant_filenames", ()) or ():
- if entry_scheme == scheme:
- return filename
- return None
+ filename says WHICH artifact, the repo says which base.
+
+ Rows come in two shapes. ``(scheme, filename)`` is the historical one and is TASK-AGNOSTIC.
+ ``(scheme, task, filename)`` names an artifact for one task only and wins over the agnostic
+ row when ``task`` matches. That distinction exists because a family can hold several denoiser
+ PARTITIONS in one repo (MiniMax-H3: keyframe vs reference), whose checkpoints have identical
+ key sets and identical metadata and so cannot be told apart by any later check -- picking the
+ wrong one generates from the wrong partition rather than failing.
+
+ ``task = None`` therefore sees only the agnostic rows, and a scheme with no row for the task
+ asked for falls back to the agnostic one, i.e. exactly today's behaviour. Malformed rows are
+ skipped rather than raising: this runs on a refusal path where a table typo must not 500."""
+ wanted = (task or "").strip().lower()
+ agnostic: Optional[str] = None
+ for entry in getattr(fam, "prequant_filenames", ()) or ():
+ if not isinstance(entry, (tuple, list)):
+ continue
+ if len(entry) == 2:
+ entry_scheme, filename = entry
+ if entry_scheme == scheme and agnostic is None and filename:
+ agnostic = filename
+ elif len(entry) == 3:
+ entry_scheme, entry_task, filename = entry
+ if (
+ wanted
+ and entry_scheme == scheme
+ and (entry_task or "").strip().lower() == wanted
+ and filename
+ ):
+ return filename
+ return agnostic
# The release where diffusers' own requires-python went ">= 3.10.0", which makes 0.36.0 the newest
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.py
index 149cb9f2cf9..a8edb0a3c21 100644
--- a/studio/backend/core/inference/diffusion_prequant.py
+++ b/studio/backend/core/inference/diffusion_prequant.py
@@ -137,6 +137,7 @@ def resolve_prequant_source(
*,
path_override: Optional[str] = None,
base_repo: Optional[str] = None,
+ task: Optional[str] = None,
) -> Optional[PrequantSource]:
"""Resolve where the checkpoint for ``(fam, scheme)`` comes from.
@@ -144,6 +145,11 @@ def resolve_prequant_source(
``scheme`` (variant-specific when ``base_repo`` names a base with its own baked
checkpoint); (3) None -> no pre-quant, caller quantises dense. Pure: no IO, no torch.
+ ``task`` names the workflow / denoiser PARTITION the load is bringing up, for the families
+ that host more than one under a single repo and scheme (MiniMax-H3's keyframe and reference
+ denoisers). It only ever selects a more specific filename: unset, or set to a task the family
+ declares nothing for, resolves exactly what it resolved before.
+
Both names are repo-ROOT names. Every hosted prequant repo, image and video alike, keeps its
checkpoints at the root, so there is no directory to prepend; a repo that nested them would
404 on the primary AND on the fallback and the load would silently fall back to dense.
@@ -152,10 +158,16 @@ def resolve_prequant_source(
if override:
return PrequantSource(kind = "path", location = override, filename = None)
preferred = None
+ agnostic = None
try:
from .diffusion_families import family_prequant_filename, family_prequant_repo
+
repo_id = family_prequant_repo(fam, scheme, base_repo = base_repo)
- preferred = family_prequant_filename(fam, scheme)
+ preferred = family_prequant_filename(fam, scheme, task = task)
+ # What the same call would have resolved WITHOUT a task, which is what decides whether a
+ # fallback is safe below. Skipped when no task was asked for, since then the two are the
+ # same lookup.
+ agnostic = family_prequant_filename(fam, scheme) if task else preferred
except Exception: # noqa: BLE001 — a bad family object must not break the load
repo_id = None
if repo_id:
@@ -165,11 +177,20 @@ def resolve_prequant_source(
# fallback, so a build that knows the new name gets it and every older build keeps
# resolving the artifact it already understands. Without an override nothing changes: the
# derived name is primary and the legacy transformer_<scheme>.pt is the fallback.
+ #
+ # A TASK-SPECIFIC name gets NO fallback. The other artifacts in the repo are the same
+ # family, the same scheme and the same base, so every check the loader makes would pass
+ # on them -- the fallback would quietly install another partition's denoiser and generate
+ # from the wrong weights, which is precisely what naming the artifact per task prevents.
+ # Absent is better than wrong here: no artifact means the released bfloat16 denoiser.
+ task_specific = preferred is not None and preferred != agnostic
return PrequantSource(
kind = "repo",
location = repo_id,
filename = preferred or derived,
- fallback_filename = derived if preferred else prequant_filename(scheme),
+ fallback_filename = (
+ None if task_specific else (derived if preferred else prequant_filename(scheme))
+ ),
)
return None
@@ -339,6 +360,7 @@ def load_prequantized_transformer(
fast_accum: Optional[bool] = None,
cache_dir: Optional[str] = None,
prepare_model: Optional[Any] = None,
+ config_subfolder: str = "transformer",
logger: Any = None,
) -> Optional[Any]:
"""Load the pre-quantized transformer described by ``source`` onto ``device``.
@@ -347,6 +369,12 @@ def load_prequantized_transformer(
lands under huggingface_hub's import-time constant, so a mid-session cache change re-downloads
into a root Studio no longer reads.
+ ``config_subfolder`` is where the DENOISER CONFIG lives inside ``base``, defaulting to the
+ universal ``transformer``. A family hosting several denoiser partitions in one repo overrides
+ it with the one this checkpoint belongs to (MiniMax-H3's ``transformer_ref``): the scoped
+ download stages only that partition, so reading the config from the other one would send an
+ otherwise fully staged load back to the Hub.
+
``prepare_model`` (optional) is called as ``prepare_model(transformer, metadata)`` on the
freshly built skeleton, AFTER ``from_config`` and BEFORE ``load_state_dict``. That window is
the only one where a family can reshape the module to match how the checkpoint was baked (a
@@ -398,7 +426,9 @@ def load_prequantized_transformer(
# Read from the root that actually supplied the checkpoint: after a mid-session cache change
# the pinned root may be gone or read-only, and load_config's raise is swallowed below into
# a None return, silently dropping a prequant whose checkpoint is cached and already loaded.
- config = _load_transformer_config(transformer_cls, base, hf_token, cache_dir, path)
+ config = _load_transformer_config(
+ transformer_cls, base, hf_token, cache_dir, path, config_subfolder
+ )
from accelerate import init_empty_weights
metadata = ckpt.get("metadata") or {}
@@ -599,13 +629,14 @@ def _load_transformer_config(
hf_token: Optional[str],
cache_dir: Optional[str],
checkpoint_path: str,
+ subfolder: str = "transformer",
) -> Any:
"""``transformer_cls.load_config`` against the checkpoint's cache root, then the other one."""
last: Optional[BaseException] = None
for root in _config_cache_roots(checkpoint_path, cache_dir):
try:
return transformer_cls.load_config(
- base, subfolder = "transformer", token = hf_token, cache_dir = root
+ base, subfolder = subfolder, token = hf_token, cache_dir = root
)
except Exception as exc: # noqa: BLE001 — try the other root before giving up
last = exc
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 59742d3c61d..26bf6a1b912 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -122,6 +122,7 @@ from .video_families import (
snap_video_size,
supported_video_family_names,
validate_video_request_shape,
+ video_family_prequant_available,
video_family_prequant_repo,
video_family_prequant_schemes,
)
@@ -137,6 +138,7 @@ from .video_minimax_h3 import (
fit_h3_reference_image,
h3_canvas_for_aspect,
h3_conditioning_mode,
+ h3_denoiser_component,
h3_transformer_resident_gb,
h3_transformer_task,
)
@@ -850,36 +852,34 @@ class VideoBackend:
# "auto" is a request for the backend's own choice, not for a specific scheme, so it is
# never refused: it simply stays on the released bfloat16 components.
if requested_scheme is not None and requested_scheme != TQ_AUTO:
- # The hosted checkpoints are FL2VA denoisers. The two partitions share module
- # shapes and the same base model, so a Ref2VA load would install one, pass every
- # metadata check, and have load_components skip the real Ref2VA transformer --
- # generating from the wrong partition instead of failing. Refuse until a matching
- # checkpoint exists; there is no in-place quantise seam to fall back on.
- from .video_minimax_h3 import H3_TASK_REFERENCES
- if (h3_task or "").strip().lower() == H3_TASK_REFERENCES:
- raise ValueError(
- f"transformer_quant '{requested_scheme}' is unavailable for "
- f"'{fam.name}' reference video: the hosted pre-quantized checkpoints are "
- f"keyframe (fl2va) denoisers, and seeding one into the reference workflow "
- f"would generate from the wrong partition. Load reference video without "
- f"transformer_quant, or pick a keyframe task."
- )
- if video_family_prequant_repo(fam, requested_scheme, quant_base) is None:
- # There is no in-place quantise seam here: the workflow's own component loader
- # builds the denoiser, so a scheme without a hosted pre-quantized checkpoint
- # cannot be served at all, and letting it through would download ~98.7 GB of
- # dense weights and then silently ignore the request.
- available = video_family_prequant_schemes(fam)
+ # Asked per (scheme, TASK), not per scheme. A family can host one denoiser per
+ # workflow partition in the same repo -- MiniMax-H3 hosts a keyframe (fl2va, which
+ # also covers text-only) and a reference (ref2va) checkpoint -- and the two share
+ # module shapes, config and base model, so a mismatched one would install, pass
+ # every metadata check, and have load_components skip the real denoiser,
+ # generating from the wrong partition instead of failing. A pair with no hosted
+ # checkpoint is refused here; there is no in-place quantise seam to fall back on,
+ # because the workflow's own component loader builds the denoiser and letting the
+ # request through would download ~98.7 GB of dense weights and then silently
+ # ignore it.
+ if not video_family_prequant_available(
+ fam, requested_scheme, task = h3_task, base_repo = quant_base
+ ):
+ available = video_family_prequant_schemes(fam, task = h3_task)
hint = (
f"Use one of: {', '.join(available)}."
if available
else "Leave transformer_quant unset for this model."
)
+ # Name the partition when one was asked for, so "fp8 is unavailable" does not
+ # read as a claim about the whole family when it is only true of this task.
+ task_label = f" {h3_task}" if h3_task else ""
raise ValueError(
f"transformer_quant '{requested_scheme}' is unavailable for "
- f"'{fam.name}': its Modular Diffusers workflow builds the denoiser itself, "
- f"so only schemes with a hosted pre-quantized checkpoint can be applied "
- f"and the dense weights cannot be quantized in place. {hint}"
+ f"'{fam.name}'{task_label}: its Modular Diffusers workflow builds the "
+ f"denoiser itself, so only schemes with a hosted pre-quantized checkpoint "
+ f"can be applied and the dense weights cannot be quantized in place. "
+ f"{hint}"
)
from .video_minimax_h3 import is_h3_native, validate_h3_transformer_filename
@@ -1101,7 +1101,7 @@ class VideoBackend:
# The same deal for the denoiser: a hosted pre-quantized checkpoint replaces the dense
# DiT shards, so the estimate and the scoped pull below both drop them.
skip_transformer_weights = self._denoiser_prequant_covered(
- fam, kwargs.get("transformer_quant"), base
+ fam, kwargs.get("transformer_quant"), base, kwargs.get("h3_task")
)
# And for MiniMax-H3's conditioner, whose hosted quantized artifact replaces the base
# repo's 62 GB dense text_encoder/ shards outright.
@@ -1678,7 +1678,10 @@ class VideoBackend:
@staticmethod
def _denoiser_prequant_covered(
- fam: Any, transformer_quant: Optional[str], base: Optional[str]
+ fam: Any,
+ transformer_quant: Optional[str],
+ base: Optional[str],
+ h3_task: Optional[str] = None,
) -> bool:
"""True when a hosted PRE-QUANTIZED denoiser checkpoint replaces the dense DiT shards.
@@ -1686,6 +1689,10 @@ class VideoBackend:
stage weights another one skipped. Only a modular-workflow family qualifies: every other
family quantises its own dense transformer on device and still needs those shards.
+ ``h3_task`` names the partition, because coverage is per (scheme, task): a scheme whose
+ hosted checkpoint is the OTHER partition covers nothing here, and answering True for it
+ would drop the very shards that load then has to open.
+
Never raises and never touches the network -- a pure registry lookup -- because it runs on
the download-planning path, where a failure would cost the whole plan."""
try:
@@ -1698,13 +1705,17 @@ class VideoBackend:
# hosted checkpoints were measured and left opt-in: see _load_h3_modular_pipeline.
if scheme is None or scheme == TQ_AUTO:
return False
- return video_family_prequant_repo(fam, scheme, base) is not None
+ return video_family_prequant_available(fam, scheme, task = h3_task, base_repo = base)
except Exception: # noqa: BLE001 -- an unanswerable probe keeps the dense shards
return False
@staticmethod
def _denoiser_prequant_hub_files(
- fam: Any, transformer_quant: Optional[str], base: Optional[str], api: Any
+ fam: Any,
+ transformer_quant: Optional[str],
+ base: Optional[str],
+ api: Any,
+ h3_task: Optional[str] = None,
) -> tuple[Optional[str], list[tuple[str, int]]]:
"""``(repo_id, [(rfilename, size)])`` for the hosted pre-quantized denoiser, or
``(None, [])``.
@@ -1722,7 +1733,10 @@ class VideoBackend:
return None, []
try:
from .diffusion_prequant import resolve_prequant_source
- source = resolve_prequant_source(fam, scheme, base_repo = base)
+
+ # Task-keyed, like the coverage probe: staging the other partition's checkpoint would
+ # advertise the right byte count for the wrong file.
+ source = resolve_prequant_source(fam, scheme, base_repo = base, task = h3_task)
except Exception as exc: # noqa: BLE001 -- a bad registry entry must not sink the plan
logger.warning("video.denoiser_prequant_unresolved: %s", exc)
return None, []
@@ -1807,12 +1821,15 @@ class VideoBackend:
instead by a hosted pre-cast fp8 checkpoint (LTX-2's Gemma3 encoder is
~49 GB of the base repo). Their configs stay: the pre-cast loader
meta-inits the encoder from the base repo's component config;
- - the dense ``transformer/`` weight shards under
+ - 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).
- ``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.
+ 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),
@@ -1822,11 +1839,13 @@ class VideoBackend:
siblings = list(info.siblings or [])
is_h3_modular = any(s.rfilename == "modular_model_index.json" for s in siblings)
- h3_denoiser_prefix = (
- "transformer_ref/"
- if (h3_task or "").strip().lower() == H3_TASK_REFERENCES
- else "transformer/"
- )
+ h3_is_references = is_h3_modular and (h3_task or "").strip().lower() == H3_TASK_REFERENCES
+ h3_denoiser_prefix = "transformer_ref/" if h3_is_references else "transformer/"
+ # Which component's dense weight shards ``skip_transformer_weights`` drops. It has to be
+ # the partition this load will actually open: a reference load stages transformer_ref/ and
+ # nothing else, so dropping "transformer/" drops nothing and the plan carries the full
+ # 66.28 GB the pre-quantized checkpoint exists to replace.
+ h3_skip_component = h3_denoiser_prefix.rstrip("/")
h3_prefixes = (
"audio_scheduler/",
"audio_vae/",
@@ -1854,7 +1873,7 @@ class VideoBackend:
continue
# is_prequant_covered_weight is component-agnostic (it matches "<component>/" against a
# weight suffix), so the encoder helper serves the denoiser verbatim.
- if skip_transformer_weights and is_prequant_covered_weight(name, ("transformer",)):
+ if skip_transformer_weights and is_prequant_covered_weight(name, (h3_skip_component,)):
continue
if name.startswith("text_encoder/diffusion_pytorch_model"):
continue
@@ -2060,8 +2079,10 @@ class VideoBackend:
for component, files in te_files.items():
total += add(te_sources[component].location, files)
# The denoiser's replacement artifact, for the same reason: the base entry below drops
- # the dense DiT shards whenever this resolves, so it has to be staged in their place.
- dq_repo, dq_files = self._denoiser_prequant_hub_files(fam, transformer_quant, base, api)
+ # the dense DiT shards only when this resolves, so it is staged in their place.
+ dq_repo, dq_files = self._denoiser_prequant_hub_files(
+ fam, transformer_quant, base, api, h3_task
+ )
if dq_repo:
total += add(dq_repo, dq_files)
# And H3's quantized conditioner, which replaces the base repo's dense text_encoder/.
@@ -2087,8 +2108,18 @@ class VideoBackend:
skip_te_components = (
tuple(te_files) + (("text_encoder",) if h3_te_repo else ())
),
- skip_transformer_weights = self._denoiser_prequant_covered(
- fam, transformer_quant, base
+ # Gated on the artifact RESOLVING, exactly like the two encoder skips
+ # above, not on the registry alone: the registry says a checkpoint should
+ # exist, dq_repo says one does. When the task-specific file is absent or
+ # its repo cannot be read, dropping the dense shards leaves a plan with
+ # NEITHER denoiser, and the bf16 fallback the loader documents has nothing
+ # to fall back to offline. The registry probe still runs, because it is
+ # the one that refuses a non-modular family and an auto request.
+ skip_transformer_weights = (
+ dq_repo is not None
+ and self._denoiser_prequant_covered(
+ fam, transformer_quant, base, h3_task
+ )
),
h3_task = h3_task,
),
@@ -3294,6 +3325,10 @@ class VideoBackend:
text_encoder_quant_is_auto = _h3_precision_unset(text_encoder_quant)
# Load one denoiser partition. fl2va also covers text-only generation.
workflow = h3_task or fam.modular_workflow
+ # Which component this workflow's denoise step reads. One repo, two partitions: seeding
+ # the wrong attribute leaves the block with no denoiser AND has load_components fetch the
+ # dense 66.28 GB partition the seed was meant to replace.
+ denoiser_component = h3_denoiser_component(workflow)
manager = diffusers.ComponentsManager()
load_kwargs: dict[str, Any] = {
"components_manager": manager,
@@ -3320,12 +3355,18 @@ class VideoBackend:
)
if scheme == TQ_AUTO: # defence in depth; _h3_precision_unset already caught "auto"
scheme = None
- # The hosted checkpoints are keyframe (fl2va) denoisers. validate_load_request refuses this
- # pairing on the route; a direct call lands here, and seeding one would silently generate
- # the wrong partition rather than fail, so drop to the released components instead.
- if scheme is not None and workflow == H3_TASK_REFERENCES:
+ # Per (scheme, PARTITION), not per scheme: each workflow denoises against its own
+ # checkpoint partition and they are indistinguishable once loaded, so a scheme that has an
+ # artifact for the other one has none for this. It used to be enough to ask "is this the
+ # reference workflow", because only the keyframe partition had hosted checkpoints; both do
+ # now. validate_load_request refuses an unavailable pairing on the route; a direct call
+ # lands here and drops to the released components instead of silently generating from the
+ # wrong partition.
+ if scheme is not None and not video_family_prequant_available(
+ fam, scheme, task = workflow, base_repo = base
+ ):
transformer_quant_reason = (
- f"no hosted pre-quantized {scheme} checkpoint for {fam.name} reference video"
+ f"no hosted pre-quantized {scheme} checkpoint for {fam.name} {workflow}"
)
scheme = None
# The conventional loader refuses an oversized unified-memory load before any weight is
@@ -3348,7 +3389,7 @@ class VideoBackend:
from .diffusion_transformer_quant import DEFAULT_MIN_LINEAR_FEATURES
from .video_minimax_h3_adaln import h3_prepare_prequant_model
- source = resolve_prequant_source(fam, scheme, base_repo = base)
+ source = resolve_prequant_source(fam, scheme, base_repo = base, task = workflow)
if source is None:
# validate_load_request already refused this on the route; a direct call lands here.
transformer_quant_reason = (
@@ -3381,6 +3422,13 @@ class VideoBackend:
# without this reshape the strict load fails and every hosted checkpoint falls
# back to the dense download it exists to avoid.
prepare_model = h3_prepare_prequant_model(logger),
+ # Read the DENOISER CONFIG from this workflow's own partition. The two H3
+ # partitions ship byte-identical configs today, so this changes no shape; it
+ # changes which file has to exist. A reference load stages transformer_ref/
+ # and nothing under transformer/, so defaulting to "transformer" would send a
+ # fully staged, offline-ready load back to the Hub for a config it never
+ # planned for -- and on failure straight to the dense fallback it cannot pull.
+ config_subfolder = denoiser_component,
logger = logger,
)
if transformer is None:
@@ -3395,7 +3443,7 @@ class VideoBackend:
# every component whose attribute is already set, so the dense 66.3 GB
# transformer is never fetched. It must happen BEFORE load_components -- after,
# the dense one has already been pulled and built.
- pipe.update_components(transformer = transformer)
+ pipe.update_components(**{denoiser_component: transformer})
transformer_quant_engaged = scheme
transformer_quant_reason = (
f"hosted pre-quantized {scheme} denoiser checkpoint ({source.location})"
@@ -3619,7 +3667,10 @@ class VideoBackend:
memory_reserve_margin = "40GB",
)
offload_policy = "model"
- denoiser = getattr(pipe, "transformer", None)
+ # The partition this workflow opened, not a hardcoded "transformer": a reference run
+ # denoises out of transformer_ref, so pinning and sizing both have to name it or they
+ # act on a component this load never built.
+ denoiser = getattr(pipe, denoiser_component, None)
if transformer_quant_engaged:
# enable_auto_cpu_offload just parked every component on the CPU and will move
# each one back inside its own pre_forward. A torchao pre-quantized denoiser does
diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.py
index 2f2513626ec..e00244bd00f 100644
--- a/studio/backend/core/inference/video_families.py
+++ b/studio/backend/core/inference/video_families.py
@@ -104,7 +104,16 @@ class VideoFamily:
# that asks for it by name and the old one to every build that does not. That is what lets a
# rotated (v2) checkpoint ship without regressing an already-installed Studio, which would
# otherwise refuse the v2 tag and fall all the way back to the dense download.
- prequant_filenames: tuple[tuple[str, str], ...] = field(default_factory = tuple)
+ # A row may also be (scheme, task, filename), naming the artifact for ONE task; it beats the
+ # task-agnostic row and, unlike it, gets no filename fallback (see resolve_prequant_source).
+ prequant_filenames: tuple[tuple[str, ...], ...] = field(default_factory = tuple)
+ # Tasks whose denoiser is a DIFFERENT checkpoint partition from the one the task-agnostic
+ # ``prequant_filenames`` / ``prequant_repos`` rows describe. Such a task is served ONLY by its
+ # own (scheme, task, filename) row: the partitions share a base, a class, a config and a key
+ # set, so nothing downstream can tell them apart and an unnamed artifact would load cleanly
+ # and generate from the wrong partition. Empty for every family with a single denoiser, which
+ # is what makes this field free to ignore.
+ prequant_partition_tasks: tuple[str, ...] = field(default_factory = tuple)
# Modular Diffusers workflow to load instead of a conventional DiffusionPipeline. Its
# components are loaded without pruning the workflow's routing blocks.
modular_workflow: Optional[str] = None
@@ -177,7 +186,22 @@ _FAMILIES: tuple[VideoFamily, ...] = (
# its own name rather than over MiniMax-H3-INT8.pt keeps both true at once: this build
# gets the rotated artifact, and an older install still resolves the plain one instead of
# refusing the v2 tag and falling back to the 66.3 GB dense download.
- prequant_filenames = (("int8", "MiniMax-H3-INT8-ConvRot.pt"),),
+ # The reference (ref2va) denoiser is a SECOND partition in the same base repo, so it gets
+ # its own artifact under its own name for both schemes. The two partitions are otherwise
+ # indistinguishable to the loader -- same class, same config, same 635 keys, same
+ # base_model_id -- so the task, not any later check, is the only thing that keeps a
+ # reference load off the keyframe weights. Keyframe (fl2va, which also covers text-only)
+ # keeps resolving exactly what it resolved before: the rotated INT8 by name, FP8 by the
+ # derived MiniMax-H3-FP8.pt.
+ prequant_filenames = (
+ ("int8", "MiniMax-H3-INT8-ConvRot.pt"),
+ ("int8", "ref2va", "MiniMax-H3-Ref2VA-INT8-ConvRot.pt"),
+ ("fp8", "ref2va", "MiniMax-H3-Ref2VA-FP8.pt"),
+ ),
+ # Keeps the two partitions honest: without a ref2va row above, a ref2va prequant pick is
+ # refused rather than served the keyframe checkpoint. Equal to H3_TASK_REFERENCES; the
+ # literal avoids importing the H3 helper module into the registry.
+ prequant_partition_tasks = ("ref2va",),
# Both schemes are ~20.3 GB resident against the 66.3 GB dense denoiser; see the field.
prequant_resident_gb = 20.3,
modular_workflow = "fl2va",
@@ -404,11 +428,57 @@ def video_family_prequant_repo(
return None
-def video_family_prequant_schemes(fam: VideoFamily) -> tuple[str, ...]:
+def video_family_prequant_task_specific(fam: VideoFamily, scheme: str, task: str) -> bool:
+ """True when the family names an artifact for exactly this ``(scheme, task)`` pair.
+
+ Reads the same ``prequant_filenames`` table ``resolve_prequant_source`` reads, through the
+ shared resolver, so the answer here and the file the load asks for cannot drift."""
+ wanted = (task or "").strip().lower()
+ if not wanted:
+ return False
+ try:
+ from .diffusion_families import family_prequant_filename
+ specific = family_prequant_filename(fam, scheme, task = wanted)
+ except Exception: # noqa: BLE001 -- a bad table is "no artifact", never a 500
+ return False
+ return specific is not None and specific != family_prequant_filename(fam, scheme)
+
+
+def video_family_prequant_available(
+ fam: VideoFamily,
+ scheme: str,
+ *,
+ task: Optional[str] = None,
+ base_repo: Optional[str] = None,
+) -> bool:
+ """True when a hosted pre-quantized denoiser really covers ``(scheme, task)``.
+
+ ``video_family_prequant_repo`` answers "is there a checkpoint for this scheme"; this answers
+ the question a load actually has, which also names the PARTITION. A task listed in
+ ``prequant_partition_tasks`` is served only by its own ``(scheme, task, filename)`` row, so a
+ scheme that has the repo but not that row is unavailable for it -- the alternative is loading
+ another partition's denoiser, which passes every check and generates the wrong thing.
+
+ Every other task, and every family that declares no partition tasks, gets exactly the old
+ answer. Pure, and never raises: this runs on the refusal and download-planning paths."""
+ if video_family_prequant_repo(fam, scheme, base_repo) is None:
+ return False
+ wanted = (task or "").strip().lower()
+ partition_tasks = {
+ (t or "").strip().lower() for t in (getattr(fam, "prequant_partition_tasks", ()) or ())
+ }
+ if wanted and wanted in partition_tasks:
+ return video_family_prequant_task_specific(fam, scheme, wanted)
+ return True
+
+
+def video_family_prequant_schemes(fam: VideoFamily, task: Optional[str] = None) -> tuple[str, ...]:
"""Every scheme this family has a hosted denoiser checkpoint for, in table order.
Used to name the workable schemes in a refusal message, so a rejected request tells the caller
- what to pick instead of only what failed. Malformed rows are skipped, as above."""
+ what to pick instead of only what failed. With ``task``, the list is narrowed to the schemes
+ that cover THAT task, so a reference-video refusal cannot advertise a keyframe-only scheme.
+ Malformed rows are skipped, as above."""
schemes: list[str] = []
for entry in getattr(fam, "prequant_repos", ()) or ():
if isinstance(entry, (tuple, list)) and len(entry) == 2 and entry[0] not in schemes:
@@ -416,6 +486,8 @@ def video_family_prequant_schemes(fam: VideoFamily) -> tuple[str, ...]:
for entry in getattr(fam, "prequant_variant_repos", ()) or ():
if isinstance(entry, (tuple, list)) and len(entry) == 3 and entry[1] not in schemes:
schemes.append(entry[1])
+ if task:
+ schemes = [s for s in schemes if video_family_prequant_available(fam, s, task = task)]
return tuple(schemes)
diff --git a/studio/backend/core/inference/video_minimax_h3.py b/studio/backend/core/inference/video_minimax_h3.py
index b6262d92a42..efd2bac8f4d 100644
--- a/studio/backend/core/inference/video_minimax_h3.py
+++ b/studio/backend/core/inference/video_minimax_h3.py
@@ -325,6 +325,19 @@ def h3_transformer_task(filename: str) -> str:
return H3_TASK_REFERENCES if name.startswith("minimax_h3_ref2va") else H3_TASK_KEYFRAMES
+def h3_denoiser_component(task: Optional[str]) -> str:
+ """The pipeline component / base-repo subfolder holding ``task``'s denoiser partition.
+
+ One repo, two partitions: the keyframe workflows (fl2va, and text-only through it) denoise
+ against ``transformer``, the reference workflow against ``transformer_ref``. Diffusers names
+ the components that way too, so this single answer serves the seed target, the offload pin and
+ the config subfolder alike -- and seeding ``transformer`` for a reference load would leave the
+ denoise step with no denoiser and pull the dense 66.28 GB partition anyway."""
+ return (
+ "transformer_ref" if (task or "").strip().lower() == H3_TASK_REFERENCES else "transformer"
+ )
+
+
def fit_h3_reference_image(image: Any, *, width: int, height: int, policy: str) -> Any:
"""Scale a reference to its policy limit without changing its aspect ratio or upscaling."""
from PIL import Image
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 8822609b012..dd5892faa3b 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -2064,6 +2064,71 @@ def test_base_download_files_stages_the_h3_partition_the_load_will_open():
assert shared in keyframes and shared in references
+def test_base_download_files_skips_the_partition_the_prequant_checkpoint_replaces():
+ """``skip_transformer_weights`` has to drop the shards of the partition THIS load opens.
+
+ The skip named the literal ``transformer/``, which a reference load never stages in the first
+ place, so a ref2va pre-quantized pick dropped nothing: the plan carried the full 66.28 GB of
+ ``transformer_ref/`` that the checkpoint exists to replace, and the disk preflight sized a
+ download the load never opens. Both partitions' configs must survive their own skip, since
+ the pre-quant loader meta-inits the DiT from one of them.
+ """
+ info = types.SimpleNamespace(siblings = _H3_SIBLINGS)
+
+ keyframes = dict(
+ VideoBackend._base_download_files(info, "pipeline", skip_transformer_weights = True)
+ )
+ assert not any(n.startswith("transformer/diffusion_pytorch_model") for n in keyframes)
+ assert "transformer/config.json" in keyframes
+
+ references = dict(
+ VideoBackend._base_download_files(
+ info, "pipeline", skip_transformer_weights = True, h3_task = "ref2va"
+ )
+ )
+ assert not any(n.startswith("transformer_ref/diffusion_pytorch_model") for n in references)
+ assert "transformer_ref/config.json" in references
+ # And the other partition is still absent entirely, so the skip cannot have swapped which one
+ # is staged instead of dropping its weights.
+ assert not any(n.startswith("transformer/") for n in references)
+ # 66 of the 68 units in the reference plan were the dense denoiser; without the fix the totals
+ # are identical with and without the skip.
+ assert sum(references.values()) < sum(
+ size for _n, size in VideoBackend._base_download_files(info, "pipeline", h3_task = "ref2va")
+ )
+
+
+def test_a_quantized_reference_load_resolves_the_reference_denoiser():
+ # This pairing used to be refused outright: the only hosted checkpoints were fl2va denoisers,
+ # and one seeded into the reference workflow would have installed cleanly, passed every
+ # metadata check and generated from the keyframe partition. Now that a ref2va artifact exists
+ # for both schemes the refusal must be gone -- and must resolve the REFERENCE file, since
+ # picking the keyframe one is the exact failure the refusal was standing in for.
+ from core.inference.diffusion_prequant import resolve_prequant_source
+
+ backend = VideoBackend()
+ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")
+ for scheme, expected in (
+ ("int8", "MiniMax-H3-Ref2VA-INT8-ConvRot.pt"),
+ ("fp8", "MiniMax-H3-Ref2VA-FP8.pt"),
+ ):
+ try:
+ backend.validate_load_request(
+ "MiniMaxAI/MiniMax-H3",
+ family_override = "minimax-h3",
+ model_kind = "pipeline",
+ transformer_quant = scheme,
+ h3_task = "ref2va",
+ )
+ except ValueError as exc: # pragma: no cover - only on a regression
+ pytest.fail(f"ref2va {scheme} should be loadable but was refused: {exc}")
+ except Exception:
+ # Anything past the quant check (the diffusers probe) is not this test's business.
+ pass
+ source = resolve_prequant_source(fam, scheme, task = "ref2va")
+ assert source.filename == expected
+
+
def test_load_progress_clamps_overshoot(fake_runtime, monkeypatch):
# The cache scan counts blobs a broader previous pull left behind, so the counter must never exceed the scoped estimate.
backend = VideoBackend()
@@ -2669,6 +2734,81 @@ def test_download_plan_keeps_the_dense_denoiser_when_the_prequant_repo_is_missin
by_repo = {entry["repo_id"]: entry for entry in plan["entries"]}
assert "unsloth/MiniMax-H3-FP8" not in by_repo
+ assert any(
+ f.startswith("transformer/diffusion_pytorch_model")
+ for f in by_repo["MiniMaxAI/MiniMax-H3"]["files"]
+ )
+ assert plan["total_bytes"] == sum(e["bytes"] for e in plan["entries"])
+
+
+_H3_REF_BASE_SIBLINGS = _H3_BASE_SIBLINGS + [
+ # What marks the repo as the modular workflow, and so what makes the partition split real.
+ _PlanSibling("modular_model_index.json", 1),
+ _PlanSibling("transformer_ref/config.json", 1),
+ _PlanSibling("transformer_ref/diffusion_pytorch_model-00001-of-00002.safetensors", 40),
+ _PlanSibling("transformer_ref/diffusion_pytorch_model-00002-of-00002.safetensors", 26),
+]
+
+
+def test_download_plan_keeps_the_dense_reference_shards_when_its_artifact_is_absent(monkeypatch):
+ # A task-specific row gets NO filename fallback, so a Ref2VA checkpoint that is renamed or not
+ # yet published resolves to nothing while the repo itself reads fine. The registry still says
+ # the scheme is covered, and dropping transformer_ref/ on that word alone leaves a plan with
+ # neither denoiser: the disk preflight under-reports by 66 GB and an offline stage finishes
+ # with nothing for the documented bf16 fallback to open.
+ _cuda_bf16_target(monkeypatch)
+ _plan_api(
+ monkeypatch,
+ {
+ "MiniMaxAI/MiniMax-H3": _H3_REF_BASE_SIBLINGS,
+ # Only the keyframe artifacts; the reference ones are missing.
+ "unsloth/MiniMax-H3-FP8": _H3_PREQUANT_SIBLINGS,
+ },
+ )
+
+ plan = VideoBackend().download_plan(
+ "MiniMaxAI/MiniMax-H3",
+ family_override = "minimax-h3",
+ model_kind = "pipeline",
+ transformer_quant = "fp8",
+ h3_task = "ref2va",
+ )
+
+ by_repo = {entry["repo_id"]: entry for entry in plan["entries"]}
+ # No entry may be invented for a file the repo does not have.
+ assert "unsloth/MiniMax-H3-FP8" not in by_repo
+ base = by_repo["MiniMaxAI/MiniMax-H3"]["files"]
+ assert "transformer_ref/diffusion_pytorch_model-00001-of-00002.safetensors" in base
+ assert "transformer_ref/diffusion_pytorch_model-00002-of-00002.safetensors" in base
+ assert plan["total_bytes"] == sum(e["bytes"] for e in plan["entries"])
+
+
+def test_download_plan_still_drops_the_reference_shards_its_artifact_replaces(monkeypatch):
+ # The other half of the gate: once the Ref2VA artifact really resolves, the dense reference
+ # shards leave the base entry and the checkpoint is staged in their place.
+ _cuda_bf16_target(monkeypatch)
+ _plan_api(
+ monkeypatch,
+ {
+ "MiniMaxAI/MiniMax-H3": _H3_REF_BASE_SIBLINGS,
+ "unsloth/MiniMax-H3-FP8": _H3_PREQUANT_SIBLINGS
+ + [_PlanSibling("MiniMax-H3-Ref2VA-FP8.pt", 20)],
+ },
+ )
+
+ plan = VideoBackend().download_plan(
+ "MiniMaxAI/MiniMax-H3",
+ family_override = "minimax-h3",
+ model_kind = "pipeline",
+ transformer_quant = "fp8",
+ h3_task = "ref2va",
+ )
+
+ by_repo = {entry["repo_id"]: entry for entry in plan["entries"]}
+ assert by_repo["unsloth/MiniMax-H3-FP8"]["files"] == ["MiniMax-H3-Ref2VA-FP8.pt"]
+ base = by_repo["MiniMaxAI/MiniMax-H3"]["files"]
+ assert not any(f.startswith("transformer_ref/diffusion_pytorch_model") for f in base)
+ assert "transformer_ref/config.json" in base
assert plan["total_bytes"] == sum(e["bytes"] for e in plan["entries"])
@@ -2697,22 +2837,6 @@ def test_download_plan_adds_no_prequant_entry_without_a_scheme(monkeypatch):
)
-def test_a_quantized_reference_load_is_refused_rather_than_run_on_the_wrong_partition():
- # The hosted checkpoints are FL2VA denoisers. Ref2VA shares their module shapes and base
- # model, so one installs cleanly, passes every metadata check, and makes load_components skip
- # the real Ref2VA transformer: the request generates from the keyframe partition instead of
- # failing. There is no in-place quantise seam to fall back on, so this has to be a refusal.
- backend = VideoBackend()
- with pytest.raises(ValueError, match = "reference video"):
- backend.validate_load_request(
- "MiniMaxAI/MiniMax-H3",
- family_override = "minimax-h3",
- model_kind = "pipeline",
- transformer_quant = "int8",
- h3_task = "ref2va",
- )
-
-
def test_direct_h3_native_load_uses_sd_cpp_path(monkeypatch):
backend = VideoBackend()
calls = []
@@ -4580,6 +4704,117 @@ def test_h3_modular_load_pins_a_hosted_prequant_denoiser_out_of_the_offload_rota
assert "pinned" not in calls
+def test_h3_modular_load_seeds_the_partition_its_workflow_denoises_against(monkeypatch):
+ """One repo, two partitions, two component names.
+
+ ref2va's denoise step reads ``transformer_ref``; fl2va (and text-only through it) reads
+ ``transformer``. Seeding the wrong attribute is silent in both directions: the block finds no
+ denoiser where it looks, and ``load_components`` then fetches the dense 66.28 GB partition the
+ seed existed to replace. The offload pin has to follow the same name, or a pre-quantized
+ denoiser stays in the rotation and dies mid-block on its first move.
+ """
+ import types
+
+ from core.inference.video import VideoBackend
+
+ calls: dict = {}
+
+ class _FakeModularPipeline:
+ @classmethod
+ def from_pretrained(cls, repo, **kwargs):
+ return cls()
+
+ def load_components(self, **kwargs):
+ calls["workflow"] = kwargs.get("workflow")
+
+ def update_components(self, **kwargs):
+ calls.setdefault("seeded", {}).update(kwargs)
+ for name, value in kwargs.items():
+ setattr(self, name, value)
+
+ def to(self, device):
+ return self
+
+ manager = types.SimpleNamespace(enable_auto_cpu_offload = lambda **kwargs: None)
+ diffusers = types.SimpleNamespace(
+ ComponentsManager = lambda: manager,
+ ModularPipeline = _FakeModularPipeline,
+ MiniMaxH3Transformer3DModel = object,
+ )
+ torch = types.SimpleNamespace(bfloat16 = "bf16")
+ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")
+
+ seeded = object()
+ import core.inference.diffusion_prequant as prequant_module
+
+ monkeypatch.setattr(
+ prequant_module,
+ "load_prequantized_transformer",
+ lambda *args, **kwargs: calls.setdefault("loader_kwargs", kwargs) and seeded or seeded,
+ )
+ monkeypatch.setattr(
+ prequant_module,
+ "pin_prequantized_module",
+ lambda mgr, module, device, **kwargs: calls.setdefault("pinned", module) is not None,
+ )
+
+ def load(task):
+ calls.clear()
+ return VideoBackend()._load_h3_modular_pipeline(
+ diffusers = diffusers,
+ torch = torch,
+ fam = fam,
+ repo_id = "MiniMaxAI/MiniMax-H3",
+ base = fam.base_repo,
+ kind = "pipeline",
+ dtype = torch.bfloat16,
+ device = "cuda",
+ hf_token = None,
+ memory_mode = None,
+ transformer_quant = "int8",
+ h3_task = task,
+ _load_token = None,
+ _base_local_dir = None,
+ )
+
+ status = load("ref2va")
+ assert status["transformer_quant"] == "int8"
+ assert calls["workflow"] == "ref2va"
+ assert calls["seeded"] == {"transformer_ref": seeded}
+ assert calls["pinned"] is seeded
+ # The config comes from the same partition, because that is the only one the scoped download
+ # stages for this task.
+ assert calls["loader_kwargs"]["config_subfolder"] == "transformer_ref"
+
+ status = load("fl2va")
+ assert status["transformer_quant"] == "int8"
+ assert calls["seeded"] == {"transformer": seeded}
+ assert calls["loader_kwargs"]["config_subfolder"] == "transformer"
+
+
+def test_denoiser_prequant_coverage_is_asked_per_partition():
+ # The dense-shard skip is only safe when a checkpoint really covers THIS task. A scheme whose
+ # only hosted artifact belongs to the other partition covers nothing, and answering yes would
+ # drop the very shards the load then has to open.
+ from core.inference.video_families import VideoFamily
+
+ fam = VideoFamily(
+ name = "partitioned",
+ pipeline_class = "P",
+ transformer_class = "T",
+ base_repo = "org/partitioned",
+ modular_workflow = "fl2va",
+ prequant_repos = (("int8", "unsloth/Test-FP8"), ("fp8", "unsloth/Test-FP8")),
+ prequant_filenames = (("fp8", "ref2va", "Test-Ref2VA-FP8.pt"),),
+ prequant_partition_tasks = ("ref2va",),
+ )
+ assert VideoBackend._denoiser_prequant_covered(fam, "int8", None, "fl2va") is True
+ assert VideoBackend._denoiser_prequant_covered(fam, "int8", None, "ref2va") is False
+ assert VideoBackend._denoiser_prequant_covered(fam, "fp8", None, "ref2va") is True
+ # No task named at all keeps the historical per-scheme answer.
+ assert VideoBackend._denoiser_prequant_covered(fam, "int8", None) is True
+
+
def test_h3_native_progress_reads_only_the_denoise_bar(monkeypatch):
# Replay real log shapes to isolate the denoise progress bar.
calls: list = []
@@ -5984,7 +6219,9 @@ def test_the_h3_modular_refusal_reruns_when_the_prequant_checkpoint_does_not_lan
monkeypatch.setattr(
prequant_mod,
"resolve_prequant_source",
- lambda fam, scheme, base_repo = None: types.SimpleNamespace(location = "unsloth/H3-FP8"),
+ lambda fam, scheme, base_repo = None, task = None: types.SimpleNamespace(
+ location = "unsloth/H3-FP8"
+ ),
)
monkeypatch.setattr(prequant_mod, "load_prequantized_transformer", lambda *a, **k: None)
diff --git a/studio/backend/tests/test_video_prequant.py b/studio/backend/tests/test_video_prequant.py
index 6683b1a0f50..d778c628f74 100644
--- a/studio/backend/tests/test_video_prequant.py
+++ b/studio/backend/tests/test_video_prequant.py
@@ -21,6 +21,7 @@ from core.inference.video import VideoBackend
from core.inference.video_families import (
VideoFamily,
detect_video_family,
+ video_family_prequant_available,
video_family_prequant_repo,
video_family_prequant_schemes,
)
@@ -166,6 +167,167 @@ def test_the_names_are_built_from_the_repo_and_the_scheme():
assert resolve_prequant_source(fam, "int8").fallback_filename == "transformer_int8.pt"
+# ── task-keyed artifacts: one repo, one scheme, two denoiser partitions ──────────
+#
+# MiniMax-H3 hosts a keyframe (fl2va, which also covers text-only) and a reference (ref2va)
+# denoiser. They share a class, a config, a 635-key state dict and a base_model_id, so no check
+# downstream can tell them apart: the TASK is the only thing standing between a reference load and
+# the keyframe weights, and getting it wrong renders plausibly rather than failing.
+
+
+def test_a_task_specific_row_beats_the_task_agnostic_one():
+ fam = _fam(
+ prequant_repos = (("int8", "unsloth/Test-FP8"),),
+ prequant_filenames = (
+ ("int8", "Test-INT8-ConvRot.pt"),
+ ("int8", "ref2va", "Test-Ref2VA-INT8-ConvRot.pt"),
+ ),
+ prequant_partition_tasks = ("ref2va",),
+ )
+ assert resolve_prequant_source(fam, "int8", task = "ref2va").filename == (
+ "Test-Ref2VA-INT8-ConvRot.pt"
+ )
+ # Case and whitespace must not change which partition is picked.
+ assert resolve_prequant_source(fam, "int8", task = " Ref2VA ").filename == (
+ "Test-Ref2VA-INT8-ConvRot.pt"
+ )
+
+
+def test_a_task_specific_artifact_gets_no_filename_fallback():
+ # The fallback exists so an older name still resolves when the preferred one is absent. Here
+ # every other file in the repo is the same family, scheme and base, so a fallback would install
+ # ANOTHER PARTITION's denoiser -- it would pass every check and generate the wrong thing. No
+ # artifact is the correct outcome: the load keeps the released bfloat16 denoiser.
+ fam = _fam(
+ prequant_repos = (("int8", "unsloth/Test-FP8"),),
+ prequant_filenames = (
+ ("int8", "Test-INT8-ConvRot.pt"),
+ ("int8", "ref2va", "Test-Ref2VA-INT8-ConvRot.pt"),
+ ),
+ prequant_partition_tasks = ("ref2va",),
+ )
+ assert resolve_prequant_source(fam, "int8", task = "ref2va").fallback_filename is None
+ # The task-agnostic pick keeps its fallback, unchanged.
+ assert resolve_prequant_source(fam, "int8").fallback_filename == "Test-INT8.pt"
+
+
+def test_a_scheme_without_a_task_row_resolves_exactly_what_it_did_before():
+ # Back-compat, stated as an equality rather than a literal: whatever the task-agnostic lookup
+ # gives, a task the table says nothing about must give the same thing.
+ fam = _fam(
+ prequant_repos = (("int8", "unsloth/Test-FP8"), ("fp8", "unsloth/Test-FP8")),
+ prequant_filenames = (("int8", "Test-INT8-ConvRot.pt"),),
+ )
+ for scheme in ("int8", "fp8"):
+ plain = resolve_prequant_source(fam, scheme)
+ for task in ("fl2va", "t2va", "anything-at-all"):
+ assert resolve_prequant_source(fam, scheme, task = task) == plain
+
+
+def test_a_family_predating_the_task_shape_is_unaffected_by_a_task():
+ # A table written entirely as 2-tuples, asked with a task. It must not raise and must not
+ # change its answer -- the field is free to ignore for every family with one denoiser.
+ import types
+
+ fam = _fam(prequant_repos = (("fp8", "unsloth/Test-FP8"),))
+ assert resolve_prequant_source(fam, "fp8", task = "ref2va") == resolve_prequant_source(fam, "fp8")
+ assert resolve_prequant_source(types.SimpleNamespace(), "fp8", task = "ref2va") is None
+
+
+def test_a_partition_task_with_no_artifact_of_its_own_is_unavailable():
+ # The refusal's whole condition. The scheme HAS a hosted repo, so the old per-scheme question
+ # answers yes; the pair (scheme, task) has nothing, and serving the keyframe file instead is
+ # the failure mode this replaced.
+ fam = _fam(
+ prequant_repos = (("int8", "unsloth/Test-FP8"), ("fp8", "unsloth/Test-FP8")),
+ prequant_filenames = (("fp8", "ref2va", "Test-Ref2VA-FP8.pt"),),
+ prequant_partition_tasks = ("ref2va",),
+ )
+ assert video_family_prequant_repo(fam, "int8") == "unsloth/Test-FP8"
+ assert video_family_prequant_available(fam, "int8", task = "ref2va") is False
+ assert video_family_prequant_available(fam, "fp8", task = "ref2va") is True
+ # Not a partition task, so the artifact-per-task rule does not apply.
+ assert video_family_prequant_available(fam, "int8", task = "fl2va") is True
+ assert video_family_prequant_available(fam, "int8") is True
+ # And the refusal message names only what actually works for that task.
+ assert video_family_prequant_schemes(fam, task = "ref2va") == ("fp8",)
+ assert video_family_prequant_schemes(fam) == ("int8", "fp8")
+
+
+ "scheme, expected",
+ [("int8", "MiniMax-H3-Ref2VA-INT8-ConvRot.pt"), ("fp8", "MiniMax-H3-Ref2VA-FP8.pt")],
+)
+def test_h3_reference_video_resolves_its_own_hosted_denoiser(scheme, expected):
+ fam = detect_video_family("MiniMaxAI/MiniMax-H3")
+ src = resolve_prequant_source(fam, scheme, task = "ref2va")
+ assert src.filename == expected
+ assert src.fallback_filename is None
+ assert "/" not in src.filename and "\\" not in src.filename
+
+
[email protected]("task", [None, "fl2va", "t2va"])
+def test_h3_keyframe_and_text_only_resolve_exactly_what_they_resolved_before(task):
+ # The published fl2va artifacts must not move: the rotated INT8 by name (with the plain one
+ # still its fallback for older installs) and FP8 by the derived repo-root name.
+ fam = detect_video_family("MiniMaxAI/MiniMax-H3")
+ int8 = resolve_prequant_source(fam, "int8", task = task)
+ assert int8.filename == "MiniMax-H3-INT8-ConvRot.pt"
+ assert int8.fallback_filename == "MiniMax-H3-INT8.pt"
+ fp8 = resolve_prequant_source(fam, "fp8", task = task)
+ assert fp8.filename == "MiniMax-H3-FP8.pt"
+
+
+def test_the_h3_partition_task_matches_the_reference_workflow_name():
+ # The registry spells the task as a literal to stay import-free; pin it to the constant the
+ # loader and the download planner branch on, so the two cannot drift apart silently.
+ from core.inference.video_minimax_h3 import H3_TASK_REFERENCES
+ fam = detect_video_family("MiniMaxAI/MiniMax-H3")
+ assert fam.prequant_partition_tasks == (H3_TASK_REFERENCES,)
+
+
+def test_a_reference_load_is_refused_when_its_scheme_has_no_reference_artifact(monkeypatch):
+ # The refusal is now conditional, not blanket, so it needs a family where the pair genuinely
+ # does not exist. int8 here has the repo but only a keyframe artifact.
+ fam = _fam(
+ name = "partitioned",
+ modular_workflow = "fl2va",
+ prequant_repos = (("int8", "unsloth/Test-FP8"), ("fp8", "unsloth/Test-FP8")),
+ prequant_filenames = (("fp8", "ref2va", "Test-Ref2VA-FP8.pt"),),
+ prequant_partition_tasks = ("ref2va",),
+ )
+ monkeypatch.setattr("core.inference.video._detect_load_family", lambda *a, **k: fam)
+ monkeypatch.setattr("core.inference.video._is_trusted_video_repo", lambda repo: True)
+ backend = VideoBackend()
+ with pytest.raises(ValueError) as excinfo:
+ backend.validate_load_request(
+ "org/test-video",
+ model_kind = "pipeline",
+ transformer_quant = "int8",
+ h3_task = "ref2va",
+ )
+ message = str(excinfo.value)
+ assert "int8" in message and "ref2va" in message
+ # It says what to use instead, and does NOT advertise the scheme that only covers the other
+ # partition.
+ assert "fp8" in message
+ # The pair that DOES exist is not refused. Asserted on the message rather than on success:
+ # this synthetic family names a pipeline class the diffusers probe further down cannot find,
+ # and that unrelated failure must neither mask a regression nor pass this test for the wrong
+ # reason.
+ try:
+ backend.validate_load_request(
+ "org/test-video",
+ model_kind = "pipeline",
+ transformer_quant = "fp8",
+ h3_task = "ref2va",
+ )
+ except Exception as exc: # noqa: BLE001
+ assert "transformer_quant" not in str(
+ exc
+ ), f"fp8 ref2va should be loadable but was refused: {exc}"
+
+
# ── validate_load_request: refuse BEFORE the download ────────────────────────────
def test_a_modular_family_refuses_a_single_file_load_before_anything_downloads():
# Previously this reached the loader only after ~98.7 GB had downloaded AND after the resident
diff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.py
index 263842685c8..8abd0528be7 100644
--- a/studio/backend/tests/test_video_routes.py
+++ b/studio/backend/tests/test_video_routes.py
@@ -1327,11 +1327,15 @@ def test_video_download_plan_refuses_an_unavailable_transformer_quant(client, mo
def test_video_download_plan_refuses_a_quantized_reference_task(client, monkeypatch):
- # One of the quant-keyed refusals is task-keyed: the hosted pre-quantized H3 checkpoints are
- # fl2va denoisers, so a quantized ref2va would seed the wrong partition. Validation only sees
- # that when the route forwards h3_task, and this is the route that stages the download -- so
- # without it the plan pulls the 66 GB dense transformer_ref/ AND the incompatible fl2va quant
- # before /video/load rejects the identical request.
+ # One of the quant-keyed refusals is task-keyed: a pre-quantized H3 denoiser belongs to ONE
+ # partition, so a scheme whose only artifact is the keyframe one must not be seeded into the
+ # reference workflow. Validation only sees the task when the route forwards h3_task, and this
+ # is the route that stages the download -- so without it the plan pulls the 66 GB dense
+ # transformer_ref/ AND the wrong-partition quant before /video/load rejects the same request.
+ # nvfp4 stands in for that pair here: int8 and fp8 both ship a reference artifact now, so
+ # neither is refused any more (test_a_quantized_reference_load_resolves_the_reference_denoiser
+ # in test_video_backend.py pins that), and the per-scheme table in test_video_prequant.py
+ # covers a family where the pair itself is missing.
backend = video_module.get_video_backend()
monkeypatch.setattr(
backend,
@@ -1351,16 +1355,16 @@ def test_video_download_plan_refuses_a_quantized_reference_task(client, monkeypa
json = {
"model_path": "MiniMaxAI/MiniMax-H3",
"model_kind": "pipeline",
- "transformer_quant": "fp8",
+ "transformer_quant": "nvfp4",
"h3_task": "ref2va",
},
)
assert resp.status_code == 400
detail = resp.json()["detail"]
- assert "fp8" in detail
+ assert "nvfp4" in detail
# Naming the way out, not just the dead end.
- assert "keyframe" in detail
+ assert "int8" in detail and "fp8" in detail
def test_video_download_plan_hands_the_h3_task_to_validation(client, monkeypatch):