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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Diffusion: allow fp8 on Qwen-Image again, and split the training deny (#8018)
Daniel Han8e558606ab9d
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex dcc0f1b85bc..f1387def963 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -1162,6 +1162,53 @@ class DiffusionBackend:except Exception: # noqa: BLE001 — widening the prefetch is best-effort onlyreturn False+ @staticmethod+ def _auto_prequant_retry_scheme(+ target: Any,+ fam: Any,+ requested: Optional[str],+ chosen: Optional[str],+ *,+ base_repo: Optional[str],+ path_override: Optional[str],+ loras: Any,+ ) -> Optional[str]:+ """A lower auto rung than ``chosen`` that HAS a usable prequant, or None.++ Only when ``auto`` was requested: an explicit scheme is honored or refused, never+ swapped. A baked LoRA takes the dense path regardless, so it gets no retry."""+ if normalize_transformer_quant(requested) != TQ_AUTO or _has_active_lora(loras):+ return None+ try:+ from .diffusion_transformer_quant import auto_scheme_candidates+ candidates = auto_scheme_candidates(target, getattr(fam, "name", None))+ except Exception: # noqa: BLE001 -- no candidates is just "no retry"+ return None+ seen_chosen = False+ for candidate in candidates:+ if candidate == chosen:+ seen_chosen = True+ continue+ # Strictly BELOW the winner: a higher rung was already rejected by the ladder.+ if not seen_chosen:+ continue+ source = usable_prequant_source(+ fam, candidate, path_override = path_override, base_repo = base_repo+ )+ if source is None:+ continue+ # Same cached-only rule _uncached_prequant_repo applies to the winner. That guard runs+ # select_transformer_quant_scheme, which only ever sees the winner, so a retry that+ # returned an UNCACHED repo would smuggle past it and download a second multi-GB+ # denoiser for a pick that already has its GGUF. A local override is the operator's own+ # file and costs no bytes.+ if source.kind == "repo" and not prequant_checkpoint_cached(+ source, cache_dir = hub_cache_dir()+ ):+ continue+ return candidate+ return None+def _prefetch_files(self,repo_id: str,@@ -2427,6 +2474,32 @@ class DiffusionBackend:force_dense = _has_active_lora(loras),logger = logger,)++ # Defined OUTSIDE the candidate check: the retry below rebinds ``candidate``+ # and calls this, and that retry is reached precisely when the first+ # resolve returned None (a free-disk gate skipping the dense download while+ # a lower cached prequant still passes). Nested, the name would be unbound+ # there and the retry would raise UnboundLocalError under the load lock+ # instead of loading the cached rung. Reads ``candidate`` at CALL time, so+ # every call still sizes whichever candidate is current.+ def _replan_candidate():+ return self._plan_memory(+ target,+ single_file_path,+ base,+ fam,+ memory_mode,+ cpu_offload,+ kind = kind,+ repo_id = repo_id,+ fetch_base = fetch_base,+ transformer_resident_override_mib = (+ candidate.transient_transformer_mib+ ),+ # Pass the companion estimate so prefetched base shards aren't double-counted.+ companion_override_mib = candidate.companions_mib,+ )+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.@@ -2436,25 +2509,6 @@ class DiffusionBackend:"the server log)")if candidate is not None:-- def _replan_candidate():- return self._plan_memory(- target,- single_file_path,- base,- fam,- memory_mode,- cpu_offload,- kind = kind,- repo_id = repo_id,- fetch_base = fetch_base,- transformer_resident_override_mib = (- candidate.transient_transformer_mib- ),- # Pass the companion estimate so prefetched base shards aren't double-counted.- companion_override_mib = candidate.companions_mib,- )-replanned = _replan_candidate()if (replanned.offload_policy != OFFLOAD_NONE@@ -2488,6 +2542,52 @@ class DiffusionBackend:# The GGUF plan declined resident; a prequant-sized replan says nothing about the dense build.if candidate.prequant:dense_fallback_allowed = False+ if quant_plan is None:+ # Nothing resident for auto's WINNER, either because it has no candidate+ # at all or because its replan still offloads. Without this the load+ # leaves quant_plan unset and the gate below skips the dense/prequant+ # path entirely, so a lower rung whose checkpoint is CACHED and would+ # fit never gets looked at. Same retry as the resident branch, just+ # reached from the side where the GGUF plan already wanted offload.+ retry = self._auto_prequant_retry_scheme(+ target,+ fam,+ transformer_quant,+ select_transformer_quant_scheme(+ target,+ transformer_quant,+ family = getattr(fam, "name", None),+ ),+ base_repo = base,+ path_override = transformer_prequant_path,+ loras = loras,+ )+ retry_candidate = (+ resolve_dense_quant_candidate(+ fam = fam,+ target = target,+ requested = retry,+ base_repo = base,+ prequant_path = transformer_prequant_path,+ force_dense = _has_active_lora(loras),+ logger = logger,+ )+ if retry is not None+ else None+ )+ if retry_candidate is not None:+ candidate = retry_candidate+ retry_plan = _replan_candidate()+ if retry_plan.offload_policy == OFFLOAD_NONE:+ logger.info(+ "diffusion.transformer_quant: auto's pick does not fit "+ "resident; retrying at %s, whose checkpoint is cached",+ retry,+ )+ transformer_quant = retry+ quant_plan = retry_plan+ if candidate.prequant:+ dense_fallback_allowed = Falseelse:# This materialises the dense bf16 transformer, so re-check the fit rather than OOMing after eviction (skipped for a prequant).scheme = select_transformer_quant_scheme(@@ -2517,6 +2617,11 @@ class DiffusionBackend:self._dense_transformer_resident_bytes(fetch_base, _base_local_dir)// (1024 * 1024))+ dense_possible = True+ # Why the dense bf16 build is out, in the caller's terms, filled in by+ # whichever branch below rules it out. Only becomes the load's decline+ # reason if the auto retry then fails to find a rung that does fit.+ dense_decline_reason: Optional[str] = Noneif dense_mib > 0:dense_plan = self._plan_memory(target,@@ -2534,16 +2639,105 @@ class DiffusionBackend:base_local_dir = _base_local_dir,)if dense_plan.offload_policy != OFFLOAD_NONE:+ dense_possible = Falsedense_fallback_allowed = False- # 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"- )+ dense_decline_reason = (+ "the dense bf16 transformer this quant is built from does not "+ f"fit resident ({dense_mib} MiB; the plan picked "+ f"'{dense_plan.offload_policy}' offload)"+ )+ elif not _transformer_prefetched:+ # dense_mib == 0 with nothing staged is not "no information": the+ # prefetch's capacity gate DECLINED the base transformer/ shards, so the+ # dense bf16 build cannot run at all. Reading it as unknown and skipping+ # the retry left the regression alive on the fresh Qwen cache this was+ # written for: fp8 wins, only int8 is published, the load runs fp8 with+ # no prequant and no dense fallback, and drops straight to GGUF.+ dense_possible = False+ dense_decline_reason = (+ "the base transformer this quant is built from was not staged (the "+ "prefetch's capacity gate declined its shards), so the dense bf16 "+ "build cannot run on this host"+ )+ # A dense misfit with a prequant source only forbids the dense fallback; with+ # none, auto could still have picked a DIFFERENT scheme that does have a+ # hosted checkpoint. auto returns one winner, and a winner with no published+ # prequant that also cannot build dense would drop the whole pick to GGUF+ # even though a lower rung would have loaded. Only for auto: an explicit+ # scheme is never swapped (same contract as select_transformer_quant_scheme).+ if not dense_possible and prequant is None:+ retry = self._auto_prequant_retry_scheme(+ target,+ fam,+ transformer_quant,+ scheme,+ base_repo = base,+ path_override = transformer_prequant_path,+ loras = loras,+ )+ # Existence is not fit: an int8 checkpoint can outweigh the Q4 GGUF that+ # planned resident, so a host that fits the GGUF need not fit the rung+ # being retried. Size it and replan, exactly as the offload branch does,+ # or the load moves it onto CUDA after eviction under a GGUF-sized+ # budget and OOMs there.+ retry_candidate = (+ resolve_dense_quant_candidate(+ fam = fam,+ target = target,+ requested = retry,+ base_repo = base,+ prequant_path = transformer_prequant_path,+ force_dense = _has_active_lora(loras),+ logger = logger,+ )+ if retry is not None+ else None+ )+ retry_plan = (+ self._plan_memory(+ target,+ single_file_path,+ base,+ fam,+ memory_mode,+ cpu_offload,+ kind = kind,+ repo_id = repo_id,+ fetch_base = fetch_base,+ transformer_resident_override_mib = (+ retry_candidate.transient_transformer_mib+ ),+ companion_override_mib = retry_candidate.companions_mib,+ )+ if retry_candidate is not None+ else None+ )+ if retry_plan is not None and retry_plan.offload_policy == OFFLOAD_NONE:+ logger.info(+ "diffusion.transformer_quant: %s has no prequant and cannot "+ "build dense; retrying auto at %s, whose checkpoint is cached "+ "and plans resident",+ scheme,+ retry,+ )+ # Pin it: the load below re-selects from this value.+ transformer_quant = retry+ quant_plan = retry_plan+ dense_fallback_allowed = False+ else:+ # No prequant source and no retry rung that fits: the fast path is+ # out, so say which of the two halves failed. The reason reaches the+ # caller as the 409 detail on an explicit pin, and as the "Auto: OFF"+ # badge otherwise, so "no hosted checkpoint" alone would leave a user+ # who has one wondering why it was ignored.+ dense_declined = True+ transformer_quant_decline = (+ f"{dense_decline_reason}, and no hosted pre-quantised "+ "checkpoint is available to build it from"+ if dense_decline_reason+ else "no hosted pre-quantised checkpoint is available and the "+ "dense bf16 transformer cannot be built on this host"+ )if (kind == "gguf"and normalize_transformer_quant(transformer_quant) is not None@@ -2986,7 +3180,9 @@ class DiffusionBackend:),"transformer_quant": (# The RAW request, not the tri-state rewrite: an "Auto: OFF" badge- # and a declined "FP8" must not look the same.+ # and a declined "FP8" must not look the same. Captured before the+ # rewrite, so it is also immune to the auto retries pinning a+ # concrete rung: a pick that fell back to a lower rung is still auto.transformer_quant_requested,transformer_quant_engaged or "off",# A recorded decline wins: it names WHY, where the generic stringsdiff --git a/studio/backend/core/inference/diffusion_auto_policy.py b/studio/backend/core/inference/diffusion_auto_policy.pyindex f7a67c91040..4e7e84b6aa7 100644--- a/studio/backend/core/inference/diffusion_auto_policy.py+++ b/studio/backend/core/inference/diffusion_auto_policy.py@@ -192,18 +192,35 @@ def resolve_dense_quant_candidate(if scheme is None:return Noneprequant_available = False+ prequant_cached = False# force_dense: the loader will SKIP the prequant shortcut (e.g. a LoRA bake), so size the candidate for the dense build.if not force_dense:try:- from .diffusion_prequant import usable_prequant_source+ from .diffusion_prequant import prequant_checkpoint_cached, usable_prequant_source# usable_ (not resolve_): a local path override counts only when the loader will accept it (allowlisted AND present), else it rebuilds dense after eviction.src = usable_prequant_source(fam, scheme, path_override = prequant_path, base_repo = base_repo)prequant_available = src is not None+ if src is not None and getattr(src, "kind", None) == "path":+ # A local override is the operator's own file on disk: it downloads nothing, so the+ # space gate has no claim on it. prequant_checkpoint_cached only answers for hosted+ # repos (_cached_in_root returns None for any other kind), so asking it here would+ # report False and re-apply the gate to a file that costs no bytes, which is the+ # opposite of what the retry assumes about local paths.+ prequant_cached = True+ elif src is not None:+ # Pin the ACTIVE root, as the retry and the loader both do. Unpinned,+ # cached_checkpoint_path searches only huggingface_hub's import-time constant, so+ # after a cache-folder change the retry proves the checkpoint cached in the live+ # root and this would still call it uncached and re-apply the gate. Imported from+ # utils rather than diffusion.hub_cache_dir, which would be a circular import.+ from utils.hf_cache_settings import active_hf_hub_cache+ prequant_cached = prequant_checkpoint_cached(src, cache_dir = active_hf_hub_cache())except Exception: # noqa: BLE001 -- prequant probing must never sink the candidateprequant_available = False+ prequant_cached = Falseestimate = estimate_dense_quant(fam, scheme, base_repo = base_repo, prequant_available = prequant_available)@@ -217,9 +234,12 @@ def resolve_dense_quant_candidate(estimate.companions_mib,prequant_available,)- if estimate is not None:- # The dense path may DOWNLOAD the artifact into the HF cache, which must never wedge a nearly full disk; a cached re-download is a no-op, so- # this only trips on an already-critical disk. Size it by what lands on DISK: a prequant fetches the quantised checkpoint, else the base repo's.+ # A cached prequant checkpoint downloads nothing, so the space gate has no claim on it. The+ # gate used to run anyway, which discarded exactly the candidate the auto retry exists to find:+ # that retry only ever proposes a rung whose checkpoint is already cached, so on a low-disk or+ # moved-cache install every retry fell back to the GGUF despite a resident-fit local artifact.+ if estimate is not None and not (estimate.prequant and prequant_cached):+ # The dense path may DOWNLOAD the artifact into the HF cache, which must never wedge a nearly full disk. Size it by what lands on DISK: a prequant fetches the quantised checkpoint, else the base repo's.needed_mib = (estimate.steady_transformer_mibif estimate.prequantdiff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex a6afe37e809..fb983cc7147 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -206,9 +206,10 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (pipeline_class = "QwenImagePipeline",transformer_class = "QwenImageTransformer2DModel",base_repo = "Qwen/Qwen-Image",- # int8 only: fp8 is family-denied (_FAMILY_SCHEME_DENY) so a repo entry would be dead.+ # int8 only: no fp8 DiT checkpoint is published for this family yet. fp8 is no longer+ # denied for inference, so adding one here would now be live rather than dead.prequant_repos = (("int8", "unsloth/Qwen-Image-FP8"),),- # Pre-cast Qwen2.5-VL-7B (16.6 -> 8.8 GB). The DiT fp8 denial is a transformer-scheme rule; the layerwise TE cast is unaffected.+ # Pre-cast Qwen2.5-VL-7B (16.6 -> 8.8 GB). Always was independent of the DiT scheme rules.te_prequant_repos = (("fp8", "text_encoder", "unsloth/Qwen-Image-FP8"),),cfg_kwarg = "true_cfg_scale",aliases = ("qwen_image", "qwenimage"),diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.pyindex 6ede53b94c0..b8e348d2520 100644--- a/studio/backend/core/inference/diffusion_prequant.py+++ b/studio/backend/core/inference/diffusion_prequant.py@@ -144,6 +144,50 @@ def resolve_prequant_source(return None+_LOCAL_PREQUANT_SCHEME: dict[tuple[str, int, int], Optional[str]] = {}+++def local_prequant_scheme(path: str) -> Optional[str]:+ """The scheme a local pre-quant checkpoint records, or None when it cannot be read.++ ``resolve_prequant_source`` hands back a ``path`` source for ANY override, whatever scheme was+ asked for: the file is never inspected. That is fine when the caller named the scheme, but+ under ``auto`` the ladder picks one and an override baked for a different scheme then reads as+ an available pre-quant. Planning skips staging the dense transformer, the loader reaches the+ same ``metadata.scheme`` check that runs at load time, refuses the file, and with no dense+ fallback the pick silently drops to GGUF.++ Cheap despite the file size: ``mmap`` plus ``map_location = "meta"`` maps the storages instead+ of reading them, so only the pickle structure is parsed (~1s on a 34 GB checkpoint). Cached on+ (path, mtime, size) because the auto ladder asks once per candidate scheme. ``weights_only``+ has to be False for the torchao subclasses, which is what the loader already does, and the+ path is allowlisted before we get here, so this opens nothing new."""+ import os++ try:+ real = os.path.expanduser(path)+ st = os.stat(real)+ # Nanoseconds, not int(st_mtime): an atomic swap for a same-sized artifact inside the same+ # second would otherwise reuse the previous scheme for the life of the process, and int8+ # and fp8 checkpoints of one model are exactly that shape.+ key = (real, st.st_mtime_ns, int(st.st_size))+ except Exception: # noqa: BLE001 -- unreadable is "unknown", handled by the caller+ return None+ if key in _LOCAL_PREQUANT_SCHEME:+ return _LOCAL_PREQUANT_SCHEME[key]+ scheme: Optional[str] = None+ try:+ import torch+ obj = torch.load(real, map_location = "meta", weights_only = False, mmap = True)+ if isinstance(obj, dict) and obj.get("format") == PREQUANT_FORMAT:+ recorded = (obj.get("metadata") or {}).get("scheme")+ scheme = str(recorded) if recorded else None+ except Exception: # noqa: BLE001 -- a checkpoint we cannot parse is "unknown", never a match+ scheme = None+ _LOCAL_PREQUANT_SCHEME[key] = scheme+ return scheme++def usable_prequant_source(fam: Any,scheme: str,@@ -152,13 +196,22 @@ def usable_prequant_source(base_repo: Optional[str] = None,) -> Optional[PrequantSource]:"""``resolve_prequant_source``, but a local path counts only when the loader would- accept it: inside the allowlist AND present on disk. Otherwise resolves to None so- memory planning falls back to dense-fit checks up front, instead of the loader refusing- the path only after the resident pipeline was evicted and dense bf16 materialises under- a plan that never budgeted for it (evict-then-OOM). Hosted-repo sources are unaffected."""+ accept it: inside the allowlist AND present on disk AND baked for THIS scheme. Otherwise+ resolves to None so memory planning falls back to dense-fit checks up front, instead of the+ loader refusing the path only after the resident pipeline was evicted and dense bf16+ materialises under a plan that never budgeted for it (evict-then-OOM). Hosted-repo sources are+ unaffected.++ The scheme check matters most under ``auto``, which picks a scheme the user never named: an+ int8 override must not read as an available fp8 pre-quant just because the file exists. A+ checkpoint whose scheme cannot be read is treated as not usable, matching every other unknown+ here, since the loader would reject it too."""src = resolve_prequant_source(fam, scheme, path_override = path_override, base_repo = base_repo)- if src is not None and src.kind == "path" and not local_prequant_path_ready(src.location):- return None+ if src is not None and src.kind == "path":+ if not local_prequant_path_ready(src.location):+ return None+ if local_prequant_scheme(src.location) != scheme:+ return Nonereturn src@@ -484,6 +537,37 @@ def _load_transformer_config(raise last # type: ignore[misc]+def _fp8_activation_floor_present(state_dict: Any, logger: Any) -> bool:+ """True unless some fp8 tensor was quantised with no activation lower bound.++ Only the first quantised tensor is inspected: the builder applies one config to the whole+ module, so the floor is uniform. A state dict with no fp8 tensor at all is left to the other+ checks (an empty or wrong-scheme artifact is their business, not this one)."""+ from .diffusion_transformer_quant import TQ_FP8++ try:+ items = state_dict.items() if hasattr(state_dict, "items") else ()+ for name, tensor in items:+ kwargs = getattr(tensor, "act_quant_kwargs", None)+ if kwargs is None:+ continue+ if getattr(kwargs, "hp_value_lb", None):+ return True+ _warn(+ logger,+ TQ_FP8,+ ValueError(+ f"fp8 checkpoint has no activation scale floor on {name!r} "+ "(built before activation_value_lb); a zero activation row renders black. "+ "Rebuild it"+ ),+ )+ return False+ except Exception: # noqa: BLE001 -- an unreadable state dict is the other checks' problem+ return True+ return True++def _validate_checkpoint(ckpt: Any,scheme: str,@@ -524,6 +608,15 @@ def _validate_checkpoint(),)return False+ # fp8 also REQUIRES the activation scale floor, and this is checked on the loaded TENSORS, not+ # on metadata. torchao's per-row activation quantiser divides by each row's amax, so a zero row+ # (qwen's text stream emits them) gives scale 0 and NaN qdata unless activation_value_lb floors+ # it. That floor is serialised per tensor as act_quant_kwargs.hp_value_lb, so an artifact built+ # before the fix stays broken however it is loaded, and it predates any metadata field we could+ # stamp -- and "absent is accepted for back-compat", the convention every check above follows,+ # is exactly wrong here. Reading the tensors is fail-closed and needs no format bump.+ if scheme == TQ_FP8 and not _fp8_activation_floor_present(ckpt.get("state_dict"), logger):+ return Falseckpt_base = meta.get("base_model_id")if base:# Keys matching a different base can load strict=True and generate from the wrong weights. Our builder always records base_model_id, so one omitting it against a requested base is untrustworthy.diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.pyindex 2391eccc822..42ffc54a2e3 100644--- a/studio/backend/core/inference/diffusion_transformer_quant.py+++ b/studio/backend/core/inference/diffusion_transformer_quant.py@@ -128,11 +128,29 @@ _AUTO_LADDER: tuple[tuple[tuple[int, int], tuple[str, ...]], ...] = ()# Families whose activation ranges break specific schemes at the MODEL level (the smoke probe only proves the GEMM runs). Measured with the-# 28-pair prequant accuracy gate on B200: qwen-image + fp8 renders every frame black, + mxfp8 does semantic damage at 1024px, + nvfp4 is-# unusable (LPIPS 0.51). int8 dynamic is excellent on Qwen, so auto falls through to it. The deny also applies to an EXPLICIT request.+# 28-pair prequant accuracy gate on B200: qwen-image + mxfp8 does semantic damage at 1024px, + nvfp4 is unusable (LPIPS 0.51). Neither has a+# known fix, so both stay denied and auto falls through to int8 (excellent on Qwen). The deny also applies to an EXPLICIT request.+#+# fp8 was denied here too, for black frames. That cause is gone: it was torchao's fp8 scale chooser having no eps clamp, so qwen's all-zero+# text rows gave scale 0 and NaN, and ``_make_quant_config`` now floors it with ``activation_value_lb``. Re-measured on B200 with the floor,+# and BOTH paths the deny governs clear the 0.10 LPIPS bar, which is why it is safe to drop rather than just the checkpoint half:+# prequant checkpoint, full 28-pair gate -> 28/28 PASS (SSIM 0.87-0.99, LPIPS 0.027-0.228, CLIP delta <= 0.019)+# on-the-fly quantize_, gate's simple_object prompt at its own seeds -> LPIPS 0.048 / 0.033 / 0.027 / 0.063+# against pre-floor plain fp8 at LPIPS 0.712 with SSIM 0.016 and mean luma 0. Keeping the deny cost real speed: it pinned qwen to int8 at+# 1.10x bf16 when compiled fp8 measures 1.21x._FAMILY_SCHEME_DENY: dict[str, frozenset[str]] = {- "qwen-image": frozenset({TQ_FP8, TQ_MXFP8, TQ_NVFP4}),- "qwen-image-edit": frozenset({TQ_FP8, TQ_MXFP8, TQ_NVFP4}), # same DiT+ "qwen-image": frozenset({TQ_MXFP8, TQ_NVFP4}),+ "qwen-image-edit": frozenset({TQ_MXFP8, TQ_NVFP4}), # same DiT+}+++# Schemes denied for TRAINING on top of the inference table. Training holds a stricter bar because+# the evidence above is rendering evidence: it says a frozen fp8 forward reconstructs the bf16 image,+# not that a LoRA converges when its frozen linears are fp8. Nobody has run that, so qwen fp8 stays+# out of the Train UI until someone does. Delete the entry once a training run is measured.+_FAMILY_TRAIN_SCHEME_DENY: dict[str, frozenset[str]] = {+ "qwen-image": frozenset({TQ_FP8}),+ "qwen-image-edit": frozenset({TQ_FP8}),}@@ -140,6 +158,13 @@ def _family_denied(family, scheme: str) -> bool:return scheme in _FAMILY_SCHEME_DENY.get(str(family or "").strip().lower(), ())+def _family_train_denied(family, scheme: str) -> bool:+ """``_family_denied`` plus the training-only additions. Every inference deny also applies to+ training (a scheme that cannot render cannot train), so this is a superset, never a bypass."""+ key = str(family or "").strip().lower()+ return _family_denied(family, scheme) or scheme in _FAMILY_TRAIN_SCHEME_DENY.get(key, ())++def family_denies_scheme(family: Optional[str], scheme: str) -> bool:"""Whether the measured deny list rules ``scheme`` out for ``family``, regardless of hardware.@@ -359,6 +384,30 @@ def select_transformer_quant_scheme(return None+def auto_scheme_candidates(target: Any, family: Optional[str] = None) -> tuple[str, ...]:+ """Every scheme ``auto`` would accept on this device, best first.++ ``select_transformer_quant_scheme`` returns only the winner, which is all the load needs+ until the winner turns out to have no hosted prequant AND not to fit dense. The caller then+ needs to know what auto would have picked NEXT, so it can reach a scheme that does have a+ checkpoint instead of dropping to GGUF. Same ladder, same deny list, same smoke probe as the+ auto branch of the selector, so the two can never disagree about what is allowed."""+ if not dense_transformer_supported(target):+ return ()+ device = str(getattr(target, "device", "cuda"))+ cap = _capability()+ if cap is None:+ return ()+ for floor, schemes in _AUTO_LADDER:+ if cap >= floor:+ return tuple(+ scheme+ for scheme in _prefer_consumer_scheme(schemes, device)+ if not _family_denied(family, scheme) and _scheme_supported(scheme, device)+ )+ return ()++def _prefer_consumer_scheme(schemes: tuple[str, ...], device: Any) -> tuple[str, ...]:"""Reorder an arch tier's schemes for the GPU class. On consumer / workstation cards moveint8 first: they halve fp8/fp16 FP32-accumulate while int8 runs full-rate, so int8 is asdiff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.pyindex 2273da37cfa..bd481ea50a3 100644--- a/studio/backend/core/training/diffusion_train_common.py+++ b/studio/backend/core/training/diffusion_train_common.py@@ -489,7 +489,7 @@ def family_train_infos() -> list[dict[str, Any]]:base repos, the recommended starting hyperparameters, and a VRAM/access note. Built fromthe family registry so it stays in sync with what the trainers actually support."""from core.inference.diffusion_families import detect_family- from core.inference.diffusion_transformer_quant import _family_denied+ from core.inference.diffusion_transformer_quant import _family_train_denieddit_modes, dit_recommended = train_precision_modes()infos: list[dict[str, Any]] = []@@ -501,7 +501,8 @@ def family_train_infos() -> list[dict[str, Any]]:# base_precision applies to the DiT trainer only; SDXL keeps its mixed_precision lever. compile applies everywhere.is_dit = name in _DIT_TRAIN_FAMILIES# On a non-bf16 CUDA GPU the start preflight rejects EVERY DiT family, so advertise no precision, else /info offers an- # nf4 DiT option that always 400s. Otherwise drop any scheme this family's DiT corrupts (fp8 on Qwen-Image).+ # nf4 DiT option that always 400s. Otherwise drop any scheme this family's DiT corrupts, plus any the TRAINING bar+ # holds back even though inference passes (fp8 on Qwen-Image: rendering is validated, a training run is not).dit_block = (bf16_unsupported_reason(name) or dit_accelerator_missing_reason(name)if is_dit@@ -510,7 +511,7 @@ def family_train_infos() -> list[dict[str, Any]]:if not is_dit or dit_block:fam_modes: list[str] = []else:- fam_modes = [m for m in dit_modes if not _family_denied(name, m)]+ fam_modes = [m for m in dit_modes if not _family_train_denied(name, m)]spec = _FAMILY_TRAIN_SPECS.get(name, {})infos.append({@@ -695,15 +696,15 @@ class DiffusionLoraConfig:f"base_precision={base_precision!r} trains in bf16 compute; set "f"mixed_precision to bf16.")- # Some DiT families are corrupted by fp8 activation range: outliers exceed even per-row fp8, so the frozen linears- # learn against a garbage forward. The inference path denies these too; mirror it so the run fails fast. int8 is unaffected.- from core.inference.diffusion_transformer_quant import _family_denied+ # Refuse a scheme this family's DiT is known to corrupt, and also one the training bar holds back while+ # inference allows it: qwen-image fp8 now renders inside the accuracy gate, but no one has measured whether a+ # LoRA converges against fp8-frozen linears, so it fails fast here rather than silently training on faith.+ from core.inference.diffusion_transformer_quant import _family_train_denied- if _family_denied(resolved_family, base_precision):+ if _family_train_denied(resolved_family, base_precision):raise ValueError(- f"base_precision={base_precision!r} is not supported for "- f"{resolved_family}: its activations exceed fp8's range and corrupt the "- f"trained result. Use 'nf4', 'int8', 'bf16', or 'auto'."+ f"base_precision={base_precision!r} is not validated for training "+ f"{resolved_family}. Use 'nf4', 'int8', 'bf16', or 'auto'.")# flow_shift: None resolves to the family default ("auto" only for qwen-image, whose scheduler skips its static shift under use_dynamic_shifting); an explicit value is validated and kept.flow_shift = self.flow_shiftdiff --git a/studio/backend/tests/test_diffusion_auto_policy.py b/studio/backend/tests/test_diffusion_auto_policy.pyindex a6f55785f49..8eb9490adeb 100644--- a/studio/backend/tests/test_diffusion_auto_policy.py+++ b/studio/backend/tests/test_diffusion_auto_policy.py@@ -150,6 +150,88 @@ def test_candidate_disk_gate_skips_when_cache_disk_low(monkeypatch):)+def test_candidate_disk_gate_spares_an_already_cached_prequant(monkeypatch):+ """A cached checkpoint downloads nothing, so the space gate has no claim on it.++ The gate's own comment said a cached re-download is a no-op, but it ran regardless. That+ discarded exactly the candidate the auto retry exists to find: the retry only ever proposes a+ rung whose checkpoint is already cached, so on a low-disk or moved-cache install every retry+ fell back to the GGUF despite a resident-fit local artifact.+ """+ import core.inference.diffusion_auto_policy as ap+ import core.inference.diffusion_prequant as pq++ _patch_selector(monkeypatch, scheme = "int8")+ monkeypatch.setattr(+ pq, "usable_prequant_source", lambda *a, **k: type("S", (), {"kind": "repo"})()+ )+ monkeypatch.setattr(pq, "prequant_checkpoint_cached", lambda *a, **k: True)+ # Far too little space for the checkpoint, which is precisely the case being excused.+ monkeypatch.setattr(ap, "_hf_cache_free_mib", lambda: 1024)+ est = resolve_dense_quant_candidate(fam = _fam("z-image"), target = object(), requested = "auto")+ assert isinstance(est, DenseQuantEstimate)+ assert est.prequant is True++ # Uncached on the same low disk still trips the gate: this excuses a cached artifact, not+ # every prequant.+ monkeypatch.setattr(pq, "prequant_checkpoint_cached", lambda *a, **k: False)+ assert (+ resolve_dense_quant_candidate(fam = _fam("z-image"), target = object(), requested = "auto")+ is None+ )+++def test_a_local_override_is_never_gated_on_disk_space(monkeypatch):+ """A local path override downloads nothing, so the space gate has no claim on it.++ prequant_checkpoint_cached only answers for hosted repos (_cached_in_root returns None for any+ other kind), so probing a path source there reports False and re-applies the gate to a file+ already on disk. The retry treats a local override as costing no bytes; this has to agree, or a+ low-disk host drops the local rung to GGUF.+ """+ import core.inference.diffusion_auto_policy as ap+ import core.inference.diffusion_prequant as pq++ _patch_selector(monkeypatch, scheme = "int8")+ monkeypatch.setattr(+ pq, "usable_prequant_source", lambda *a, **k: type("S", (), {"kind": "path"})()+ )+ # Would say "not cached" for a path source, exactly as the real one does.+ monkeypatch.setattr(pq, "prequant_checkpoint_cached", lambda *a, **k: False)+ monkeypatch.setattr(ap, "_hf_cache_free_mib", lambda: 1024)+ est = resolve_dense_quant_candidate(fam = _fam("z-image"), target = object(), requested = "auto")+ assert isinstance(est, DenseQuantEstimate)+++def test_the_cached_probe_is_pinned_to_the_active_cache_root(monkeypatch):+ """Unpinned, cached_checkpoint_path reads only huggingface_hub's import-time constant.++ Studio's cache folder is a setting, so after it changes the retry proves the checkpoint cached+ in the LIVE root while an unpinned probe here still calls it uncached and re-applies the gate,+ defeating the moved-cache retry this excuse exists for. The retry and the loader both pin the+ active root; so must this.+ """+ import core.inference.diffusion_auto_policy as ap+ import core.inference.diffusion_prequant as pq+ import utils.hf_cache_settings as cache_settings++ seen: list = []++ _patch_selector(monkeypatch, scheme = "int8")+ monkeypatch.setattr(+ pq, "usable_prequant_source", lambda *a, **k: type("S", (), {"kind": "repo"})()+ )+ monkeypatch.setattr(cache_settings, "active_hf_hub_cache", lambda: "/live-root")+ monkeypatch.setattr(+ pq,+ "prequant_checkpoint_cached",+ lambda _src, **kw: (seen.append(kw.get("cache_dir")), True)[1],+ )+ monkeypatch.setattr(ap, "_hf_cache_free_mib", lambda: 1024)+ resolve_dense_quant_candidate(fam = _fam("z-image"), target = object(), requested = "auto")+ assert seen == ["/live-root"], seen++def test_candidate_disk_gate_unprobeable_disk_passes(monkeypatch):# Disk probing must never sink the candidate: unprobeable (None) passes through.import core.inference.diffusion_auto_policy as apdiff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 52c1cf05614..7b3e05a4c9f 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -5883,6 +5883,373 @@ def test_a_superseding_load_fences_queued_generations_too(fake_runtime, tmp_pathassert backend._teardown_waiters == 0+# ── auto retry to a scheme that has a hosted prequant ────────────────────────────+++def test_auto_retries_a_lower_scheme_that_has_a_prequant(monkeypatch):+ # Qwen-Image is the live case. auto picks fp8, but only an int8 DiT checkpoint is published,+ # so usable_prequant_source(fp8) is empty; on a host that rejects the ~40 GB dense transient+ # the pick used to drop to GGUF even though the int8 checkpoint would have loaded. The retry+ # walks the rest of auto's ladder for a rung that HAS one.+ from core.inference.diffusion import DiffusionBackend++ monkeypatch.setattr(+ "core.inference.diffusion_transformer_quant.auto_scheme_candidates",+ lambda target, family = None: ("fp8", "mxfp8", "int8"),+ )+ have = {"int8"}+ monkeypatch.setattr(+ "core.inference.diffusion.usable_prequant_source",+ lambda fam, scheme, path_override = None, base_repo = None: (+ types.SimpleNamespace(kind = "repo", location = f"unsloth/{scheme}")+ if scheme in have+ else None+ ),+ )+ cached = {"int8"}+ monkeypatch.setattr(+ "core.inference.diffusion.prequant_checkpoint_cached",+ lambda source, cache_dir = None: source.location.rsplit("/", 1)[-1] in cached,+ )+ fam = types.SimpleNamespace(name = "qwen-image")+ retry = DiffusionBackend._auto_prequant_retry_scheme(+ object(),+ fam,+ "auto",+ "fp8",+ base_repo = "Qwen/Qwen-Image",+ path_override = None,+ loras = None,+ )+ assert retry == "int8"++ # An UNCACHED hosted repo is not a retry: for a GGUF pick the policy is cached-only, since+ # fetching one means downloading a second multi-GB denoiser for a pick that already has its+ # GGUF. _uncached_prequant_repo enforces that for auto's winner and only ever sees the winner,+ # so without this check the retry would smuggle an uncached repo straight past it.+ cached.clear()+ assert (+ DiffusionBackend._auto_prequant_retry_scheme(+ object(),+ fam,+ "auto",+ "fp8",+ base_repo = "Qwen/Qwen-Image",+ path_override = None,+ loras = None,+ )+ is None+ )+ # A local override is the operator's own file, so it costs no bytes and needs no cache hit.+ monkeypatch.setattr(+ "core.inference.diffusion.usable_prequant_source",+ lambda fam, scheme, path_override = None, base_repo = None: (+ types.SimpleNamespace(kind = "path", location = "/tmp/int8.pt")+ if scheme == "int8"+ else None+ ),+ )+ assert (+ DiffusionBackend._auto_prequant_retry_scheme(+ object(),+ fam,+ "auto",+ "fp8",+ base_repo = "Qwen/Qwen-Image",+ path_override = None,+ loras = None,+ )+ == "int8"+ )++ # An EXPLICIT scheme is never swapped: same contract as select_transformer_quant_scheme.+ assert (+ DiffusionBackend._auto_prequant_retry_scheme(+ object(),+ fam,+ "fp8",+ "fp8",+ base_repo = "Qwen/Qwen-Image",+ path_override = None,+ loras = None,+ )+ is None+ )++ # Nothing below the winner has a checkpoint -> no retry, and the caller declines dense.+ monkeypatch.setattr(+ "core.inference.diffusion.usable_prequant_source",+ lambda fam, scheme, path_override = None, base_repo = None: None,+ )+ assert (+ DiffusionBackend._auto_prequant_retry_scheme(+ object(),+ fam,+ "auto",+ "fp8",+ base_repo = "Qwen/Qwen-Image",+ path_override = None,+ loras = None,+ )+ is None+ )+++def test_the_retry_never_climbs_above_the_scheme_auto_already_chose(monkeypatch):+ # Rungs ABOVE the winner were already rejected by the ladder (denied, or the probe refused+ # them), so offering one back would hand the loader a scheme auto itself would not pick.+ from core.inference.diffusion import DiffusionBackend++ monkeypatch.setattr(+ "core.inference.diffusion_transformer_quant.auto_scheme_candidates",+ lambda target, family = None: ("fp8", "mxfp8", "int8"),+ )+ # fp8 (above the chosen mxfp8) has a prequant; int8 (below) does not.+ monkeypatch.setattr(+ "core.inference.diffusion.usable_prequant_source",+ lambda fam, scheme, path_override = None, base_repo = None: (+ types.SimpleNamespace(kind = "path", location = "/tmp/fp8.pt") if scheme == "fp8" else None+ ),+ )+ assert (+ DiffusionBackend._auto_prequant_retry_scheme(+ object(),+ types.SimpleNamespace(name = "qwen-image"),+ "auto",+ "mxfp8",+ base_repo = "Qwen/Qwen-Image",+ path_override = None,+ loras = None,+ )+ is None+ )+++def test_the_offload_retry_runs_when_the_auto_winner_had_no_candidate_at_all(+ fake_runtime, tmp_path, monkeypatch+):+ # The retry exists for exactly this case: auto's winner yields NO DenseQuantEstimate (the+ # free-disk gate skips its uncached dense download) while a lower rung whose checkpoint is+ # already cached would have loaded resident. The replan helper used to be defined inside the+ # `candidate is not None` block, so reaching the retry from here raised UnboundLocalError+ # under the load lock instead of loading that cached rung.+ import dataclasses++ from core.inference import diffusion as dmod++ backend = DiffusionBackend()+ _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, "_uncached_prequant_repo", lambda *a, **k: None)+ monkeypatch.setattr(+ DiffusionBackend, "_auto_prequant_retry_scheme", staticmethod(lambda *a, **k: "int8")+ )++ resolved = []++ def fake_resolve(**kw):+ resolved.append(kw.get("requested"))+ # The winner has no candidate; the retried rung does.+ if len(resolved) == 1:+ return None+ return types.SimpleNamespace(+ transient_transformer_mib = 12_000, companions_mib = 8_000, prequant = True+ )++ monkeypatch.setattr(dmod, "resolve_dense_quant_candidate", fake_resolve)++ orig_plan = DiffusionBackend._plan_memory++ def spy_plan(+ self,+ *a,+ transformer_resident_override_mib = None,+ **k,+ ):+ real = orig_plan(+ self, *a, transformer_resident_override_mib = transformer_resident_override_mib, **k+ )+ if transformer_resident_override_mib is None:+ # Initial GGUF plan wants offload, which is the branch the retry lives in.+ return dataclasses.replace(real, offload_policy = "model")+ return dataclasses.replace(real, offload_policy = "none")++ monkeypatch.setattr(DiffusionBackend, "_plan_memory", spy_plan)++ attempted = []++ def fake_dense_load(self, *a, **k):+ attempted.append(k.get("allow_dense_fallback"))+ raise RuntimeError("test: stop after reaching the fast path")++ monkeypatch.setattr(DiffusionBackend, "_load_dense_quant_pipeline", fake_dense_load)+ (tmp_path / "m.gguf").write_bytes(b"x")+ backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "m.gguf",+ family_override = "qwen-image",+ transformer_quant = "auto",+ )++ # Both resolves ran, so the retry was actually taken rather than dying on the way in.+ assert len(resolved) == 2+ # A prequant-sized plan never licenses the unbudgeted dense bf16 build as a fallback.+ assert attempted == [False]+++def test_the_resident_retry_runs_when_the_dense_shards_were_never_staged(+ fake_runtime, tmp_path, monkeypatch+):+ # The fresh-Qwen-cache path this PR exists for. The prefetch capacity gate declines the base+ # transformer/ shards, so _dense_transformer_resident_bytes reads 0. Treating that as "no+ # information" and skipping the retry left the load running fp8 with no published prequant and+ # no dense fallback, which drops straight back to GGUF.+ import dataclasses++ from core.inference import diffusion as dmod++ backend = DiffusionBackend()+ _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, "_uncached_prequant_repo", lambda *a, **k: None)+ # The winner has no usable checkpoint, and no shards were staged, so no dense build either.+ monkeypatch.setattr(dmod, "usable_prequant_source", lambda *a, **k: None)+ monkeypatch.setattr(+ DiffusionBackend, "_dense_transformer_resident_bytes", lambda self, *a, **k: 0+ )+ monkeypatch.setattr(+ DiffusionBackend, "_auto_prequant_retry_scheme", staticmethod(lambda *a, **k: "int8")+ )+ monkeypatch.setattr(+ dmod,+ "resolve_dense_quant_candidate",+ lambda **kw: types.SimpleNamespace(+ transient_transformer_mib = 12_000, companions_mib = 8_000, prequant = True+ ),+ )++ orig_plan = DiffusionBackend._plan_memory++ def spy_plan(+ self,+ *a,+ transformer_resident_override_mib = None,+ **k,+ ):+ real = orig_plan(+ self, *a, transformer_resident_override_mib = transformer_resident_override_mib, **k+ )+ # The GGUF plan is RESIDENT here: this is the other branch from the offload retry.+ return dataclasses.replace(real, offload_policy = "none")++ monkeypatch.setattr(DiffusionBackend, "_plan_memory", spy_plan)++ seen = []++ def fake_dense_load(self, *a, **k):+ seen.append(a[7] if len(a) > 7 else k.get("transformer_quant"))+ raise RuntimeError("test: stop after reaching the fast path")++ monkeypatch.setattr(DiffusionBackend, "_load_dense_quant_pipeline", fake_dense_load)+ (tmp_path / "m.gguf").write_bytes(b"x")+ backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "m.gguf",+ family_override = "qwen-image",+ transformer_quant = "auto",+ _transformer_prefetched = False,+ )+ # Retried down to the cached rung rather than attempting the unbuildable winner.+ assert seen == ["int8"]+++def test_the_resident_retry_declines_a_rung_that_does_not_plan_resident(+ fake_runtime, tmp_path, monkeypatch+):+ # Existence is not fit: an int8 checkpoint can outweigh the Q4 GGUF that planned resident, so a+ # host that fits the GGUF need not fit the rung being retried. Without the replan the loader+ # moves it onto CUDA after eviction under a GGUF-sized budget.+ import dataclasses++ from core.inference import diffusion as dmod++ backend = DiffusionBackend()+ _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, "_uncached_prequant_repo", lambda *a, **k: None)+ monkeypatch.setattr(dmod, "usable_prequant_source", lambda *a, **k: None)+ monkeypatch.setattr(+ DiffusionBackend, "_dense_transformer_resident_bytes", lambda self, *a, **k: 0+ )+ monkeypatch.setattr(+ DiffusionBackend, "_auto_prequant_retry_scheme", staticmethod(lambda *a, **k: "int8")+ )+ monkeypatch.setattr(+ dmod,+ "resolve_dense_quant_candidate",+ lambda **kw: types.SimpleNamespace(+ transient_transformer_mib = 900_000, companions_mib = 8_000, prequant = True+ ),+ )++ orig_plan = DiffusionBackend._plan_memory++ def spy_plan(+ self,+ *a,+ transformer_resident_override_mib = None,+ **k,+ ):+ real = orig_plan(+ self, *a, transformer_resident_override_mib = transformer_resident_override_mib, **k+ )+ if transformer_resident_override_mib is None:+ return dataclasses.replace(real, offload_policy = "none")+ # The retried rung does NOT fit.+ return dataclasses.replace(real, offload_policy = "model")++ monkeypatch.setattr(DiffusionBackend, "_plan_memory", spy_plan)++ attempted = []+ monkeypatch.setattr(+ DiffusionBackend,+ "_load_dense_quant_pipeline",+ lambda self, *a, **k: attempted.append(True),+ )+ (tmp_path / "m.gguf").write_bytes(b"x")+ backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "m.gguf",+ family_override = "qwen-image",+ transformer_quant = "auto",+ _transformer_prefetched = False,+ )+ # Declined: neither the winner nor the retried rung is loadable, so the GGUF stands.+ assert attempted == []+++def test_an_auto_pick_that_retried_a_lower_rung_is_still_badged_auto():+ # build_resolved_record calls anything but None/""/"auto" an explicit request, so handing it the+ # pinned retry value would badge a backend decision as the user's own choice.+ from core.inference.diffusion_auto_policy import build_resolved_record++ record = build_resolved_record({"transformer_quant": ("auto", "int8", "retried")})+ assert record["transformer_quant"]["source"] == "auto"+ assert record["transformer_quant"]["value"] == "int8"+ # And the contrast: a user who really typed int8 is not relabelled.+ explicit = build_resolved_record({"transformer_quant": ("int8", "int8", "requested")})+ assert explicit["transformer_quant"]["source"] == "explicit"++def test_download_plan_skips_files_already_in_the_cache(monkeypatch):# Entries are what the Downloads panel lists, so a model fully on disk must plan nothing._fake_hf_api(diff --git a/studio/backend/tests/test_diffusion_prequant.py b/studio/backend/tests/test_diffusion_prequant.pyindex adc069c75ec..71d01ca6da0 100644--- a/studio/backend/tests/test_diffusion_prequant.py+++ b/studio/backend/tests/test_diffusion_prequant.py@@ -155,17 +155,86 @@ def test_usable_source_disallowed_path_is_none(tmp_path, monkeypatch):def test_usable_source_allowed_present_path_wins(tmp_path, monkeypatch):- # Allowlisted AND present: the override is usable and beats the hosted repo, exactly like resolve_prequant_source.+ # Allowlisted, present AND baked for this scheme: the override is usable and beats the hosted repo, exactly like resolve_prequant_source.import osckpt = tmp_path / "model.pt"ckpt.write_bytes(b"x")monkeypatch.setattr(pq, "_allowed_prequant_roots", lambda: [os.path.realpath(str(tmp_path))])+ monkeypatch.setattr(pq, "local_prequant_scheme", lambda _p: "fp8")fam = _fam(prequant_repos = (("fp8", "org/hosted-fp8"),))src = pq.usable_prequant_source(fam, "fp8", path_override = str(ckpt))assert src == PrequantSource(kind = "path", location = str(ckpt), filename = None)+def test_usable_source_rejects_an_override_baked_for_another_scheme(tmp_path, monkeypatch):+ """An int8 checkpoint must not read as an available fp8 pre-quant.++ resolve_prequant_source hands back a path source for ANY override without inspecting the file,+ so under `auto` (which picks a scheme the user never named) planning would skip staging the+ dense transformer, the loader would hit the same metadata.scheme check it runs at load time,+ refuse the file, and with no dense fallback the pick silently drops to GGUF.+ """+ import os++ ckpt = tmp_path / "model.pt"+ ckpt.write_bytes(b"x")+ monkeypatch.setattr(pq, "_allowed_prequant_roots", lambda: [os.path.realpath(str(tmp_path))])+ monkeypatch.setattr(pq, "local_prequant_scheme", lambda _p: "int8")+ fam = _fam(prequant_repos = (("fp8", "org/hosted-fp8"),))+ assert pq.usable_prequant_source(fam, "fp8", path_override = str(ckpt)) is None+ # The same file IS usable for the scheme it was actually baked for.+ src = pq.usable_prequant_source(fam, "int8", path_override = str(ckpt))+ assert src == PrequantSource(kind = "path", location = str(ckpt), filename = None)+++def test_an_unreadable_override_is_not_usable(tmp_path, monkeypatch):+ # A file we cannot parse as a pre-quant checkpoint is "unknown", and the loader would reject it+ # too, so planning must budget dense rather than assume a shortcut it will not get.+ import os++ ckpt = tmp_path / "model.pt"+ ckpt.write_bytes(b"not a checkpoint")+ monkeypatch.setattr(pq, "_allowed_prequant_roots", lambda: [os.path.realpath(str(tmp_path))])+ fam = _fam(prequant_repos = (("fp8", "org/hosted-fp8"),))+ assert pq.local_prequant_scheme(str(ckpt)) is None+ assert pq.usable_prequant_source(fam, "fp8", path_override = str(ckpt)) is None+++def test_the_local_scheme_cache_survives_a_same_second_swap(tmp_path):+ """Two checkpoints of one model differ only in scheme, so an atomic swap is same-size.++ The memo key used int(st_mtime), which truncates to seconds: replacing an int8 override with+ the fp8 bake of the same model inside one second left the key unchanged, so every later probe+ in that process reported the OLD scheme. Under `auto` that is the exact failure the scheme+ check exists to stop, only inverted: planning trusts a scheme the file no longer records.+ """+ import os++ import torch++ ckpt = tmp_path / "model.pt"++ def _write(scheme, pad):+ torch.save(+ {"format": pq.PREQUANT_FORMAT, "metadata": {"scheme": scheme, "pad": "x" * pad}},+ str(ckpt),+ )++ _write("int8", 8)+ stamp = os.stat(str(ckpt)).st_mtime_ns+ size = os.stat(str(ckpt)).st_size+ assert pq.local_prequant_scheme(str(ckpt)) == "int8"++ # Same size, and a timestamp inside the same second as the first write.+ _write("fp8", 9)+ assert os.stat(str(ckpt)).st_size == size, "the two bakes must be same-size for this to bite"+ os.utime(str(ckpt), ns = (stamp + 1, stamp + 1))+ assert int(os.stat(str(ckpt)).st_mtime) == int(stamp / 1e9)++ assert pq.local_prequant_scheme(str(ckpt)) == "fp8"++def test_usable_source_repo_unaffected_by_allowlist(monkeypatch):# Hosted-repo sources are first-party and keep resolving with no allowlist at all.monkeypatch.setattr(pq, "_allowed_prequant_roots", lambda: [])@@ -1295,3 +1364,36 @@ def test_the_config_follows_the_checkpoint_into_the_other_cache_root(monkeypatchassert isinstance(out, _Transformer) # the prequant loaded instead of being droppedassert seen == [None] # read straight through the root that supplied the checkpoint+++# ── fp8 activation scale floor ──────────────────────────────────────────────────+++class _FakeFp8Tensor:+ """Stands in for a torchao Float8Tensor: only act_quant_kwargs.hp_value_lb is read."""++ def __init__(self, hp_value_lb):+ self.act_quant_kwargs = types.SimpleNamespace(hp_value_lb = hp_value_lb)+++def test_an_fp8_checkpoint_without_the_activation_floor_is_rejected():+ # A checkpoint built before activation_value_lb bakes hp_value_lb=None into every quantised+ # tensor, and stays broken however it is loaded: torchao's per-row activation quantiser divides+ # by the row amax, so qwen's all-zero text rows give scale 0 and NaN. The metadata checks around+ # this one all accept an absent field for back-compat, which is exactly wrong here, so the floor+ # is read off the TENSORS instead. Measured: 412 of 512 rows non-finite without it, 0 with it.+ floored = {"blocks.0.attn.to_q.weight": _FakeFp8Tensor(1e-12)}+ unfloored = {"blocks.0.attn.to_q.weight": _FakeFp8Tensor(None)}+ assert pq._fp8_activation_floor_present(floored, None) is True+ assert pq._fp8_activation_floor_present(unfloored, None) is False+ # Zero is not a floor either: it is what an unclamped amax divide produces.+ assert pq._fp8_activation_floor_present({"w": _FakeFp8Tensor(0.0)}, None) is False+++def test_the_floor_check_ignores_dense_and_unreadable_state_dicts():+ # A dense tensor carries no act_quant_kwargs, so it is not evidence of a missing floor; the+ # scheme / granularity checks own that case. Same for a state dict this cannot walk at all:+ # failing closed here would reject every int8 checkpoint too.+ assert pq._fp8_activation_floor_present({"w": object()}, None) is True+ assert pq._fp8_activation_floor_present(None, None) is True+ assert pq._fp8_activation_floor_present({}, None) is Truediff --git a/studio/backend/tests/test_diffusion_transformer_quant.py b/studio/backend/tests/test_diffusion_transformer_quant.pyindex 8db28437c38..c5f8cbbc96f 100644--- a/studio/backend/tests/test_diffusion_transformer_quant.py+++ b/studio/backend/tests/test_diffusion_transformer_quant.py@@ -379,7 +379,8 @@ def test_an_unusable_scheme_names_the_fault_the_user_can_actually_fix(monkeypatc"'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")+ # mxfp8, not fp8: fp8 on qwen-image is no longer denied, so it would take the GPU branch here.+ denied = tq.explain_unusable_scheme("qwen-image", "mxfp8")assert "measured accuracy gate" in denied and "whatever the GPU" in deniedassert "on this GPU" not in denied.replace("whatever the GPU", "")@@ -391,7 +392,7 @@ def test_an_unusable_scheme_names_the_fault_the_user_can_actually_fix(monkeypatcassert "cannot import name 'ScalingType'" in brokenassert "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")+ assert "measured accuracy gate" in tq.explain_unusable_scheme("qwen-image", "mxfp8")def test_torchao_unavailable_reason_is_resolved_once_and_covers_the_stub(monkeypatch):@@ -750,19 +751,27 @@ def test_quantize_transformer_tolerates_failure(monkeypatch):# ── family scheme deny (measured model-level breakage) ────────────────────────-def test_family_deny_auto_skips_fp8_for_qwen(monkeypatch):- # B200 with every scheme available: per-row fp8 renders black frames on the Qwen DiT, so auto skips fp8 / nvfp4 / mxfp8 and falls to int8.+def test_family_deny_auto_skips_mx_and_nvfp4_for_qwen(monkeypatch):+ # B200 with every scheme available: mxfp8 and nvfp4 still damage the Qwen DiT, so auto skips+ # them. fp8 is no longer denied (activation_value_lb fixed the black frames), so auto now+ # takes fp8 first on a data-center part rather than falling all the way to int8._stub_torch(monkeypatch, cc = (10, 0))_allow(monkeypatch, {TQ_FP8, TQ_NVFP4, TQ_MXFP8, TQ_INT8})+ assert select_transformer_quant_scheme(_target(), "auto", family = "qwen-image") == TQ_FP8+ assert select_transformer_quant_scheme(_target(), "auto", family = "qwen-image-edit") == TQ_FP8+ # With fp8 unavailable the deny still bites: mxfp8 / nvfp4 are skipped and int8 is the pick.+ _allow(monkeypatch, {TQ_NVFP4, TQ_MXFP8, TQ_INT8})assert select_transformer_quant_scheme(_target(), "auto", family = "qwen-image") == TQ_INT8- assert select_transformer_quant_scheme(_target(), "auto", family = "qwen-image-edit") == TQ_INT8-def test_family_deny_refuses_explicit_fp8_for_qwen(monkeypatch):- # An explicit fp8 on qwen-image returns None (same contract as an unsupported scheme); int8 stays honored on qwen, and fp8 outside the deny table.+def test_family_deny_refuses_explicit_mxfp8_and_nvfp4_for_qwen(monkeypatch):+ # An explicit denied scheme returns None (same contract as an unsupported scheme). fp8 and int8+ # are both honored on qwen now, and fp8 outside the deny table is unaffected._stub_torch(monkeypatch, cc = (10, 0))- _allow(monkeypatch, {TQ_FP8, TQ_INT8})- assert select_transformer_quant_scheme(_target(), "fp8", family = "qwen-image") is None+ _allow(monkeypatch, {TQ_FP8, TQ_MXFP8, TQ_NVFP4, TQ_INT8})+ assert select_transformer_quant_scheme(_target(), "mxfp8", family = "qwen-image") is None+ assert select_transformer_quant_scheme(_target(), "nvfp4", family = "qwen-image") is None+ assert select_transformer_quant_scheme(_target(), "fp8", family = "qwen-image") == TQ_FP8assert select_transformer_quant_scheme(_target(), "int8", family = "qwen-image") == TQ_INT8assert select_transformer_quant_scheme(_target(), "fp8", family = "z-image") == TQ_FP8@@ -777,6 +786,7 @@ def test_family_deny_no_family_keeps_ladder(monkeypatch):def test_quantize_transformer_threads_family(monkeypatch):# quantize_transformer passes the family down to the selector, so a denied (family, scheme) pair never reaches torchao.+ # mxfp8, not fp8: fp8 on qwen-image is no longer denied, so it would reach torchao and prove nothing._stub_torch(monkeypatch, cc = (10, 0))_allow(monkeypatch, {TQ_FP8, TQ_INT8})pipe = types.SimpleNamespace(transformer = types.SimpleNamespace())@@ -795,7 +805,7 @@ def test_quantize_transformer_threads_family(monkeypatch):tqz.Float8DynamicActivationFloat8WeightConfig = lambda **kw: "fp8-cfg"tqz.PerRow = lambda: "per-row"monkeypatch.setitem(sys.modules, "torchao.quantization", tqz)- assert quantize_transformer(pipe, _target(), mode = "fp8", family = "qwen-image") is None+ assert quantize_transformer(pipe, _target(), mode = "mxfp8", family = "qwen-image") is Noneassert called == {}@@ -829,6 +839,69 @@ def test_the_attention_trim_families_exclude_their_small_m_text_streams():assert exclude_tokens_for_scheme(TQ_INT8, "ltx-2") == _INT8_EXCLUDE_NAME_TOKENS+def test_the_training_deny_is_a_superset_of_the_inference_deny():+ # The two tables are separate because rendering evidence is not training evidence, but the+ # relationship must only ever go one way: anything inference refuses, training refuses too.+ # A regression making training MORE permissive than inference would let a scheme that cannot+ # even render reach a trainer, which is the one direction this split must not allow.+ from core.inference.diffusion_transformer_quant import (+ _FAMILY_SCHEME_DENY,+ TQ_SCHEMES,+ _family_denied,+ _family_train_denied,+ )++ families = set(_FAMILY_SCHEME_DENY) | {"qwen-image", "qwen-image-edit", "z-image", "sdxl", ""}+ for fam in families:+ for scheme in TQ_SCHEMES:+ if _family_denied(fam, scheme):+ assert _family_train_denied(fam, scheme), (fam, scheme)++ # And the specific split this change introduces: qwen-image fp8 renders (gate 28/28) but is not+ # cleared for training, so inference allows it and training does not.+ for fam in ("qwen-image", "qwen-image-edit"):+ assert not _family_denied(fam, TQ_FP8)+ assert _family_train_denied(fam, TQ_FP8)+ # int8 was never denied on either side and must stay available.+ assert not _family_train_denied(fam, TQ_INT8)+++def test_auto_scheme_candidates_lists_the_whole_ladder_not_just_the_winner(monkeypatch):+ # select_transformer_quant_scheme returns one winner. When that winner has no hosted prequant+ # AND cannot fit dense, the loader needs to know what auto would have picked NEXT, or the pick+ # drops to GGUF even though a lower rung would have loaded. Same ladder, deny list and probe.+ from core.inference.diffusion_transformer_quant import auto_scheme_candidates++ _stub_torch(monkeypatch, cc = (10, 0))+ _allow(monkeypatch, {TQ_FP8, TQ_MXFP8, TQ_INT8})+ assert auto_scheme_candidates(_target()) == (TQ_FP8, TQ_MXFP8, TQ_INT8)+ # The deny list still applies: qwen-image keeps mxfp8 out, so fp8 then int8.+ assert auto_scheme_candidates(_target(), "qwen-image") == (TQ_FP8, TQ_INT8)+ # Whatever the probe refuses is absent, so the list can never offer an unusable scheme.+ _allow(monkeypatch, {TQ_INT8})+ assert auto_scheme_candidates(_target(), "qwen-image") == (TQ_INT8,)+ # A target the dense path cannot use has no candidates at all.+ assert auto_scheme_candidates(_target(device = "cpu")) == ()+++def test_the_candidate_list_agrees_with_the_selector_on_the_winner(monkeypatch):+ # The two must never disagree about what auto is allowed to pick, so the selector's answer is+ # always the head of the candidate list. A drift here would let the retry path propose a scheme+ # auto itself would refuse.+ from core.inference.diffusion_transformer_quant import auto_scheme_candidates+ for cc, allowed, family in (+ ((10, 0), {TQ_FP8, TQ_MXFP8, TQ_INT8}, None),+ ((10, 0), {TQ_FP8, TQ_MXFP8, TQ_INT8}, "qwen-image"),+ ((8, 9), {TQ_FP8, TQ_INT8}, "qwen-image-edit"),+ ((8, 0), {TQ_INT8}, None),+ ):+ _stub_torch(monkeypatch, cc = cc)+ _allow(monkeypatch, allowed)+ chosen = select_transformer_quant_scheme(_target(), "auto", family = family)+ candidates = auto_scheme_candidates(_target(), family)+ assert (candidates[0] if candidates else None) == chosen, (cc, family)++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.