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.

Report the precision actually in use, and refuse an explicit one we cannot honor (#8165)

Daniel Han39147e4b68a5
diff --git a/scripts/image_speedmem_bench.py b/scripts/image_speedmem_bench.py
index 1df7e34b03f..63bb4210567 100644
--- a/scripts/image_speedmem_bench.py
+++ b/scripts/image_speedmem_bench.py
@@ -199,9 +199,10 @@ def _apply_levers(
engaged: dict[str, Any] = {"te": None, "attn": None, "cache": None, "speed_optims": {}}
if cfg["te"] != "none":
+ # Returns (mode, reason, status) now; this bench only reports the mode that engaged.
engaged["te"] = quantize_text_encoders(
pipe, tgt, mode = cfg["te"], family = fam_obj.name, logger = logger
- )
+ ).mode
speed_mode = cfg["speed"]
engaged["attn"] = apply_attention_backend(
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index c7c59274a88..1bf8e83f144 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -112,7 +112,14 @@ from .diffusion_cache import (
maybe_toggle_step_cache,
normalize_transformer_cache,
)
-from .diffusion_precision import normalize_te_quant, quantize_text_encoders
+from .diffusion_precision import (
+ effective_te_quant,
+ normalize_te_quant,
+ quantize_text_encoders,
+ te_quant_needs_resident_weights,
+ te_quant_supported,
+ torchao_quantize_importable,
+)
from .diffusion_te_prequant import te_prequant_pipe_kwargs
from .diffusion_prequant import (
load_prequantized_transformer,
@@ -121,14 +128,20 @@ from .diffusion_prequant import (
usable_prequant_source,
)
from .diffusion_auto_policy import (
+ RESOLVED_APPLIED,
+ RESOLVED_FELL_BACK,
+ RESOLVED_UNSUPPORTED,
build_resolved_record,
family_bf16_components_gb,
+ precision_fallback_allowed,
+ precision_refusal_message,
resolve_dense_quant_candidate,
)
from .diffusion_transformer_quant import (
TQ_AUTO,
DEFAULT_MIN_LINEAR_FEATURES,
dense_transformer_supported,
+ explain_unusable_scheme,
normalize_transformer_quant,
quantize_transformer,
select_transformer_quant_scheme,
@@ -845,6 +858,19 @@ def _uncached_prequant_repo(
return None
+def _memory_request_forces_offload(memory_mode: Optional[str], cpu_offload: bool) -> bool:
+ """Whether this memory request offloads the transformer no matter what the weights measure.
+
+ ``balanced`` and ``low_vram`` name their policy outright in ``resolve_offload_policy``, and
+ the legacy ``cpu_offload`` flag forces whole-module offload when no mode was supplied.
+ ``fast`` and ``auto`` are decided from the measured footprint, so they are not knowable here.
+ """
+ mode = normalize_memory_mode(memory_mode)
+ if mode in (MEMORY_MODE_BALANCED, MEMORY_MODE_LOW_VRAM):
+ return True
+ return mode is None and bool(cpu_offload)
+
+
class DiffusionBackend:
"""Holds at most one loaded diffusers pipeline. All mutations are serialised."""
@@ -883,6 +909,128 @@ class DiffusionBackend:
target = resolve_diffusion_device_target()
return target.device, target.dtype
+ # Memory requests whose offload policy is decided by the REQUEST rather than by the measured
+ # footprint. `fast` and `auto` are measurements and so cannot be judged network-free.
+ def assert_precision_available(
+ self,
+ fam: Optional[DiffusionFamily],
+ *,
+ model_kind: str,
+ transformer_quant: Optional[str] = None,
+ text_encoder_quant: Optional[str] = None,
+ memory_mode: Optional[str] = None,
+ cpu_offload: bool = False,
+ ) -> None:
+ """Raise ``RuntimeError`` (the route's 409) when an EXPLICIT precision cannot run here.
+
+ Only the host-level impossibilities, which are knowable network-free: the wrong load kind,
+ a device with no dense-quant path, and a scheme this GPU or family rules out. Anything
+ needing the measured footprint is decided inside ``load_pipeline``. ``auto`` is never
+ refused -- delegating the choice is exactly what it means.
+
+ Public because the ROUTE has to make this call itself, before it takes the GPU: the copy
+ in ``begin_load`` runs inside ``acquire_for``, which evicts chat under the arbiter lock
+ before the register callback, and after ``select_and_activate_engine``, which unloads the
+ resident model on an engine switch."""
+ if precision_fallback_allowed():
+ return
+ pinned = normalize_transformer_quant(transformer_quant)
+ te_mode = normalize_te_quant(text_encoder_quant)
+ if pinned is None and te_mode is None:
+ return
+ # One probe for both checks (it reads the live device).
+ target = self._resolve_device_target(fam)
+ if pinned is not None and pinned != TQ_AUTO:
+ reason = None
+ if model_kind != "gguf":
+ reason = (
+ f"the dense transformer-quant path applies to GGUF picks only, and this is a "
+ f"'{model_kind}' load, which runs the precision its checkpoint carries"
+ )
+ elif _memory_request_forces_offload(memory_mode, cpu_offload):
+ # Not a measurement: balanced and low_vram name their policy outright, and the
+ # legacy flag forces model offload. Offload hooks move modules with Module.to(),
+ # which torchao tensors do not survive, so the loader skips the dense build for
+ # any of them -- and the strict refusal then landed after the resident model was
+ # already gone. The two requests are incompatible on their face; say so here.
+ requested_memory = normalize_memory_mode(memory_mode) or "cpu_offload"
+ reason = (
+ f"'{requested_memory}' memory places the transformer under CPU offload, and "
+ "torchao quantised tensors cannot be moved by the offload hooks, so the dense "
+ "quant is skipped"
+ )
+ elif not dense_transformer_supported(target):
+ reason = (
+ "this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16)"
+ )
+ elif (
+ select_transformer_quant_scheme(
+ target,
+ pinned,
+ family = getattr(fam, "name", None),
+ # This gate runs BEFORE the arbiter evicts the resident model, so a smoke probe
+ # that runs out of VRAM here has not shown the scheme unusable, only that the
+ # GPU is still full. Refusing on that would reject a load the eviction was
+ # about to make room for.
+ unproven_ok = True,
+ )
+ is None
+ ):
+ # An explicit scheme is never swapped for another, so a None means the family's
+ # measured deny list, a torchao that cannot run here, or a GPU without the kernels.
+ # They read the same to the selector and need different fixes from the user.
+ reason = explain_unusable_scheme(getattr(fam, "name", None), pinned)
+ if reason is not None:
+ raise RuntimeError(
+ precision_refusal_message(
+ "transformer_quant",
+ pinned,
+ reason,
+ off_label = "Off to run the checkpoint as-is",
+ )
+ )
+ # The mode the loader will ACTUALLY attempt, not the raw request: an explicit int8
+ # on a family with no keep-bf16 schedule is rewritten to layerwise fp8 before
+ # support is consulted, and that path needs no torchao. Refusing on the raw int8
+ # rejected loads the runtime would run and report as fell_back -- Windows ROCm,
+ # where the torchao stub kills int8 while fp8 still works.
+ te_effective = effective_te_quant(te_mode, getattr(fam, "name", None))
+ te_reason = None
+ if te_quant_needs_resident_weights(te_effective) and not torchao_quantize_importable():
+ # The casters import torchao only after the pipeline is downloaded and built, so a
+ # broken or absent install failed through load-progress instead of this 409.
+ te_reason = (
+ "torchao is not importable on this install, and these encoder modes are torchao "
+ "quantisations"
+ )
+ elif te_effective is not None and not te_quant_supported(target, te_effective):
+ te_reason = (
+ "this device does not have the tensor cores that backend needs (a CUDA GPU in "
+ "bf16, plus fp8 / int8 / NVFP4 support depending on the mode)"
+ )
+ elif te_quant_needs_resident_weights(te_effective) and _memory_request_forces_offload(
+ memory_mode, cpu_offload
+ ):
+ # Same fence as the dense transformer above, on the encoder: offload hooks move
+ # modules with Module.to(), torchao tensors do not survive it, and the loader reports
+ # those modes unsupported once offload is active -- after the resident pipeline is
+ # already gone. Layerwise fp8 is a dtype cast and is unaffected.
+ requested_memory = normalize_memory_mode(memory_mode) or "cpu_offload"
+ te_reason = (
+ f"'{requested_memory}' memory places the text encoder under CPU offload, and "
+ "torchao quantised tensors cannot be moved by the offload hooks"
+ )
+ if te_reason is not None:
+ raise RuntimeError(
+ precision_refusal_message(
+ "text_encoder_quant",
+ te_mode,
+ te_reason,
+ off_label = "leave it unset to keep the dense bf16 encoder",
+ auto_available = False,
+ )
+ )
+
def _resolve_device_target(self, fam: Optional[DiffusionFamily]) -> DiffusionDeviceTarget:
"""The device target with the family fp16 guard applied.
@@ -1248,6 +1396,16 @@ class DiffusionBackend:
family_override = family_override,
model_kind = model_kind,
)
+ # Refuse an EXPLICIT precision this host can never honor BEFORE the load starts, so the
+ # route answers 409 with the reason instead of evicting the resident model, downloading
+ # several GB and only then failing. The declines that need the real footprint (a VRAM
+ # misfit, a failed build) can only be found mid-load and surface through load-progress.
+ self.assert_precision_available(
+ fam,
+ model_kind = resolve_model_kind(gguf_filename, model_kind),
+ transformer_quant = transformer_quant,
+ text_encoder_quant = text_encoder_quant,
+ )
with self._lock:
# Allow starting over a previously-failed load, but not over a live one.
@@ -2135,6 +2293,9 @@ class DiffusionBackend:
fetch_base = fetch_base,
)
+ # The caller's RAW request, captured before the tri-state below rewrites it: status
+ # has to be able to say "you asked for fp8" long after the loader declined it.
+ transformer_quant_requested = transformer_quant
# Dtype tri-state: unset/"auto" -> hardware ladder; "none"/"off" pins GGUF-as-is; an explicit scheme pins it.
transformer_quant_auto = transformer_quant is None or str(
transformer_quant
@@ -2145,11 +2306,52 @@ class DiffusionBackend:
speed_mode is not None and str(speed_mode).strip().lower() == SPEED_OFF
)
transformer_quant = "off" if speed_off else TQ_AUTO
+ # The one case that must fail closed: a named scheme (not auto, not off). Normalized
+ # here so "FP8" and "fp8" refuse identically; a bogus value already raised above.
+ transformer_quant_pinned = (
+ None
+ if transformer_quant_auto
+ else normalize_transformer_quant(transformer_quant_requested)
+ )
# Default-on fast path (GGUF kind only): dense bf16 + torchao quant beats GGUF per-matmul dequant on speed AND quality. Needs CUDA + bf16 + a resident fit.
pipe = None
transformer_quant_engaged = None
quant_plan = None
+ # Why the dense quant did not engage, in the caller's terms. Threaded into
+ # `resolved` so a fallback is visible, and into the refusal so it is actionable.
+ transformer_quant_decline: Optional[str] = None
+ transformer_quant_decline_status = RESOLVED_FELL_BACK
+ if transformer_quant_pinned is not None and kind != "gguf":
+ # The dense fast path replaces a GGUF transformer with a quantised dense build;
+ # the other kinds run the precision their checkpoint already carries, so an
+ # explicit scheme here was accepted and then ignored outright.
+ transformer_quant_decline = (
+ f"the dense transformer-quant path applies to GGUF picks only, and this is "
+ f"a '{kind}' load, which runs the precision its checkpoint carries"
+ )
+ transformer_quant_decline_status = RESOLVED_UNSUPPORTED
+ elif transformer_quant_pinned is not None and not dense_transformer_supported(
+ target
+ ):
+ transformer_quant_decline = (
+ "this device cannot run a dense torchao quant (it needs a CUDA GPU in "
+ "bf16)"
+ )
+ transformer_quant_decline_status = RESOLVED_UNSUPPORTED
+ elif transformer_quant_pinned is not None and (
+ select_transformer_quant_scheme(
+ target, transformer_quant_pinned, family = getattr(fam, "name", None)
+ )
+ is None
+ ):
+ # An explicit scheme is never swapped for another, so a None here means this GPU
+ # (or this family's measured deny list) rules it out.
+ transformer_quant_decline = (
+ f"'{transformer_quant_pinned}' is not usable for family "
+ f"'{getattr(fam, 'name', None)}' on this GPU"
+ )
+ transformer_quant_decline_status = RESOLVED_UNSUPPORTED
# The GGUF-size plan can mis-budget the fast path, so preflight the real footprint pre-eviction. Also set below when an auto quant declines a hosted pre-quant.
dense_declined = False
# False when the plan only holds a PREQUANT-sized build: a failed prequant load must raise, not materialise the
@@ -2178,6 +2380,12 @@ class DiffusionBackend:
uncached_prequant,
)
dense_declined = True
+ # Auto-only branch, so this reason only ever reaches an "Auto: OFF" badge.
+ transformer_quant_decline = (
+ f"the hosted pre-quant checkpoint in {uncached_prequant} is not "
+ "cached, and an auto quant never downloads a second transformer for "
+ "a GGUF pick"
+ )
if (
kind == "gguf"
and normalize_transformer_quant(transformer_quant) is not None
@@ -2196,6 +2404,14 @@ class DiffusionBackend:
force_dense = _has_active_lora(loras),
logger = logger,
)
+ if candidate is None:
+ # No basis to re-plan (no size entry, or the model cache is too full for
+ # the artifact), so the GGUF plan's offload stands and the quant cannot.
+ transformer_quant_decline = (
+ f"the memory plan picked '{plan.offload_policy}' offload and there "
+ "is no quantised candidate to re-plan against on this host (see "
+ "the server log)"
+ )
if candidate is not None:
def _replan_candidate():
@@ -2236,6 +2452,14 @@ class DiffusionBackend:
replanned.offload_policy,
"; ".join(replanned.reasons),
)
+ transformer_quant_decline = (
+ f"the quantised build still needs '{replanned.offload_policy}' "
+ f"offload here ("
+ f"{replanned.estimates.get('resident_required_mib')} MiB "
+ f"required vs a "
+ f"{replanned.estimates.get('safe_device_budget_mib')} MiB "
+ "budget), and torchao tensors cannot be offloaded"
+ )
if replanned.offload_policy == OFFLOAD_NONE:
quant_plan = replanned
# The GGUF plan declined resident; a prequant-sized replan says nothing about the dense build.
@@ -2291,6 +2515,12 @@ class DiffusionBackend:
# No prequant source: a dense misfit skips the fast path; with one, only the dense fallback is forbidden.
if prequant is None:
dense_declined = True
+ transformer_quant_decline = (
+ "the dense bf16 transformer this quant is built from does "
+ f"not fit resident ({dense_mib} MiB; the plan picked "
+ f"'{dense_plan.offload_policy}' offload), and no hosted "
+ "pre-quantised checkpoint is available to build it from"
+ )
if (
kind == "gguf"
and normalize_transformer_quant(transformer_quant) is not None
@@ -2323,6 +2553,13 @@ class DiffusionBackend:
)
pipe = None
transformer_quant_engaged = None
+ # Formatted BEFORE the del below, and redacted: this reaches the client both
+ # as a status tooltip and (for an explicit ask) as the refusal message.
+ from utils.native_path_leases import redact_native_paths
+
+ transformer_quant_decline = redact_native_paths(
+ f"the quantised transformer build failed ({exc})"
+ )
# Drop the exception before clearing the cache: its traceback pins the dense transformer's VRAM.
del exc
# Guarded: a sticky CUDA error can raise; the fallback must reach the GGUF build.
@@ -2349,6 +2586,26 @@ class DiffusionBackend:
"adapters, free VRAM, or pick a smaller model."
)
+ # Fail closed on a declined EXPLICIT precision. Loading the GGUF here produced a
+ # perfectly good image at a precision the caller never asked for, and nothing in
+ # the response said so, which is why a successful render could not be taken as
+ # proof the requested precision ran. `auto` is untouched: falling down the ladder
+ # is what it asks for.
+ if (
+ pipe is None
+ and transformer_quant_pinned is not None
+ and not precision_fallback_allowed()
+ ):
+ raise RuntimeError(
+ precision_refusal_message(
+ "transformer_quant",
+ transformer_quant_pinned,
+ transformer_quant_decline
+ or "the quantised transformer build did not engage on this host",
+ off_label = "Off to run the checkpoint as-is",
+ )
+ )
+
if pipe is None:
if kind == "pipeline":
# Full diffusers repo: from_pretrained pulls every component and re-applies embedded quant config.
@@ -2628,7 +2885,7 @@ class DiffusionBackend:
transformer_quant_engaged,
)
# Quantise the dense companion text encoder(s) before placement so offload moves the smaller weights.
- te_quant = quantize_text_encoders(
+ te_outcome = quantize_text_encoders(
pipe,
target,
mode = text_encoder_quant,
@@ -2636,6 +2893,27 @@ class DiffusionBackend:
offload_active = plan.offload_policy != OFFLOAD_NONE,
logger = logger,
)
+ te_quant = te_outcome.mode
+ # Same contract for the other half of "the requested precision": an explicit
+ # encoder mode that engaged NOTHING leaves a dense bf16 encoder the caller did
+ # not ask for, and a PARTIAL cast leaves a pipeline conditioning off a mixture
+ # of quantised and dense encoders. A mode that engaged something ELSE
+ # (int8 -> fp8) is reported by the badge instead: the encoder IS quantised on
+ # every tower, just not the way asked.
+ if (
+ (te_quant is None or te_outcome.partial)
+ and normalize_te_quant(text_encoder_quant) is not None
+ and not precision_fallback_allowed()
+ ):
+ raise RuntimeError(
+ precision_refusal_message(
+ "text_encoder_quant",
+ normalize_te_quant(text_encoder_quant) or "",
+ te_outcome.reason or "no text encoder could be cast",
+ off_label = "leave it unset to keep the dense bf16 encoder",
+ auto_available = False,
+ )
+ )
# Persistent conditioning cache (UNSLOTH_DIFFUSION_COND_CACHE_DIR): repeated prompts skip the text-encoder
# forward. After the TE quant so the key reflects the encoders that run; ``base`` keys the companion repo.
@@ -2671,18 +2949,41 @@ class DiffusionBackend:
else "requested",
),
"transformer_quant": (
- transformer_quant,
+ # The RAW request, not the tri-state rewrite: an "Auto: OFF" badge
+ # and a declined "FP8" must not look the same.
+ transformer_quant_requested,
transformer_quant_engaged or "off",
- # The None reason matches the load kind (GGUF loaded vs dense kept).
+ # A recorded decline wins: it names WHY, where the generic strings
+ # below only say the GGUF ran.
(
- "not engaged (GGUF transformer loaded)"
- if kind == "gguf"
- else "dense transformer kept unquantized"
+ transformer_quant_decline
+ or (
+ "not engaged (GGUF transformer loaded)"
+ if kind == "gguf"
+ else "dense transformer kept unquantized"
+ )
)
if transformer_quant_engaged is None
else "re-planned resident for the quantised artifact"
if quant_plan is not None
else "engaged on the dense fast path",
+ # Honored when the quant engaged AND when the ask was "off" (a
+ # request NOT to quantise, which the GGUF build satisfies).
+ RESOLVED_APPLIED
+ if transformer_quant_engaged is not None
+ or transformer_quant_pinned is None
+ else transformer_quant_decline_status,
+ ),
+ "text_encoder_quant": (
+ text_encoder_quant,
+ te_quant or "off",
+ te_outcome.reason
+ or (
+ "dense bf16 text encoder(s) loaded"
+ if te_quant is None
+ else "dense text encoder(s) quantised in place"
+ ),
+ te_outcome.status,
),
"attention_backend": (
attention_backend,
@@ -3489,6 +3790,13 @@ class DiffusionBackend:
logger = logger,
)
object.__setattr__(state, "attention_backend", attention_engaged)
+ # Keep the badge in step with the state it describes: the top-level field moved, so leaving
+ # `resolved` on the load-time value would make the panel report an attention backend that is
+ # no longer the one running. Same in-place update as the fields above.
+ if isinstance(state.resolved, dict) and "attention_backend" in state.resolved:
+ entry = dict(state.resolved["attention_backend"])
+ entry["value"] = attention_engaged or "native"
+ object.__setattr__(state, "resolved", {**state.resolved, "attention_backend": entry})
gguf_transformer = state.kind == "gguf" and state.transformer_quant is None
if compile_eligible(target, is_gguf = gguf_transformer, family = state.family):
compile_ctx = compile_cache.begin(
@@ -3960,6 +4268,11 @@ class DiffusionBackend:
"model_kind": state.kind,
"gguf_filename": state.gguf_filename,
"transformer_quant": state.transformer_quant,
+ # Read off the ENGAGED state, never the request: a recipe that claimed a
+ # precision the load declined is the same lie the status badges just fixed.
+ "text_encoder_quant": state.text_encoder_quant,
+ "memory_mode": state.memory_mode,
+ "offload_policy": state.offload_policy,
# Adapters baked in at LOAD time: disabling them at generate time is not the same build, so they belong to the build record.
"baked_loras": _baked_lora_names(state.pipe),
# The adapters ACTUALLY attached, at non-zero weight, for this generation.
diff --git a/studio/backend/core/inference/diffusion_auto_policy.py b/studio/backend/core/inference/diffusion_auto_policy.py
index c03c69b96df..f7a67c91040 100644
--- a/studio/backend/core/inference/diffusion_auto_policy.py
+++ b/studio/backend/core/inference/diffusion_auto_policy.py
@@ -239,22 +239,114 @@ def resolve_dense_quant_candidate(
return estimate
+# ── strict precision (fail closed on a declined EXPLICIT request) ────────────
+# An `auto` precision is a delegation, so falling back down the ladder is the feature working. An
+# EXPLICIT scheme is a contract: silently loading the GGUF (or a dense bf16 DiT) instead produced a
+# perfectly good image at a precision nobody asked for, which is exactly what made a successful
+# render worthless as proof that the requested precision ran. Escape hatch for anyone who relied on
+# the old behaviour; unset (the default) fails closed.
+_PRECISION_FALLBACK_ENV = "UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK"
+
+
+def precision_fallback_allowed() -> bool:
+ """Whether a declined EXPLICIT precision request may fall back silently (opt-in)."""
+ value = str(os.environ.get(_PRECISION_FALLBACK_ENV, "")).strip().lower()
+ return value in ("1", "true", "yes", "on")
+
+
+def precision_refusal_message(
+ control: str,
+ requested: str,
+ reason: str,
+ *,
+ off_label: str,
+ auto_available: bool = True,
+) -> str:
+ """The client-facing refusal for a declined explicit precision: what was asked, why it could
+ not run, and the settings that always work. ``off_label`` names this backend's "run the
+ checkpoint as-is" option, which differs between the image and video loaders.
+
+ ``auto_available`` is False for controls with no auto mode. ``text_encoder_quant`` is one:
+ both request models restrict it to fp8 / fp8_dynamic / int8 / nvfp4, so a user who followed a
+ "Choose Auto" instruction there got a 422 from request validation instead of a working load."""
+ remedy = (
+ "Choose Auto to let the backend pick the fastest precision this host can run, "
+ f"or {off_label}."
+ if auto_available
+ else f"{off_label[:1].upper()}{off_label[1:]}."
+ )
+ return f"{control}='{requested}' could not be used: {reason}. {remedy}"
+
+
# ── resolved-record (status surface) ─────────────────────────────────────────
-def build_resolved_record(
- controls: dict[str, tuple[Optional[Any], Any, str]],
-) -> dict[str, dict[str, Any]]:
+# How the engaged value relates to what the caller asked for. Additive on the status payload: every
+# honored request and every auto decision reports "applied", so a client that ignores the field sees
+# exactly today's behaviour.
+RESOLVED_APPLIED = "applied" # the ask was honored (or there was no ask)
+RESOLVED_FELL_BACK = "fell_back" # an explicit ask was declined and something ELSE engaged
+RESOLVED_UNSUPPORTED = "unsupported" # an explicit ask cannot run on this host / model at all
+
+# Requests that mean "do not engage this control", so an "off" engagement HONORS them.
+_RESOLVED_OFF_VALUES = frozenset({"", "none", "off", "false", "0"})
+
+# Controls whose REQUEST and ENGAGED value share one vocabulary, so a mismatch is derivable here
+# rather than trusted from the call site (a decline site that forgets to classify itself still
+# reports the truth). memory_mode is deliberately absent: it requests a MODE ("low_vram") and
+# engages an offload POLICY ("sequential"), so comparing the two would report every honored
+# request as a fallback. attention_backend is absent for the same reason ("cudnn" engages as
+# "_native_cudnn").
+_RESOLVED_COMPARABLE = frozenset({"transformer_quant", "text_encoder_quant"})
+
+
+def _resolved_norm(value: Any) -> str:
+ """A control value folded to its comparison key; every "off" spelling folds to ""."""
+ if value is None:
+ return ""
+ text = str(value).strip().lower().replace("-", "_")
+ return "" if text in _RESOLVED_OFF_VALUES else text
+
+
+def _resolved_values_match(explicit: Any, engaged: Any) -> bool:
+ """Whether ``engaged`` is what ``explicit`` asked for (cpu_offload compares as a boolean)."""
+ if isinstance(explicit, bool) or isinstance(engaged, bool):
+ return bool(explicit) == bool(engaged)
+ return _resolved_norm(explicit) == _resolved_norm(engaged)
+
+
+def build_resolved_record(controls: dict[str, tuple]) -> dict[str, dict[str, Any]]:
"""The per-control ``resolved`` record for status: engaged value + provenance.
- ``controls`` maps a control name to ``(explicit, engaged, reason)``, where ``explicit`` is the
- raw request (None / "" / "auto" = left to the backend). Rendered as an "Auto: X" badge."""
+ ``controls`` maps a control name to ``(explicit, engaged, reason)`` or
+ ``(explicit, engaged, reason, status)``, where ``explicit`` is the raw request
+ (None / "" / "auto" = left to the backend) and ``status`` is one of the ``RESOLVED_*``
+ constants (omit it to let this derive one).
+
+ Each entry carries BOTH sides of the story: ``requested`` (what the caller asked for, verbatim,
+ ``null`` when they left it to us) and ``value`` (what actually engaged), plus the ``status``
+ saying whether those agree. A successful load whose requested precision was declined therefore
+ stays visible instead of being erased into a bare ``source: "explicit"``, which rendered no
+ badge at all while the dropdown kept advertising the request."""
record: dict[str, dict[str, Any]] = {}
- for name, (explicit, engaged, reason) in controls.items():
+ for name, entry in controls.items():
+ explicit, engaged, reason = entry[0], entry[1], entry[2]
+ status = entry[3] if len(entry) > 3 else None
left_to_backend = explicit is None or (
isinstance(explicit, str) and explicit.strip().lower() in ("", "auto")
)
+ if left_to_backend:
+ # The backend chose it, so there is nothing to decline: this is the "Auto: X" badge.
+ status = RESOLVED_APPLIED
+ elif status is None:
+ status = (
+ RESOLVED_FELL_BACK
+ if name in _RESOLVED_COMPARABLE and not _resolved_values_match(explicit, engaged)
+ else RESOLVED_APPLIED
+ )
record[name] = {
"value": engaged,
+ "requested": None if left_to_backend else explicit,
"source": "auto" if left_to_backend else "explicit",
+ "status": status,
"reason": reason,
}
return record
diff --git a/studio/backend/core/inference/diffusion_precision.py b/studio/backend/core/inference/diffusion_precision.py
index 859c3ea5f7c..52bb1cc6b1c 100644
--- a/studio/backend/core/inference/diffusion_precision.py
+++ b/studio/backend/core/inference/diffusion_precision.py
@@ -25,9 +25,17 @@ the quality cost with scripts/diffusion_quality.py. torch / diffusers / torchao
from __future__ import annotations
-from typing import Any, Optional
+from typing import Any, NamedTuple, Optional
+
+from .diffusion_auto_policy import (
+ RESOLVED_APPLIED,
+ RESOLVED_FELL_BACK,
+ RESOLVED_UNSUPPORTED,
+)
# stdlib-only module (no torch), so this stays inside the "imported lazily" promise above.
+from functools import lru_cache
+
from core._torchao_stub import is_stubbed
TE_QUANT_FP8 = "fp8"
@@ -67,6 +75,49 @@ def normalize_te_quant(value: Optional[str]) -> Optional[str]:
return normalized
+def effective_te_quant(mode: Optional[str], family: Optional[str]) -> Optional[str]:
+ """The text-encoder mode ``quantize_text_encoders`` will ACTUALLY attempt for ``family``.
+
+ An explicit int8 on a family with no keep-bf16 schedule is rewritten to layerwise fp8
+ before support is ever consulted -- a documented downgrade that reports ``fell_back`` and
+ needs no torchao. A caller that asks ``te_quant_supported`` about the raw request therefore
+ refuses loads the runtime would run: on Windows ROCm the torchao stub makes int8
+ unsupported while fp8 still works.
+ """
+ normalized = normalize_te_quant(mode)
+ if normalized == TE_QUANT_INT8 and _TE_INT8_SKIP.get((family or "").lower()) is None:
+ return TE_QUANT_FP8
+ return normalized
+
+
+def te_quant_needs_resident_weights(mode: Optional[str]) -> bool:
+ """Whether ``mode`` is a torchao text-encoder cast, which CPU offload rules out.
+
+ Offload hooks move modules with ``Module.to()``, which torchao's tensor subclasses do not
+ survive, so ``quantize_text_encoders`` reports those modes unsupported once offload is
+ active. Plain layerwise fp8 is a dtype cast and is unaffected.
+ """
+ return mode in _TE_TORCHAO_MODES
+
+
+@lru_cache(maxsize = 1)
+def torchao_quantize_importable() -> bool:
+ """Whether ``torchao.quantization.quantize_`` is really there and really torchao's.
+
+ The casters import it only after the pipeline has been downloaded and built, so a broken or
+ absent install failed through load-progress rather than the pre-load 409 the strict contract
+ promises. The pre-handoff gates ask this so the refusal arrives before the download.
+ ``is_stubbed`` covers the Windows-ROCm stub, whose quantize_ is a no-op that would otherwise
+ report the mode applied against an untouched bf16 encoder. Cached: the answer cannot change
+ inside a process, and the gate runs on every load.
+ """
+ try:
+ from torchao.quantization import quantize_ # noqa: F401
+ except Exception: # noqa: BLE001 -- absent, broken build, missing native symbol
+ return False
+ return not is_stubbed("torchao")
+
+
def te_quant_supported(target: Any, mode: str) -> bool:
"""Whether ``mode`` is usable for ``target``: a CUDA bf16 device plus the tensor-core class
each backend needs -- fp8 dtype (fp8), fp8 GEMM sm_89+ (fp8_dynamic), int8 sm_80+ (int8),
@@ -97,6 +148,26 @@ def te_quant_supported(target: Any, mode: str) -> bool:
return False
+class TEQuantOutcome(NamedTuple):
+ """What the text-encoder pass actually did, so status can report it instead of guessing.
+
+ ``mode`` is the quantisation APPLIED (None = the encoders stayed dense bf16), ``reason`` is
+ the short human-readable why when that differs from the request, and ``status`` is one of the
+ ``RESOLVED_*`` constants. Every early return below used to be a bare ``None``: an int8 request
+ silently became fp8, an offloaded load silently kept a dense encoder, and an unsupported GPU
+ returned without so much as a log line.
+
+ ``partial`` is True when SOME encoder took the cast and another did not. The mode did engage,
+ so ``mode`` is not None, but a pipeline conditioning off a mixture of quantised and dense
+ encoders is not the build that was asked for and the loaders refuse it like any other declined
+ explicit precision."""
+
+ mode: Optional[str]
+ reason: str = ""
+ status: str = RESOLVED_APPLIED
+ partial: bool = False
+
+
def quantize_text_encoders(
pipe: Any,
target: Any,
@@ -105,21 +176,27 @@ def quantize_text_encoders(
family: Optional[str] = None,
offload_active: bool = False,
logger: Any = None,
-) -> Optional[str]:
- """Quantise each present text encoder in place with ``mode``. Returns the mode applied, or
- None when disabled, unsupported, or nothing was cast. ``int8`` needs a per-family schedule
- (``_TE_INT8_SKIP``); without one it falls back to ``fp8``. Under ``offload_active`` the torchao
- modes are skipped (their subclasses reject ``Module.to()``); layerwise ``fp8`` still engages.
- Best-effort: any failure leaves the encoder dense."""
+) -> TEQuantOutcome:
+ """Quantise each present text encoder in place with ``mode``. Returns a ``TEQuantOutcome``
+ carrying the mode applied (None when disabled, unsupported, or nothing was cast) plus WHY it
+ differs from the request. ``int8`` needs a per-family schedule (``_TE_INT8_SKIP``); without one
+ it falls back to ``fp8``. Under ``offload_active`` the torchao modes are skipped (their
+ subclasses reject ``Module.to()``); layerwise ``fp8`` still engages. Best-effort: any failure
+ leaves the encoder dense."""
mode = normalize_te_quant(mode)
if mode is None:
- return None
+ return TEQuantOutcome(None)
+ downgrade_reason = ""
skip: Optional[tuple[int, int]] = None
if mode == TE_QUANT_INT8:
skip = _TE_INT8_SKIP.get((family or "").lower())
if skip is None:
_note(logger, f"int8 has no keep-bf16 schedule for family '{family}'; using fp8")
mode = TE_QUANT_FP8
+ downgrade_reason = (
+ f"int8 has no measured keep-bf16 schedule for family '{family}' "
+ "(it degrades large encoders without one), so fp8 was used instead"
+ )
# torchao modes produce subclasses that reject Module.to(), which an offload placement uses. Layerwise fp8 streams fine.
if offload_active and mode in (TE_QUANT_INT8, TE_QUANT_FP8_DYNAMIC, TE_QUANT_NVFP4):
_note(
@@ -127,9 +204,21 @@ def quantize_text_encoders(
f"text-encoder '{mode}' skipped under offload (torchao tensors reject Module.to()); "
"pin a resident memory mode or use fp8",
)
- return None
+ return TEQuantOutcome(
+ None,
+ f"text-encoder '{mode}' cannot run under offload (torchao tensors reject "
+ "Module.to()); pin a resident memory mode, or use fp8",
+ RESOLVED_UNSUPPORTED,
+ )
if not te_quant_supported(target, mode):
- return None
+ # Previously a silent return: the only decline site in the loader with no log at all.
+ _note(logger, f"text-encoder '{mode}' is not supported on this device; left dense")
+ return TEQuantOutcome(
+ None,
+ f"this device cannot run text-encoder '{mode}' (it needs a CUDA GPU in bf16 with the "
+ "tensor cores that backend requires), so the dense bf16 encoder was kept",
+ RESOLVED_UNSUPPORTED,
+ )
if mode == TE_QUANT_INT8:
first, last = skip # type: ignore[misc]
@@ -142,6 +231,7 @@ def quantize_text_encoders(
else:
caster = _cast_fp8
cast: list[str] = []
+ failed: list[str] = []
for attr in _TEXT_ENCODER_ATTRS:
encoder = getattr(pipe, attr, None)
if encoder is None:
@@ -150,8 +240,28 @@ def quantize_text_encoders(
caster(encoder, target)
cast.append(attr)
except Exception as exc: # noqa: BLE001 — leave this encoder dense
+ failed.append(attr)
_warn(logger, f"{mode}:{attr}", exc)
- return mode if cast else None
+ if not cast:
+ return TEQuantOutcome(
+ None,
+ f"no text encoder on this pipeline could be cast to '{mode}' (see the server log)",
+ RESOLVED_FELL_BACK,
+ )
+ if failed:
+ # A sibling took the cast, so `mode` DID engage -- but the encoders that did not are still
+ # dense bf16 and the prompt is conditioned by both. Reporting "applied" here was the one
+ # path where an engaged mode could still be a lie about the build that ran.
+ return TEQuantOutcome(
+ mode,
+ f"'{mode}' engaged on {', '.join(cast)} but {', '.join(failed)} could not be cast and "
+ "stayed dense bf16 (see the server log), so conditioning is a mixture",
+ RESOLVED_FELL_BACK,
+ True,
+ )
+ if downgrade_reason:
+ return TEQuantOutcome(mode, downgrade_reason, RESOLVED_FELL_BACK)
+ return TEQuantOutcome(mode, "dense text encoder(s) quantised in place", RESOLVED_APPLIED)
def _te_exclude_tokens(encoder: Any) -> tuple[str, ...]:
diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.py
index e9189bbf7d2..2391eccc822 100644
--- a/studio/backend/core/inference/diffusion_transformer_quant.py
+++ b/studio/backend/core/inference/diffusion_transformer_quant.py
@@ -23,6 +23,7 @@ probe is best-effort: an unsupported scheme yields None and the caller loads GGU
from __future__ import annotations
+import re as _re
from typing import Any, Optional
# stdlib-only module (no torch), so this stays inside the "imported lazily" promise above.
@@ -139,6 +140,88 @@ def _family_denied(family, scheme: str) -> bool:
return scheme in _FAMILY_SCHEME_DENY.get(str(family or "").strip().lower(), ())
+def family_denies_scheme(family: Optional[str], scheme: str) -> bool:
+ """Whether the measured deny list rules ``scheme`` out for ``family``, regardless of hardware.
+
+ Public so the refusal message can tell the two "no" answers apart. ``select_transformer_quant_scheme``
+ folds a family deny and a missing kernel into the same ``None``, and an EXPLICIT scheme now fails
+ closed, so that single answer is the whole explanation the user gets."""
+ return _family_denied(family, scheme)
+
+
+def explain_unusable_scheme(family: Optional[str], scheme: str) -> str:
+ """Why ``select_transformer_quant_scheme`` answered None for an EXPLICIT ``scheme``.
+
+ One ``None`` covers three different faults, and the caller turns it into a 409, so the message
+ has to separate them: a family the scheme is measured to break, a torchao that cannot run at
+ all in this install, and a GPU without the kernels. Only the last is a hardware limit, and only
+ the last is what the message used to say."""
+ if family_denies_scheme(family, scheme):
+ return (
+ f"'{scheme}' is ruled out for family '{family}' by the measured accuracy gate (it "
+ "renders black frames or fails the quality bar on this DiT), whatever the GPU"
+ )
+ unavailable = torchao_unavailable_reason()
+ if unavailable is not None:
+ return (
+ f"the torchao in this install cannot run any dense quant scheme ({unavailable}); this "
+ "is a package/version problem, not a limit of the GPU"
+ )
+ return f"'{scheme}' is not usable for family '{family}' on this GPU"
+
+
+# The reason torchao cannot be used AT ALL, resolved once. None means it imports.
+_TORCHAO_UNAVAILABLE: Optional[tuple[Optional[str]]] = None
+
+
+def torchao_unavailable_reason() -> Optional[str]:
+ """Why no dense quant scheme can run in this install, or ``None`` when torchao is usable.
+
+ ``_smoke_probe`` swallows every failure, so a torchao that does not IMPORT is indistinguishable
+ from a GPU that lacks the kernels. That did not matter while a declined explicit scheme fell
+ back silently; now it is refused, and the message is all the user has. A torch/torchao version
+ skew is the common cause and it is not a hardware fault: telling a Blackwell owner "'fp8' is not
+ usable on this GPU" when the real error is ``cannot import name 'ScalingType' from
+ torch.nn.functional`` points them at the wrong fix entirely."""
+ global _TORCHAO_UNAVAILABLE
+ if _TORCHAO_UNAVAILABLE is not None:
+ return _TORCHAO_UNAVAILABLE[0]
+ reason: Optional[str] = None
+ if is_stubbed("torchao"):
+ # The Windows-ROCm stub imports fine and quantises nothing, so the import test below passes.
+ reason = "this platform ships a torchao stub whose quantize_ is a no-op"
+ else:
+ try:
+ from torchao.quantization import quantize_ # noqa: F401
+ except Exception as exc: # noqa: BLE001 — any import failure means the same thing here
+ import logging
+
+ # The full text, paths included, goes to the server log; the client gets it stripped.
+ # This string is interpolated into the precision-refusal RuntimeError, which both load
+ # routes return verbatim as the 409 detail, and an ImportError routinely names the
+ # absolute file of the module that raised it.
+ logging.getLogger(__name__).warning(
+ "torchao is unusable: %s: %s", type(exc).__name__, exc
+ )
+ reason = _strip_paths(f"{type(exc).__name__}: {exc}")
+ _TORCHAO_UNAVAILABLE = (reason,)
+ return reason
+
+
+# An absolute POSIX or Windows path, up to the first whitespace / quote / bracket. Deliberately
+# requires a directory separator so dotted module names ("torch.nn.functional") survive intact:
+# those are the actionable half of the message.
+_ABS_PATH_RE = _re.compile(r"(?:[A-Za-z]:)?[\\/](?:[^\s'\"()<>|]*[\\/])+[^\s'\"()<>|]*")
+
+
+def _strip_paths(text: str) -> str:
+ """``text`` with server filesystem paths replaced by ``<path>``.
+
+ Refusal reasons reach an authenticated caller as a 409 body. The reason a load was refused is
+ the caller's business; where this machine keeps its site-packages is not."""
+ return _ABS_PATH_RE.sub("<path>", text)
+
+
# Cache of (scheme, device) -> bool so the quantise+matmul smoke test runs once.
_SMOKE_CACHE: dict[tuple[str, str], bool] = {}
@@ -238,6 +321,8 @@ def select_transformer_quant_scheme(
target: Any,
requested: Optional[str],
family: Optional[str] = None,
+ *,
+ unproven_ok: bool = False,
) -> Optional[str]:
"""The concrete scheme to apply, or None to fall back to GGUF.
@@ -245,7 +330,13 @@ def select_transformer_quant_scheme(
quantise+matmul smoke test, so an unavailable Blackwell fp4/mx kernel lands on fp8/int8
with no error. An explicit scheme is honored only if supported (else None), never swapped.
``family`` applies the measured deny list (``_FAMILY_SCHEME_DENY``): schemes that produce
- black frames / out-of-bar drift are skipped by ``auto`` and refused when explicit."""
+ black frames / out-of-bar drift are skipped by ``auto`` and refused when explicit.
+
+ ``unproven_ok`` is for the PRE-EVICTION route gate. The smoke test allocates, so a resident
+ chat/image/video model can make it fail for want of VRAM rather than for want of a kernel; the
+ gate runs before the arbiter has evicted that model, so treating "could not tell" as "not
+ supported" refuses a load the very next moment would have run. It answers "is this scheme
+ provably unusable here", and the real selection still happens after the handoff."""
requested = normalize_transformer_quant(requested)
if requested is None or not dense_transformer_supported(target):
return None
@@ -253,7 +344,7 @@ def select_transformer_quant_scheme(
if requested != TQ_AUTO:
if _family_denied(family, requested):
return None
- return requested if _scheme_supported(requested, device) else None
+ return requested if _scheme_supported(requested, device, unproven_ok = unproven_ok) else None
cap = _capability()
if cap is None:
return None
@@ -286,7 +377,12 @@ def _capability() -> Optional[tuple[int, int]]:
return None
-def _scheme_supported(scheme: str, device: str) -> bool:
+def _scheme_supported(
+ scheme: str,
+ device: str,
+ *,
+ unproven_ok: bool = False,
+) -> bool:
"""CUDA + (for fp8) the fp8 dtype + a cached quantise+matmul smoke test for ``scheme``."""
try:
import torch
@@ -296,10 +392,15 @@ def _scheme_supported(scheme: str, device: str) -> bool:
return False
except Exception:
return False
- return _smoke_probe(scheme, device)
+ return _smoke_probe(scheme, device, unproven_ok = unproven_ok)
-def _smoke_probe(scheme: str, device: str) -> bool:
+def _smoke_probe(
+ scheme: str,
+ device: str,
+ *,
+ unproven_ok: bool = False,
+) -> bool:
"""True iff a tiny Linear quantised with ``scheme`` runs one M=32 forward and returns
finite values. Cached per (scheme, device). Makes ``auto`` robust to a build lacking a
prototype kernel: it fails here and the ladder moves on, rather than crashing at the first
@@ -333,12 +434,44 @@ def _smoke_probe(scheme: str, device: str) -> bool:
out = lin(x)
torch.cuda.synchronize()
ok = bool(torch.isfinite(out).all().item())
- except Exception:
+ except Exception as exc: # noqa: BLE001
+ if _is_out_of_memory(exc):
+ # NOT cached, and NOT a verdict. An out-of-memory says nothing about the scheme, and
+ # the probe now runs on the ROUTE thread -- BEFORE the arbiter evicts the resident chat
+ # model, which is the whole point of raising the refusal early -- so it meets a full
+ # GPU by design. Caching it would refuse every later EXPLICIT request for this scheme
+ # for the life of the process, on a host that runs it fine once the eviction has
+ # happened; and answering "unsupported" to the pre-eviction gate (``unproven_ok``)
+ # refuses THIS load for the same reason the eviction was about to remove.
+ return unproven_ok
ok = False
_SMOKE_CACHE[key] = ok
return ok
+def _is_out_of_memory(exc: BaseException) -> bool:
+ """Whether ``exc`` is an allocator failure rather than a verdict on the scheme.
+
+ ``torch.OutOfMemoryError`` subclasses ``RuntimeError``, not ``MemoryError``, and moved between
+ ``torch.cuda`` and ``torch`` across releases, so both names are tried and the message is the
+ backstop (a CUDA OOM surfaced through another wrapper still says "out of memory")."""
+ try:
+ import torch
+ named = tuple(
+ t
+ for t in (
+ getattr(torch, "OutOfMemoryError", None),
+ getattr(torch.cuda, "OutOfMemoryError", None),
+ )
+ if isinstance(t, type)
+ )
+ if named and isinstance(exc, named):
+ return True
+ except Exception: # noqa: BLE001 — no torch: the message test below still applies
+ pass
+ return isinstance(exc, MemoryError) or "out of memory" in str(exc).lower()
+
+
def _resolve_fast_accum(fast_accum: Optional[bool]) -> bool:
"""The fp8 ``use_fast_accum`` to apply. ``None`` (auto) is fast accumulate; an explicit bool
forces it.
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 6d82cc68166..9afd4a49e20 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -1100,6 +1100,15 @@ class SdCppDiffusionBackend:
# The BUILD, for the recipe: the repo id alone does not say WHICH GGUF quant ran, and two quants make different pixels.
"model_kind": "gguf",
"gguf_filename": state.gguf_filename,
+ # The rest of the build the recipe records. The native engine has no dense
+ # quant path and no memory-mode planner, so those two are honestly null -- but
+ # the offload it ran under is real (sd-cli flags) and status() already derives
+ # it the same way. Omitting them here persisted null for every native image and
+ # left the recipe unable to say how the picture was produced.
+ "transformer_quant": None,
+ "text_encoder_quant": None,
+ "memory_mode": None,
+ "offload_policy": "active" if state.offload_flags else "none",
}
except SdCppCancelled as exc:
raise RuntimeError(DIFFUSION_CANCELLED_MSG) from exc
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 20a75088305..443d2c284f0 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -75,15 +75,32 @@ from .diffusion_speed import (
restore_backend_flags,
snapshot_backend_flags,
)
-from .diffusion_auto_policy import _QUANT_STEADY_FACTOR, build_resolved_record
+from .diffusion_auto_policy import (
+ _QUANT_STEADY_FACTOR,
+ RESOLVED_APPLIED,
+ RESOLVED_FELL_BACK,
+ RESOLVED_UNSUPPORTED,
+ build_resolved_record,
+ precision_fallback_allowed,
+ precision_refusal_message,
+)
from .diffusion_transformer_quant import (
TQ_AUTO,
dense_transformer_supported,
+ explain_unusable_scheme,
normalize_transformer_quant,
quantize_transformer,
select_transformer_quant_scheme,
)
-from .diffusion_precision import normalize_te_quant, quantize_text_encoders
+from .diffusion import _memory_request_forces_offload
+from .diffusion_precision import (
+ effective_te_quant,
+ normalize_te_quant,
+ quantize_text_encoders,
+ te_quant_needs_resident_weights,
+ te_quant_supported,
+ torchao_quantize_importable,
+)
from .video_families import (
VIDEO_CANCELLED_MSG,
VIDEO_GENERATION_BUSY_MSG,
@@ -137,6 +154,109 @@ def resolve_video_model_kind(gguf_filename: Optional[str], model_kind: Optional[
return "gguf" if gguf_filename.strip().lower().endswith(".gguf") else "single_file"
+def assert_video_precision_available(
+ fam: Any,
+ *,
+ model_kind: str,
+ transformer_quant: Optional[str] = None,
+ text_encoder_quant: Optional[str] = None,
+ memory_mode: Optional[str] = None,
+) -> None:
+ """Raise ``RuntimeError`` (the route's 409) when an EXPLICIT precision cannot run here.
+
+ The image twin, ``DiffusionBackend.assert_precision_available``: only the network-free
+ host-level impossibilities (wrong load kind, no dense-quant path, a scheme this GPU or family
+ rules out). Footprint-dependent declines belong to ``load_pipeline``; ``auto`` is never
+ refused.
+
+ Public because the ROUTE has to make this call itself, before it takes the GPU: the copy in
+ ``begin_load`` runs inside ``acquire_for``, which evicts chat under the arbiter lock before the
+ register callback."""
+ if precision_fallback_allowed():
+ return
+ pinned = normalize_transformer_quant(transformer_quant)
+ te_mode = normalize_te_quant(text_encoder_quant)
+ if pinned is None and te_mode is None:
+ return
+ # One probe for both checks (it reads the live device).
+ target = resolve_diffusion_device_target()
+ if pinned is not None and pinned != TQ_AUTO:
+ reason = None
+ if model_kind != "pipeline":
+ reason = (
+ f"the dense DiT quant applies to full-pipeline loads only, and this is a "
+ f"'{model_kind}' load, which runs the precision its checkpoint carries"
+ )
+ elif not dense_transformer_supported(target):
+ reason = "this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16)"
+ elif _memory_request_forces_offload(memory_mode, False):
+ # balanced and low_vram name their offload policy without measuring anything, and
+ # offload hooks move modules with Module.to(), which torchao tensors do not survive.
+ # load_pipeline therefore skips the dense build and the strict refusal landed after
+ # acquire_for and the teardown had already evicted the resident model.
+ reason = (
+ f"'{normalize_memory_mode(memory_mode)}' memory places the DiT under CPU "
+ "offload, and torchao quantised tensors cannot be moved by the offload hooks"
+ )
+ elif (
+ select_transformer_quant_scheme(
+ target,
+ pinned,
+ family = getattr(fam, "name", None),
+ # Pre-eviction: an OOM in the smoke probe is the resident model, not the scheme.
+ unproven_ok = True,
+ )
+ is None
+ ):
+ # An explicit scheme is never swapped for another, so a None means the family's
+ # measured deny list, a torchao that cannot run here, or a GPU without the kernels.
+ # They read the same to the selector and need different fixes from the user.
+ reason = explain_unusable_scheme(getattr(fam, "name", None), pinned)
+ if reason is not None:
+ raise RuntimeError(
+ precision_refusal_message(
+ "transformer_quant", pinned, reason, off_label = "Off to run the DiT at bf16"
+ )
+ )
+ # The mode the loader will ACTUALLY attempt, not the raw request: an explicit int8
+ # on a family with no keep-bf16 schedule is rewritten to layerwise fp8 before
+ # support is consulted, and that path needs no torchao. Refusing on the raw int8
+ # rejected loads the runtime would run and report as fell_back -- Windows ROCm,
+ # where the torchao stub kills int8 while fp8 still works.
+ te_effective = effective_te_quant(te_mode, getattr(fam, "name", None))
+ te_reason = None
+ if te_quant_needs_resident_weights(te_effective) and not torchao_quantize_importable():
+ # Same as the image gate: the casters import torchao only after the pipeline is built.
+ te_reason = (
+ "torchao is not importable on this install, and these encoder modes are torchao "
+ "quantisations"
+ )
+ elif te_effective is not None and not te_quant_supported(target, te_effective):
+ te_reason = (
+ "this device does not have the tensor cores that backend needs (a CUDA GPU in "
+ "bf16, plus fp8 / int8 / NVFP4 support depending on the mode)"
+ )
+ elif te_quant_needs_resident_weights(te_effective) and _memory_request_forces_offload(
+ memory_mode, False
+ ):
+ # Same fence on the encoder: the loader reports those modes unsupported once offload is
+ # active, and by then the resident model is gone. Layerwise fp8 is a dtype cast.
+ te_reason = (
+ f"'{normalize_memory_mode(memory_mode)}' memory places the text encoder under CPU "
+ "offload, and torchao quantised tensors cannot be moved by the offload hooks"
+ )
+ if te_reason is not None:
+ raise RuntimeError(
+ precision_refusal_message(
+ "text_encoder_quant",
+ te_mode,
+ te_reason,
+ off_label = "leave it unset to keep the dense bf16 encoder",
+ auto_available = False,
+ )
+ )
+
+
def _is_trusted_video_repo(repo_id: str) -> bool:
"""Whether a NON-GGUF load may deserialise this repo (see the image twin)."""
try:
@@ -505,6 +625,17 @@ class VideoBackend:
transformer_quant = transformer_quant,
text_encoder_quant = text_encoder_quant,
)
+ # Refuse an EXPLICIT precision this host can never honor BEFORE the load starts, so the
+ # route answers 409 with the reason instead of evicting the resident model and pulling
+ # tens of GB first. Footprint-dependent declines still surface via load-progress. The
+ # ROUTE makes the same call earlier still (see assert_video_precision_available): this one
+ # runs inside acquire_for, which has already evicted chat by the time it fires.
+ assert_video_precision_available(
+ fam,
+ model_kind = resolve_video_model_kind(gguf_filename, model_kind),
+ transformer_quant = transformer_quant,
+ text_encoder_quant = text_encoder_quant,
+ )
with self._lock:
if self._loading is not None and self._loading.error is None:
raise RuntimeError("A video load is already in progress.")
@@ -1147,6 +1278,13 @@ class VideoBackend:
# Size tables below are bf16 (2-byte), so scale dense estimates when the promotion lands fp32 on an accelerator.
dtype_scale = 2.0 if device != "cpu" and dtype is torch.float32 else 1.0
+ # What the CALLER asked for, before the rewrite below. The record has to report this, not
+ # the internal value: an omitted precision under speed_mode="off" becomes "off" here, and
+ # reporting that as the request makes the resolved record say the user pinned bf16. The
+ # frontend then hides the Auto badge and reseeds the Precision select to none, so after
+ # the user changes Speed and reloads, quantisation stays pinned off for no reason they
+ # can see.
+ transformer_quant_requested = transformer_quant
# Precision tri-state: unset/"auto" -> hardware ladder; "none"/"off" pins dense bf16; an explicit scheme pins it. Pipeline-kind only.
if transformer_quant is None or str(transformer_quant).strip().lower() in (
"",
@@ -1324,6 +1462,26 @@ class VideoBackend:
# low-precision tensor cores. CUDA + bf16 only, best-effort. Quant must precede compile (eager is ~30x slower).
transformer_quant_engaged: Optional[str] = None
quant_skipped_for_offload = False
+ # An EXPLICIT scheme (not auto, not off) is a contract, so a decline below must be reported
+ # and -- unless the escape hatch is set -- must stop the load rather than quietly running
+ # the DiT at bf16 while the Precision dropdown still reads FP8.
+ transformer_quant_pinned = normalize_transformer_quant(transformer_quant)
+ if transformer_quant_pinned == TQ_AUTO:
+ transformer_quant_pinned = None
+ # Why the quant did not engage, in the caller's terms; threaded into `resolved`.
+ transformer_quant_decline: Optional[str] = None
+ transformer_quant_decline_status = RESOLVED_FELL_BACK
+ if transformer_quant_pinned is not None and kind != "pipeline":
+ transformer_quant_decline = (
+ f"the dense DiT quant applies to full-pipeline loads only, and this is a "
+ f"'{kind}' load, which runs the precision its checkpoint carries"
+ )
+ transformer_quant_decline_status = RESOLVED_UNSUPPORTED
+ elif transformer_quant_pinned is not None and not dense_transformer_supported(target):
+ transformer_quant_decline = (
+ "this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16)"
+ )
+ transformer_quant_decline_status = RESOLVED_UNSUPPORTED
if (
kind == "pipeline"
and normalize_transformer_quant(transformer_quant) is not None
@@ -1338,6 +1496,11 @@ class VideoBackend:
plan.offload_policy,
)
quant_skipped_for_offload = True
+ transformer_quant_decline = (
+ f"the memory plan picked '{plan.offload_policy}' offload, which moves the DiT via "
+ "Module.to(); torchao quantized tensors reject that. Pin a resident memory mode "
+ "(Fast) to combine quant with this model"
+ )
elif (
kind == "pipeline"
and normalize_transformer_quant(transformer_quant) is not None
@@ -1365,12 +1528,38 @@ class VideoBackend:
)
if engaged:
transformer_quant_engaged = engaged[0]
+ elif transformer_quant_pinned is not None:
+ transformer_quant_decline = (
+ f"'{transformer_quant_pinned}' did not engage on family '{fam.name}' with this "
+ "GPU (the scheme is unsupported here, or the family's measured deny list "
+ "rules it out); see the server log"
+ )
+ transformer_quant_decline_status = RESOLVED_UNSUPPORTED
# The quant-sized plan is valid only when quant engaged; a dense fallback keeps bf16 placement.
if quant_replanned and transformer_quant_engaged is None:
plan = bf16_plan
+ # Fail closed on a declined EXPLICIT precision, mirroring the image loader: a clip rendered
+ # at bf16 under a Precision dropdown still reading FP8 is not evidence the request ran.
+ if (
+ transformer_quant_engaged is None
+ and transformer_quant_pinned is not None
+ and not precision_fallback_allowed()
+ ):
+ del pipe
+ clear_gpu_cache()
+ raise RuntimeError(
+ precision_refusal_message(
+ "transformer_quant",
+ transformer_quant_pinned,
+ transformer_quant_decline
+ or "the quantised DiT build did not engage on this host",
+ off_label = "Off to run the DiT at bf16",
+ )
+ )
+
# dense text-encoder quant (opt-in): the companion encoder is often the largest resident, so quantise it in place before placement, for every kind. Best-effort.
- text_encoder_quant_engaged = quantize_text_encoders(
+ text_encoder_outcome = quantize_text_encoders(
pipe,
target,
mode = text_encoder_quant,
@@ -1378,6 +1567,28 @@ class VideoBackend:
offload_active = plan.offload_policy != "none",
logger = logger,
)
+ text_encoder_quant_engaged = text_encoder_outcome.mode
+ # Same contract for the other half of "the requested precision": an explicit encoder mode
+ # that engaged NOTHING leaves a dense bf16 encoder the caller did not ask for, and a
+ # PARTIAL cast leaves conditioning split across quantised and dense towers. A mode that
+ # engaged something ELSE (int8 -> fp8) is reported by the badge instead: the encoder is
+ # quantised, just not the way asked, and the reason says so.
+ if (
+ (text_encoder_quant_engaged is None or text_encoder_outcome.partial)
+ and normalize_te_quant(text_encoder_quant) is not None
+ and not precision_fallback_allowed()
+ ):
+ del pipe
+ clear_gpu_cache()
+ raise RuntimeError(
+ precision_refusal_message(
+ "text_encoder_quant",
+ normalize_te_quant(text_encoder_quant) or "",
+ text_encoder_outcome.reason or "no text encoder could be cast",
+ off_label = "leave it unset to keep the dense bf16 encoder",
+ auto_available = False,
+ )
+ )
# optimisation layers in the image backend order: step cache FIRST (compile keys fullgraph off an active cache),
# then attention, speed, placement. A clip denoise runs minutes, so even a dense load amortises the compile.
@@ -1514,25 +1725,38 @@ class VideoBackend:
cache_reason,
),
"transformer_quant": (
- transformer_quant,
+ transformer_quant_requested,
transformer_quant_engaged or "off",
# Honest framing: the shipped torchao schemes cut load time and resident memory ~2x, but per-step GEMMs are at best bf16 parity.
"DiT(s) quantised (halves resident weights; hosted checkpoints cut "
"load time; per-step speed is roughly bf16 parity)"
if transformer_quant_engaged is not None
+ # A recorded decline names WHY; the generic strings are the fallback.
else (
- "skipped: offload moves the DiT, unsupported for torchao "
- "tensors; pin a resident memory mode to combine them"
- if quant_skipped_for_offload
- else "not engaged (dense bf16 DiT loaded)"
+ transformer_quant_decline
+ or (
+ "skipped: offload moves the DiT, unsupported for torchao "
+ "tensors; pin a resident memory mode to combine them"
+ if quant_skipped_for_offload
+ else "not engaged (dense bf16 DiT loaded)"
+ )
),
+ # Honored when the quant engaged AND when the ask was "off" (bf16 is what
+ # that asks for). Only reached with the escape hatch set for a pinned ask.
+ RESOLVED_APPLIED
+ if transformer_quant_engaged is not None or transformer_quant_pinned is None
+ else transformer_quant_decline_status,
),
"text_encoder_quant": (
text_encoder_quant,
text_encoder_quant_engaged or "off",
- "dense text encoder quantised in place"
- if text_encoder_quant_engaged is not None
- else "not engaged (dense bf16 text encoder loaded)",
+ text_encoder_outcome.reason
+ or (
+ "dense text encoder quantised in place"
+ if text_encoder_quant_engaged is not None
+ else "not engaged (dense bf16 text encoder loaded)"
+ ),
+ text_encoder_outcome.status,
),
}
)
@@ -1743,6 +1967,15 @@ class VideoBackend:
"seed": result["seed"],
"has_audio": result["has_audio"],
"model": result["repo_id"],
+ # The load-time build, so a clip's recipe still names the precision it ran at
+ # once the model is unloaded. All engaged values; absent keys read back as null
+ # on sidecars written before this existed (they are not in _REQUIRED_META).
+ "model_kind": result.get("model_kind"),
+ "gguf_filename": result.get("gguf_filename"),
+ "transformer_quant": result.get("transformer_quant"),
+ "text_encoder_quant": result.get("text_encoder_quant"),
+ "memory_mode": result.get("memory_mode"),
+ "offload_policy": result.get("offload_policy"),
"created_at": created_at,
},
)
@@ -1980,6 +2213,15 @@ class VideoBackend:
"has_audio": bool(audio_track is not None),
"steps": steps,
"guidance": guidance,
+ # The BUILD this clip came off, read from the ENGAGED state and never from the
+ # request, so a saved MP4 can never be labelled with a precision that did not
+ # run. Mirrors what the image gallery already records.
+ "model_kind": state.kind,
+ "gguf_filename": state.gguf_filename,
+ "transformer_quant": state.transformer_quant,
+ "text_encoder_quant": state.text_encoder_quant,
+ "memory_mode": state.memory_mode,
+ "offload_policy": state.offload_policy,
}
except Exception:
self._gen = {"active": False}
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 0310fff96af..93effb2ea82 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -2443,7 +2443,9 @@ class DiffusionLoadRequest(BaseModel):
"CUDA cc>=8.9), fp8_dynamic (torchao compute fp8 on the tensor cores, ~2x + faster, "
"cc>=8.9), int8 (torchao compute int8 with per-family keep-bf16 layers; falls back to "
"fp8 where no schedule exists; cc>=8.0), or nvfp4 (~4x smaller, Blackwell sm_100+). A "
- "memory-vs-quality tradeoff (shifts fine detail), not free; pairs well with balanced mode.",
+ "memory-vs-quality tradeoff (shifts fine detail), not free; pairs well with balanced mode. "
+ "Fails CLOSED when NOTHING could be cast (409, or a load-progress error); an int8 request "
+ "downgraded to fp8 loads and is reported through the status resolved record instead.",
)
transformer_quant: Optional[Literal["auto", "none", "off", "int8", "fp8", "nvfp4", "mxfp8"]] = (
Field(
@@ -2454,7 +2456,11 @@ class DiffusionLoadRequest(BaseModel):
"low-precision tensor cores (data-center fp8, consumer/Ampere int8), "
"falling back to the GGUF when the device, VRAM or disk cannot take "
"it. none/off pins running the GGUF as-is; an explicit scheme forces "
- "that scheme. Dense path needs CUDA + bf16.",
+ "that scheme. Dense path needs CUDA + bf16. An EXPLICIT scheme fails "
+ "CLOSED: where it cannot be honored the load is refused (409, or an "
+ "error phase on load-progress for the footprint-dependent declines) "
+ "rather than silently running the GGUF at another precision. Only "
+ "auto falls back.",
)
)
transformer_quant_fast_accum: Optional[bool] = Field(
@@ -2814,6 +2820,19 @@ class GalleryImage(BaseModel):
description = "Transformer quantisation scheme actually engaged on the dense fast path "
"(int8/fp8/nvfp4/mxfp8), or null when the GGUF ran as-is",
)
+ text_encoder_quant: Optional[str] = Field(
+ None,
+ description = "Text-encoder quantisation actually engaged (fp8/fp8_dynamic/int8/nvfp4), "
+ "or null when the dense bf16 encoder ran. Absent on records written before this existed.",
+ )
+ memory_mode: Optional[str] = Field(
+ None, description = "Memory mode the load ran under: auto | fast | balanced | low_vram"
+ )
+ offload_policy: Optional[str] = Field(
+ None,
+ description = "Offload policy actually engaged: none | group | model | sequential. Part of "
+ "the build: an offloaded pipeline declines the torchao text-encoder modes.",
+ )
baked_loras: list[str] = Field(
default_factory = list,
description = "Adapter ids baked into the transformer AT LOAD TIME (before quantize + "
@@ -2887,12 +2906,30 @@ class DiffusionResolvedControl(BaseModel):
control is off, or ``true``/``false`` for cpu_offload), so it is typed ``Any``.
``source`` is "auto" when this backend decided it or "explicit" when the caller did;
``reason`` is the short human-readable why the frontend shows as a tooltip.
+
+ ``requested`` and ``status`` carry the OTHER half: what was asked for and whether it was
+ honored. Without them a declined request was indistinguishable from an honored one -- the
+ engaged value was reported truthfully, but the ask it replaced was gone, so the UI kept
+ advertising a precision that never engaged.
"""
value: Any = Field(
None, description = "The engaged value: a string, a boolean (cpu_offload), or null."
)
+ requested: Any = Field(
+ None,
+ description = "What the caller asked for, verbatim (a string, a boolean for cpu_offload), "
+ "or null when they left this control to the backend. Compare with ``value`` to see "
+ "whether the request survived.",
+ )
source: str = Field(..., description = '"auto" (backend decided) or "explicit" (caller set it)')
+ status: str = Field(
+ "applied",
+ description = 'Whether the request was honored: "applied" (it was, or there was no '
+ 'request), "fell_back" (an explicit request was declined and something else engaged) or '
+ '"unsupported" (an explicit request cannot run on this host / model at all). Defaulted '
+ "so a client reading an older backend's payload still parses.",
+ )
reason: str = Field("", description = "Short human-readable reason for the resolved value.")
@@ -3262,6 +3299,32 @@ class GalleryVideo(BaseModel):
seed: int = Field(..., description = "Seed used")
has_audio: bool = Field(False, description = "Whether the MP4 carries an audio track")
model: Optional[str] = Field(None, description = "Model repo id that produced it")
+ # The load-time BUILD, mirroring GalleryImage: the repo id alone does not say which checkpoint
+ # ran or at what precision, so a clip could not be told apart from one rendered at another. All
+ # optional, so sidecars written before this existed still list.
+ model_kind: Optional[str] = Field(
+ None, description = "How the model was loaded: gguf, single_file or pipeline"
+ )
+ gguf_filename: Optional[str] = Field(
+ None,
+ description = "The single-file checkpoint the load committed, for a gguf/single_file load",
+ )
+ transformer_quant: Optional[str] = Field(
+ None,
+ description = "Dense DiT quantisation actually engaged (int8/fp8/nvfp4/mxfp8), or null "
+ "when the DiT(s) ran at their loaded bf16 precision",
+ )
+ text_encoder_quant: Optional[str] = Field(
+ None,
+ description = "Text-encoder quantisation actually engaged (fp8/fp8_dynamic/int8/nvfp4), "
+ "or null when the dense bf16 encoder ran",
+ )
+ memory_mode: Optional[str] = Field(
+ None, description = "Memory mode the load ran under: auto | fast | balanced | low_vram"
+ )
+ offload_policy: Optional[str] = Field(
+ None, description = "Offload policy actually engaged: none | group | model | sequential"
+ )
created_at: str = Field(..., description = "Creation time (ISO 8601 timestamp)")
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 9a17d1bddd7..6fa96823aca 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -20049,6 +20049,18 @@ def _diffusion_training_admission():
yield
+def _training_is_active() -> bool:
+ """The non-raising half of the load guard, for callers that must not take the GPU."""
+ from core.training import get_training_backend
+
+ try:
+ if get_training_backend().is_training_active():
+ return True
+ except Exception as e: # noqa: BLE001 -- an unreadable LLM backend is not evidence of idle
+ logger.warning("Could not check training state: %s", e)
+ return _diffusion_training_active()
+
+
def _guard_diffusion_load_against_training() -> None:
"""Refuse loading an image model while a training run is active. Unlike chat,
a diffusion pipeline's VRAM can't be cheaply estimated before the load, so the
@@ -20116,6 +20128,34 @@ async def diffusion_download_plan(
if fam is not None and predict_engine(fam, model_kind = kind) == ENGINE_SD_CPP:
from core.inference.sd_cpp_backend import get_sd_cpp_backend
planner = get_sd_cpp_backend()
+ # BEFORE the plan is handed back and staged. The load route refuses a precision this
+ # host cannot honour, but the UI plans and downloads first, so an explicit FP8 on an
+ # unsupported host paid for the GGUF and its companions -- or tens of GB of video
+ # weights -- and then got the predictable 409. Both checks are network-free.
+ # Not while a trainer holds the GPU. An UNCACHED scheme sends
+ # assert_precision_available into a quantise-and-matmul smoke probe, which initialises
+ # CUDA and allocates in the Studio process -- the very thing the load route's training
+ # guard exists to prevent, and the plan runs BEFORE that guard has had a say. Staging
+ # files during training is legitimate and needs no GPU, so the plan is answered without
+ # the precision check; /images/load still refuses the same pick afterwards.
+ if fam is not None and not await asyncio.to_thread(_training_is_active):
+ if planner is backend:
+ await asyncio.to_thread(
+ backend.assert_precision_available,
+ fam,
+ model_kind = kind,
+ transformer_quant = request.transformer_quant,
+ text_encoder_quant = request.text_encoder_quant,
+ # The memory request settles the offload policy for balanced/low_vram before
+ # anything is measured, and an offloaded transformer skips the dense quant.
+ memory_mode = getattr(request, "memory_mode", None),
+ cpu_offload = bool(getattr(request, "cpu_offload", False)),
+ )
+ else:
+ _assert_native_precision_unset(
+ transformer_quant = request.transformer_quant,
+ text_encoder_quant = request.text_encoder_quant,
+ )
plan = await asyncio.to_thread(
planner.download_plan,
request.model_path,
@@ -20137,6 +20177,47 @@ async def diffusion_download_plan(
return DiffusionDownloadPlanResponse(**plan)
except (ValueError, FileNotFoundError) as exc:
raise HTTPException(status_code = 400, detail = redact_native_paths(str(exc)))
+ except RuntimeError as exc:
+ # Same status the load route gives the same refusal, so the UI can reuse one handler:
+ # the precision gate above raises RuntimeError, and a 500 here would read as a server
+ # fault rather than the deliberate "this host cannot honour that pick" answer.
+ raise HTTPException(status_code = 409, detail = redact_native_paths(str(exc)))
+
+
+def _assert_native_precision_unset(
+ *, transformer_quant: Optional[str] = None, text_encoder_quant: Optional[str] = None
+) -> None:
+ """Refuse an EXPLICIT precision on the native sd.cpp engine, which cannot honour one.
+
+ It accepts both knobs for interface parity with the diffusers backend and ignores them, so
+ without this an explicit FP8 loads happily, quantises nothing, and reports null -- the silent
+ mismatch the resolved-precision work exists to remove. `auto` and `none` pass through: they
+ delegate the choice, and nothing is being promised.
+
+ Raises RuntimeError, which the route maps to 409 alongside the diffusers refusals."""
+ from core.inference.diffusion_auto_policy import precision_fallback_allowed
+ from core.inference.diffusion_precision import normalize_te_quant
+ from core.inference.diffusion_transformer_quant import TQ_AUTO, normalize_transformer_quant
+
+ if precision_fallback_allowed():
+ return
+ pinned = normalize_transformer_quant(transformer_quant)
+ te_mode = normalize_te_quant(text_encoder_quant)
+ asked = []
+ if pinned is not None and pinned != TQ_AUTO:
+ asked.append(f"transformer_quant={pinned!r}")
+ if te_mode is not None and te_mode != TQ_AUTO:
+ asked.append(f"text_encoder_quant={te_mode!r}")
+ if not asked:
+ return
+ raise RuntimeError(
+ # "could not be used", the same wording the diffusers refusals use: the frontend
+ # classifies a precision refusal by that phrase and rendered this one as a generic
+ # one-line error instead of under the actionable title.
+ f"{' and '.join(asked)} could not be used: this pick runs on the native engine, which "
+ "loads a GGUF checkpoint as it is and has no torchao quantisation path. Leave the "
+ "precision on 'auto', or pick a model that loads through diffusers."
+ )
@studio_router.post("/images/load", response_model = DiffusionStatusResponse)
@@ -20158,6 +20239,7 @@ async def load_diffusion_model(
select_and_activate_engine,
)
from core.inference.gpu_arbiter import acquire_for, release, DIFFUSION
+ from core.inference.sd_cpp_engine import ENGINE_DIFFUSERS, ENGINE_SD_CPP
from utils.native_path_leases import redact_native_paths
backend = get_diffusion_backend()
@@ -20207,6 +20289,33 @@ async def load_diffusion_model(
pending_name = predict_engine(fam, model_kind = kind) if fam is not None else None
except Exception: # noqa: BLE001 -- a probe failure must not refuse a loadable pick
pending_name = None
+ # Same bar, same reason, for an EXPLICIT precision this host can never honor. begin_load
+ # makes the identical network-free check, but it runs inside acquire_for -- which evicts
+ # chat under the arbiter lock BEFORE the register callback -- and after selection, which
+ # unloads the resident model on an engine switch. So a refusal raised there arrives having
+ # already destroyed the two things the 409 exists to preserve. `auto` is never refused, so
+ # a caller that left the precision to the backend cannot reach this.
+ if fam is not None and pending_name == ENGINE_DIFFUSERS:
+ await asyncio.to_thread(
+ backend.assert_precision_available,
+ fam,
+ model_kind = kind,
+ transformer_quant = request.transformer_quant,
+ text_encoder_quant = request.text_encoder_quant,
+ memory_mode = getattr(request, "memory_mode", None),
+ cpu_offload = bool(getattr(request, "cpu_offload", False)),
+ )
+ elif fam is not None and pending_name == ENGINE_SD_CPP:
+ # The native engine accepts both knobs for interface parity and ignores them. It was
+ # excluded from the gate above so as not to refuse loads that work today, but the
+ # loads it "works" for are precisely the silent mismatch this whole change exists to
+ # remove: an explicit FP8 succeeds, quantises nothing, and reports null. Refusing is
+ # also what the diffusers path already does on the same CPU-only host, so leaving the
+ # two engines disagreeing was the worse of the options.
+ _assert_native_precision_unset(
+ transformer_quant = request.transformer_quant,
+ text_encoder_quant = request.text_encoder_quant,
+ )
preflighted = None
if pending_name is not None and (needs_gpu or pending_name != active_engine_name()):
preflighted = engine_for(pending_name)
@@ -20223,6 +20332,28 @@ async def load_diffusion_model(
# on the CPU path too when a preflight was owed there, since the switch is what is at stake.
if (needs_gpu or preflighted is not None) and engine is not preflighted:
await asyncio.to_thread(_preflight, engine)
+ # And the precision gate, against the engine that was actually activated. When
+ # predict_engine RAISED, pending_name stayed None and both arms above were skipped, so
+ # a selection that then landed on sd.cpp accepted an explicit FP8, quantised nothing
+ # and reported null -- the exact silent mismatch this change exists to remove. Re-run
+ # only when the prediction was inconclusive or wrong; a correct one already paid it.
+ activated = active_engine_name()
+ if fam is not None and activated != pending_name:
+ if activated == ENGINE_SD_CPP:
+ _assert_native_precision_unset(
+ transformer_quant = request.transformer_quant,
+ text_encoder_quant = request.text_encoder_quant,
+ )
+ elif activated == ENGINE_DIFFUSERS:
+ await asyncio.to_thread(
+ backend.assert_precision_available,
+ fam,
+ model_kind = kind,
+ transformer_quant = request.transformer_quant,
+ text_encoder_quant = request.text_encoder_quant,
+ memory_mode = getattr(request, "memory_mode", None),
+ cpu_offload = bool(getattr(request, "cpu_offload", False)),
+ )
def _start_engine_load():
# Kicks the slow load onto a background thread and returns at once (the client polls images/load-progress).
@@ -20405,6 +20536,12 @@ async def generate_diffusion_image(
"model_kind": result.get("model_kind"),
"gguf_filename": result.get("gguf_filename"),
"transformer_quant": result.get("transformer_quant"),
+ # The other half of the build's precision: the text encoder is often the
+ # largest resident component and its quant changes the conditioning, and
+ # the memory mode decides whether the torchao TE modes could run at all.
+ "text_encoder_quant": result.get("text_encoder_quant"),
+ "memory_mode": result.get("memory_mode"),
+ "offload_policy": result.get("offload_policy"),
"baked_loras": list(result.get("baked_loras") or []),
# The adapters APPLIED to this generation. A baked-but-disabled adapter is recorded above as part of the build instead.
"loras": [f"{l.id}:{l.weight:g}" for l in request.loras or []],
diff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.py
index f4db80d5725..d8f7196143b 100644
--- a/studio/backend/routes/video.py
+++ b/studio/backend/routes/video.py
@@ -46,6 +46,12 @@ logger = get_logger(__name__)
router = APIRouter()
+def _training_is_active() -> bool:
+ """The non-raising half of the load guard, for callers that must not take the GPU."""
+ from routes.inference import _training_is_active as _images_training_is_active
+ return _images_training_is_active()
+
+
def _guard_video_load_against_training() -> None:
"""Refuse loading a video model while a training run is active. Unlike chat,
a video pipeline's VRAM can't be cheaply estimated before the load, so the
@@ -86,7 +92,11 @@ async def video_download_plan(
"""The repos + files this pick needs, so the frontend stages them through the Hub
download manager instead of the load downloading inline. Mirrors /images/download-plan."""
from core.inference.diffusion import resolve_local_single_file
- from core.inference.video import get_video_backend, resolve_video_model_kind
+ from core.inference.video import (
+ assert_video_precision_available,
+ get_video_backend,
+ resolve_video_model_kind,
+ )
from utils.native_path_leases import redact_native_paths
backend = get_video_backend()
@@ -97,7 +107,7 @@ async def video_download_plan(
if sole is not None:
request.gguf_filename = sole
kind = resolve_video_model_kind(sole, None)
- await asyncio.to_thread(
+ fam = await asyncio.to_thread(
backend.validate_load_request,
request.model_path,
gguf_filename = request.gguf_filename,
@@ -105,6 +115,22 @@ async def video_download_plan(
model_kind = kind,
base_repo = request.base_repo,
)
+ # BEFORE the plan is staged, as on the images side: /video/load refuses a precision this
+ # host cannot honour, but the UI plans and downloads first, so an explicit FP8 on an
+ # unsupported host paid for tens of GB of weights to be told afterwards. Network-free.
+ #
+ # Skipped while a trainer holds the GPU: an uncached scheme takes this into a
+ # quantise-and-matmul smoke probe that initialises CUDA in the Studio process, and the
+ # plan runs before the load's training guard can refuse. Staging needs no GPU.
+ if fam is not None and not await asyncio.to_thread(_training_is_active):
+ await asyncio.to_thread(
+ assert_video_precision_available,
+ fam,
+ model_kind = kind,
+ transformer_quant = request.transformer_quant,
+ text_encoder_quant = request.text_encoder_quant,
+ memory_mode = request.memory_mode,
+ )
plan = await asyncio.to_thread(
backend.download_plan,
request.model_path,
@@ -119,6 +145,10 @@ async def video_download_plan(
return DiffusionDownloadPlanResponse(**plan)
except (ValueError, FileNotFoundError) as exc:
raise HTTPException(status_code = 400, detail = redact_native_paths(str(exc)))
+ except RuntimeError as exc:
+ # Mirrors /video/load and /images/download-plan: the precision gate above raises
+ # RuntimeError, and that refusal is a 409, not a server fault.
+ raise HTTPException(status_code = 409, detail = redact_native_paths(str(exc)))
@router.post("/video/load", response_model = VideoStatusResponse)
@@ -128,7 +158,11 @@ async def load_video_model(
from core.inference.diffusion import resolve_local_single_file
from core.inference.diffusion_device import resolve_diffusion_device_target
from core.inference.gpu_arbiter import VIDEO, acquire_for, release
- from core.inference.video import get_video_backend, resolve_video_model_kind
+ from core.inference.video import (
+ assert_video_precision_available,
+ get_video_backend,
+ resolve_video_model_kind,
+ )
from utils.native_path_leases import redact_native_paths
backend = get_video_backend()
@@ -142,7 +176,7 @@ async def load_video_model(
request.gguf_filename = sole
kind = resolve_video_model_kind(sole, None)
# Validate cheaply BEFORE touching the GPU so an unloadable pick can't evict chat then 400.
- await asyncio.to_thread(
+ fam = await asyncio.to_thread(
backend.validate_load_request,
request.model_path,
gguf_filename = request.gguf_filename,
@@ -152,8 +186,26 @@ async def load_video_model(
transformer_quant = request.transformer_quant,
text_encoder_quant = request.text_encoder_quant,
)
- # Refuse while training is running (VRAM competition). Mirrors the image-load guard.
+ # Refuse while training is running (VRAM competition) BEFORE the precision check below:
+ # that check runs an uncached quantise+matmul probe on the GPU, which would initialise a
+ # CUDA context and allocate alongside the training subprocess for a load that is about to
+ # be rejected anyway. Mirrors the image-load route, which already guards first.
_guard_video_load_against_training()
+ # Same bar for an EXPLICIT precision this host can never honor. begin_load makes the
+ # identical network-free check, but it runs inside acquire_for, which evicts chat under the
+ # arbiter lock BEFORE the register callback -- so a refusal raised there arrives having
+ # already taken the GPU away from the model it was meant to preserve. `auto` is never
+ # refused, so a caller that left the precision to the backend cannot reach this.
+ await asyncio.to_thread(
+ assert_video_precision_available,
+ fam,
+ model_kind = kind,
+ transformer_quant = request.transformer_quant,
+ text_encoder_quant = request.text_encoder_quant,
+ # The memory request settles the offload policy for balanced/low_vram before
+ # anything is measured, and an offloaded DiT or encoder skips the torchao build.
+ memory_mode = request.memory_mode,
+ )
# Take the GPU from chat only for a non-CPU load. Release stale VIDEO ownership on a CPU load (owner-guarded no-op).
device = await asyncio.to_thread(lambda: resolve_diffusion_device_target().device)
diff --git a/studio/backend/tests/test_diffusion_auto_policy.py b/studio/backend/tests/test_diffusion_auto_policy.py
index 54d17736bfb..a6f55785f49 100644
--- a/studio/backend/tests/test_diffusion_auto_policy.py
+++ b/studio/backend/tests/test_diffusion_auto_policy.py
@@ -20,6 +20,8 @@ from core.inference.diffusion_auto_policy import (
build_resolved_record,
estimate_dense_quant,
family_bf16_components_gb,
+ precision_fallback_allowed,
+ precision_refusal_message,
resolve_dense_quant_candidate,
)
from core.inference.diffusion_memory import (
@@ -294,3 +296,78 @@ def test_resolved_record_marks_auto_and_explicit():
assert record["cpu_offload"]["source"] == "explicit"
assert record["transformer_quant"]["value"] == "fp8"
assert all("reason" in v for v in record.values())
+
+
+def test_resolved_record_keeps_the_request_beside_the_engaged_value():
+ # P1-2: a declined explicit precision must not collapse into a bare source="explicit" that
+ # renders no badge while the dropdown still advertises the ask.
+ record = build_resolved_record(
+ {
+ "transformer_quant": ("fp8", "off", "the dense build did not fit", "fell_back"),
+ "text_encoder_quant": ("int8", "fp8", "no keep-bf16 schedule"),
+ "memory_mode": ("low_vram", "sequential", "planned"),
+ }
+ )
+ assert record["transformer_quant"]["requested"] == "fp8"
+ assert record["transformer_quant"]["value"] == "off"
+ assert record["transformer_quant"]["status"] == "fell_back"
+ # Derived without the call site classifying it: request and engaged value disagree.
+ assert record["text_encoder_quant"]["status"] == "fell_back"
+ # ...but only where the two share a vocabulary. memory_mode requests a MODE and engages an
+ # offload POLICY, so an honored request must not be reported as a fallback.
+ assert record["memory_mode"]["status"] == "applied"
+
+
+def test_resolved_record_treats_an_honored_off_request_as_applied():
+ # "none"/"off"/"" all ask for no quant, which an "off" engagement satisfies.
+ record = build_resolved_record(
+ {
+ "transformer_quant": ("none", "off", "GGUF loaded"),
+ "text_encoder_quant": ("fp8", "fp8", "cast in place"),
+ "cpu_offload": (True, True, "legacy flag"),
+ }
+ )
+ assert record["transformer_quant"]["status"] == "applied"
+ assert record["text_encoder_quant"]["status"] == "applied"
+ assert record["cpu_offload"]["status"] == "applied"
+
+
+def test_resolved_record_auto_never_reports_a_fallback():
+ # An auto request delegates the choice, so a decline is the ladder working: no ask to betray.
+ record = build_resolved_record({"transformer_quant": (None, "off", "no CUDA")})
+ assert record["transformer_quant"]["source"] == "auto"
+ assert record["transformer_quant"]["requested"] is None
+ assert record["transformer_quant"]["status"] == "applied"
+
+
+def test_precision_fallback_escape_hatch(monkeypatch):
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK", raising = False)
+ assert precision_fallback_allowed() is False
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK", "1")
+ assert precision_fallback_allowed() is True
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK", "0")
+ assert precision_fallback_allowed() is False
+
+
+def test_the_refusal_only_offers_auto_where_auto_exists():
+ # transformer_quant has an "auto" mode, so pointing the user at it is the right advice.
+ msg = precision_refusal_message(
+ "transformer_quant",
+ "nvfp4",
+ "this GPU has no fp4 tensor cores",
+ off_label = "Off to run the checkpoint as-is",
+ )
+ assert "Choose Auto" in msg and msg.endswith("or Off to run the checkpoint as-is.")
+
+ # text_encoder_quant does not: both request models restrict it to fp8 / fp8_dynamic / int8 /
+ # nvfp4, so a user who followed "Choose Auto" here got a 422 from request validation. The
+ # remedy has to name the thing that actually works.
+ te = precision_refusal_message(
+ "text_encoder_quant",
+ "int8",
+ "this device does not have the tensor cores that backend needs",
+ off_label = "leave it unset to keep the dense bf16 encoder",
+ auto_available = False,
+ )
+ assert "Auto" not in te
+ assert te.endswith("Leave it unset to keep the dense bf16 encoder.")
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index bc94fa6576d..ff126ece898 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -2679,6 +2679,16 @@ def test_load_reports_memory_plan_fields_on_cpu(fake_runtime, tmp_path):
assert pipe.moved_to == "cpu" and pipe.vae_tiled and pipe.vae_sliced
+def allow_precision_fallback(monkeypatch):
+ """Restore the pre-P1-2 behaviour where a DECLINED explicit precision silently loaded the GGUF.
+
+ The tests below are about which PLANNING path ran, not about the precision contract, and the
+ strict default now stops the load before their assertions can look at it. The refusal itself
+ is covered by test_explicit_transformer_quant_refuses_instead_of_loading_the_gguf."""
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK", "1")
+
+
def _force_cuda_target(backend, monkeypatch):
"""Drive the loader down the CUDA (offload-capable) path under the stub."""
torch = sys.modules["torch"]
@@ -2724,7 +2734,9 @@ def test_load_explicit_cpu_offload_engages_model_offload_on_cuda(
assert status["offload_policy"] == "model" and status["cpu_offload"] is True
-def test_load_speed_mode_gguf_auto_defaults_and_explicit(fake_runtime, tmp_path):
+def test_load_speed_mode_gguf_auto_defaults_and_explicit(
+ fake_runtime, tmp_path, allow_precision_fallback
+):
# No speed_mode on a GGUF model resolves to auto `default`; compile is CUDA-only, so nothing engages on this CPU stub.
(tmp_path / "m.gguf").write_bytes(b"x")
backend = DiffusionBackend()
@@ -2748,8 +2760,13 @@ def test_load_speed_mode_gguf_auto_defaults_and_explicit(fake_runtime, tmp_path)
family_override = "z-image",
text_encoder_quant = "nvfp4",
)
- # Under the CPU stub nvfp4 is unsupported, so it engages nothing.
+ # Under the CPU stub nvfp4 is unsupported, so it engages nothing (the legacy escape hatch is
+ # set; the strict default refuses the load -- see
+ # test_explicit_text_encoder_quant_refuses_when_nothing_engaged).
assert status3["text_encoder_quant"] is None
+ resolved_te = status3["resolved"]["text_encoder_quant"]
+ assert resolved_te["requested"] == "nvfp4" and resolved_te["value"] == "off"
+ assert resolved_te["status"] == "unsupported"
def test_load_fast_mode_stays_resident_on_cuda(fake_runtime, tmp_path, monkeypatch):
@@ -2956,7 +2973,7 @@ def test_transformer_quant_prequant_load_fails_falls_back_to_dense(
def test_prequant_failure_never_pulls_unprefetched_dense_shards(
- fake_runtime, tmp_path, monkeypatch
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
):
# The prefetch skips the base repo's transformer/ shards whenever a prequant checkpoint is expected, so a failed prequant fetch
# would send from_pretrained after them inside the load lock, after eviction, unpreemptable, past a 100% progress report.
@@ -3020,7 +3037,282 @@ def test_run_load_flags_the_transformer_prefetched_from_the_staged_file_list(mon
assert seen == [expected for _files, expected in cases]
-def test_transformer_quant_falls_back_to_gguf_on_failure(fake_runtime, tmp_path, monkeypatch):
+# ── P1-2: the reported precision must be the precision that ran ───────────────
+
+
+def _stub_declining_dense_quant(backend, monkeypatch):
+ """Reach the dense fast path, then have the quantiser decline (the NVIDIA scenario: FP8 asked
+ for, transformer FP8 disabled at runtime, the Q4_K_M GGUF loaded instead)."""
+ from core.inference import diffusion as dmod
+
+ _force_cuda_target(backend, monkeypatch)
+ monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ )
+ monkeypatch.setattr(dmod, "resolve_prequant_source", lambda fam, scheme, **kw: None)
+
+ @classmethod
+ def _from_pretrained(cls, base, **kwargs):
+ return object()
+
+ monkeypatch.setattr(_FakeTransformer, "from_pretrained", _from_pretrained, raising = False)
+ monkeypatch.setattr(dmod, "quantize_transformer", lambda pipe, target, **kw: None)
+
+
+def test_declined_explicit_precision_reports_the_ask_and_the_outcome(
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
+):
+ # The headline of P1-2: FP8 requested on a Q4_K_M GGUF, transformer FP8 declined. With the
+ # legacy escape hatch the GGUF still loads, and status has to carry BOTH sides -- the ask, the
+ # engaged value, and that they disagree -- so a rendered image cannot be read as proof of FP8.
+ backend = DiffusionBackend()
+ _stub_declining_dense_quant(backend, monkeypatch)
+ (tmp_path / "z-image-turbo-Q4_K_M.gguf").write_bytes(b"x")
+ status = backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = "z-image-turbo-Q4_K_M.gguf",
+ family_override = "z-image",
+ transformer_quant = "fp8",
+ )
+ # Runtime telemetry: fp8 is NOT engaged.
+ assert status["transformer_quant"] is None
+ resolved = status["resolved"]["transformer_quant"]
+ assert resolved["requested"] == "fp8"
+ assert resolved["value"] == "off"
+ assert resolved["source"] == "explicit"
+ assert resolved["status"] == "fell_back"
+ assert "build failed" in resolved["reason"]
+
+
+def test_auto_precision_still_falls_back_silently(fake_runtime, tmp_path, monkeypatch):
+ # `auto` delegates the choice, so a decline is the ladder working as designed: no refusal, and
+ # the record stays a plain "Auto: OFF" with nothing requested. This must NOT change.
+ from core.inference import diffusion as dmod
+
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: False)
+ (tmp_path / "m.gguf").write_bytes(b"x")
+ status = backend.load_pipeline(str(tmp_path), gguf_filename = "m.gguf", family_override = "z-image")
+ assert status["loaded"] is True
+ assert status["transformer_quant"] is None
+ resolved = status["resolved"]["transformer_quant"]
+ assert resolved["source"] == "auto"
+ assert resolved["requested"] is None
+ assert resolved["status"] == "applied"
+ assert resolved["value"] == "off"
+
+
+def test_explicit_transformer_quant_refuses_instead_of_loading_the_gguf(
+ fake_runtime, tmp_path, monkeypatch
+):
+ # Same decline, strict default: the load stops with an actionable reason rather than producing
+ # images at a precision nobody asked for. Nothing is left half-loaded (_unload_locked ran).
+ backend = DiffusionBackend()
+ _stub_declining_dense_quant(backend, monkeypatch)
+ (tmp_path / "z-image-turbo-Q4_K_M.gguf").write_bytes(b"x")
+ with pytest.raises(RuntimeError) as excinfo:
+ backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = "z-image-turbo-Q4_K_M.gguf",
+ family_override = "z-image",
+ transformer_quant = "fp8",
+ )
+ message = str(excinfo.value)
+ assert "transformer_quant='fp8' could not be used" in message
+ assert "build failed" in message
+ # Actionable: it names the two settings that always work.
+ assert "Auto" in message and "Off" in message
+ assert backend.status()["loaded"] is False
+ assert backend._state is None
+
+
+def test_explicit_off_is_honored_not_reported_as_a_fallback(fake_runtime, tmp_path, monkeypatch):
+ # "Off" asks NOT to quantise, which the GGUF build satisfies: an explicit request that was met.
+ (tmp_path / "m.gguf").write_bytes(b"x")
+ status = DiffusionBackend().load_pipeline(
+ str(tmp_path),
+ gguf_filename = "m.gguf",
+ family_override = "z-image",
+ transformer_quant = "none",
+ )
+ resolved = status["resolved"]["transformer_quant"]
+ assert resolved["source"] == "explicit" and resolved["requested"] == "none"
+ assert resolved["value"] == "off" and resolved["status"] == "applied"
+
+
+def test_begin_load_refuses_an_explicit_precision_this_host_cannot_run(
+ fake_runtime, tmp_path, monkeypatch
+):
+ # The host-level impossibilities are caught BEFORE the background load starts, so the route can
+ # answer 409 instead of evicting a working model and failing several GB later. The stub target
+ # is CPU, so no dense torchao path exists.
+ (tmp_path / "m.gguf").write_bytes(b"x")
+ backend = DiffusionBackend()
+ with pytest.raises(RuntimeError) as excinfo:
+ backend.begin_load(
+ str(tmp_path),
+ gguf_filename = "m.gguf",
+ family_override = "z-image",
+ model_kind = "gguf",
+ transformer_quant = "fp8",
+ )
+ assert "transformer_quant='fp8' could not be used" in str(excinfo.value)
+ assert "CUDA GPU in bf16" in str(excinfo.value)
+ # Nothing was started: no in-flight load to poll and no model evicted.
+ assert backend.load_progress()["phase"] is None
+
+
+def test_a_refusal_caused_by_a_broken_torchao_says_so_instead_of_blaming_the_gpu(
+ fake_runtime, tmp_path, monkeypatch
+):
+ # Measured on a B200 whose torchao could not import (`cannot import name 'ScalingType' from
+ # torch.nn.functional`, a torch/torchao skew): every explicit scheme was refused as "'fp8' is
+ # not usable for family '...' on this GPU". That is false, and it is now the whole message the
+ # user gets, since an explicit scheme fails closed instead of quietly running the GGUF. A skew
+ # is fixed by a pip install; a GPU limit is not, so the two must not read the same.
+ from core.inference import diffusion as dmod
+ import core.inference.diffusion_transformer_quant as tq
+
+ (tmp_path / "m.gguf").write_bytes(b"x")
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ # The device clears the dense-path bar; the SCHEME still comes back None, which is the exact
+ # shape of a host whose torchao cannot load its kernels.
+ monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(dmod, "select_transformer_quant_scheme", lambda *a, **k: None)
+ monkeypatch.setattr(
+ tq, "_TORCHAO_UNAVAILABLE", ("ImportError: cannot import name 'ScalingType'",)
+ )
+
+ with pytest.raises(RuntimeError) as excinfo:
+ backend.begin_load(
+ str(tmp_path),
+ gguf_filename = "m.gguf",
+ family_override = "z-image",
+ model_kind = "gguf",
+ transformer_quant = "fp8",
+ )
+ message = str(excinfo.value)
+ assert "transformer_quant='fp8' could not be used" in message
+ assert "cannot import name 'ScalingType'" in message
+ assert "not a limit of the GPU" in message
+ assert "is not usable for family" not in message
+
+
+def test_begin_load_refuses_an_explicit_text_encoder_quant_this_host_cannot_run(
+ fake_runtime, tmp_path, monkeypatch
+):
+ # The text encoder is the other half of "the requested precision": the CPU stub cannot cast it,
+ # and that used to return None with no log line at all.
+ (tmp_path / "m.gguf").write_bytes(b"x")
+ with pytest.raises(RuntimeError, match = "text_encoder_quant='fp8' could not be used"):
+ DiffusionBackend().begin_load(
+ str(tmp_path),
+ gguf_filename = "m.gguf",
+ family_override = "z-image",
+ model_kind = "gguf",
+ text_encoder_quant = "fp8",
+ )
+
+
+def test_explicit_text_encoder_quant_refuses_when_nothing_engaged(
+ fake_runtime, tmp_path, monkeypatch
+):
+ # An encoder mode that cast NOTHING leaves a dense bf16 encoder the caller did not ask for, so
+ # the load stops rather than generating at a precision the request did not describe. Reaches
+ # load_pipeline directly, past the begin_load preflight, so the deep path is covered too.
+ (tmp_path / "m.gguf").write_bytes(b"x")
+ with pytest.raises(RuntimeError) as excinfo:
+ DiffusionBackend().load_pipeline(
+ str(tmp_path),
+ gguf_filename = "m.gguf",
+ family_override = "z-image",
+ text_encoder_quant = "nvfp4",
+ )
+ assert "text_encoder_quant='nvfp4' could not be used" in str(excinfo.value)
+
+
+def test_explicit_text_encoder_quant_refuses_a_partial_cast(fake_runtime, tmp_path, monkeypatch):
+ # One encoder took the cast and its sibling did not, so the mode DID engage -- and the old
+ # check, which only looked for "nothing engaged", let the load through and recorded the
+ # requested mode as the engaged precision while conditioning ran off a mixture of a quantised
+ # and a dense bf16 tower. That is the one lie this whole change exists to stop.
+ from core.inference import diffusion as dmod
+ from core.inference.diffusion_precision import TEQuantOutcome
+
+ (tmp_path / "m.gguf").write_bytes(b"x")
+ monkeypatch.setattr(
+ dmod,
+ "quantize_text_encoders",
+ lambda *a, **k: TEQuantOutcome(
+ "fp8",
+ "'fp8' engaged on text_encoder but text_encoder_2 stayed dense",
+ "fell_back",
+ True,
+ ),
+ )
+ with pytest.raises(RuntimeError) as excinfo:
+ DiffusionBackend().load_pipeline(
+ str(tmp_path),
+ gguf_filename = "m.gguf",
+ family_override = "z-image",
+ text_encoder_quant = "fp8",
+ )
+ message = str(excinfo.value)
+ assert "text_encoder_quant='fp8' could not be used" in message
+ assert "text_encoder_2" in message
+ # And the remedy names something the request model accepts: text_encoder_quant has no "auto".
+ assert "Auto" not in message
+
+
+def test_text_encoder_int8_downgrade_is_reported_not_refused(fake_runtime, tmp_path, monkeypatch):
+ # int8 without a measured keep-bf16 schedule becomes fp8. The encoder IS quantised, just not
+ # the way asked, so this WARNS through the resolved record instead of stopping the load.
+ from core.inference import diffusion as dmod
+ from core.inference.diffusion_precision import TEQuantOutcome
+
+ monkeypatch.setattr(
+ dmod,
+ "quantize_text_encoders",
+ lambda pipe, target, **kw: TEQuantOutcome(
+ "fp8", "int8 has no measured keep-bf16 schedule for family 'z-image'", "fell_back"
+ ),
+ )
+ (tmp_path / "m.gguf").write_bytes(b"x")
+ status = DiffusionBackend().load_pipeline(
+ str(tmp_path),
+ gguf_filename = "m.gguf",
+ family_override = "z-image",
+ text_encoder_quant = "int8",
+ )
+ assert status["loaded"] is True
+ assert status["text_encoder_quant"] == "fp8"
+ resolved = status["resolved"]["text_encoder_quant"]
+ assert resolved["requested"] == "int8"
+ assert resolved["value"] == "fp8"
+ assert resolved["status"] == "fell_back"
+ assert "keep-bf16 schedule" in resolved["reason"]
+
+
+def test_begin_load_never_refuses_auto(fake_runtime, tmp_path, monkeypatch):
+ # The same CPU host with `auto` must sail through: delegating the choice is not a contract.
+ (tmp_path / "m.gguf").write_bytes(b"x")
+ backend = DiffusionBackend()
+ started = backend.begin_load(
+ str(tmp_path),
+ gguf_filename = "m.gguf",
+ family_override = "z-image",
+ model_kind = "gguf",
+ transformer_quant = "auto",
+ )
+ assert started["loaded"] is False # returns immediately; the load runs on a thread
+
+
+def test_transformer_quant_falls_back_to_gguf_on_failure(
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
+):
# A dense/quant failure (here quantize returns None) must fall back to the GGUF build, not error.
from core.inference import diffusion as dmod
@@ -3046,7 +3338,9 @@ def test_transformer_quant_falls_back_to_gguf_on_failure(fake_runtime, tmp_path,
assert _FakeTransformer.last["path"] # GGUF from_single_file used
-def test_transformer_quant_skipped_when_plan_offloads(fake_runtime, tmp_path, monkeypatch):
+def test_transformer_quant_skipped_when_plan_offloads(
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
+):
# The dense bf16 transformer only fits resident, so when the plan would offload (low_vram) the fast path is skipped.
from core.inference import diffusion as dmod
@@ -3073,7 +3367,7 @@ def test_transformer_quant_skipped_when_plan_offloads(fake_runtime, tmp_path, mo
def test_dense_quant_skipped_when_dense_transformer_does_not_fit(
- fake_runtime, tmp_path, monkeypatch
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
):
# The GGUF fits resident but the dense bf16 transformer does not: skip the fast path up front and load GGUF resident, not evicted then offloaded.
from core.inference import diffusion as dmod
@@ -3124,7 +3418,7 @@ def test_dense_quant_skipped_when_dense_transformer_does_not_fit(
def test_dense_quant_prequant_proceeds_but_forbids_dense_fallback(
- fake_runtime, tmp_path, monkeypatch
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
):
# With a prequant checkpoint a dense misfit must NOT decline the fast path, but the dense re-check still gates the in-loader fallback.
from core.inference import diffusion as dmod
@@ -3180,7 +3474,7 @@ def test_dense_quant_prequant_proceeds_but_forbids_dense_fallback(
def test_dense_quant_replan_retries_once_on_transient_free_undercount(
- fake_runtime, tmp_path, monkeypatch
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
):
# A transient foreign allocation makes an empty card look full and the replan declines resident, but the candidate fits total capacity, so the loader retries once on a fresh settled snapshot.
import dataclasses
@@ -3248,7 +3542,9 @@ def test_dense_quant_replan_retries_once_on_transient_free_undercount(
assert attempted == [False] # fast path attempted; prequant-sized plan forbids dense fallback
-def test_dense_quant_replan_no_retry_when_capacity_truly_short(fake_runtime, tmp_path, monkeypatch):
+def test_dense_quant_replan_no_retry_when_capacity_truly_short(
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
+):
# When the candidate does NOT fit total capacity, the decline is real: no retry.
import dataclasses
@@ -3363,7 +3659,9 @@ def test_declined_dense_with_baked_loras_fails_instead_of_silent_drop(
)
-def test_declined_dense_without_loras_still_falls_back_to_gguf(fake_runtime, tmp_path, monkeypatch):
+def test_declined_dense_without_loras_still_falls_back_to_gguf(
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
+):
# The plain decline (no adapters requested) keeps the silent GGUF fallback: weight-0 adapters count as "none".
backend = DiffusionBackend()
_decline_dense_quant(backend, monkeypatch, tmp_path)
@@ -3591,7 +3889,9 @@ def test_assemble_pipe_routes_krea2_per_component(monkeypatch):
assert calls == {"base": "unsloth/Krea-2-Turbo", "transformer": marker, "device": "cuda:0"}
-def test_dense_quant_unusable_prequant_path_runs_dense_refit(fake_runtime, tmp_path, monkeypatch):
+def test_dense_quant_unusable_prequant_path_runs_dense_refit(
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
+):
# A request prequant path the loader refuses resolves to no usable source, so the dense-fit re-check must run and decline up front instead of OOMing after eviction.
from core.inference import diffusion as dmod
@@ -3641,7 +3941,7 @@ def test_dense_quant_unusable_prequant_path_runs_dense_refit(fake_runtime, tmp_p
def test_transformer_quant_unsupported_scheme_skips_dense_download(
- fake_runtime, tmp_path, monkeypatch
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
):
# An explicit unsupported scheme must fail BEFORE materialising the multi-GB dense transformer, then fall back to GGUF.
from core.inference import diffusion as dmod
@@ -3916,7 +4216,7 @@ def test_a_weighted_lora_is_still_treated_as_a_bake(fake_runtime, tmp_path, monk
def test_an_explicit_quant_request_still_downloads_the_hosted_prequant(
- fake_runtime, tmp_path, monkeypatch
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
):
# Only the AUTO-derived case is restricted: asking for fp8 asks for the artifact serving it.
_stub_hosted_prequant(monkeypatch, cached = False)
@@ -4108,11 +4408,38 @@ def test_diffusion_status_response_carries_resolved():
rec = {"transformer_quant": {"value": "fp8", "source": "auto", "reason": "blackwell"}}
resp = DiffusionStatusResponse(loaded = True, resolved = rec)
# The typed field coerces the record into DiffusionResolvedControl objects; the serialized form must round-trip.
- assert resp.model_dump()["resolved"] == rec
+ # requested/status are additive with defaults, so a record from an older backend still parses.
+ assert resp.model_dump()["resolved"] == {
+ "transformer_quant": {
+ "value": "fp8",
+ "requested": None,
+ "source": "auto",
+ "status": "applied",
+ "reason": "blackwell",
+ }
+ }
# Absent by default (nothing resolved / native engine).
assert DiffusionStatusResponse(loaded = False).resolved is None
+def test_diffusion_status_response_carries_requested_precision():
+ # The point of P1-2: a DECLINED explicit precision must survive the API boundary, so the UI can
+ # say "you asked for fp8, the GGUF ran" instead of rendering the request as if it engaged.
+ from models.inference import DiffusionStatusResponse
+
+ rec = {
+ "transformer_quant": {
+ "value": "off",
+ "requested": "fp8",
+ "source": "explicit",
+ "status": "fell_back",
+ "reason": "the dense bf16 transformer does not fit resident",
+ }
+ }
+ resp = DiffusionStatusResponse(loaded = True, resolved = rec)
+ assert resp.model_dump()["resolved"] == rec
+
+
def test_companion_cache_bytes_local_dir_excludes_transformer(tmp_path):
# A local diffusers base: sum the on-disk VAE / text-encoder weights, excluding transformer/ (the GGUF supplies it) and non-weight files.
(tmp_path / "vae").mkdir()
@@ -4571,7 +4898,7 @@ def test_dense_transformer_bytes_read_the_other_root_and_treat_the_snapshot_as_a
@pytest.mark.parametrize("staged", [False, True])
def test_dense_fit_check_runs_for_a_base_the_live_cache_root_does_not_hold(
- fake_runtime, tmp_path, monkeypatch, staged
+ fake_runtime, tmp_path, monkeypatch, staged, allow_precision_fallback
):
# End of the same hole, at the load: with no usable prequant the loader materialises the dense
# bf16 transformer, so the fit re-check has to run, and it only runs when the size lookup finds
diff --git a/studio/backend/tests/test_diffusion_precision.py b/studio/backend/tests/test_diffusion_precision.py
index cd90c141f18..d8ad0adccc2 100644
--- a/studio/backend/tests/test_diffusion_precision.py
+++ b/studio/backend/tests/test_diffusion_precision.py
@@ -23,6 +23,7 @@ from core.inference.diffusion_precision import (
_cast_int8_selective,
_cast_nvfp4,
_keep_bf16_block_fqns,
+ effective_te_quant,
normalize_te_quant,
quantize_text_encoders,
te_quant_supported,
@@ -148,8 +149,8 @@ def test_fp8_dynamic_supported_requires_sm89_and_fp8(monkeypatch):
def test_quantize_disabled_returns_none(monkeypatch):
_stub_torch(monkeypatch)
pipe = types.SimpleNamespace(text_encoder = object())
- assert quantize_text_encoders(pipe, _target(), mode = None) is None
- assert quantize_text_encoders(pipe, _target(), mode = "none") is None
+ assert quantize_text_encoders(pipe, _target(), mode = None).mode is None
+ assert quantize_text_encoders(pipe, _target(), mode = "none").mode is None
def test_quantize_fp8_casts_all_encoders(monkeypatch):
@@ -158,8 +159,9 @@ def test_quantize_fp8_casts_all_encoders(monkeypatch):
_stub_casters(monkeypatch, recorder)
te1, te3 = object(), object()
pipe = types.SimpleNamespace(text_encoder = te1, text_encoder_2 = None, text_encoder_3 = te3)
- mode = quantize_text_encoders(pipe, _target(), mode = "fp8")
- assert mode == TE_QUANT_FP8
+ outcome = quantize_text_encoders(pipe, _target(), mode = "fp8")
+ assert outcome.mode == TE_QUANT_FP8
+ assert outcome.status == "applied"
assert recorder == [("fp8", te1), ("fp8", te3)]
@@ -169,8 +171,8 @@ def test_quantize_nvfp4_uses_torchao(monkeypatch):
_stub_casters(monkeypatch, recorder)
te = object()
pipe = types.SimpleNamespace(text_encoder = te)
- mode = quantize_text_encoders(pipe, _target(), mode = "nvfp4")
- assert mode == TE_QUANT_NVFP4
+ outcome = quantize_text_encoders(pipe, _target(), mode = "nvfp4")
+ assert outcome.mode == TE_QUANT_NVFP4
assert recorder == [("nvfp4", te)]
@@ -179,7 +181,10 @@ def test_quantize_nvfp4_unsupported_on_hopper_is_noop(monkeypatch):
recorder: list = []
_stub_casters(monkeypatch, recorder)
pipe = types.SimpleNamespace(text_encoder = object())
- assert quantize_text_encoders(pipe, _target(cc = (9, 0)), mode = "nvfp4") is None
+ outcome = quantize_text_encoders(pipe, _target(cc = (9, 0)), mode = "nvfp4")
+ assert outcome.mode is None
+ # An unsupported request is now REPORTED rather than silently skipped.
+ assert outcome.status == "unsupported" and "nvfp4" in outcome.reason
assert recorder == []
@@ -196,8 +201,9 @@ def test_quantize_tolerates_caster_failure(monkeypatch):
monkeypatch.setitem(sys.modules, "diffusers.hooks", hooks)
monkeypatch.setitem(sys.modules, "diffusers.hooks.layerwise_casting", casting)
pipe = types.SimpleNamespace(text_encoder = object())
- # The only encoder fails to cast -> nothing applied -> None.
- assert quantize_text_encoders(pipe, _target(), mode = "fp8") is None
+ # The only encoder fails to cast -> nothing applied -> None, reported as a fallback.
+ outcome = quantize_text_encoders(pipe, _target(), mode = "fp8")
+ assert outcome.mode is None and outcome.status == "fell_back"
# ── int8 (selective) + fp8_dynamic routing ─────────────────────────────────────
@@ -212,8 +218,9 @@ def test_quantize_int8_uses_family_keep_bf16_schedule(monkeypatch):
)
te = object()
pipe = types.SimpleNamespace(text_encoder = te)
- mode = quantize_text_encoders(pipe, _target(), mode = "int8", family = "qwen-image")
- assert mode == TE_QUANT_INT8
+ outcome = quantize_text_encoders(pipe, _target(), mode = "int8", family = "qwen-image")
+ assert outcome.mode == TE_QUANT_INT8
+ assert outcome.status == "applied"
assert calls == [(te, 6, 6)]
@@ -226,8 +233,11 @@ def test_quantize_int8_unknown_family_falls_back_to_fp8(monkeypatch):
monkeypatch.setattr(dp, "_cast_fp8", lambda enc, tgt: fp8_calls.append(enc))
te = object()
pipe = types.SimpleNamespace(text_encoder = te)
- mode = quantize_text_encoders(pipe, _target(), mode = "int8", family = "wan-umt5")
- assert mode == TE_QUANT_FP8
+ outcome = quantize_text_encoders(pipe, _target(), mode = "int8", family = "wan-umt5")
+ assert outcome.mode == TE_QUANT_FP8
+ # The downgrade is reported, not silent: this is what the status badge renders.
+ assert outcome.status == "fell_back"
+ assert "no measured keep-bf16 schedule" in outcome.reason and "wan-umt5" in outcome.reason
assert int8_calls == [] and fp8_calls == [te]
@@ -238,8 +248,8 @@ def test_quantize_fp8_dynamic_uses_compute_caster(monkeypatch):
monkeypatch.setattr(dp, "_cast_fp8_dynamic", lambda enc, tgt: calls.append(enc))
te = object()
pipe = types.SimpleNamespace(text_encoder = te)
- mode = quantize_text_encoders(pipe, _target(), mode = "fp8_dynamic")
- assert mode == TE_QUANT_FP8_DYNAMIC
+ outcome = quantize_text_encoders(pipe, _target(), mode = "fp8_dynamic")
+ assert outcome.mode == TE_QUANT_FP8_DYNAMIC
assert calls == [te]
@@ -248,7 +258,7 @@ def test_quantize_int8_unsupported_hw_is_noop(monkeypatch):
_stub_torch(monkeypatch, cc = (7, 5))
monkeypatch.setattr(dp, "_cast_int8_selective", lambda *a: pytest.fail("must not cast"))
pipe = types.SimpleNamespace(text_encoder = object())
- assert quantize_text_encoders(pipe, _target(), mode = "int8", family = "qwen-image") is None
+ assert quantize_text_encoders(pipe, _target(), mode = "int8", family = "qwen-image").mode is None
def test_quantize_te_skips_torchao_modes_under_offload(monkeypatch):
@@ -263,18 +273,23 @@ def test_quantize_te_skips_torchao_modes_under_offload(monkeypatch):
dp, "_cast_int8_selective", lambda *a: pytest.fail("torchao caster must not run")
)
pipe = types.SimpleNamespace(text_encoder = object())
- assert quantize_text_encoders(pipe, _target(), mode = "fp8_dynamic", offload_active = True) is None
- assert quantize_text_encoders(pipe, _target(), mode = "nvfp4", offload_active = True) is None
+ skipped = quantize_text_encoders(pipe, _target(), mode = "fp8_dynamic", offload_active = True)
+ assert skipped.mode is None and skipped.status == "unsupported"
+ assert "offload" in skipped.reason
+ assert quantize_text_encoders(pipe, _target(), mode = "nvfp4", offload_active = True).mode is None
assert (
quantize_text_encoders(
pipe, _target(), mode = "int8", family = "qwen-image", offload_active = True
- )
+ ).mode
is None
)
# Layerwise fp8 is not torchao and streams fine under offload, so it still engages.
fp8_calls: list = []
monkeypatch.setattr(dp, "_cast_fp8", lambda enc, tgt: fp8_calls.append(enc))
- assert quantize_text_encoders(pipe, _target(), mode = "fp8", offload_active = True) == TE_QUANT_FP8
+ assert (
+ quantize_text_encoders(pipe, _target(), mode = "fp8", offload_active = True).mode
+ == TE_QUANT_FP8
+ )
assert len(fp8_calls) == 1
@@ -458,3 +473,49 @@ def test_fp8_dynamic_filter_skips_zero_row_linear(monkeypatch):
live = types.SimpleNamespace(weight = _FakeWeight([[0.5, 0.5], [0.5, 0.5]]))
assert ff(dead, "text_model.encoder.layers.2.self_attn.out_proj") is False
assert ff(live, "text_model.encoder.layers.2.mlp.fc1") is True
+
+
+def test_quantize_partial_cast_is_reported_as_a_mixture(monkeypatch):
+ # One encoder takes the cast and its sibling does not. The mode DID engage, so the old code
+ # returned "applied" and both loaders' fail-closed checks (which only look at mode is None)
+ # let the load through, recording the requested mode as the engaged precision -- while the
+ # prompt was conditioned by one quantised and one dense bf16 tower.
+ _stub_torch(monkeypatch)
+ good, bad = object(), object()
+
+ def _caster(enc, tgt):
+ if enc is bad:
+ raise RuntimeError("fp8 unsupported for this layer")
+
+ monkeypatch.setattr(dp, "_cast_fp8", _caster)
+ pipe = types.SimpleNamespace(text_encoder = good, text_encoder_2 = bad)
+ outcome = quantize_text_encoders(pipe, _target(), mode = "fp8")
+ assert outcome.mode == TE_QUANT_FP8
+ assert outcome.partial is True
+ assert outcome.status == "fell_back"
+ assert "text_encoder_2" in outcome.reason
+
+
+def test_quantize_full_cast_is_not_partial(monkeypatch):
+ # The other side of the same fence: every present encoder cast, so nothing is a mixture and
+ # the loaders must not refuse.
+ _stub_torch(monkeypatch)
+ monkeypatch.setattr(dp, "_cast_fp8", lambda enc, tgt: None)
+ pipe = types.SimpleNamespace(text_encoder = object(), text_encoder_2 = object())
+ outcome = quantize_text_encoders(pipe, _target(), mode = "fp8")
+ assert outcome.partial is False and outcome.status == "applied"
+
+
+def test_int8_without_a_schedule_reports_fp8_as_the_effective_mode():
+ # quantize_text_encoders rewrites an int8 request to layerwise fp8 on any family with no
+ # keep-bf16 schedule, and that path never touches torchao. A gate that asks about the raw
+ # int8 therefore refuses loads the runtime would happily run and report as fell_back: on a
+ # host whose torchao cannot do int8 while fp8 still works, every unscheduled family died.
+ assert effective_te_quant(TE_QUANT_INT8, "z-image-turbo") == TE_QUANT_FP8
+ assert effective_te_quant(TE_QUANT_INT8, None) == TE_QUANT_FP8
+ # A family WITH a schedule really does run int8, so the gate must keep asking about int8.
+ assert effective_te_quant(TE_QUANT_INT8, "qwen-image") == TE_QUANT_INT8
+ assert effective_te_quant(TE_QUANT_INT8, "Flux.2-Dev") == TE_QUANT_INT8
+ # Every other mode is its own effective mode, and absent stays absent.
+ assert effective_te_quant(TE_QUANT_FP8_DYNAMIC, "z-image-turbo") == TE_QUANT_FP8_DYNAMIC
+ assert effective_te_quant(None, "qwen-image") is None
diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.py
index b5a0e5acf79..be69f19eb4c 100644
--- a/studio/backend/tests/test_diffusion_routes.py
+++ b/studio/backend/tests/test_diffusion_routes.py
@@ -10,6 +10,8 @@ diffusers, weights, or a GPU.
from __future__ import annotations
+import types
+
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
@@ -69,6 +71,18 @@ class _FakeBackend:
# The real backends probe the Hub for a gated companion here; the fake clears every pick.
return None
+ def assert_precision_available(self, fam, **kwargs):
+ # The route's pre-eviction precision refusal, asked of the backend. The fake clears every
+ # request; the tests that care re-patch this to raise.
+ self.last_precision_kwargs = dict(kwargs)
+ return None
+
+ def download_plan(self, model_path, **kwargs):
+ # The plan route's staging answer. The fake records what it was asked so a test can prove
+ # the precision refusal ran BEFORE the plan was built (this never gets called then).
+ self.last_plan_kwargs = dict(kwargs)
+ return {"entries": [], "total_bytes": 0, "incompatible_reason": None}
+
def begin_load(self, model_path, **kwargs):
# The real backend loads on a thread; the fake completes instantly.
self.loaded = True
@@ -1206,7 +1220,13 @@ def test_status_passes_through_resolved(client, monkeypatch):
backend = diffusion_module.get_diffusion_backend()
resolved = {
"speed_mode": {"value": "eager", "source": "auto", "reason": "per-kind default"},
- "transformer_quant": {"value": "int8", "source": "explicit", "reason": "requested"},
+ "transformer_quant": {
+ "value": "off",
+ "requested": "fp8",
+ "source": "explicit",
+ "status": "fell_back",
+ "reason": "the dense bf16 transformer does not fit resident",
+ },
"cpu_offload": {"value": False, "source": "auto", "reason": "from the memory plan"},
"transformer_cache": {"value": None, "source": "auto", "reason": "few-step model"},
}
@@ -1214,10 +1234,14 @@ def test_status_passes_through_resolved(client, monkeypatch):
backend, "status", lambda: {**_unloaded_status(), "loaded": True, "resolved": resolved}
)
body = client.get("/api/inference/images/status").json()
- assert body["resolved"] == resolved
assert body["resolved"]["speed_mode"]["source"] == "auto"
# The cpu_offload value stays a real boolean (not coerced to a string).
assert body["resolved"]["cpu_offload"]["value"] is False
+ # A declined explicit precision keeps BOTH sides across the boundary: ask and outcome.
+ assert body["resolved"]["transformer_quant"] == resolved["transformer_quant"]
+ # Entries from an older backend (no requested/status) still parse, defaulted to "applied".
+ assert body["resolved"]["speed_mode"]["requested"] is None
+ assert body["resolved"]["speed_mode"]["status"] == "applied"
def test_status_resolved_defaults_to_null(client):
@@ -1226,6 +1250,278 @@ def test_status_resolved_defaults_to_null(client):
assert body["resolved"] is None
+def test_load_refuses_an_unusable_explicit_precision_with_409(client, monkeypatch):
+ # begin_load raises for an EXPLICIT precision this host cannot honor, and the route surfaces it
+ # as a 409 carrying the reason -- instead of accepting the load and rendering at some other
+ # precision. The frontend shows the detail verbatim.
+ from core.inference.diffusion_auto_policy import precision_refusal_message
+
+ backend = diffusion_module.get_diffusion_backend()
+ refusal = precision_refusal_message(
+ "transformer_quant",
+ "fp8",
+ "this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16)",
+ off_label = "Off to run the checkpoint as-is",
+ )
+
+ def _refuse(model_path, **kwargs):
+ raise RuntimeError(refusal)
+
+ monkeypatch.setattr(backend, "begin_load", _refuse)
+ resp = client.post(
+ "/api/inference/images/load",
+ json = {
+ "model_path": "unsloth/Z-Image-Turbo-GGUF",
+ "gguf_filename": "z-image-turbo-Q4_K_M.gguf",
+ "transformer_quant": "fp8",
+ },
+ )
+ assert resp.status_code == 409
+ detail = resp.json()["detail"]
+ assert "transformer_quant='fp8' could not be used" in detail
+ assert "Auto" in detail and "Off" in detail
+ # Nothing was loaded, so the UI is not left half-initialised.
+ assert client.get("/api/inference/images/status").json()["loaded"] is False
+
+
+def test_precision_refusal_precedes_eviction_and_engine_selection(client, monkeypatch):
+ # The refusal has to land BEFORE the GPU handoff. acquire_for evicts chat under the arbiter
+ # lock before it runs the register callback, and select_and_activate_engine unloads the
+ # resident model on an engine switch, so a refusal made inside begin_load arrives having
+ # already destroyed both things the 409 exists to preserve.
+ import core.inference.diffusion_engine_router as engine_router
+ from core.inference.diffusion_auto_policy import precision_refusal_message
+
+ backend = diffusion_module.get_diffusion_backend()
+ evicted = []
+ selected = []
+ monkeypatch.setitem(gpu_arbiter._EVICTORS, gpu_arbiter.CHAT, lambda: evicted.append("chat"))
+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)
+ monkeypatch.setattr(
+ engine_router,
+ "select_and_activate_engine",
+ lambda fam, **kw: (selected.append(fam), backend)[1],
+ )
+ refusal = precision_refusal_message(
+ "transformer_quant",
+ "fp8",
+ "this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16)",
+ off_label = "Off to run the checkpoint as-is",
+ )
+
+ def _refuse(fam, **kwargs):
+ raise RuntimeError(refusal)
+
+ monkeypatch.setattr(backend, "assert_precision_available", _refuse)
+ # begin_load must never be reached: the download and the eviction both hang off it.
+ monkeypatch.setattr(
+ backend,
+ "begin_load",
+ lambda *a, **k: pytest.fail("begin_load ran after an impossible precision"),
+ )
+ resp = client.post(
+ "/api/inference/images/load",
+ json = {
+ "model_path": "unsloth/Z-Image-Turbo-GGUF",
+ "gguf_filename": "z-image-turbo-Q4_K_M.gguf",
+ "transformer_quant": "fp8",
+ },
+ )
+ assert resp.status_code == 409
+ assert "transformer_quant='fp8' could not be used" in resp.json()["detail"]
+ assert evicted == [] # chat still holds the GPU
+ assert selected == [] # and the engine was never switched
+ assert gpu_arbiter.current_owner() == gpu_arbiter.CHAT
+
+
+def test_the_native_engine_refuses_an_explicit_precision_it_cannot_honour(client, monkeypatch):
+ """sd.cpp accepts transformer_quant / text_encoder_quant for interface parity and IGNORES
+ them, so an explicit fp8 used to load happily, quantise nothing and report null -- the exact
+ silent mismatch this change exists to remove, on the one engine that was exempt from it. The
+ diffusers path already refuses on the same CPU-only host, so exempting this one also left the
+ two engines disagreeing about the same request."""
+ import core.inference.diffusion_engine_router as engine_router
+ from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+
+ monkeypatch.setattr(engine_router, "predict_engine", lambda fam, **kw: ENGINE_SD_CPP)
+ resp = client.post(
+ "/api/inference/images/load",
+ json = {
+ "model_path": "unsloth/Z-Image-Turbo-GGUF",
+ "gguf_filename": "z-image-turbo-Q4_K_M.gguf",
+ "transformer_quant": "fp8",
+ },
+ )
+ assert resp.status_code == 409, resp.text
+ assert "native engine" in resp.json()["detail"]
+
+
+def test_a_failed_engine_prediction_still_gates_the_precision_after_selection(client, monkeypatch):
+ """predict_engine is a probe, and a probe can raise -- an sd-cli query against a broken
+ install, a filesystem error reading the cache. That left pending_name None, so BOTH gate arms
+ above were skipped, and selection then landed on sd.cpp anyway: the explicit fp8 was accepted,
+ nothing was quantised and the status reported null. The gate is re-asked of the engine that
+ was actually activated, so an inconclusive prediction cannot buy a silent mismatch."""
+ import core.inference.diffusion_engine_router as engine_router
+ from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+
+ backend = diffusion_module.get_diffusion_backend()
+
+ def _boom(fam, **kw):
+ raise RuntimeError("sd-cli probe failed")
+
+ monkeypatch.setattr(engine_router, "predict_engine", _boom)
+ monkeypatch.setattr(engine_router, "active_engine_name", lambda: ENGINE_SD_CPP)
+ monkeypatch.setattr(
+ engine_router,
+ "select_and_activate_engine",
+ lambda fam, **kw: backend,
+ )
+ monkeypatch.setattr(
+ backend,
+ "begin_load",
+ lambda *a, **k: pytest.fail("begin_load ran after an unhonourable precision"),
+ )
+ resp = client.post(
+ "/api/inference/images/load",
+ json = {
+ "model_path": "unsloth/Z-Image-Turbo-GGUF",
+ "gguf_filename": "z-image-turbo-Q4_K_M.gguf",
+ "transformer_quant": "fp8",
+ },
+ )
+ assert resp.status_code == 409, resp.text
+ assert "native engine" in resp.json()["detail"]
+
+
[email protected]("quant", [None, "auto", "none"])
+def test_the_native_engine_still_loads_when_nothing_was_promised(client, monkeypatch, quant):
+ """The refusal is about an explicit request only. Omitted, auto and none all delegate the
+ choice, so a CPU-only host's ordinary GGUF load must keep working exactly as it does today."""
+ import core.inference.diffusion_engine_router as engine_router
+ from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+
+ monkeypatch.setattr(engine_router, "predict_engine", lambda fam, **kw: ENGINE_SD_CPP)
+ payload = {
+ "model_path": "unsloth/Z-Image-Turbo-GGUF",
+ "gguf_filename": "z-image-turbo-Q4_K_M.gguf",
+ }
+ if quant is not None:
+ payload["transformer_quant"] = quant
+ resp = client.post("/api/inference/images/load", json = payload)
+ assert resp.status_code == 200, resp.text
+
+
+def test_the_plan_refuses_an_impossible_precision_before_anything_is_staged(client, monkeypatch):
+ """The UI plans first and stages every entry it gets back, so a refusal that only lives in
+ /images/load arrives AFTER the download it should have prevented -- the GGUF and its
+ companions on the image side, tens of GB on the video one. Both checks are network-free, so
+ doing them here costs nothing."""
+ from core.inference.diffusion_auto_policy import precision_refusal_message
+
+ backend = diffusion_module.get_diffusion_backend()
+ refusal = precision_refusal_message(
+ "transformer_quant",
+ "fp8",
+ "this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16)",
+ off_label = "Off to run the checkpoint as-is",
+ )
+
+ def _refuse(fam, **kwargs):
+ raise RuntimeError(refusal)
+
+ monkeypatch.setattr(backend, "assert_precision_available", _refuse)
+ monkeypatch.setattr(
+ backend,
+ "download_plan",
+ lambda *a, **k: pytest.fail("the plan was built for a precision that cannot be honoured"),
+ )
+ resp = client.post(
+ "/api/inference/images/download-plan",
+ json = {
+ "model_path": "unsloth/Z-Image-Turbo-GGUF",
+ "gguf_filename": "z-image-turbo-Q4_K_M.gguf",
+ "transformer_quant": "fp8",
+ },
+ )
+ assert resp.status_code == 409, resp.text
+ assert "transformer_quant='fp8' could not be used" in resp.json()["detail"]
+
+
+def test_the_plan_does_not_probe_the_gpu_while_training_holds_it(client, monkeypatch):
+ """An UNCACHED scheme sends assert_precision_available into a quantise-and-matmul smoke
+ probe, which initialises CUDA and allocates in the Studio process. /images/load refuses
+ outright while a trainer is running, for exactly that reason -- but the UI asks for the
+ plan first, so the probe ran before that guard had a say. Staging files needs no GPU, so
+ the plan is answered; the load still refuses the same pick afterwards."""
+ import routes.inference as inference_routes
+
+ backend = diffusion_module.get_diffusion_backend()
+ monkeypatch.setattr(inference_routes, "_training_is_active", lambda: True)
+ monkeypatch.setattr(
+ backend,
+ "assert_precision_available",
+ lambda *a, **k: pytest.fail("the precision probe must not touch the GPU during training"),
+ )
+
+ resp = client.post(
+ "/api/inference/images/download-plan",
+ json = {
+ "model_path": "unsloth/Z-Image-Turbo-GGUF",
+ "gguf_filename": "z-image-turbo-Q4_K_M.gguf",
+ "transformer_quant": "fp8",
+ },
+ )
+ assert resp.status_code == 200, resp.text
+
+
+def test_the_native_plan_refuses_the_same_request_the_native_load_would(client, monkeypatch):
+ import core.inference.diffusion_engine_router as engine_router
+ from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+
+ monkeypatch.setattr(engine_router, "predict_engine", lambda fam, **kw: ENGINE_SD_CPP)
+ resp = client.post(
+ "/api/inference/images/download-plan",
+ json = {
+ "model_path": "unsloth/Z-Image-Turbo-GGUF",
+ "gguf_filename": "z-image-turbo-Q4_K_M.gguf",
+ "transformer_quant": "fp8",
+ },
+ )
+ assert resp.status_code == 409, resp.text
+ assert "native engine" in resp.json()["detail"]
+
+
+def test_the_plan_still_answers_when_nothing_was_promised(client):
+ resp = client.post(
+ "/api/inference/images/download-plan",
+ json = {
+ "model_path": "unsloth/Z-Image-Turbo-GGUF",
+ "gguf_filename": "z-image-turbo-Q4_K_M.gguf",
+ },
+ )
+ assert resp.status_code == 200, resp.text
+
+
+def test_the_native_refusal_is_waived_by_the_fallback_escape_hatch(client, monkeypatch):
+ """Same escape hatch as every other precision refusal, or this one becomes the only
+ unbypassable member of the family."""
+ import core.inference.diffusion_engine_router as engine_router
+ from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+
+ monkeypatch.setattr(engine_router, "predict_engine", lambda fam, **kw: ENGINE_SD_CPP)
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK", "1")
+ resp = client.post(
+ "/api/inference/images/load",
+ json = {
+ "model_path": "unsloth/Z-Image-Turbo-GGUF",
+ "gguf_filename": "z-image-turbo-Q4_K_M.gguf",
+ "transformer_quant": "fp8",
+ },
+ )
+ assert resp.status_code == 200, resp.text
+
+
def test_download_plan_forwards_the_load_time_controls(client, monkeypatch):
# The plan drives the staged download, so it must be computed from the SAME configuration the load will run with: the
# prefetch decision reads the memory policy, prequant path and adapter selection as well as speed/quant.
@@ -1464,6 +1760,11 @@ def test_recipe_records_the_load_time_build(client, monkeypatch):
"model_kind": "gguf",
"gguf_filename": "z-image-turbo-Q8_0.gguf",
"transformer_quant": "int8",
+ # The rest of the precision picture, all ENGAGED values: the text encoder is often the
+ # largest resident component and the memory mode decides whether it could be cast.
+ "text_encoder_quant": "fp8",
+ "memory_mode": "balanced",
+ "offload_policy": "group",
# Baked at LOAD time; the generate request below carries no adapters, so the applied set is empty.
"baked_loras": ["bakedlora"],
"active_loras": [],
@@ -1483,9 +1784,15 @@ def test_recipe_records_the_load_time_build(client, monkeypatch):
assert img["model_kind"] == "gguf"
assert img["gguf_filename"] == "z-image-turbo-Q8_0.gguf"
assert img["transformer_quant"] == "int8"
+ assert img["text_encoder_quant"] == "fp8"
+ assert img["memory_mode"] == "balanced"
+ assert img["offload_policy"] == "group"
# The bake is recorded even though nothing was applied to THIS generation.
assert img["baked_loras"] == ["bakedlora"]
assert img["loras"] == []
+ # The recipe survives a reload from the PNG's own text chunk, not just this response.
+ listed = client.get("/api/inference/images/gallery").json()["images"][0]
+ assert listed["text_encoder_quant"] == "fp8" and listed["memory_mode"] == "balanced"
def test_recipe_build_fields_absent_on_an_engine_that_omits_them(client):
@@ -1499,6 +1806,11 @@ def test_recipe_build_fields_absent_on_an_engine_that_omits_them(client):
assert img["model_kind"] is None
assert img["gguf_filename"] is None
assert img["transformer_quant"] is None
+ # Same for the precision fields added later: absent keys read back as null, and the PNG still
+ # lists (they are not in image_gallery._REQUIRED_META).
+ assert img["text_encoder_quant"] is None
+ assert img["memory_mode"] is None and img["offload_policy"] is None
+ assert len(client.get("/api/inference/images/gallery").json()["images"]) == 1
assert img["baked_loras"] == []
@@ -1522,3 +1834,164 @@ def test_gallery_image_accepts_a_record_written_before_the_build_fields():
assert record.gguf_filename is None
assert record.transformer_quant is None
assert record.baked_loras == []
+
+
+ "memory",
+ [
+ {"memory_mode": "balanced"},
+ {"memory_mode": "low_vram"},
+ {"cpu_offload": True},
+ ],
+)
+def test_an_offloading_memory_request_refuses_an_explicit_precision(monkeypatch, memory):
+ """balanced and low_vram name their offload policy outright, and the legacy cpu_offload flag
+ forces whole-module offload. Offload hooks move modules with Module.to(), which torchao
+ tensors do not survive, so the loader skips the dense build -- and the strict refusal then
+ arrived after the resident image model had already been torn down. The two requests are
+ incompatible on their face, so the refusal is owed before anything is staged or evicted."""
+ from core.inference.diffusion import DiffusionBackend
+
+ backend = DiffusionBackend.__new__(DiffusionBackend)
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_resolve_device_target",
+ lambda self, fam: types.SimpleNamespace(device = "cuda", dtype = "bfloat16", _cc = (10, 0)),
+ )
+ with pytest.raises(RuntimeError) as excinfo:
+ backend.assert_precision_available(
+ None, model_kind = "gguf", transformer_quant = "fp8", **memory
+ )
+ assert "transformer_quant='fp8' could not be used" in str(excinfo.value)
+ assert "offload" in str(excinfo.value)
+
+
+def test_a_measured_memory_mode_is_not_refused_by_the_precision_gate(monkeypatch):
+ """fast and auto decide their policy from the MEASURED footprint, so they are not knowable
+ network-free and this gate has no business refusing them."""
+ from core.inference.diffusion import _memory_request_forces_offload
+
+ assert _memory_request_forces_offload("fast", False) is False
+ assert _memory_request_forces_offload("auto", False) is False
+ assert _memory_request_forces_offload(None, False) is False
+ # The legacy flag applies only when no mode was named, matching resolve_offload_policy.
+ assert _memory_request_forces_offload("fast", True) is False
+ assert _memory_request_forces_offload(None, True) is True
+
+
+def test_fast_and_auto_memory_do_not_refuse_a_precision(client, monkeypatch):
+ """The other side of the fence: fast and auto decide their policy from the MEASURED
+ footprint, so they are not knowable network-free and must not be refused here."""
+ import core.inference.diffusion_engine_router as engine_router
+ from core.inference.diffusion_engine_router import ENGINE_DIFFUSERS
+
+ backend = diffusion_module.get_diffusion_backend()
+ monkeypatch.setattr(engine_router, "predict_engine", lambda fam, **kw: ENGINE_DIFFUSERS)
+ seen: list = []
+ monkeypatch.setattr(backend, "assert_precision_available", lambda *a, **k: seen.append(k))
+ for mode in ("fast", "auto"):
+ resp = client.post(
+ "/api/inference/images/load",
+ json = {
+ "model_path": "unsloth/Z-Image-Turbo-GGUF",
+ "gguf_filename": "z-image-turbo-Q4_K_M.gguf",
+ "transformer_quant": "fp8",
+ "memory_mode": mode,
+ },
+ )
+ assert resp.status_code != 409, resp.text
+ # And the gate was told about the memory request either way, so the decision is its to make.
+ assert seen and all("memory_mode" in kwargs for kwargs in seen)
+
+
[email protected]("mode", ["int8", "fp8_dynamic", "nvfp4"])
+def test_an_offloading_memory_request_refuses_a_torchao_text_encoder(monkeypatch, mode):
+ """The encoder side of the same fence. quantize_text_encoders reports the torchao modes
+ unsupported once offload is active -- the hooks move modules with Module.to(), which those
+ tensor subclasses do not survive -- so the strict refusal landed after the resident image
+ pipeline had already been unloaded."""
+ from core.inference.diffusion import DiffusionBackend
+
+ backend = DiffusionBackend.__new__(DiffusionBackend)
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_resolve_device_target",
+ lambda self, fam: types.SimpleNamespace(device = "cuda", dtype = "bfloat16", _cc = (10, 0)),
+ )
+ # Support and the torchao install are not what is under test here.
+ monkeypatch.setattr(diffusion_module, "te_quant_supported", lambda target, m: True)
+ monkeypatch.setattr(diffusion_module, "torchao_quantize_importable", lambda: True)
+ with pytest.raises(RuntimeError) as excinfo:
+ backend.assert_precision_available(
+ # A family WITH an int8 schedule, so the int8 case is not downgraded to fp8 first.
+ types.SimpleNamespace(name = "qwen-image"),
+ model_kind = "gguf",
+ text_encoder_quant = mode,
+ memory_mode = "low_vram",
+ )
+ assert "text_encoder_quant" in str(excinfo.value)
+ assert "offload" in str(excinfo.value)
+
+
+def test_layerwise_fp8_survives_an_offloading_memory_request(monkeypatch):
+ """fp8 is a dtype cast, not a torchao tensor subclass, so offload does not rule it out and
+ refusing it would reject a load the runtime runs."""
+ from core.inference.diffusion import DiffusionBackend
+
+ backend = DiffusionBackend.__new__(DiffusionBackend)
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_resolve_device_target",
+ lambda self, fam: types.SimpleNamespace(device = "cuda", dtype = "bfloat16", _cc = (10, 0)),
+ )
+ monkeypatch.setattr(diffusion_module, "te_quant_supported", lambda target, m: True)
+ monkeypatch.setattr(diffusion_module, "torchao_quantize_importable", lambda: True)
+ backend.assert_precision_available(
+ types.SimpleNamespace(name = "qwen-image"),
+ model_kind = "gguf",
+ text_encoder_quant = "fp8",
+ memory_mode = "low_vram",
+ )
+
+
[email protected]("mode", ["int8", "fp8_dynamic", "nvfp4"])
+def test_a_broken_torchao_refuses_a_torchao_text_encoder_before_the_download(monkeypatch, mode):
+ """The casters import torchao only after the pipeline has been downloaded and built, so an
+ absent or broken install failed through load-progress instead of the pre-load 409 the strict
+ contract promises. The device check cannot see it: a CUDA bf16 host with no torchao passes
+ every capability test."""
+ from core.inference.diffusion import DiffusionBackend
+
+ backend = DiffusionBackend.__new__(DiffusionBackend)
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_resolve_device_target",
+ lambda self, fam: types.SimpleNamespace(device = "cuda", dtype = "bfloat16", _cc = (10, 0)),
+ )
+ monkeypatch.setattr(diffusion_module, "te_quant_supported", lambda target, m: True)
+ monkeypatch.setattr(diffusion_module, "torchao_quantize_importable", lambda: False)
+ with pytest.raises(RuntimeError) as excinfo:
+ backend.assert_precision_available(
+ types.SimpleNamespace(name = "qwen-image"),
+ model_kind = "gguf",
+ text_encoder_quant = mode,
+ )
+ assert "torchao is not importable" in str(excinfo.value)
+
+
+def test_layerwise_fp8_does_not_need_torchao(monkeypatch):
+ """fp8 is a plain dtype cast, so a host without torchao still runs it and refusing it would
+ reject a load that works."""
+ from core.inference.diffusion import DiffusionBackend
+
+ backend = DiffusionBackend.__new__(DiffusionBackend)
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_resolve_device_target",
+ lambda self, fam: types.SimpleNamespace(device = "cuda", dtype = "bfloat16", _cc = (10, 0)),
+ )
+ monkeypatch.setattr(diffusion_module, "te_quant_supported", lambda target, m: True)
+ monkeypatch.setattr(diffusion_module, "torchao_quantize_importable", lambda: False)
+ backend.assert_precision_available(
+ types.SimpleNamespace(name = "qwen-image"), model_kind = "gguf", text_encoder_quant = "fp8"
+ )
diff --git a/studio/backend/tests/test_diffusion_transformer_quant.py b/studio/backend/tests/test_diffusion_transformer_quant.py
index b0a323daef9..8db28437c38 100644
--- a/studio/backend/tests/test_diffusion_transformer_quant.py
+++ b/studio/backend/tests/test_diffusion_transformer_quant.py
@@ -86,7 +86,7 @@ def test_dense_transformer_supported_requires_cuda_bf16(monkeypatch):
def _allow(monkeypatch, allowed):
"""Force ``_scheme_supported`` to accept only ``allowed`` (simulates smoke results)."""
- monkeypatch.setattr(tq, "_scheme_supported", lambda scheme, device: scheme in allowed)
+ monkeypatch.setattr(tq, "_scheme_supported", lambda scheme, device, **kw: scheme in allowed)
def test_auto_blackwell_prefers_fp8_then_falls_back(monkeypatch):
@@ -281,6 +281,136 @@ def test_smoke_probe_caches_and_tolerates_failure(monkeypatch):
assert tq._smoke_probe(TQ_INT8, "cuda") is False
+def test_the_smoke_probe_does_not_cache_an_out_of_memory(monkeypatch):
+ # A full GPU is not a verdict on the scheme, and this probe now runs on the ROUTE thread --
+ # before the arbiter evicts the resident chat model, which is the point of raising the refusal
+ # early -- so it meets a full GPU by design. Caching that answer would refuse every later
+ # EXPLICIT request for the scheme for the life of the process, on a host that runs it fine.
+ class _OOM(RuntimeError):
+ pass
+
+ class _Lin:
+ def __init__(self, *a, **k):
+ pass
+
+ def to(self, **k):
+ return self
+
+ def __call__(self, x):
+ return x
+
+ torch = types.ModuleType("torch")
+ torch.bfloat16 = "bfloat16"
+ torch.nn = types.SimpleNamespace(Linear = _Lin)
+ torch.randn = lambda *a, **k: _FakeTensor()
+ torch.isfinite = lambda t: _FakeBool(True)
+ torch.no_grad = lambda: __import__("contextlib").nullcontext()
+ torch.cuda = types.SimpleNamespace(
+ is_available = lambda: True, synchronize = lambda: None, OutOfMemoryError = _OOM
+ )
+ torch.OutOfMemoryError = _OOM
+ monkeypatch.setitem(sys.modules, "torch", torch)
+
+ tqz = types.ModuleType("torchao.quantization")
+ calls = {"n": 0}
+
+ def _quantize(
+ module,
+ config,
+ filter_fn = None,
+ ):
+ calls["n"] += 1
+
+ tqz.quantize_ = _quantize
+ monkeypatch.setitem(sys.modules, "torchao.quantization", tqz)
+ # The config builder is where the allocation lands in practice; raising there keeps this test
+ # off the real torchao, which _make_quant_config would otherwise import for its config classes.
+ fault: list = [_OOM("CUDA out of memory. Tried to allocate 2.00 GiB")]
+
+ def _config(scheme, fast_accum = None):
+ if fault[0] is not None:
+ raise fault[0]
+ return "cfg"
+
+ monkeypatch.setattr(tq, "_make_quant_config", _config)
+
+ tq._SMOKE_CACHE.clear()
+ assert tq._smoke_probe(TQ_INT8, "cuda") is False
+ assert tq._SMOKE_CACHE == {}, "an OOM must not be remembered as 'this scheme cannot run'"
+ # The eviction happens, memory frees, and the very next ask gets the real answer.
+ fault[0] = None
+ assert tq._smoke_probe(TQ_INT8, "cuda") is True
+ assert calls["n"] == 1
+
+ # A NON-memory failure is still cached: that one really is a property of the build.
+ tq._SMOKE_CACHE.clear()
+ fault[0] = RuntimeError("kernel unavailable")
+ assert tq._smoke_probe(TQ_INT8, "cuda") is False
+ assert tq._SMOKE_CACHE == {(TQ_INT8, "cuda"): False}
+
+ # And the PRE-EVICTION caller gets "could not tell", not "cannot run": the gate it feeds turns
+ # a False into a 409 before the arbiter has freed the VRAM the probe wanted, so answering
+ # "unsupported" there refuses a load the eviction was about to make room for. A non-memory
+ # failure stays False for that caller too -- that one is a real verdict.
+ tq._SMOKE_CACHE.clear()
+ fault[0] = _OOM("CUDA out of memory. Tried to allocate 2.00 GiB")
+ assert tq._smoke_probe(TQ_INT8, "cuda", unproven_ok = True) is True
+ assert tq._SMOKE_CACHE == {}
+ fault[0] = RuntimeError("kernel unavailable")
+ assert tq._smoke_probe(TQ_INT8, "cuda", unproven_ok = True) is False
+
+
+def test_an_oom_is_recognised_however_it_is_spelled():
+ # torch.OutOfMemoryError subclasses RuntimeError (not MemoryError) and has moved between
+ # torch.cuda and torch across releases, so neither name alone is enough.
+ assert tq._is_out_of_memory(MemoryError("no room")) is True
+ assert tq._is_out_of_memory(RuntimeError("CUDA out of memory. Tried to allocate 2 GiB")) is True
+ assert tq._is_out_of_memory(RuntimeError("kernel unavailable")) is False
+ assert tq._is_out_of_memory(ImportError("cannot import name 'ScalingType'")) is False
+
+
+def test_an_unusable_scheme_names_the_fault_the_user_can_actually_fix(monkeypatch):
+ # select_transformer_quant_scheme folds three different faults into one None, and an EXPLICIT
+ # scheme now fails CLOSED, so that None becomes the whole explanation on a 409. Measured on a
+ # B200 whose torchao could not import (a torch/torchao skew): every explicit scheme was refused
+ # with "not usable ... on this GPU", which is false and sends the owner hunting for hardware.
+ monkeypatch.setattr(tq, "_TORCHAO_UNAVAILABLE", (None,))
+ assert tq.explain_unusable_scheme("z-image-turbo", "fp8") == (
+ "'fp8' is not usable for family 'z-image-turbo' on this GPU"
+ )
+ # The measured deny list wins over both: it holds on every GPU, so naming hardware would be wrong.
+ denied = tq.explain_unusable_scheme("qwen-image", "fp8")
+ assert "measured accuracy gate" in denied and "whatever the GPU" in denied
+ assert "on this GPU" not in denied.replace("whatever the GPU", "")
+
+ # A torchao that cannot import is a package problem, and the message has to say so.
+ monkeypatch.setattr(
+ tq, "_TORCHAO_UNAVAILABLE", ("ImportError: cannot import name 'ScalingType'",)
+ )
+ broken = tq.explain_unusable_scheme("z-image-turbo", "fp8")
+ assert "cannot import name 'ScalingType'" in broken
+ assert "not a limit of the GPU" in broken
+ # ...but a denied family is still reported as denied, whatever torchao is doing.
+ assert "measured accuracy gate" in tq.explain_unusable_scheme("qwen-image", "fp8")
+
+
+def test_torchao_unavailable_reason_is_resolved_once_and_covers_the_stub(monkeypatch):
+ monkeypatch.setattr(tq, "_TORCHAO_UNAVAILABLE", None)
+ monkeypatch.setattr(tq, "is_stubbed", lambda pkg: True)
+ reason = tq.torchao_unavailable_reason()
+ assert reason is not None and "stub" in reason
+ # Cached: flipping the stub answer does not re-resolve within a process.
+ monkeypatch.setattr(tq, "is_stubbed", lambda pkg: False)
+ assert tq.torchao_unavailable_reason() == reason
+
+ monkeypatch.setattr(tq, "_TORCHAO_UNAVAILABLE", None)
+ monkeypatch.setitem(
+ sys.modules, "torchao.quantization", types.ModuleType("torchao.quantization")
+ )
+ sys.modules["torchao.quantization"].quantize_ = lambda *a, **k: None
+ assert tq.torchao_unavailable_reason() is None
+
+
def test_the_smoke_probe_feeds_zero_rows_not_only_noise(monkeypatch):
# The finiteness check above is only meaningful if the input actually contains a zero row:
# torch.randn alone never produces one, which is exactly how the silent degradation survived.
@@ -697,3 +827,57 @@ def test_the_attention_trim_families_exclude_their_small_m_text_streams():
assert exclude_tokens_for_scheme("fp8", "hunyuanvideo-1.5") == ()
assert exclude_tokens_for_scheme(TQ_INT8, "ltx-2") == _INT8_EXCLUDE_NAME_TOKENS
+
+
+def test_the_pre_eviction_gate_does_not_refuse_on_an_indeterminate_probe(monkeypatch):
+ # The route-level precision gate asks the selector, not the probe, so unproven_ok has to reach
+ # through select_transformer_quant_scheme for the leniency to exist where it matters.
+ monkeypatch.setattr(tq, "dense_transformer_supported", lambda target: True)
+ seen: list = []
+
+ def _supported(
+ scheme,
+ device,
+ *,
+ unproven_ok = False,
+ ):
+ seen.append(unproven_ok)
+ return unproven_ok
+
+ monkeypatch.setattr(tq, "_scheme_supported", _supported)
+ target = types.SimpleNamespace(device = "cuda")
+ assert tq.select_transformer_quant_scheme(target, "fp8") is None
+ assert tq.select_transformer_quant_scheme(target, "fp8", unproven_ok = True) == "fp8"
+ assert seen == [False, True]
+
+
+def test_a_refusal_reason_does_not_carry_server_paths(monkeypatch):
+ # The torchao import error is interpolated into the precision-refusal RuntimeError, which both
+ # load routes return verbatim as the 409 detail. An ImportError routinely names the absolute
+ # file that raised it, so the reason has to be stripped while the log keeps the whole thing.
+ monkeypatch.setattr(tq, "_TORCHAO_UNAVAILABLE", None)
+ monkeypatch.setattr(tq, "is_stubbed", lambda pkg: False)
+ broken = types.ModuleType("torchao.quantization")
+
+ def _raise():
+ raise ImportError(
+ "cannot import name 'ScalingType' from 'torch.nn.functional' "
+ "(/srv/unsloth/.venv/lib/python3.12/site-packages/torch/nn/functional.py)"
+ )
+
+ broken.__getattr__ = lambda name: _raise()
+ monkeypatch.setitem(sys.modules, "torchao.quantization", broken)
+ reason = tq.torchao_unavailable_reason()
+ assert reason is not None
+ assert "/srv/unsloth" not in reason and "site-packages" not in reason
+ # The actionable half survives: the caller still learns WHICH import broke.
+ assert "ScalingType" in reason and "torch.nn.functional" in reason
+
+
+def test_paths_are_stripped_without_eating_dotted_module_names():
+ assert tq._strip_paths("ImportError: no module 'torchao.quantization'") == (
+ "ImportError: no module 'torchao.quantization'"
+ )
+ assert "C:\\Users" not in tq._strip_paths(
+ r"ImportError: DLL load failed: C:\Users\me\.venv\Lib\site-packages\torchao\_C.pyd"
+ )
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index 0239618a131..ac1869d733a 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -1262,3 +1262,32 @@ def test_the_delete_guard_names_the_repack_as_well_as_the_mirror(monkeypatch):
protected = _with_mirrors(["unsloth/Z-Image-Turbo-ComfyUI"])
assert "unsloth/Z-Image-Turbo-ComfyUI" in protected
assert "Comfy-Org/z_image_turbo" in protected
+
+
+def test_generate_reports_the_build_the_recipe_persists():
+ # The route writes the recipe straight off these keys, so a key the native result omits is
+ # persisted as null. The engine has no dense quant and no memory planner (honest nulls), but
+ # the offload it ran under is real -- and every native image recorded it as "unknown".
+ b = _loaded_backend()
+ s = b._state
+ b._state = bk._SdState(
+ repo_id = s.repo_id,
+ base_repo = s.base_repo,
+ family = s.family,
+ device = "cuda",
+ files = s.files,
+ vae_format = s.vae_format,
+ sampling_method = s.sampling_method,
+ flow_shift = s.flow_shift,
+ mode = s.mode,
+ gguf_filename = "z-image-turbo-Q4_K_M.gguf",
+ offload_flags = ("--vae-on-cpu", "--clip-on-cpu"),
+ )
+ out = b.generate(prompt = "a fox", width = 64, height = 64, steps = 4, seed = 1)
+ assert out["model_kind"] == "gguf"
+ assert out["gguf_filename"] == "z-image-turbo-Q4_K_M.gguf"
+ assert out["offload_policy"] == "active"
+ # Same derivation status() uses, so the recipe and the Loaded build panel cannot disagree.
+ assert out["offload_policy"] == b.status()["offload_policy"]
+ assert out["transformer_quant"] is None and out["text_encoder_quant"] is None
+ assert out["memory_mode"] is None
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index fddde6b4f00..41362dc1ffc 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -817,6 +817,10 @@ def test_ltx23_load_forwards_the_precast_encoder(fake_runtime, tmp_path, monkeyp
# The wiring half of the same bug: the 2.3 branch does not use pipe_kwargs, so the loader must pass the pre-cast encoder across explicitly.
from core.inference import diffusion_te_prequant, video_ltx2
+ # The CPU stub cannot cast the encoder, which the strict default now refuses; this test is
+ # about the WIRING, so keep the legacy silent-fallback behaviour for it.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK", "1")
+
precast = object()
monkeypatch.setattr(
diffusion_te_prequant, "te_prequant_pipe_kwargs", lambda *a, **k: {"text_encoder": precast}
@@ -1343,6 +1347,17 @@ def test_video_speed_off_suppresses_auto_dtype_quant(fake_runtime, monkeypatch):
assert status["speed_mode"] == "off"
backend.unload()
+ # ...and the RECORD still says the user asked for nothing. The suppression rewrites the
+ # internal value to "off" before the resolved record is built, and reporting that as the
+ # request makes the record claim an explicit pin: the Auto badge disappears and the Precision
+ # select reseeds to none, so after the user changes Speed and reloads, quantisation stays
+ # pinned off for no reason they can see.
+ resolved = status["resolved"]["transformer_quant"]
+ assert (
+ resolved["requested"] is None
+ ), f"the record reports {resolved['requested']!r} as the user's request; nothing was asked for"
+ assert resolved["source"] == "auto"
+
# Control: with speed NOT off the auto precision promotion still engages, so the suppression above is specific to speed=off.
backend.load_pipeline("Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline")
assert calls == [True]
@@ -1521,9 +1536,12 @@ def test_wan_a14b_dense_quant_applies_to_both_dits(fake_runtime, monkeypatch):
def test_dense_quant_skipped_under_offload(fake_runtime, monkeypatch):
- # Offload hooks move modules with Module.to(), which torchao tensors reject, so any offload policy must SKIP quant: the load succeeds dense and the record explains why.
+ # Offload hooks move modules with Module.to(), which torchao tensors reject, so any offload
+ # policy must SKIP quant. With the legacy escape hatch set the load still succeeds dense and the
+ # record explains why; the strict default refuses instead (see the test below).
import core.inference.video as video_mod
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK", "1")
monkeypatch.setattr(video_mod, "dense_transformer_supported", lambda target: True)
quantised = []
@@ -1563,7 +1581,80 @@ def test_dense_quant_skipped_under_offload(fake_runtime, monkeypatch):
assert status["offload_policy"] == "model"
assert quantised == []
assert status["transformer_quant"] is None
- assert "offload moves the DiT" in status["resolved"]["transformer_quant"]["reason"]
+ resolved = status["resolved"]["transformer_quant"]
+ assert "moves the DiT" in resolved["reason"]
+ # BOTH sides of the story survive: the ask, the outcome, and that they disagree.
+ assert resolved["requested"] == "int8"
+ assert resolved["value"] == "off"
+ assert resolved["status"] == "fell_back"
+
+
+def test_explicit_dense_quant_refuses_under_offload(fake_runtime, monkeypatch):
+ # Strict default (no escape hatch): an explicit int8 the offload plan cannot honor stops the
+ # load, rather than denoising at bf16 while the Precision dropdown still reads INT8.
+ import dataclasses
+
+ import core.inference.video as video_mod
+
+ monkeypatch.setattr(video_mod, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(
+ video_mod,
+ "quantize_transformer",
+ lambda view, target, *, mode, family, logger = None: pytest.fail("must not quantise"),
+ )
+ real_plan = video_mod.plan_diffusion_memory
+ monkeypatch.setattr(
+ video_mod,
+ "plan_diffusion_memory",
+ lambda **kwargs: dataclasses.replace(real_plan(**kwargs), offload_policy = "model"),
+ )
+ backend = VideoBackend()
+ with pytest.raises(RuntimeError) as excinfo:
+ backend.load_pipeline(
+ "Wan-AI/Wan2.2-T2V-A14B-Diffusers",
+ model_kind = "pipeline",
+ transformer_quant = "int8",
+ )
+ assert "transformer_quant='int8' could not be used" in str(excinfo.value)
+ assert "resident memory mode" in str(excinfo.value)
+ assert backend.status()["loaded"] is False
+
+
+def test_the_video_refusal_also_names_a_broken_torchao_rather_than_the_gpu(
+ fake_runtime, monkeypatch
+):
+ # The image twin's finding, shared through explain_unusable_scheme: a torchao that cannot
+ # import looks exactly like a GPU without the kernels to the selector, and a refusal that
+ # blames the GPU sends the user after hardware for what a reinstall fixes.
+ import core.inference.diffusion_transformer_quant as tq
+ import core.inference.video as video_mod
+
+ monkeypatch.setattr(video_mod, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(video_mod, "select_transformer_quant_scheme", lambda *a, **k: None)
+ monkeypatch.setattr(tq, "_TORCHAO_UNAVAILABLE", ("ImportError: no torchao kernels",))
+ with pytest.raises(RuntimeError) as excinfo:
+ video_mod.assert_video_precision_available(
+ types.SimpleNamespace(name = "ltx-2"),
+ model_kind = "pipeline",
+ transformer_quant = "nvfp4",
+ )
+ message = str(excinfo.value)
+ assert "transformer_quant='nvfp4' could not be used" in message
+ assert "no torchao kernels" in message and "not a limit of the GPU" in message
+
+
+def test_begin_load_refuses_dense_quant_on_a_non_pipeline_video_kind(fake_runtime, monkeypatch):
+ # The DiT quant only exists on the full-pipeline path, so an explicit scheme on a GGUF pick was
+ # accepted and then ignored outright. Refused before the load starts (the route's 409).
+ backend = VideoBackend()
+ with pytest.raises(RuntimeError) as excinfo:
+ backend.begin_load(
+ "unsloth/LTX-2.3-GGUF",
+ gguf_filename = "ltx-2.3-Q4_K_M.gguf",
+ model_kind = "gguf",
+ transformer_quant = "fp8",
+ )
+ assert "full-pipeline loads only" in str(excinfo.value)
def test_wan_a14b_partial_quant_fails_the_load(fake_runtime, monkeypatch):
diff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.py
index 31bf968cc33..c02c7157fa3 100644
--- a/studio/backend/tests/test_video_routes.py
+++ b/studio/backend/tests/test_video_routes.py
@@ -16,7 +16,7 @@ import threading
import time
import pytest
-from fastapi import FastAPI
+from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
import core.inference.gpu_arbiter as gpu_arbiter
@@ -311,8 +311,11 @@ def test_load_threads_options_through_to_backend(client):
assert kwargs.get("transformer_cache_threshold") == 0.1
-def test_load_threads_transformer_quant_and_guidance_2(client):
+def test_load_threads_transformer_quant_and_guidance_2(client, monkeypatch):
# The load-time transformer_quant field reaches the backend, and the per-generation guidance_2 reaches generate() (dual-DiT MoE).
+ # The dense DiT quant is pipeline-only, so a GGUF pick with an explicit scheme is refused by the
+ # route's precision gate before it gets here; stub the gate out, since this is about threading.
+ monkeypatch.setattr(video_module, "assert_video_precision_available", lambda fam, **kw: None)
resp = client.post(
"/api/inference/video/load",
json = {
@@ -342,8 +345,13 @@ def test_load_rejects_bad_transformer_quant_422(client):
assert resp.status_code == 422
-def test_load_threads_text_encoder_quant(client):
+def test_load_threads_text_encoder_quant(client, monkeypatch):
# The load-time text_encoder_quant field reaches the backend (the video path also quantises the dense companion encoder).
+ #
+ # Under the precision escape hatch, because whether an fp8 encoder is available is a
+ # property of the HOST: on a CPU-only runner the gate refuses this pick with a 409 and the
+ # forwarding this test is about never happens. The hatch is the product's own bypass.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK", "1")
resp = client.post(
"/api/inference/video/load",
json = {
@@ -657,6 +665,22 @@ def test_status_passthrough(client, monkeypatch):
resolved = {
"speed_mode": {"value": "eager", "source": "auto", "reason": "GGUF default"},
"transformer_cache": {"value": None, "source": "auto", "reason": "few-step model"},
+ # A declined explicit precision has to survive the boundary here too (the Linux half of
+ # P1-2: the label kept reading BF16 while telemetry confirmed NVFP4).
+ "transformer_quant": {
+ "value": "off",
+ "requested": "nvfp4",
+ "source": "explicit",
+ "status": "unsupported",
+ "reason": "this GPU has no NVFP4 cores",
+ },
+ "text_encoder_quant": {
+ "value": "fp8",
+ "requested": "int8",
+ "source": "explicit",
+ "status": "fell_back",
+ "reason": "int8 has no measured keep-bf16 schedule for this family",
+ },
}
monkeypatch.setattr(
backend,
@@ -672,7 +696,11 @@ def test_status_passthrough(client, monkeypatch):
)
body = client.get("/api/inference/video/status").json()
assert body["loaded"] is True and body["family"] == "ltx-2"
- assert body["resolved"] == resolved
+ assert body["resolved"]["transformer_quant"] == resolved["transformer_quant"]
+ assert body["resolved"]["text_encoder_quant"] == resolved["text_encoder_quant"]
+ # Entries from an older backend (no requested/status) still parse, defaulted to "applied".
+ assert body["resolved"]["speed_mode"]["requested"] is None
+ assert body["resolved"]["speed_mode"]["status"] == "applied"
assert body["defaults"]["frame_step"] == 8
@@ -681,6 +709,119 @@ def test_status_resolved_defaults_to_null(client):
assert body["resolved"] is None and body["defaults"] is None
+def _load_fake_video(client):
+ resp = client.post(
+ "/api/inference/video/load",
+ json = {"model_path": "unsloth/LTX-2.3-GGUF", "gguf_filename": "q.gguf"},
+ )
+ assert resp.status_code == 200
+
+
+def test_saved_clip_records_the_engaged_build(client, monkeypatch):
+ # A saved MP4 has to name the BUILD it came off, like a saved PNG already does: without it a
+ # clip rendered at bf16 is indistinguishable from one rendered at the precision that was asked
+ # for. Every value here is the ENGAGED state, never the load request.
+ backend = video_module.get_video_backend()
+ real_generate = backend.generate
+
+ def _generate(**kwargs):
+ return {
+ **real_generate(**kwargs),
+ "model_kind": "gguf",
+ "gguf_filename": "ltx-2.3-Q4_K_M.gguf",
+ "transformer_quant": None,
+ "text_encoder_quant": "fp8",
+ "memory_mode": "low_vram",
+ "offload_policy": "sequential",
+ }
+
+ monkeypatch.setattr(backend, "generate", _generate)
+ _load_fake_video(client)
+ video = _generate_and_wait(client, {"prompt": "a sloth", "seed": 3})
+ assert video["model_kind"] == "gguf"
+ assert video["gguf_filename"] == "ltx-2.3-Q4_K_M.gguf"
+ assert video["transformer_quant"] is None
+ assert video["text_encoder_quant"] == "fp8"
+ assert video["memory_mode"] == "low_vram"
+ assert video["offload_policy"] == "sequential"
+ # ...and it round-trips through the on-disk sidecar, not just the in-memory record.
+ listed = client.get("/api/inference/video/gallery").json()["videos"]
+ assert listed[0]["text_encoder_quant"] == "fp8"
+ assert listed[0]["gguf_filename"] == "ltx-2.3-Q4_K_M.gguf"
+
+
+def test_sidecars_without_the_build_fields_still_list(client):
+ # The new keys are NOT in video_gallery._REQUIRED_META, so a clip written before they existed
+ # lists with them null instead of being skipped as a foreign sidecar.
+ _load_fake_video(client)
+ video = _generate_and_wait(client, {"prompt": "a sloth"})
+ assert video["model_kind"] is None and video["transformer_quant"] is None
+ listed = client.get("/api/inference/video/gallery").json()["videos"]
+ assert len(listed) == 1 and listed[0]["text_encoder_quant"] is None
+
+
+def test_load_refuses_an_unusable_explicit_precision_with_409(client, monkeypatch):
+ # begin_load refuses an EXPLICIT precision this host cannot honor; the route answers 409 with
+ # the reason instead of accepting the load and denoising at some other precision.
+ from core.inference.diffusion_auto_policy import precision_refusal_message
+
+ backend = video_module.get_video_backend()
+ refusal = precision_refusal_message(
+ "transformer_quant",
+ "nvfp4",
+ "'nvfp4' is not usable for family 'ltx-2' on this GPU",
+ off_label = "Off to run the DiT at bf16",
+ )
+
+ def _refuse(model_path, **kwargs):
+ raise RuntimeError(refusal)
+
+ monkeypatch.setattr(backend, "begin_load", _refuse)
+ resp = client.post(
+ "/api/inference/video/load",
+ json = {"model_path": "Lightricks/LTX-2.3", "transformer_quant": "nvfp4"},
+ )
+ assert resp.status_code == 409
+ assert "transformer_quant='nvfp4' could not be used" in resp.json()["detail"]
+ assert client.get("/api/inference/video/status").json()["loaded"] is False
+
+
+def test_precision_refusal_precedes_eviction(client, monkeypatch):
+ # The refusal belongs to validate_load_request, which the route calls BEFORE the GPU handoff:
+ # acquire_for evicts chat under the arbiter lock before it runs begin_load, so a refusal made
+ # there arrives after the eviction the 409 exists to prevent.
+ from core.inference.diffusion_auto_policy import precision_refusal_message
+
+ backend = video_module.get_video_backend()
+ evicted = []
+ monkeypatch.setitem(gpu_arbiter._EVICTORS, gpu_arbiter.CHAT, lambda: evicted.append("chat"))
+ monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.CHAT)
+ refusal = precision_refusal_message(
+ "transformer_quant",
+ "nvfp4",
+ "'nvfp4' is not usable for family 'ltx-2' on this GPU",
+ off_label = "Off to run the DiT at bf16",
+ )
+
+ def _refuse(fam, **kwargs):
+ raise RuntimeError(refusal)
+
+ monkeypatch.setattr(video_module, "assert_video_precision_available", _refuse)
+ monkeypatch.setattr(
+ backend,
+ "begin_load",
+ lambda *a, **k: pytest.fail("begin_load ran after an impossible precision"),
+ )
+ resp = client.post(
+ "/api/inference/video/load",
+ json = {"model_path": "Lightricks/LTX-2.3", "transformer_quant": "nvfp4"},
+ )
+ assert resp.status_code == 409
+ assert "transformer_quant='nvfp4' could not be used" in resp.json()["detail"]
+ assert evicted == []
+ assert gpu_arbiter.current_owner() == gpu_arbiter.CHAT
+
+
def test_unload_releases_arbiter(client, monkeypatch):
# Pin VIDEO as the current owner; unload must drop that claim.
monkeypatch.setattr(gpu_arbiter, "_owner", gpu_arbiter.VIDEO)
@@ -787,6 +928,9 @@ def test_delete_guard_protects_the_loaded_video_companion_base(monkeypatch):
def test_video_download_plan_forwards_the_encoder_policy(client, monkeypatch):
# The plan drives the staged download, so it must use the encoder policy the load will run with: an fp8 request takes a hosted pre-cast encoder, and staging the dense one pulls ~49 GB of Gemma3.
+ # Same host-independence as the load twin: the plan now makes the precision check too, so
+ # without the escape hatch a GPU-less runner answers 409 and forwards nothing.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK", "1")
backend = video_module.get_video_backend()
seen: dict = {}
@@ -813,6 +957,42 @@ def test_video_download_plan_forwards_the_encoder_policy(client, monkeypatch):
assert seen["hf_token"] == "hf_secret"
+def test_the_video_plan_refuses_an_impossible_precision_before_anything_is_staged(
+ client, monkeypatch
+):
+ # The video weights are the tens-of-GB case: /video/load refuses a precision this host cannot
+ # honour, but the UI plans and stages first, so the refusal used to arrive after the download.
+ import core.inference.video as video_core
+
+ backend = video_module.get_video_backend()
+
+ def _refuse(fam, **kwargs):
+ raise RuntimeError(
+ "text_encoder_quant='fp8' could not be used: this device cannot cast the encoder."
+ )
+
+ monkeypatch.setattr(video_core, "assert_video_precision_available", _refuse)
+ monkeypatch.setattr(
+ backend,
+ "download_plan",
+ lambda *a, **k: pytest.fail("the plan was built for a precision that cannot be honoured"),
+ raising = False,
+ )
+
+ resp = client.post(
+ "/api/inference/video/download-plan",
+ json = {
+ "model_path": "unsloth/LTX-2.3-GGUF",
+ "gguf_filename": "distilled/ltx-2.3-22b-distilled-Q4_K_M.gguf",
+ "model_kind": "gguf",
+ "text_encoder_quant": "fp8",
+ },
+ )
+
+ assert resp.status_code == 409, resp.text
+ assert "could not be used" in resp.json()["detail"]
+
+
def test_video_load_guard_still_checks_diffusion_when_the_llm_probe_raises(client, monkeypatch):
# Same independence rule as the image guard: a raising LLM probe used to return early, so a video load ran into an active diffusion trainer on the same GPU.
import core.training as core_training
@@ -919,3 +1099,71 @@ def test_signed_video_link_rejects_tampering_and_other_ids(client):
def test_signed_url_mint_is_bearer_gated_and_404s_for_an_unknown_clip(client):
assert client.get("/api/inference/video/gallery/does-not-exist/signed-url").status_code == 404
+
+
+def test_the_training_guard_runs_before_the_precision_probe(client, monkeypatch):
+ # The precision gate's support check quantises a real Linear on the GPU and synchronises, so
+ # running it first initialises a CUDA context and allocates next to the training subprocess
+ # for a load that is about to be refused anyway -- and an OOM there under that contention is
+ # not a verdict on the scheme. The image route already guards first; this one now does too.
+ import routes.video as video_routes
+
+ def _refuse_training() -> None:
+ raise HTTPException(status_code = 409, detail = "Training is running.")
+
+ monkeypatch.setattr(video_routes, "_guard_video_load_against_training", _refuse_training)
+ monkeypatch.setattr(
+ video_module,
+ "assert_video_precision_available",
+ lambda fam, **kw: pytest.fail("the precision probe ran while training was active"),
+ )
+ resp = client.post(
+ "/api/inference/video/load",
+ json = {"model_path": "Lightricks/LTX-2.3", "transformer_quant": "nvfp4"},
+ )
+ assert resp.status_code == 409 and resp.json()["detail"] == "Training is running."
+
+
[email protected]("memory", ["balanced", "low_vram"])
+def test_the_video_precision_gate_sees_the_memory_request(monkeypatch, memory):
+ """balanced and low_vram settle the offload policy before anything is measured, and an
+ offloaded DiT skips the torchao build -- so load_pipeline's strict refusal arrived after
+ acquire_for and the teardown had already evicted the resident model."""
+ import types
+
+ monkeypatch.setattr(video_module, "precision_fallback_allowed", lambda: False)
+ monkeypatch.setattr(
+ video_module,
+ "resolve_diffusion_device_target",
+ lambda: types.SimpleNamespace(device = "cuda", dtype = "bfloat16"),
+ )
+ monkeypatch.setattr(video_module, "dense_transformer_supported", lambda target: True)
+ with pytest.raises(RuntimeError) as excinfo:
+ video_module.assert_video_precision_available(
+ types.SimpleNamespace(name = "wan2.2"),
+ model_kind = "pipeline",
+ transformer_quant = "fp8",
+ memory_mode = memory,
+ )
+ assert "transformer_quant='fp8' could not be used" in str(excinfo.value)
+ assert "offload" in str(excinfo.value)
+
+
+def test_the_video_gate_leaves_a_measured_memory_mode_alone(monkeypatch):
+ """fast and auto are decided from the measured footprint, so this gate cannot judge them."""
+ import types
+
+ monkeypatch.setattr(video_module, "precision_fallback_allowed", lambda: False)
+ monkeypatch.setattr(
+ video_module,
+ "resolve_diffusion_device_target",
+ lambda: types.SimpleNamespace(device = "cuda", dtype = "bfloat16"),
+ )
+ monkeypatch.setattr(video_module, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(video_module, "select_transformer_quant_scheme", lambda *a, **k: "fp8")
+ video_module.assert_video_precision_available(
+ types.SimpleNamespace(name = "wan2.2"),
+ model_kind = "pipeline",
+ transformer_quant = "fp8",
+ memory_mode = "fast",
+ )
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index 5ca600484f8..e1510a06fc2 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -5,11 +5,16 @@ import { withBackgroundLoadNotice } from "@/lib/model-lifecycle-events";
import { authFetch } from "@/features/auth";
import { readFastApiError } from "@/lib/format-fastapi-error";
-// One Advanced control's resolved value + provenance, for the "Auto: X" badges. `value` is the engaged value (null when off),
-// `source` is "auto" (this backend decided) or "explicit" (the caller set it); `reason` is the tooltip why.
+// One Advanced control's resolved value + provenance, for the Advanced-panel badges. `value` is the engaged value (null when
+// off), `requested` is what the caller asked for (null = left to the backend), `source` is "auto" (this backend decided) or
+// "explicit" (the caller set it), `status` says whether the ask survived, and `reason` is the tooltip why.
export interface DiffusionResolvedControl {
value: string | boolean | null;
+ // Absent on backends predating the requested/actual split.
+ requested?: string | boolean | null;
source: "auto" | "explicit";
+ // "applied" (honored, or nothing was asked) | "fell_back" | "unsupported". Absent on older backends.
+ status?: "applied" | "fell_back" | "unsupported";
reason: string;
}
@@ -23,6 +28,23 @@ export interface DiffusionStatus {
// Resolved load kind: "gguf" | "single_file" | "pipeline". Gates GGUF-only controls. Null when not loaded.
model_kind?: string | null;
cpu_offload: boolean;
+ // The ENGAGED runtime build. The backend has always sent these; declaring them is what lets the UI
+ // report what actually ran instead of echoing the load request back at the user.
+ // Transformer quant engaged on the dense fast path ("int8" | "fp8" | ...), null = the GGUF ran as-is.
+ transformer_quant?: string | null;
+ // Text-encoder quant engaged ("fp8" | "fp8_dynamic" | "int8" | "nvfp4"), null = dense bf16.
+ text_encoder_quant?: string | null;
+ // Memory mode the load ran under: "auto" | "fast" | "balanced" | "low_vram".
+ memory_mode?: string | null;
+ // Offload policy actually engaged: "none" | "group" | "model" | "sequential".
+ offload_policy?: string | null;
+ speed_mode?: string | null;
+ // Speed optimisations actually engaged.
+ speed_optims?: string[];
+ // Attention backend engaged via the diffusers dispatcher (e.g. "_native_cudnn"), null = default SDPA.
+ attention_backend?: string | null;
+ transformer_cache?: string | null;
+ vae_tiling?: boolean;
// Image workflows the loaded family supports (drives tab gating). Absent when nothing is loaded or on the native engine.
workflows?: string[];
// Whether the loaded model + quantisation can apply LoRA adapters (drives the LoRA picker enabled state).
@@ -62,6 +84,9 @@ export interface DiffusionLoadRequest {
// Advanced (load-time) tuning. All optional; omit for the backend's auto defaults.
speed_mode?: "off" | "eager" | "default" | "max";
transformer_quant?: "auto" | "none" | "off" | "int8" | "fp8" | "nvfp4" | "mxfp8";
+ // Text-encoder precision (omit to keep the dense bf16 encoder). Refused with a 409 when the host
+ // cannot run it, rather than loading dense and reporting nothing.
+ text_encoder_quant?: "fp8" | "fp8_dynamic" | "int8" | "nvfp4";
attention_backend?:
| "auto"
| "native"
@@ -161,6 +186,10 @@ export interface GalleryImage {
model_kind?: string | null;
gguf_filename?: string | null;
transformer_quant?: string | null;
+ // The rest of the precision picture, all ENGAGED values. Absent on records written before this existed.
+ text_encoder_quant?: string | null;
+ memory_mode?: string | null;
+ offload_policy?: string | null;
baked_loras?: string[];
loras?: string[];
controlnet?: string | null;
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 6752cc55a08..18106025036 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -76,6 +76,18 @@ import { BlobUrlCache } from "@/lib/blob-url-cache";
import { resolveDiffusionGgufFilename } from "@/lib/diffusion-gguf-filename";
import { createPickGuard, runGgufRepoPick } from "@/lib/diffusion-gguf-pick";
import { diffusionRoutePick } from "@/lib/diffusion-route-pick";
+import {
+ PRECISION_REFUSAL_TITLE,
+ denseTextEncoderBuildLabel,
+ denseTransformerBuildLabel,
+ isNativeEngineStatus,
+ formatResolvedValue,
+ isPrecisionRefusal,
+ memoryRecipeValue,
+ resolvedBadge,
+ resolvedSeedKey,
+ resolvedSelectValue,
+} from "@/lib/resolved-precision";
import {
routedGgufFilename,
routedGgufLabel,
@@ -554,18 +566,9 @@ function Field({
);
}
-// The engaged value of a resolved Advanced control, formatted for its "Auto: X" badge.
-function formatResolvedValue(key: string, value: string | boolean | null): string {
- if (key === "cpu_offload") return value ? "On" : "Off";
- if (value === null || value === "") return "Off";
- if (typeof value === "boolean") return value ? "On" : "Off";
- if (value === "_native_cudnn" || value.toLowerCase() === "cudnn") return "cuDNN";
- // Deferred speed auto: the dense pipe stays exact/eager and compiles on the 3rd image (the tooltip carries the full reason).
- if (value === "deferred") return "On from 3rd image";
- return value.toUpperCase();
-}
-
-// The "Auto: X" badge for one Advanced control, rendered only when source === "auto"; the reason is a hover tooltip.
+// The badge for one Advanced control. "Auto: X" when the backend decided it; "FP8 -> OFF" in a
+// warning tone when an EXPLICIT request was declined -- that case used to render nothing at all
+// while the dropdown kept showing the request, so a Q4_K_M GGUF could advertise FP8 it never ran.
function ResolvedBadge({
status,
controlKey,
@@ -573,18 +576,25 @@ function ResolvedBadge({
status: DiffusionStatus | null;
controlKey: string;
}) {
- const resolved = status?.resolved?.[controlKey];
- if (!resolved || resolved.source !== "auto") return null;
+ const info = resolvedBadge(controlKey, status?.resolved?.[controlKey]);
+ if (!info) return null;
const badge = (
- <span className="shrink-0 rounded-sm bg-muted px-1 py-px text-ui-9 font-medium uppercase tracking-wider text-muted-foreground">
- Auto: {formatResolvedValue(controlKey, resolved.value)}
+ <span
+ className={cn(
+ "shrink-0 rounded-sm px-1 py-px text-ui-9 font-medium uppercase tracking-wider",
+ info.tone === "warn"
+ ? "bg-destructive/15 text-destructive"
+ : "bg-muted text-muted-foreground",
+ )}
+ >
+ {info.label}
</span>
);
- if (!resolved.reason) return badge;
+ if (!info.tooltip) return badge;
return (
<Tooltip>
<TooltipTrigger asChild={true}>{badge}</TooltipTrigger>
- <TooltipContent>{resolved.reason}</TooltipContent>
+ <TooltipContent>{info.tooltip}</TooltipContent>
</Tooltip>
);
}
@@ -1027,6 +1037,24 @@ function RecipePopover({
{image.transformer_quant ? (
<RecipeRow label="Quant" value={image.transformer_quant} />
) : null}
+ {/* The ENGAGED text-encoder precision and memory placement: the encoder is often the
+ largest resident component and its cast changes the conditioning, and the memory mode
+ decides whether the torchao encoder modes could run at all. */}
+ {image.text_encoder_quant ? (
+ <RecipeRow label="TE quant" value={image.text_encoder_quant} />
+ ) : null}
+ {/* Either field is placement information. The native engine reports no memory_mode at
+ all (it has no torchao path to choose one for) while still recording an active
+ offload, so gating on memory_mode hid the offload on exactly the configuration
+ this row was extended for. Absent memory_mode stays absent: substituting "auto"
+ there would claim the memory planner picked a mode on a path that never ran it. */}
+ {image.memory_mode ||
+ (image.offload_policy && image.offload_policy !== "none") ? (
+ <RecipeRow
+ label="Memory"
+ value={memoryRecipeValue(image.memory_mode, image.offload_policy)}
+ />
+ ) : null}
{image.baked_loras?.length ? (
<RecipeRow label="Baked" value={image.baked_loras.join(", ")} wrap />
) : null}
@@ -1046,6 +1074,98 @@ function RecipePopover({
);
}
+// One "what actually ran" line in the loaded-build summary below.
+function BuildRow({ label, value, badge }: { label: string; value: string; badge?: ReactNode }) {
+ return (
+ <div className="flex items-center justify-between gap-2">
+ <span className="flex shrink-0 items-center gap-1 whitespace-nowrap text-muted-foreground">
+ {label}
+ {badge}
+ </span>
+ <span className="min-w-0 truncate text-foreground">{value}</span>
+ </div>
+ );
+}
+
+/**
+ * What the LOADED model is actually running, read from status (never from the request): the
+ * transformer and text-encoder precision, the memory mode with its resolved offload behaviour, and
+ * the attention backend. The Advanced selects above say what was ASKED for; this says what
+ * happened, and any control whose request was declined carries its reason in the badge tooltip.
+ * Without it a successful load said nothing at all about the precision it ran at.
+ */
+function LoadedBuildSummary({ status }: { status: DiffusionStatus | null }) {
+ if (!status?.loaded) return null;
+ const offload = status.offload_policy ?? "none";
+ return (
+ <div className="flex flex-col gap-1 rounded-md border border-border/60 px-2.5 py-2 text-ui-11">
+ <div className="flex items-center gap-1 pb-0.5 text-xs font-medium text-muted-foreground">
+ Loaded build
+ <InfoHint>
+ What the loaded model is actually running, reported by the backend. A control whose
+ requested value could not be used shows it next to that control, with the reason.
+ </InfoHint>
+ </div>
+ <BuildRow
+ label="Transformer"
+ value={
+ status.transformer_quant
+ ? formatResolvedValue("transformer_quant", status.transformer_quant)
+ // No dense quant ran, so the row reports what the checkpoint itself carries.
+ : denseTransformerBuildLabel(status)
+ }
+ badge={<ResolvedBadge status={status} controlKey="transformer_quant" />}
+ />
+ <BuildRow
+ label="Text encoder"
+ value={
+ status.text_encoder_quant
+ ? formatResolvedValue("text_encoder_quant", status.text_encoder_quant)
+ // No runtime TE quant engaged, which on the native engine is not the same as bf16.
+ : denseTextEncoderBuildLabel(status)
+ }
+ badge={<ResolvedBadge status={status} controlKey="text_encoder_quant" />}
+ />
+ <BuildRow
+ label="Memory"
+ value={
+ offload === "none"
+ ? `${status.memory_mode ?? "auto"} · resident`
+ : `${status.memory_mode ?? "auto"} · ${offload} offload`
+ }
+ />
+ <BuildRow
+ label="Attention"
+ value={
+ status.attention_backend
+ ? formatResolvedValue("attention_backend", status.attention_backend)
+ : // The sd.cpp engine reports no backend because it has none of ours: its attention
+ // is chosen by native flags, not by the diffusers/PyTorch dispatcher, so calling it
+ // "Native SDPA" is wrong on the default CPU image path.
+ isNativeEngineStatus(status)
+ ? "sd.cpp built-in"
+ : "Native SDPA"
+ }
+ />
+ </div>
+ );
+}
+
+/**
+ * Report a failed load. A refused precision is a long actionable sentence ("Choose Auto ... or
+ * Off ..."), so it becomes a toast description under a short title rather than one unreadable
+ * line. Nothing is left half-loaded either way: the backend refuses before it starts the load, or
+ * has already torn the partial build down by the time it reports the error.
+ */
+function reportLoadFailure(message: string | null | undefined, fallback: string): void {
+ const text = (message || "").trim();
+ if (text && isPrecisionRefusal(text)) {
+ toast.error(PRECISION_REFUSAL_TITLE, { description: text });
+ return;
+ }
+ toast.error(text || fallback);
+}
+
type Busy = "loading" | "unloading" | "generating" | null;
// The Advanced controls a load sends, with "auto" sentinels resolved to omitted. A staged download pins one at pick time.
@@ -1632,7 +1752,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
}
if (p.phase === "error") {
dismissLoadToast();
- toast.error(p.error || "Failed to load model");
+ reportLoadFailure(p.error, "Failed to load model");
setBusy(null);
// A load that failed AFTER starting leaves the previous pipeline loaded, so roll the optimistic quant label back.
if (quantRevert.current) {
@@ -1783,6 +1903,38 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
}
}, [status?.loaded, status?.repo_id, status?.base_repo, status?.model_kind]);
+ // Reseed the Advanced selects from the LOADED build, so they stop being pure local request state.
+ // An honored request re-selects itself (a no-op); a declined one snaps to what actually engaged,
+ // which is the input-side half of P1-2: the Precision dropdown must never go on advertising a
+ // scheme the loaded model is not running. Keyed on the LOAD-TIME half of the resolved record, so
+ // a user edit made after the load survives until the next load replaces it -- the backend
+ // rewrites the speed/attention/cache entries at GENERATION time, and serializing the whole record
+ // made the 3rd image of a session throw away a Precision the user had picked but not yet loaded.
+ const resolvedKey = status?.loaded ? resolvedSeedKey(status.resolved) : null;
+ useEffect(() => {
+ const record = status?.loaded ? status.resolved : null;
+ if (!record) return;
+ const quant = resolvedSelectValue(record.transformer_quant, (v) =>
+ // The engaged value spells "no quant" as "off"; the select's option for it is "none".
+ (["auto", "none", "int8", "fp8", "nvfp4", "mxfp8"] as const).find(
+ (o) => o === v || (o === "none" && v === "off"),
+ ) ?? null,
+ );
+ if (quant) setTransformerQuant(quant);
+ const memory = resolvedSelectValue(record.memory_mode, (v) =>
+ (["auto", "fast", "balanced", "low_vram"] as const).find((o) => o === v) ?? null,
+ );
+ if (memory) setMemoryMode(memory);
+ const attention = resolvedSelectValue(record.attention_backend, (v) =>
+ // The engaged value uses the dispatcher's own name; map it back to the option.
+ (["auto", "native", "cudnn", "flash3", "sage"] as const).find(
+ (o) => o === v || `_native_${o}` === v,
+ ) ?? null,
+ );
+ if (attention) setAttentionBackend(attention);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- resolvedKey stands for the record
+ }, [resolvedKey]);
+
// The adapter list a load of *repoId* would BAKE into the build, shared by the load and the download plan: a torchao int8/fp8 transformer
// takes adapters only before quantize_ + compile. Only a reload of the SAME target bakes, and it reads lastLoad.current, so call it first.
const bakedLorasFor = useCallback(
@@ -1863,7 +2015,11 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
hf_token: hfApiToken(getHfToken()),
cpu_offload: advanced.cpu_offload,
speed_mode: advanced.speed_mode,
- transformer_quant: advanced.transformer_quant,
+ // GGUF picks only: the dense fast path replaces a GGUF transformer, every other kind runs
+ // the precision its checkpoint carries. The Precision control is hidden for those kinds,
+ // but the state persists across picks, so a stale scheme would reach a load that can only
+ // decline it -- and the backend now refuses a request it cannot honor.
+ transformer_quant: opts.kind === "gguf" ? advanced.transformer_quant : undefined,
attention_backend: advanced.attention_backend,
memory_mode: advanced.memory_mode,
transformer_cache: advanced.transformer_cache,
@@ -1874,7 +2030,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
setCanReapply(prevLastLoad != null);
lastLoadRevert.current = null;
dismissLoadToast();
- toast.error(err instanceof Error ? err.message : "Failed to start load");
+ reportLoadFailure(err instanceof Error ? err.message : "", "Failed to start load");
setBusy(null);
void refreshStatus();
return false;
@@ -1955,7 +2111,9 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
hf_token: hfApiToken(getHfToken()),
cpu_offload: advanced.cpu_offload,
speed_mode: advanced.speed_mode,
- transformer_quant: advanced.transformer_quant,
+ // Dropped for the non-GGUF kinds exactly as handleLoad drops it, so the plan describes
+ // the load that will actually run.
+ transformer_quant: opts.kind === "gguf" ? advanced.transformer_quant : undefined,
memory_mode: advanced.memory_mode,
// The backend prefetch decision reads the adapter selection too: a baked LoRA always runs the dense build path. Omitting it
// planned a quantized file set and staged too little. Same list handleLoad bakes.
@@ -2613,6 +2771,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
</span>
<Switch checked={cpuOffload} onCheckedChange={setCpuOffload} />
</div>
+ <LoadedBuildSummary status={status} />
{/* A resident full pipeline is reloadable by repo id alone, so it keeps Reapply even before a user-initiated load; GGUF/single_file residents hide the button. */}
{status?.loaded && (canReapply || status?.model_kind === "pipeline") && (
<Tooltip>
diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.ts
index 23c828562e6..66c82e00874 100644
--- a/studio/frontend/src/features/video/api.ts
+++ b/studio/frontend/src/features/video/api.ts
@@ -8,11 +8,16 @@ import type { DiffusionDownloadPlan } from "@/features/images/api";
import { apiUrl } from "@/lib/api-base";
import { readFastApiError } from "@/lib/format-fastapi-error";
-// One Advanced control's resolved value + provenance for the "Auto: X" badges, same shape as the diffusion status.
-// `value` is the engaged value (string, null when off, or boolean); `source` is "auto" or "explicit"; `reason` is the tooltip.
+// One Advanced control's resolved value + provenance, same shape as the diffusion status. `value` is the engaged value
+// (string, null when off, or boolean), `requested` is what the caller asked for (null = left to the backend), `source` is
+// "auto" or "explicit", `status` says whether the ask survived, and `reason` is the tooltip.
export interface VideoResolvedControl {
value: string | boolean | null;
+ // Absent on backends predating the requested/actual split.
+ requested?: string | boolean | null;
source: "auto" | "explicit";
+ // "applied" (honored, or nothing was asked) | "fell_back" | "unsupported". Absent on older backends.
+ status?: "applied" | "fell_back" | "unsupported";
reason: string;
}
@@ -50,6 +55,8 @@ export interface VideoStatus {
transformer_cache?: string | null;
// Dense DiT precision actually engaged ("int8" | "fp8" | ...) or null for bf16.
transformer_quant?: string | null;
+ // Text-encoder quant actually engaged ("fp8" | "fp8_dynamic" | "int8" | "nvfp4") or null for dense bf16.
+ text_encoder_quant?: string | null;
// Whether the loaded family produces a synchronized audio track.
has_audio: boolean;
// Per-family generation defaults + shape constraints; null when unloaded.
@@ -109,6 +116,8 @@ export interface VideoLoadRequest {
transformer_cache_threshold?: number;
// Dense DiT precision on full-pipeline loads (omit for the hardware ladder; "none" pins bf16). GGUF / single-file checkpoints carry their own.
transformer_quant?: "none" | "fp8" | "int8" | "nvfp4" | "mxfp8";
+ // Text-encoder precision (omit to keep the dense bf16 encoder). Refused with a 409 when the host cannot run it.
+ text_encoder_quant?: "fp8" | "fp8_dynamic" | "int8" | "nvfp4";
}
export interface VideoGenerateRequest {
@@ -143,6 +152,14 @@ export interface GalleryVideo {
seed: number;
has_audio: boolean;
model?: string | null;
+ // The load-time BUILD, all ENGAGED values, so a clip's recipe still names the precision it ran at
+ // once the model is unloaded. Absent on sidecars written before this existed.
+ model_kind?: string | null;
+ gguf_filename?: string | null;
+ transformer_quant?: string | null;
+ text_encoder_quant?: string | null;
+ memory_mode?: string | null;
+ offload_policy?: string | null;
// Creation time (ISO 8601 timestamp).
created_at: string;
}
diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsx
index 974d7a91013..a09a54a30ee 100644
--- a/studio/frontend/src/features/video/video-page.tsx
+++ b/studio/frontend/src/features/video/video-page.tsx
@@ -68,6 +68,16 @@ import { cn } from "@/lib/utils";
import { resolveDiffusionGgufFilename } from "@/lib/diffusion-gguf-filename";
import { createPickGuard, runGgufRepoPick } from "@/lib/diffusion-gguf-pick";
import { diffusionRoutePick } from "@/lib/diffusion-route-pick";
+import {
+ PRECISION_REFUSAL_TITLE,
+ denseTextEncoderBuildLabel,
+ denseTransformerBuildLabel,
+ formatResolvedValue,
+ isPrecisionRefusal,
+ resolvedBadge,
+ resolvedSeedKey,
+ resolvedSelectValue,
+} from "@/lib/resolved-precision";
import {
routedGgufFilename,
routedGgufLabel,
@@ -339,16 +349,10 @@ function Field({
);
}
-// The engaged value of a resolved Advanced control, formatted for its "Auto: X" badge (`_native_cudnn` shows as cuDNN).
-function formatResolvedValue(value: string | boolean | null): string {
- if (value === null || value === "") return "Off";
- if (typeof value === "boolean") return value ? "On" : "Off";
- if (value === "_native_cudnn" || value.toLowerCase() === "cudnn") return "cuDNN";
- return value.toUpperCase();
-}
-
-// The "Auto: X" badge for one Advanced control: rendered only when the backend resolved it (source === "auto").
-// The reason is a hover tooltip. Muted pill matching the panel's other chips, same markup as the images page ResolvedBadge.
+// The badge for one Advanced control: "Auto: X" when the backend decided it, "NVFP4 -> OFF" in a
+// warning tone when an EXPLICIT request was declined. The old rule rendered nothing for the second
+// case, which is how a clip could be labelled BF16 while telemetry confirmed NVFP4 (and the other
+// way round). Same markup and helpers as the images page ResolvedBadge.
function ResolvedBadge({
status,
controlKey,
@@ -356,22 +360,113 @@ function ResolvedBadge({
status: VideoStatus | null;
controlKey: string;
}) {
- const resolved = status?.resolved?.[controlKey];
- if (!resolved || resolved.source !== "auto") return null;
+ const info = resolvedBadge(controlKey, status?.resolved?.[controlKey]);
+ if (!info) return null;
const badge = (
- <span className="shrink-0 rounded-sm bg-muted px-1 py-px text-ui-9 font-medium uppercase tracking-wider text-muted-foreground">
- Auto: {formatResolvedValue(resolved.value)}
+ <span
+ className={cn(
+ "shrink-0 rounded-sm px-1 py-px text-ui-9 font-medium uppercase tracking-wider",
+ info.tone === "warn"
+ ? "bg-destructive/15 text-destructive"
+ : "bg-muted text-muted-foreground",
+ )}
+ >
+ {info.label}
</span>
);
- if (!resolved.reason) return badge;
+ if (!info.tooltip) return badge;
return (
<Tooltip>
<TooltipTrigger asChild={true}>{badge}</TooltipTrigger>
- <TooltipContent>{resolved.reason}</TooltipContent>
+ <TooltipContent>{info.tooltip}</TooltipContent>
</Tooltip>
);
}
+// One "what actually ran" line in the loaded-build summary below. Mirrors the images page.
+function BuildRow({ label, value, badge }: { label: string; value: string; badge?: ReactNode }) {
+ return (
+ <div className="flex items-center justify-between gap-2">
+ <span className="flex shrink-0 items-center gap-1 whitespace-nowrap text-muted-foreground">
+ {label}
+ {badge}
+ </span>
+ <span className="min-w-0 truncate text-foreground">{value}</span>
+ </div>
+ );
+}
+
+/**
+ * What the LOADED model is actually running, read from status (never from the request): the DiT and
+ * text-encoder precision, the memory mode with its resolved offload behaviour, and the attention
+ * backend. The Advanced selects above say what was ASKED for; this says what happened, and any
+ * control whose request was declined carries its reason in the badge tooltip.
+ */
+function LoadedBuildSummary({ status }: { status: VideoStatus | null }) {
+ if (!status?.loaded) return null;
+ const offload = status.offload_policy ?? "none";
+ return (
+ <div className="flex flex-col gap-1 rounded-md border border-border/60 px-2.5 py-2 text-ui-11">
+ <div className="flex items-center gap-1 pb-0.5 text-xs font-medium text-muted-foreground">
+ Loaded build
+ <InfoHint>
+ What the loaded model is actually running, reported by the backend. A control whose
+ requested value could not be used shows it next to that control, with the reason.
+ </InfoHint>
+ </div>
+ <BuildRow
+ label="Transformer"
+ value={
+ status.transformer_quant
+ ? formatResolvedValue("transformer_quant", status.transformer_quant)
+ // No dense quant ran, so the row reports what the checkpoint itself carries.
+ : denseTransformerBuildLabel(status)
+ }
+ badge={<ResolvedBadge status={status} controlKey="transformer_quant" />}
+ />
+ <BuildRow
+ label="Text encoder"
+ value={
+ status.text_encoder_quant
+ ? formatResolvedValue("text_encoder_quant", status.text_encoder_quant)
+ // No runtime TE quant engaged, which on the native engine is not the same as bf16.
+ : denseTextEncoderBuildLabel(status)
+ }
+ badge={<ResolvedBadge status={status} controlKey="text_encoder_quant" />}
+ />
+ <BuildRow
+ label="Memory"
+ value={
+ offload === "none"
+ ? `${status.memory_mode ?? "auto"} · resident`
+ : `${status.memory_mode ?? "auto"} · ${offload} offload`
+ }
+ />
+ <BuildRow
+ label="Attention"
+ value={
+ status.attention_backend
+ ? formatResolvedValue("attention_backend", status.attention_backend)
+ : "Native SDPA"
+ }
+ />
+ </div>
+ );
+}
+
+/**
+ * Report a failed load. A refused precision is a long actionable sentence, so it becomes a toast
+ * description under a short title rather than one unreadable line. Mirrors the images page.
+ */
+function reportLoadFailure(message: string | null | undefined, fallback: string): void {
+ const text = (message || "").trim();
+ if (text && isPrecisionRefusal(text)) {
+ toast.error(PRECISION_REFUSAL_TITLE, { description: text });
+ return;
+ }
+ toast.error(text || fallback);
+}
+
// A compact labeled Select row for the Advanced Options panel.
function AdvancedSelect({
label,
@@ -457,6 +552,27 @@ function RecipePopover({
<RecipeRow label="Negative" value={video.negative_prompt} wrap />
) : null}
{video.model ? <RecipeRow label="Model" value={video.model} /> : null}
+ {/* The load-time build, all ENGAGED values, so a saved clip can never be labelled with a
+ precision that did not run. Matches what the images Recipe already shows. */}
+ {video.gguf_filename ? (
+ <RecipeRow label="File" value={video.gguf_filename} mono />
+ ) : null}
+ {video.transformer_quant ? (
+ <RecipeRow label="Quant" value={video.transformer_quant} />
+ ) : null}
+ {video.text_encoder_quant ? (
+ <RecipeRow label="TE quant" value={video.text_encoder_quant} />
+ ) : null}
+ {video.memory_mode ? (
+ <RecipeRow
+ label="Memory"
+ value={
+ video.offload_policy && video.offload_policy !== "none"
+ ? `${video.memory_mode} (${video.offload_policy} offload)`
+ : video.memory_mode
+ }
+ />
+ ) : null}
<RecipeRow label="Size" value={`${video.width} × ${video.height}`} />
<RecipeRow label="Frames" value={`${video.num_frames} @ ${video.fps} fps`} />
<RecipeRow label="Duration" value={`${video.duration_s.toFixed(2)}s`} />
@@ -754,6 +870,36 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
}
}, [loadedModelKey, defaultSteps, defaultGuidance]);
+ // Reseed the Advanced selects from the LOADED build, so they stop being pure local request state.
+ // An honored request re-selects itself; a declined one snaps to what actually engaged, so the
+ // Precision dropdown can never go on advertising a scheme the loaded DiT is not running. Keyed on
+ // the LOAD-TIME half of the record: the backend rewrites the transformer_cache entry at GENERATION
+ // time, so serializing the whole record let a step-cache toggle discard a pending Advanced edit.
+ const resolvedKey = status?.loaded ? resolvedSeedKey(status.resolved) : null;
+ useEffect(() => {
+ const record = status?.loaded ? status.resolved : null;
+ if (!record) return;
+ const quant = resolvedSelectValue(record.transformer_quant, (v) =>
+ // The engaged value spells "no quant" as "off"; the select's option for it is "none".
+ (["auto", "none", "int8", "fp8", "nvfp4", "mxfp8"] as const).find(
+ (o) => o === v || (o === "none" && v === "off"),
+ ) ?? null,
+ );
+ if (quant) setTransformerQuant(quant);
+ const memory = resolvedSelectValue(record.memory_mode, (v) =>
+ (["auto", "fast", "balanced", "low_vram"] as const).find((o) => o === v) ?? null,
+ );
+ if (memory) setMemoryMode(memory);
+ const attention = resolvedSelectValue(record.attention_backend, (v) =>
+ // The engaged value uses the dispatcher's own name; map it back to the option.
+ (["auto", "native", "cudnn", "flash3", "sage"] as const).find(
+ (o) => o === v || `_native_${o}` === v,
+ ) ?? null,
+ );
+ if (attention) setAttentionBackend(attention);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- resolvedKey stands for the record
+ }, [resolvedKey]);
+
// Mint (once) a playable link for a record's MP4, cached across remounts. Unlike the images gallery this does NOT download
// the file: the link goes straight into the <video> element, which streams ranges, so playback starts and seeking works.
const ensureSrc = useCallback(async (video: GalleryVideo) => {
@@ -1031,7 +1177,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
}
if (p.phase === "error") {
dismissLoadToast();
- toast.error(p.error || "Failed to load model");
+ reportLoadFailure(p.error, "Failed to load model");
setBusy(null);
if (quantRevert.current) {
setQuant(quantRevert.current.prev);
@@ -1215,14 +1361,18 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
speed_mode: speedMode === "auto" ? undefined : speedMode,
attention_backend: attentionBackend === "auto" ? undefined : attentionBackend,
transformer_cache: transformerCache === "auto" ? undefined : transformerCache,
- transformer_quant: transformerQuant === "auto" ? undefined : transformerQuant,
+ // Full-pipeline loads only: a GGUF / single-file DiT runs the precision its checkpoint
+ // carries. The Precision control is hidden for those kinds but the state persists across
+ // picks, so a stale scheme would reach a load that can only refuse it.
+ transformer_quant:
+ opts.kind === "pipeline" && transformerQuant !== "auto" ? transformerQuant : undefined,
});
} catch (err) {
lastLoad.current = prevLastLoad;
setCanReapply(prevCanReapply);
lastLoadRevert.current = null;
dismissLoadToast();
- toast.error(err instanceof Error ? err.message : "Failed to start load");
+ reportLoadFailure(err instanceof Error ? err.message : "", "Failed to start load");
setBusy(null);
void refreshStatus();
return false;
@@ -1252,6 +1402,18 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
} | null>(null);
const handleLoadRef = useRef(handleLoad);
handleLoadRef.current = handleLoad;
+ // Read through a ref for the same reason handleLoad is: loadOrStage is memoized so its
+ // consumers keep a stable identity, and a plain capture froze the precision at whatever was
+ // selected when the callback was built. The ordinary auto -> FP8 change then sent the plan no
+ // precision at all, skipping the pre-download refusal, and the user staged tens of GB before
+ // /video/load rejected the same pick.
+ const transformerQuantRef = useRef(transformerQuant);
+ transformerQuantRef.current = transformerQuant;
+ // And the memory request, for the same reason and through the same ref: the route refuses an
+ // explicit precision under balanced or low_vram only when it is told the memory mode, so a
+ // plan asked without it staged tens of GB and left the 409 to the load.
+ const memoryModeRef = useRef(memoryMode);
+ memoryModeRef.current = memoryMode;
// A download finishing while this page is hidden must not evict the model the visible page loaded. The pick is held, not dropped.
const stagedLoadDeferred = useRef(false);
// A pick made while the download ran already owns the page; only the newest may load. `isLatest`, not `holds`: leaving the
@@ -1297,6 +1459,17 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
model_kind: opts.kind,
// Same token handleLoad sends: without it the metadata lookup fails on a gated base and the plan drops the companion entry, so the load pulls those files inline.
hf_token: hfApiToken(getHfToken()),
+ // And the same precision, for the same reason: the plan refuses a scheme this host
+ // cannot honour, so omitting it staged tens of GB of weights and left the refusal to
+ // the load afterwards. Sent under the identical pipeline-only rule handleLoad applies.
+ transformer_quant:
+ opts.kind === "pipeline" && transformerQuantRef.current !== "auto"
+ ? transformerQuantRef.current
+ : undefined,
+ // The same memory request handleLoad sends: the precision gate refuses the
+ // offload-forcing modes only when it can see them.
+ memory_mode:
+ memoryModeRef.current === "auto" ? undefined : memoryModeRef.current,
});
// Superseded mid-plan: neither stage nor load, and leave `pendingStagedLoad` to its new owner.
if (!owns()) return false;
@@ -1725,6 +1898,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {
["fbcache", "First-Block-Cache"],
]}
/>
+ <LoadedBuildSummary status={status} />
{status?.loaded && canReapply && (
<Tooltip>
<TooltipTrigger asChild={true}>
diff --git a/studio/frontend/src/lib/resolved-precision.ts b/studio/frontend/src/lib/resolved-precision.ts
new file mode 100644
index 00000000000..34466402a9e
--- /dev/null
+++ b/studio/frontend/src/lib/resolved-precision.ts
@@ -0,0 +1,273 @@
+// 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 Advanced panel's resolved-control decisions, as pure functions the pages render.
+ *
+ * The old badge rule was `source === "auto"`, so an EXPLICIT precision the backend declined
+ * rendered no badge at all while the dropdown kept advertising the request: a Q4_K_M GGUF could
+ * show FP8 with transformer FP8 disabled, and a successfully generated image proved nothing about
+ * the precision that ran. These helpers decide from BOTH sides of the record -- what was asked for
+ * and what engaged -- so a fallback is impossible to miss, and they seed the Advanced selects from
+ * the loaded model instead of leaving them as pure local request state.
+ */
+
+// One Advanced control's engaged value + provenance. Structurally shared by the image and video
+// status payloads; declared here so this module needs neither feature's api.ts.
+export interface ResolvedControl {
+ value: string | boolean | null;
+ // What the caller asked for, or null when they left it to the backend. Absent on older backends.
+ requested?: string | boolean | null;
+ source: "auto" | "explicit";
+ // "applied" | "fell_back" | "unsupported". Absent on older backends, which only ever applied.
+ status?: string;
+ reason: string;
+}
+
+export type ResolvedBadgeTone = "auto" | "warn";
+
+export interface ResolvedBadgeInfo {
+ // Full badge text, e.g. "Auto: FP8" or "FP8 -> OFF".
+ label: string;
+ // "auto" is the neutral informational pill; "warn" flags a request that did not survive.
+ tone: ResolvedBadgeTone;
+ // Hover tooltip: the backend's reason, prefixed for a declined request so the pill is readable
+ // even when the reason alone reads like a statement of fact.
+ tooltip: string;
+}
+
+// The backend refuses an EXPLICIT precision it cannot honor rather than loading at some other one
+// (409 from /images/load and /video/load, or an error phase on load-progress once the decline can
+// only be found mid-load). The detail is one long actionable sentence, so the pages show it as a
+// toast DESCRIPTION under this title instead of as an unreadable single line.
+export const PRECISION_REFUSAL_TITLE = "Requested precision is not available";
+
+/** Whether a load failure is that refusal, so it can be presented as an actionable choice. */
+export function isPrecisionRefusal(message: string): boolean {
+ return /_quant='[^']*' could not be used/.test(message);
+}
+
+/** Whether an engaged/requested value means "this control is off". */
+function isOff(value: string | boolean | null | undefined): boolean {
+ if (value === null || value === undefined || value === false) return true;
+ if (value === true) return false;
+ const text = String(value).trim().toLowerCase().replace(/-/g, "_");
+ return text === "" || text === "none" || text === "off" || text === "0";
+}
+
+/** The engaged value of a resolved Advanced control, formatted for its badge. */
+export function formatResolvedValue(key: string, value: string | boolean | null | undefined): string {
+ if (key === "cpu_offload") return value ? "On" : "Off";
+ if (value === null || value === undefined || value === "") return "Off";
+ if (typeof value === "boolean") return value ? "On" : "Off";
+ if (value === "_native_cudnn" || value.toLowerCase() === "cudnn") return "cuDNN";
+ // Deferred speed auto: the dense pipe stays exact/eager and compiles on the 3rd image (the tooltip carries the full reason).
+ if (value === "deferred") return "On from 3rd image";
+ return value.toUpperCase();
+}
+
+/**
+ * Whether the caller's request survived. True when they left the control to the backend (there was
+ * no request to betray) or when the backend says it applied it.
+ *
+ * The `status` field is authoritative rather than a `requested !== value` string comparison,
+ * because several controls answer in a DIFFERENT vocabulary than they are asked in: memory_mode
+ * takes "low_vram" and reports the offload policy "sequential", attention_backend takes "cudnn" and
+ * reports "_native_cudnn". Comparing those directly would flag every honored request as a
+ * fallback. The backend, which owns both vocabularies, classifies it once. Older backends send no
+ * `status` at all, so they fall back to the mismatch test, which is still right for the precision
+ * controls (the ones P1-2 is about) since those echo their own vocabulary.
+ *
+ * Only the two statuses that MEAN a decline are read as one. `status` is deliberately typed wider
+ * than the backend's union so a NEWER backend's fourth value still parses, but treating anything
+ * that is not "applied" as a failure defeats that: an unknown status would paint a red
+ * "FP8 -> FP8" over a request that was honored, and on memory_mode (asked "low_vram", answered
+ * "sequential") a "LOW_VRAM -> SEQUENTIAL" that never happened. An unrecognised status is not a
+ * decline -- staying quiet is the safe direction, since the build that adds a status ships the
+ * frontend that understands it.
+ */
+export function isResolvedHonored(resolved: ResolvedControl | undefined | null): boolean {
+ if (!resolved) return true;
+ if (resolved.source === "auto") return true;
+ if (resolved.status) return resolved.status !== "fell_back" && resolved.status !== "unsupported";
+ // Older backend: no status field. Compare directly, treating every "off" spelling as equal.
+ const requested = resolved.requested;
+ if (requested === undefined || requested === null) return true;
+ if (isOff(requested) && isOff(resolved.value)) return true;
+ return (
+ String(requested).trim().toLowerCase().replace(/-/g, "_") ===
+ String(resolved.value ?? "").trim().toLowerCase().replace(/-/g, "_")
+ );
+}
+
+/**
+ * The badge for one Advanced control, or null when there is nothing to say (the caller set it and
+ * got it). A backend decision reads "Auto: X"; a declined request reads "FP8 -> OFF" so the ask and
+ * the outcome are both on screen.
+ */
+export function resolvedBadge(
+ key: string,
+ resolved: ResolvedControl | undefined | null,
+): ResolvedBadgeInfo | null {
+ if (!resolved) return null;
+ const engaged = formatResolvedValue(key, resolved.value);
+ if (!isResolvedHonored(resolved)) {
+ const asked = formatResolvedValue(key, resolved.requested ?? null);
+ const verb = resolved.status === "unsupported" ? "not supported" : "not applied";
+ return {
+ label: `${asked} → ${engaged}`,
+ tone: "warn",
+ tooltip: resolved.reason
+ ? `You requested ${asked}; ${engaged} was used because ${resolved.reason}.`
+ : `You requested ${asked}, but it was ${verb} here; ${engaged} was used instead.`,
+ };
+ }
+ if (resolved.source !== "auto") return null;
+ return { label: `Auto: ${engaged}`, tone: "auto", tooltip: resolved.reason };
+}
+
+/**
+ * The value an Advanced select should show for the LOADED model, mapped into that select's option
+ * vocabulary by `toOption`. Returns null when the record says nothing useful, so the caller keeps
+ * whatever the user has typed.
+ *
+ * - the backend chose it -> "auto" (the badge already names what that resolved to)
+ * - an honored explicit request -> that request
+ * - a DECLINED explicit request -> the value that actually engaged
+ *
+ * The last line is the P1-2 fix on the input side: the selects were pure local request state, so a
+ * declined FP8 stayed selected indefinitely and the interface went on displaying a precision the
+ * loaded model was not running.
+ */
+export function resolvedSelectValue<T extends string>(
+ resolved: ResolvedControl | undefined | null,
+ toOption: (value: string) => T | null,
+): T | null {
+ if (!resolved) return null;
+ if (resolved.source === "auto") return toOption("auto");
+ const source = isResolvedHonored(resolved) ? resolved.requested : resolved.value;
+ if (source === undefined) return null;
+ if (source === null) return toOption("none");
+ if (typeof source === "boolean") return toOption(source ? "on" : "none");
+ return toOption(String(source));
+}
+
+/**
+ * The key the pages run their Advanced-reseed effect on: the LOAD-TIME half of the resolved record.
+ *
+ * NOT the whole record serialized. The backend rewrites entries of it at GENERATION time -- the
+ * speed_mode and attention_backend entries when the deferred compile profile engages on the 3rd
+ * image, the transformer_cache entry whenever the step-cache threshold flips -- so keying the
+ * effect on the whole blob re-ran the reseed mid-session and overwrote a Precision the user had
+ * picked but not yet loaded. That is the opposite of the intent: an edit made after the load is
+ * meant to survive until the next LOAD replaces it.
+ *
+ * Only the controls the reseed writes are in the key, and for attention only the REQUEST side:
+ * `value` is the field the generation-time rewrite touches, and the reseed's answer for an auto or
+ * an honored request does not read it anyway. A reload still re-fires, including a Reapply with
+ * new options, because that always lands a different request or engaged value on one of these.
+ */
+export function resolvedSeedKey(
+ resolved: Record<string, ResolvedControl> | null | undefined,
+): string | null {
+ if (!resolved) return null;
+ const part = (control: ResolvedControl | undefined, withValue: boolean): string => {
+ if (!control) return "";
+ const engaged = withValue ? String(control.value ?? "") : "";
+ return `${control.source}:${String(control.requested ?? "")}:${engaged}`;
+ };
+ return [
+ part(resolved.transformer_quant, true),
+ part(resolved.memory_mode, true),
+ part(resolved.attention_backend, false),
+ ].join("|");
+}
+
+/**
+ * Whether a status describes the native sd.cpp engine rather than a diffusers pipeline.
+ *
+ * It reports `dtype: "gguf"` and no `engine`/`model_kind` of its own, and the two behave
+ * differently in ways the Loaded-build panel has to say out loud -- its attention is chosen by
+ * native flags, not by the PyTorch dispatcher, and its components are whatever the checkpoint
+ * and its companion bundle hold.
+ */
+export function isNativeEngineStatus(status: {
+ engine?: string | null;
+ dtype?: string | null;
+}): boolean {
+ const engine = String(status.engine ?? "").trim().toLowerCase();
+ if (engine) return engine.includes("sd_cpp") || engine.includes("sd.cpp") || engine === "native";
+ return status.dtype === "gguf";
+}
+
+/**
+ * The Loaded-build panel's Transformer row when no dense quant engaged.
+ *
+ * Shared by the image and video pages because the mistake it prevents is the same on both: the
+ * default arm is BF16, and only a full diffusers repo actually is. A GGUF pick runs the
+ * checkpoint's own quantisation, so the BF16 arm has to be the LAST resort.
+ *
+ * `dtype === "gguf"` is the native sd.cpp engine, which reports no `model_kind` at all -- without
+ * that arm every native GGUF load, the default CPU path, was labelled BF16 in the one panel whose
+ * whole job is to say what actually loaded.
+ *
+ * A single_file load is NOT "as in checkpoint": `from_single_file` is handed the resolved
+ * `torch_dtype`, so an fp8 safetensors is upcast on load (the memory planner budgets the ~2x for
+ * exactly that). Reporting the storage precision there hid the runtime dtype, which is the one
+ * thing this row exists to state, so it reads the dtype like any other dense load.
+ */
+export function denseTransformerBuildLabel(status: {
+ model_kind?: string | null;
+ dtype?: string | null;
+}): string {
+ if (status.model_kind === "gguf" || status.dtype === "gguf") return "GGUF (as-is)";
+ return denseDtypeLabel(status.dtype);
+}
+
+/**
+ * The dtype the pipeline actually loaded in, not the one the happy path uses.
+ *
+ * A CPU diffusers load reports float32, an older accelerator resolves to float16, and an
+ * fp16-incompatible family is promoted to float32 by the video loader -- and all three were
+ * labelled BF16 by the panel whose whole job is to say what loaded. Unknown falls back to BF16,
+ * which is what a diffusers load that reports nothing is.
+ */
+function denseDtypeLabel(dtype: string | null | undefined): string {
+ const text = String(dtype ?? "").trim().toLowerCase();
+ if (text.includes("bfloat16") || text === "bf16") return "BF16";
+ if (text.includes("float16") || text === "fp16") return "FP16";
+ if (text.includes("float32") || text === "fp32") return "FP32";
+ if (text.includes("float64")) return "FP64";
+ return "BF16";
+}
+
+/**
+ * The Loaded-build panel's Text encoder row when no runtime text-encoder quant engaged.
+ *
+ * The native sd.cpp engine has no runtime TE quant at all, so its status always reports
+ * `text_encoder_quant: null` -- which is not evidence of a bf16 encoder. Its companion bundle is
+ * whatever the family's asset mapping names, and several are not bf16 (FLUX.1 loads
+ * `t5xxl_fp16.safetensors`). A null on that engine means "as stored", not BF16.
+ */
+export function denseTextEncoderBuildLabel(status: { dtype?: string | null }): string {
+ return status.dtype === "gguf" ? "As in checkpoint" : denseDtypeLabel(status.dtype);
+}
+
+/**
+ * The Recipe popover's Memory row: the placement that actually ran.
+ *
+ * The two fields answer different questions and either can be absent. `memory_mode` is the
+ * torchao-side memory planner's pick, and the native sd.cpp engine never runs it, so its records
+ * carry `memory_mode: null` alongside a real `offload_policy`. Substituting "auto" there claimed
+ * the planner had chosen a mode on a path that has no planner -- so an absent mode reports the
+ * offload alone, which is all that engine knows.
+ */
+export function memoryRecipeValue(
+ memoryMode: string | null | undefined,
+ offloadPolicy: string | null | undefined,
+): string {
+ const offloading = offloadPolicy != null && offloadPolicy !== "" && offloadPolicy !== "none";
+ if (!offloading) return memoryMode ?? "";
+ if (!memoryMode) return `${offloadPolicy} offload`;
+ return `${memoryMode} (${offloadPolicy} offload)`;
+}
diff --git a/studio/frontend/tests/dense-transformer-build-label.test.ts b/studio/frontend/tests/dense-transformer-build-label.test.ts
new file mode 100644
index 00000000000..19899df01d5
--- /dev/null
+++ b/studio/frontend/tests/dense-transformer-build-label.test.ts
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ denseTextEncoderBuildLabel,
+ denseTransformerBuildLabel,
+ isNativeEngineStatus,
+ isPrecisionRefusal,
+ memoryRecipeValue,
+} from "../src/lib/resolved-precision.ts";
+
+test("a native sd.cpp load is not labelled BF16", () => {
+ // The native engine reports dtype "gguf" and no model_kind, so the kind-only rule fell through
+ // to the BF16 arm and mislabelled every native GGUF checkpoint -- the default CPU path.
+ assert.equal(denseTransformerBuildLabel({ dtype: "gguf" }), "GGUF (as-is)");
+ assert.equal(denseTransformerBuildLabel({ dtype: "gguf", model_kind: null }), "GGUF (as-is)");
+});
+
+test("the diffusers kinds keep their own labels", () => {
+ assert.equal(denseTransformerBuildLabel({ model_kind: "gguf", dtype: "bfloat16" }), "GGUF (as-is)");
+ // A single-file fp8 checkpoint is upcast by from_single_file to the resolved torch_dtype, so
+ // the row states the dtype the transformer is actually running in, not how it was stored.
+ assert.equal(
+ denseTransformerBuildLabel({ model_kind: "single_file", dtype: "bfloat16" }),
+ "BF16",
+ );
+ assert.equal(
+ denseTransformerBuildLabel({ model_kind: "single_file", dtype: "float16" }),
+ "FP16",
+ );
+ // Only a full diffusers repo is genuinely bf16.
+ assert.equal(denseTransformerBuildLabel({ model_kind: "pipeline", dtype: "bfloat16" }), "BF16");
+});
+
+test("a native text encoder is not labelled BF16 either", () => {
+ // The native engine has no runtime TE quant, so its status always reports null -- and several
+ // families' native companion bundles are not bf16 (FLUX.1 loads t5xxl_fp16.safetensors).
+ assert.equal(denseTextEncoderBuildLabel({ dtype: "gguf" }), "As in checkpoint");
+ // The diffusers path really does load the base repo's dense bf16 encoder.
+ assert.equal(denseTextEncoderBuildLabel({ dtype: "bfloat16" }), "BF16");
+ assert.equal(denseTextEncoderBuildLabel({}), "BF16");
+});
+
+test("the dense label follows the dtype the pipeline actually loaded in", () => {
+ // BF16 is the happy path, not the only one: a CPU diffusers load reports float32, an older
+ // accelerator resolves to float16, and the video loader promotes an fp16-incompatible family
+ // to float32 -- all three were labelled BF16 by the panel whose job is to say what loaded.
+ assert.equal(denseTransformerBuildLabel({ model_kind: "pipeline", dtype: "float32" }), "FP32");
+ assert.equal(denseTransformerBuildLabel({ model_kind: "pipeline", dtype: "float16" }), "FP16");
+ assert.equal(
+ denseTransformerBuildLabel({ model_kind: "pipeline", dtype: "torch.bfloat16" }),
+ "BF16",
+ );
+ // Unknown stays BF16: a diffusers load that reports nothing is one.
+ assert.equal(denseTransformerBuildLabel({ model_kind: "pipeline" }), "BF16");
+ // The text encoder reads the same dtype, and its gguf arm still wins.
+ assert.equal(denseTextEncoderBuildLabel({ dtype: "float32" }), "FP32");
+ assert.equal(denseTextEncoderBuildLabel({ dtype: "float16" }), "FP16");
+ assert.equal(denseTextEncoderBuildLabel({ dtype: "gguf" }), "As in checkpoint");
+});
+
+test("the native engine is recognisable so its attention is not called SDPA", () => {
+ // sd.cpp reports no attention backend because it has none of ours: its attention comes from
+ // native flags, not the PyTorch dispatcher, so "Native SDPA" is wrong on the default CPU path.
+ assert.equal(isNativeEngineStatus({ dtype: "gguf" }), true);
+ assert.equal(isNativeEngineStatus({ engine: "sd_cpp", dtype: "bfloat16" }), true);
+ assert.equal(isNativeEngineStatus({ engine: "diffusers", dtype: "gguf" }), false);
+ assert.equal(isNativeEngineStatus({ dtype: "bfloat16" }), false);
+ assert.equal(isNativeEngineStatus({}), false);
+});
+
+test("the native precision refusal is classified like the diffusers one", () => {
+ // The native gate says the same "could not be used" now, so the long actionable sentence is
+ // shown under the precision title instead of as a generic one-line error.
+ assert.equal(
+ isPrecisionRefusal(
+ "transformer_quant='fp8' could not be used: this pick runs on the native engine, which " +
+ "loads a GGUF checkpoint as it is and has no torchao quantisation path.",
+ ),
+ true,
+ );
+ // Both knobs refused at once puts an "and" between the clauses.
+ assert.equal(
+ isPrecisionRefusal(
+ "transformer_quant='fp8' and text_encoder_quant='int8' could not be used: ...",
+ ),
+ true,
+ );
+ assert.equal(isPrecisionRefusal("Failed to load model: out of memory"), false);
+});
+
+test("an absent memory mode does not become Auto", () => {
+ // The native engine records memory_mode null with a real offload_policy. The old nullish
+ // fallback rendered that as "auto (model offload)", claiming the memory planner had picked a
+ // mode on the one path that never runs the planner.
+ assert.equal(memoryRecipeValue(null, "model"), "model offload");
+ assert.equal(memoryRecipeValue(undefined, "sequential"), "sequential offload");
+ assert.equal(memoryRecipeValue("balanced", "model"), "balanced (model offload)");
+ assert.equal(memoryRecipeValue("balanced", "none"), "balanced");
+ assert.equal(memoryRecipeValue(null, "none"), "");
+});
diff --git a/studio/frontend/tests/loaded-build-panel-rows.test.ts b/studio/frontend/tests/loaded-build-panel-rows.test.ts
new file mode 100644
index 00000000000..2a7d9dc4ab3
--- /dev/null
+++ b/studio/frontend/tests/loaded-build-panel-rows.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
+
+/**
+ * Two rows of the Loaded-build panel, checked against the source that renders them.
+ *
+ * Both cases are the native sd.cpp engine, which is the DEFAULT image path on a host with no
+ * usable GPU -- so a row that is only correct for diffusers is wrong for most first runs.
+ */
+
+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/images/images-page.tsx", import.meta.url)),
+ "utf8",
+);
+
+test("the Memory recipe row renders on an offload with no memory mode", () => {
+ // The native engine reports memory_mode null (it has no torchao path to choose one for) while
+ // still recording an active offload, so gating the row on memory_mode alone hid the offload
+ // policy on exactly the configuration the row was extended to expose.
+ const guard = source.match(
+ /\{image\.memory_mode \|\|\s*\n\s*\(image\.offload_policy && image\.offload_policy !== "none"\) \?/,
+ );
+ assert.ok(guard, "the Memory row must render when EITHER field conveys placement");
+});
+
+test("sd.cpp attention is not reported as Native SDPA", () => {
+ // Its attention is chosen by native flags, not by the diffusers/PyTorch dispatcher.
+ const attention = source.slice(
+ source.indexOf('label="Attention"'),
+ source.indexOf('label="Attention"') + 700,
+ );
+ assert.ok(
+ attention.includes("isNativeEngineStatus(status)"),
+ "the fallback must distinguish the native engine before naming SDPA",
+ );
+ assert.ok(attention.includes("sd.cpp"), "the native arm needs its own label");
+ assert.ok(attention.includes('"Native SDPA"'), "diffusers keeps its label");
+});
diff --git a/studio/frontend/tests/resolved-precision.test.ts b/studio/frontend/tests/resolved-precision.test.ts
new file mode 100644
index 00000000000..70a8fec8bfe
--- /dev/null
+++ b/studio/frontend/tests/resolved-precision.test.ts
@@ -0,0 +1,315 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ PRECISION_REFUSAL_TITLE,
+ type ResolvedControl,
+ isPrecisionRefusal,
+ isResolvedHonored,
+ resolvedBadge,
+ resolvedSeedKey,
+ resolvedSelectValue,
+} from "../src/lib/resolved-precision.ts";
+
+const QUANT_OPTIONS = ["auto", "none", "int8", "fp8", "nvfp4", "mxfp8"] as const;
+const toQuantOption = (v: string) =>
+ QUANT_OPTIONS.find((o) => o === v || (o === "none" && v === "off")) ?? null;
+
+test("a declined explicit precision renders a warning badge naming both sides", () => {
+ // The bug: the badge only rendered for source === "auto", so an explicit FP8 the backend
+ // declined showed nothing while the Precision dropdown kept advertising FP8.
+ const resolved: ResolvedControl = {
+ value: "off",
+ requested: "fp8",
+ source: "explicit",
+ status: "fell_back",
+ reason: "the dense bf16 transformer does not fit resident",
+ };
+ const badge = resolvedBadge("transformer_quant", resolved);
+ assert.ok(badge);
+ assert.equal(badge.label, "FP8 → OFF");
+ assert.equal(badge.tone, "warn");
+ assert.match(badge.tooltip, /You requested FP8/);
+ assert.match(badge.tooltip, /does not fit resident/);
+ assert.equal(isResolvedHonored(resolved), false);
+});
+
+test("an honored explicit request renders no badge", () => {
+ const resolved: ResolvedControl = {
+ value: "fp8",
+ requested: "fp8",
+ source: "explicit",
+ status: "applied",
+ reason: "engaged on the dense fast path",
+ };
+ assert.equal(resolvedBadge("transformer_quant", resolved), null);
+ assert.equal(isResolvedHonored(resolved), true);
+});
+
+test("a backend decision still renders the neutral Auto badge", () => {
+ const resolved: ResolvedControl = {
+ value: "off",
+ requested: null,
+ source: "auto",
+ status: "applied",
+ reason: "not engaged (GGUF transformer loaded)",
+ };
+ const badge = resolvedBadge("transformer_quant", resolved);
+ assert.deepEqual(badge, {
+ label: "Auto: OFF",
+ tone: "auto",
+ tooltip: "not engaged (GGUF transformer loaded)",
+ });
+});
+
+test("a control answered in another vocabulary is not reported as a fallback", () => {
+ // memory_mode is REQUESTED as a mode and ENGAGED as an offload policy, so a raw string compare
+ // would call every honored request a fallback. The backend's status field decides.
+ const resolved: ResolvedControl = {
+ value: "sequential",
+ requested: "low_vram",
+ source: "explicit",
+ status: "applied",
+ reason: "planned from measured free VRAM",
+ };
+ assert.equal(isResolvedHonored(resolved), true);
+ assert.equal(resolvedBadge("memory_mode", resolved), null);
+});
+
+test("an older backend without requested/status keeps today's behaviour", () => {
+ // No status field: an explicit control renders nothing, an auto one renders its Auto badge.
+ assert.equal(
+ resolvedBadge("transformer_quant", { value: "int8", source: "explicit", reason: "requested" }),
+ null,
+ );
+ const auto = resolvedBadge("speed_mode", {
+ value: "eager",
+ source: "auto",
+ reason: "per-kind default",
+ });
+ assert.equal(auto?.label, "Auto: EAGER");
+ assert.equal(auto?.tone, "auto");
+});
+
+test("an older backend still flags a mismatch it can see", () => {
+ // requested present but status absent: fall back to comparing, which is right for the precision
+ // controls (they answer in the vocabulary they are asked in).
+ const resolved: ResolvedControl = {
+ value: "off",
+ requested: "fp8",
+ source: "explicit",
+ reason: "",
+ };
+ assert.equal(isResolvedHonored(resolved), false);
+ assert.equal(resolvedBadge("transformer_quant", resolved)?.tone, "warn");
+});
+
+test("a status this build has never heard of is not read as a decline", () => {
+ // Forwards compat the OTHER way: `status` is typed wider than the backend's union precisely so a
+ // newer backend can add a fourth value. Reading everything except "applied" as a failure threw
+ // that away -- an honored FP8 came back as a red "FP8 → FP8" badge, and memory_mode (asked
+ // "low_vram", answered "sequential") as a "LOW_VRAM → SEQUENTIAL" fallback that never happened.
+ for (const status of ["partially_applied", "downgraded", "ok"]) {
+ const quant: ResolvedControl = {
+ value: "fp8",
+ requested: "fp8",
+ source: "explicit",
+ status,
+ reason: "engaged on the dense fast path",
+ };
+ assert.equal(isResolvedHonored(quant), true, status);
+ assert.equal(resolvedBadge("transformer_quant", quant), null, status);
+ // The select still shows the ask, not the engaged value it would have snapped to.
+ assert.equal(resolvedSelectValue(quant, toQuantOption), "fp8", status);
+
+ const memory: ResolvedControl = {
+ value: "sequential",
+ requested: "low_vram",
+ source: "explicit",
+ status,
+ reason: "planned from measured free VRAM",
+ };
+ assert.equal(resolvedBadge("memory_mode", memory), null, status);
+ }
+ // The two known declines keep warning.
+ for (const status of ["fell_back", "unsupported"]) {
+ const resolved: ResolvedControl = {
+ value: "off",
+ requested: "fp8",
+ source: "explicit",
+ status,
+ reason: "the host cannot run it",
+ };
+ assert.equal(isResolvedHonored(resolved), false, status);
+ assert.equal(resolvedBadge("transformer_quant", resolved)?.tone, "warn", status);
+ }
+});
+
+test("every off spelling counts as an honored off request", () => {
+ for (const [requested, value] of [
+ ["none", "off"],
+ ["off", null],
+ ["", "off"],
+ ] as Array<[string, string | null]>) {
+ assert.equal(
+ isResolvedHonored({ value, requested, source: "explicit", reason: "" }),
+ true,
+ `${requested} -> ${value}`,
+ );
+ }
+});
+
+test("cpu_offload compares as a boolean and formats as On/Off", () => {
+ assert.equal(
+ isResolvedHonored({ value: true, requested: true, source: "explicit", reason: "" }),
+ true,
+ );
+ const declined = resolvedBadge("cpu_offload", {
+ value: false,
+ requested: true,
+ source: "explicit",
+ status: "fell_back",
+ reason: "everything fits on the GPU",
+ });
+ assert.equal(declined?.label, "On → Off");
+});
+
+test("the Precision select seeds from the loaded build", () => {
+ // Auto stays auto (the badge names what it resolved to).
+ assert.equal(
+ resolvedSelectValue(
+ { value: "fp8", requested: null, source: "auto", status: "applied", reason: "" },
+ toQuantOption,
+ ),
+ "auto",
+ );
+ // An honored request re-selects itself.
+ assert.equal(
+ resolvedSelectValue(
+ { value: "int8", requested: "int8", source: "explicit", status: "applied", reason: "" },
+ toQuantOption,
+ ),
+ "int8",
+ );
+ // A DECLINED request snaps to what actually engaged, so the dropdown stops advertising it.
+ assert.equal(
+ resolvedSelectValue(
+ { value: "off", requested: "fp8", source: "explicit", status: "fell_back", reason: "" },
+ toQuantOption,
+ ),
+ "none",
+ );
+ // Nothing resolved: keep whatever the user has typed.
+ assert.equal(resolvedSelectValue(null, toQuantOption), null);
+});
+
+test("the Attention select maps the dispatcher's own name back to its option", () => {
+ const toAttentionOption = (v: string) =>
+ (["auto", "native", "cudnn", "flash3", "sage"] as const).find(
+ (o) => o === v || `_native_${o}` === v,
+ ) ?? null;
+ assert.equal(
+ resolvedSelectValue(
+ {
+ value: "_native_cudnn",
+ requested: "cudnn",
+ source: "explicit",
+ status: "applied",
+ reason: "",
+ },
+ toAttentionOption,
+ ),
+ "cudnn",
+ );
+});
+
+test("the reseed key ignores the entries the backend rewrites mid-session", () => {
+ // The reseed effect used to key on JSON.stringify(resolved). The backend mutates that record at
+ // GENERATION time -- speed_mode and attention_backend when the deferred compile profile engages
+ // on the 3rd image, transformer_cache when the step-cache threshold flips -- so the key changed
+ // with no reload behind it and the effect re-ran, overwriting a Precision the user had picked
+ // but not yet loaded.
+ const atLoad: Record<string, ResolvedControl> = {
+ transformer_quant: { value: "off", requested: null, source: "auto", status: "applied", reason: "" },
+ memory_mode: { value: "none", requested: null, source: "auto", status: "applied", reason: "" },
+ attention_backend: { value: "native", requested: null, source: "auto", status: "applied", reason: "" },
+ speed_mode: { value: "deferred", requested: null, source: "auto", status: "applied", reason: "" },
+ transformer_cache: { value: "off", requested: null, source: "auto", status: "applied", reason: "" },
+ };
+ const key = resolvedSeedKey(atLoad);
+
+ // Generation 3: the compile profile engages and the attention upgrade lands (diffusion.py).
+ const afterThirdImage: Record<string, ResolvedControl> = {
+ ...atLoad,
+ speed_mode: { ...atLoad.speed_mode, value: "default", reason: "auto: compiled on the 3rd image" },
+ attention_backend: { ...atLoad.attention_backend, value: "_native_cudnn", reason: "cuDNN upgrade" },
+ };
+ assert.equal(resolvedSeedKey(afterThirdImage), key, "a mid-session compile must not re-seed");
+ assert.notEqual(
+ JSON.stringify(afterThirdImage),
+ JSON.stringify(atLoad),
+ "the record really did change -- serializing it is what re-fired the effect",
+ );
+
+ // A step-cache toggle (both pages) is the same story.
+ const afterCacheToggle: Record<string, ResolvedControl> = {
+ ...atLoad,
+ transformer_cache: { ...atLoad.transformer_cache, value: "fbcache", reason: "auto: 40 steps" },
+ };
+ assert.equal(resolvedSeedKey(afterCacheToggle), key, "a cache toggle must not re-seed");
+
+ // A real reload still re-seeds: the request and the engaged value both move.
+ const afterReapply: Record<string, ResolvedControl> = {
+ ...atLoad,
+ transformer_quant: {
+ value: "off",
+ requested: "fp8",
+ source: "explicit",
+ status: "fell_back",
+ reason: "the dense bf16 transformer does not fit resident",
+ },
+ };
+ assert.notEqual(resolvedSeedKey(afterReapply), key, "a declined Reapply must re-seed");
+
+ // So does a load that honors a new memory mode, or a new attention request.
+ assert.notEqual(
+ resolvedSeedKey({
+ ...atLoad,
+ memory_mode: { value: "sequential", requested: "low_vram", source: "explicit", status: "applied", reason: "" },
+ }),
+ key,
+ );
+ assert.notEqual(
+ resolvedSeedKey({
+ ...atLoad,
+ attention_backend: { value: "_native_cudnn", requested: "cudnn", source: "explicit", status: "applied", reason: "" },
+ }),
+ key,
+ );
+});
+
+test("the reseed key tolerates an empty or absent record", () => {
+ assert.equal(resolvedSeedKey(null), null);
+ assert.equal(resolvedSeedKey(undefined), null);
+ // An older backend sends the record without requested/status; the key is still a stable string.
+ assert.equal(typeof resolvedSeedKey({}), "string");
+ const older = resolvedSeedKey({
+ transformer_quant: { value: "int8", source: "explicit", reason: "requested" },
+ });
+ assert.equal(typeof older, "string");
+ assert.ok(!/undefined|NaN/.test(older ?? ""), older ?? "");
+});
+
+test("a precision refusal is recognised so it can be shown as an actionable toast", () => {
+ const refusal =
+ "transformer_quant='fp8' could not be used: this device cannot run a dense torchao quant " +
+ "(it needs a CUDA GPU in bf16). Choose Auto to let the backend pick the fastest precision " +
+ "this host can run, or Off to run the checkpoint as-is.";
+ assert.equal(isPrecisionRefusal(refusal), true);
+ assert.equal(isPrecisionRefusal("text_encoder_quant='int8' could not be used: nope."), true);
+ assert.equal(isPrecisionRefusal("A diffusion load is already in progress."), false);
+ assert.equal(PRECISION_REFUSAL_TITLE, "Requested precision is not available");
+});
diff --git a/studio/frontend/tests/video-download-plan-payload.test.ts b/studio/frontend/tests/video-download-plan-payload.test.ts
new file mode 100644
index 00000000000..5cfab9a0f56
--- /dev/null
+++ b/studio/frontend/tests/video-download-plan-payload.test.ts
@@ -0,0 +1,74 @@
+// 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 staged-plan request has to carry the same precision the load will send.
+ *
+ * /video/download-plan refuses a scheme this host cannot honour, so a plan asked without the
+ * precision succeeded, staged tens of GB of pipeline weights, and left the refusal to the load
+ * afterwards -- which is the whole failure the plan-time check was added to prevent.
+ */
+
+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("the video download plan is asked with the selected precision", () => {
+ const call = source.slice(
+ source.indexOf("await getVideoDownloadPlan({"),
+ source.indexOf("await getVideoDownloadPlan({") + 900,
+ );
+ assert.ok(call.length > 0, "the plan call must exist");
+ assert.ok(
+ call.includes("transformer_quant:"),
+ "the plan must be asked with the precision the load will use",
+ );
+ // Under the same pipeline-only rule the load applies: a GGUF / single-file DiT runs the
+ // precision its checkpoint carries, and the stale control value must not reach either call.
+ assert.ok(call.includes('opts.kind === "pipeline"'));
+});
+
+test("the staged plan reads the precision live, not the value it closed over", () => {
+ // loadOrStage is memoized on [stage, pickGuard] so its consumers keep a stable identity. A
+ // plain capture of transformerQuant therefore froze at the value selected when the callback
+ // was built, and the ordinary auto -> FP8 change sent the plan no precision at all: the
+ // pre-download refusal was skipped and tens of GB were staged before the load refused it.
+ const call = source.slice(
+ source.indexOf("await getVideoDownloadPlan({"),
+ source.indexOf("await getVideoDownloadPlan({") + 900,
+ );
+ assert.ok(
+ call.includes("transformerQuantRef.current"),
+ "the plan must read the precision through the ref",
+ );
+ assert.ok(
+ !/transformerQuant\s*[!=]==/.test(call),
+ "a direct read of the memoized capture is the stale value",
+ );
+ assert.ok(
+ source.includes("transformerQuantRef.current = transformerQuant"),
+ "the ref must be kept current on every render",
+ );
+});
+
+test("the staged plan carries the memory request too", () => {
+ // The route refuses an explicit precision under balanced or low_vram only when it can see the
+ // memory mode. Omitting it here meant the plan succeeded, tens of GB were staged, and the
+ // identical pick was then rejected by /video/load -- the regression the plan gate exists for.
+ const call = source.slice(
+ source.indexOf("await getVideoDownloadPlan({"),
+ source.indexOf("await getVideoDownloadPlan({") + 1200,
+ );
+ assert.ok(call.includes("memory_mode:"), "the plan must be asked with the memory request");
+ assert.ok(
+ call.includes("memoryModeRef.current"),
+ "and read it live, like the precision",
+ );
+ assert.ok(source.includes("memoryModeRef.current = memoryMode"));
+});