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
Studio: load INT8 instead of NVFP4 on pre-Blackwell GPUs (#17229)
Daniel Han192e492e0c74
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 5721bb93cce..415536b41e0 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -515,6 +515,7 @@ from .diffusion_auto_policy import (resolve_dense_quant_candidate,)from .diffusion_nvfp4_flag import nvfp4_diffusion_enabled+from .diffusion_nvfp4_route import with_route_scopefrom .diffusion_nvfp4_install import nvfp4_backend_fields as _nvfp4_backend_fieldsfrom .diffusion_transformer_quant import (TQ_AUTO,@@ -5517,11 +5518,44 @@ class DiffusionBackend:vae_file: Optional[str] = None,allow_oversized_load: bool = False,_load_token: Optional[int] = None,+ nvfp4_route: Any = None,) -> dict[str, Any]:"""Validate, then run the (slow) load on a daemon thread. Returns at once."""with self._load_cancel_lock:entry_token = _load_tokenself._raise_if_load_cancelled(entry_token)+ from .diffusion_nvfp4_route import ROUTE_UNCHANGED, plan_nvfp4_route++ if nvfp4_route is ROUTE_UNCHANGED:+ nvfp4_route = None+ elif nvfp4_route is None:+ nvfp4_route = plan_nvfp4_route(+ media = "image",+ model_path = repo_id,+ gguf_filename = gguf_filename,+ model_kind = model_kind,+ base_repo = base_repo,+ family_override = family_override,+ transformer_quant = transformer_quant,+ text_encoder_quant = text_encoder_quant,+ transformer_prequant_path = transformer_prequant_path,+ gpu_ordinal = gpu_ordinal,+ gpu_ids = gpu_ids,+ component_files = bool(text_encoder_files or vae_file),+ )+ if nvfp4_route is not None:+ updates = nvfp4_route.updates+ repo_id = updates.get("model_path", repo_id)+ display_repo_id = updates.get("display_repo_id", display_repo_id)+ gguf_filename = updates.get("gguf_filename", gguf_filename)+ model_kind = updates.get("model_kind", model_kind)+ base_repo = updates.get("base_repo", base_repo)+ family_override = updates.get("family_override", family_override)+ transformer_quant = updates.get("transformer_quant", transformer_quant)+ text_encoder_quant = updates.get("text_encoder_quant", text_encoder_quant)+ transformer_prequant_path = updates.get(+ "transformer_prequant_path", transformer_prequant_path+ )# The probes this load adds read the Hub directly; they keep a managed account's False (anonymous) sentinel.hub_token = normalize_token(hf_token)hf_token = (hf_token.strip() if isinstance(hf_token, str) else hf_token) or None@@ -5634,11 +5668,14 @@ class DiffusionBackend:_cancel_event = cancel_event,_gpu_ordinals = gpu_ordinals,_hub_token = hub_token,+ _nvfp4_route = nvfp4_route,),daemon = True,).start()return self.status()+ # Outermost, so the resolved record reports the NVFP4 ask it replaced.+ @with_route_scope@scoped_allow_oversized_load# The multi-GPU selection (begin_load's ``_gpu_ordinals``) is visible to this load's planner and placement only.@with_load_selectiondiff --git a/studio/backend/core/inference/diffusion_auto_policy.py b/studio/backend/core/inference/diffusion_auto_policy.pyindex 0c505f80e12..10b0c520222 100644--- a/studio/backend/core/inference/diffusion_auto_policy.py+++ b/studio/backend/core/inference/diffusion_auto_policy.py@@ -498,7 +498,9 @@ def build_resolved_record(controls: dict[str, tuple]) -> dict[str, dict[str, Any"status": status,"reason": reason,}- return record+ from .diffusion_nvfp4_route import annotate_resolved++ return annotate_resolved(record)def format_resolved_for_log(record: Optional[dict[str, dict[str, Any]]]) -> str:diff --git a/studio/backend/core/inference/diffusion_nvfp4_route.py b/studio/backend/core/inference/diffusion_nvfp4_route.pynew file mode 100644index 00000000000..5a3e2a1ddd3--- /dev/null+++ b/studio/backend/core/inference/diffusion_nvfp4_route.py@@ -0,0 +1,718 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Routes an explicit NVFP4 image / video pick to INT8 (or Auto off NVIDIA) on pre-Blackwell GPUs.++Below sm_100 NVFP4 is weight-only, measured slower than INT8 and less accurate than INT8 ConvRot. Every entry point+(load and download-plan routes, backends' ``begin_load``) asks this one decision. ``UNSLOTH_NVFP4_PRE_BLACKWELL_INT8=0``+turns it off.+"""++from __future__ import annotations++import contextvars+import functools+import logging+import os+import re+import threading+from dataclasses import dataclass, field+from typing import Any, Callable, Iterable, Mapping, Optional++from .diffusion_nvfp4_flag import is_nvfp4++logger = logging.getLogger(__name__)++ROUTE_ENV = "UNSLOTH_NVFP4_PRE_BLACKWELL_INT8"+_FALSY = frozenset({"0", "false", "no", "off"})++BLACKWELL_MAJOR = 10+TURING_CAPABILITY = (7, 5)+BF16_INT8_CAPABILITY = (8, 0)++NVIDIA, ROCM, XPU, MPS, CPU, UNKNOWN = "nvidia", "rocm", "xpu", "mps", "cpu", "unknown"++INT8 = "int8"+AUTO = "auto"++REASON_INT8 = "NVFP4 needs a Blackwell GPU; using INT8"+REASON_AUTO = "NVFP4 needs a Blackwell GPU; using Auto"++TRANSFORMER_QUANT = "transformer_quant"+TEXT_ENCODER_QUANT = "text_encoder_quant"++_PICKLE_SUFFIXES = (".pt", ".pth", ".bin", ".ckpt")+++def route_enabled() -> bool:+ raw = os.environ.get(ROUTE_ENV)+ return raw is None or raw.strip().lower() not in _FALSY+++@dataclass(frozen = True)+class DeviceProfile:+ kind: str+ capabilities: tuple = ()+++_PROFILE: list = []+_PROFILE_LOCK = threading.Lock()+++def _smi_visible_capabilities(torch: Any) -> tuple:+ """nvidia-smi capabilities without a CUDA context (training may run beside us); () unless all cards match,+ since nvidia-smi rows are not torch ordinals."""+ try:+ if torch.cuda.is_initialized():+ return ()+ from utils.hardware import nvidia+ from utils.hardware.hardware import get_parent_visible_gpu_ids++ by_row = nvidia.get_compute_capabilities()+ visible = get_parent_visible_gpu_ids()+ if not by_row or not visible or any(i not in by_row for i in visible):+ return ()+ caps = tuple(sorted(by_row[i] for i in visible))+ except Exception: # noqa: BLE001 -- no reading: torch answers instead+ return ()+ if len(set(caps)) != 1:+ return ()+ return caps+++class _CudaInitRefused(RuntimeError):+ """Only torch could read the cards and the caller forbids a CUDA context."""+++def _probe_device_profile(allow_cuda_init: Any = True) -> DeviceProfile:+ """Raises when unreadable, so a transient failure is never cached."""+ try:+ import torch+ except Exception: # noqa: BLE001 -- no torch is a CPU host for this purpose+ return DeviceProfile(CPU)+ from .rocm_bf16 import is_rocm_torch++ # Not torch.version.hip (unset on AMD SDK wheels); ROCm gfx caps (RDNA 3 = 11.x) must never read as Blackwell.+ rocm = is_rocm_torch(torch)+ if not rocm:+ caps = _smi_visible_capabilities(torch)+ if caps:+ return DeviceProfile(NVIDIA, caps)+ if torch.cuda.is_available():+ if not torch.cuda.is_initialized():+ allowed = allow_cuda_init() if callable(allow_cuda_init) else allow_cuda_init+ if not allowed:+ raise _CudaInitRefused()+ caps = tuple(+ tuple(int(v) for v in torch.cuda.get_device_capability(index))+ for index in range(torch.cuda.device_count())+ )+ return DeviceProfile(ROCM if rocm else NVIDIA, caps)+ xpu = getattr(torch, "xpu", None)+ if xpu is not None and xpu.is_available():+ return DeviceProfile(XPU)+ mps = getattr(getattr(torch, "backends", None), "mps", None)+ if mps is not None and mps.is_available():+ return DeviceProfile(MPS)+ return DeviceProfile(CPU)+++def device_profile(*, allow_cuda_init: Any = True) -> DeviceProfile:+ """Cached per process; ``unknown`` when unreadable or only torch could answer and ``allow_cuda_init`` is False."""+ if _PROFILE:+ return _PROFILE[0]+ with _PROFILE_LOCK:+ if _PROFILE:+ return _PROFILE[0]+ try:+ profile = _probe_device_profile(allow_cuda_init)+ except _CudaInitRefused:+ logger.info(+ "diffusion.nvfp4_route: training is active and only CUDA could read the cards; left as is"+ )+ return DeviceProfile(UNKNOWN)+ except Exception as exc: # noqa: BLE001 -- not cached: the next request asks again+ logger.info(+ "diffusion.nvfp4_route: device unreadable (%s), request left as is",+ type(exc).__name__,+ )+ return DeviceProfile(UNKNOWN)+ _PROFILE.append(profile)+ return profile+++def reset_device_profile() -> None:+ with _PROFILE_LOCK:+ _PROFILE.clear()+++def _selected_ordinals(+ gpu_ordinal: Optional[int], gpu_ids: Optional[Iterable[int]]+) -> Optional[list]:+ selected: list = []+ if gpu_ordinal is not None:+ try:+ selected.append(int(gpu_ordinal))+ except (TypeError, ValueError):+ pass+ ids = list(gpu_ids or ())+ if ids:+ try:+ from .diffusion_device import resolve_selected_cuda_ordinals+ selected.extend(int(i) for i in resolve_selected_cuda_ordinals(ids))+ except Exception: # noqa: BLE001 -- a bad pick is the route's own 400 later+ pass+ return sorted(set(selected)) or None+++def load_capability(+ profile: DeviceProfile,+ gpu_ordinal: Optional[int] = None,+ gpu_ids: Optional[Iterable[int]] = None,+) -> tuple[Optional[tuple], bool]:+ """``(lowest relevant capability, routes)``; unpinned, a mixed box routes only if every card is pre-Blackwell."""+ caps = [tuple(c) for c in profile.capabilities if c]+ if not caps:+ return None, False+ if len(set(caps)) > 1:+ selected = _selected_ordinals(gpu_ordinal, gpu_ids)+ picked = [caps[i] for i in selected or () if 0 <= i < len(caps)]+ if picked:+ low = min(picked)+ return low, low[0] < BLACKWELL_MAJOR+ low = min(caps)+ return low, max(caps)[0] < BLACKWELL_MAJOR+++@dataclass(frozen = True)+class Nvfp4Route:+ updates: Mapping[str, Any]+ requested: Mapping[str, Any]+ reasons: Mapping[str, str]+ device: str+ capability: Optional[tuple] = None+ replaced: Optional[str] = None+ kept: tuple = field(default_factory = tuple)++ @property+ def reason(self) -> str:+ return self.reasons.get(TRANSFORMER_QUANT) or next(iter(self.reasons.values()), "")+++# Passed to ``begin_load`` so the backend does not re-decide on a card the route never saw.+ROUTE_UNCHANGED = Nvfp4Route(updates = {}, requested = {}, reasons = {}, device = UNKNOWN)+++def _name_says_nvfp4(name: Optional[str]) -> bool:+ stem = os.path.basename(str(name or "").replace("\\", "/").rstrip("/")).lower()+ stem = re.sub(r"\.(safetensors|pt|pth|bin|ckpt)$", "", stem)+ return "nvfp4" in re.split(r"[-_.\s]+", stem)+++def _looks_local(path: str) -> bool:+ return (+ os.path.isabs(path)+ or path.startswith(("~", ".", "\\"))+ or os.path.exists(os.path.expanduser(path))+ )+++def checkpoint_is_nvfp4(model_path: Optional[str], filename: Optional[str] = None) -> bool:+ """Local safetensors header wins over the name; pickles are never opened, nothing is downloaded. Never raises."""+ try:+ raw = str(model_path or "").strip()+ if not raw:+ return False+ path = (+ os.path.join(os.path.expanduser(raw), filename) if filename else os.path.expanduser(raw)+ )+ if os.path.isfile(path):+ if path.lower().endswith(".gguf"):+ return False+ if not path.lower().endswith(_PICKLE_SUFFIXES):+ from .diffusion_prequant import local_prequant_scheme+ scheme = local_prequant_scheme(path)+ if scheme is not None:+ return is_nvfp4(scheme)+ return _name_says_nvfp4(path)+ if _looks_local(raw):+ return bool(+ not filename and os.path.isdir(os.path.expanduser(raw)) and _dir_declares_nvfp4(raw)+ )+ if filename:+ if str(filename).lower().endswith(".gguf"):+ return False+ return _name_says_nvfp4(filename)+ from .diffusion_prequant import declares_nvfp4_checkpoint++ return bool(declares_nvfp4_checkpoint(raw))+ except Exception: # noqa: BLE001 -- unreadable is "not known to be NVFP4"+ return False+++def _normalized_pick(model_path: Optional[str], filename: Optional[str]) -> tuple:+ if filename or not model_path:+ return model_path, filename+ try:+ from .diffusion import split_local_checkpoint_path+ from .diffusion_local_files import resolve_local_single_file++ split = split_local_checkpoint_path(str(model_path))+ if split is not None:+ return split+ sole = resolve_local_single_file(str(model_path))+ if sole:+ return model_path, sole+ except Exception: # noqa: BLE001 -- unreadable: decided on the pick as given+ pass+ return model_path, filename+++def _dir_declares_nvfp4(path: str) -> bool:+ from .diffusion_prequant import declares_nvfp4_checkpoint+ return bool(declares_nvfp4_checkpoint(path))+++def _switch_refuses_checkpoint(model_path: Optional[str], base_repo: Optional[str]) -> bool:+ try:+ from .diffusion_prequant import declares_nvfp4_checkpoint+ return any(declares_nvfp4_checkpoint(p) for p in (model_path, base_repo) if p)+ except Exception: # noqa: BLE001+ return False+++def _families(media: str) -> tuple:+ try:+ if media == "video":+ from .video_families import _FAMILIES+ else:+ from .diffusion_families import _FAMILIES+ return tuple(_FAMILIES or ())+ except Exception: # noqa: BLE001+ return ()+++def _known_bases(fam: Any) -> dict:+ known: dict = {}+ for base in (+ getattr(fam, "base_repo", None),+ getattr(fam, "deploy_base_repo", None),+ *(getattr(fam, "train_base_repos", ()) or ()),+ *(getattr(fam, "named_variant_bases", ()) or ()),+ ):+ if isinstance(base, str) and base.strip():+ known.setdefault(base.strip().lower(), base.strip())+ return known+++def _all_bases(fam: Any) -> set:+ bases = set(_known_bases(fam))+ for row in getattr(fam, "prequant_variant_repos", ()) or ():+ if isinstance(row, tuple) and row and isinstance(row[0], str):+ bases.add(row[0].strip().lower())+ for base in getattr(fam, "prequant_excluded_bases", ()) or ():+ if isinstance(base, str):+ bases.add(base.strip().lower())+ return {b for b in bases if b}+++def hosted_nvfp4_repo_base(+ model_path: Optional[str],+ media: str,+ *,+ filename: Optional[str] = None,+ family_override: Optional[str] = None,+) -> Optional[tuple]:+ """``(family, canonical base)`` of a hosted NVFP4 repo; None if ambiguous across families or base spelling unknown."""+ key = str(model_path or "").strip().strip("/").lower()+ if not key or "/" not in key:+ return None+ hits: list = []+ for fam in _families(media):+ known = _known_bases(fam)+ for row in getattr(fam, "prequant_variant_repos", ()) or ():+ if isinstance(row, tuple) and len(row) == 3 and is_nvfp4(row[1]):+ if str(row[2]).strip().lower() == key:+ hits.append((fam, known.get(str(row[0]).strip().lower())))+ for row in getattr(fam, "prequant_repos", ()) or ():+ if isinstance(row, tuple) and len(row) == 2 and is_nvfp4(row[0]):+ if str(row[1]).strip().lower() == key:+ hits.append((fam, getattr(fam, "base_repo", None)))+ if family_override:+ wanted = str(family_override).strip().lower()+ hits = [h for h in hits if str(getattr(h[0], "name", "")).lower() == wanted]+ if len(hits) > 1 and filename:+ name = os.path.basename(str(filename)).lower()+ hits = [+ h+ for h in hits+ if any(+ isinstance(r, tuple) and r and is_nvfp4(r[0]) and str(r[-1]).lower() == name+ for r in getattr(h[0], "prequant_filenames", ()) or ()+ )+ ]+ if len(hits) != 1 or not hits[0][1]:+ return None+ return hits[0]+++def _detect_family(+ media: str,+ model_path: str,+ filename: Optional[str],+ override: Optional[str],+ model_kind: Optional[str] = None,+) -> Any:+ try:+ if media == "video":+ from .video import _detect_load_family+ return _detect_load_family(model_path, filename, override, None, model_kind)+ from .diffusion_families import detect_family_for_pick+ return detect_family_for_pick(model_path, filename, override)+ except Exception: # noqa: BLE001 -- an unresolvable family keeps today's behaviour+ return None+++def _fold(text: Optional[str]) -> str:+ return "".join(c for c in str(text or "").lower() if c.isalnum())+++def _stem(repo: str) -> str:+ return _fold(re.sub(r"-diffusers$", "", repo.rsplit("/", 1)[-1], flags = re.IGNORECASE))+++def _named_base(fam: Any, names: list) -> Optional[str]:+ """Longest matching base wins (Qwen-Image-2512 never reads as Qwen-Image); canonical spelling only."""+ known = _known_bases(fam)+ stems = [(b, _stem(b)) for b in _all_bases(fam)]+ for name in reversed(names):+ folded = _fold(os.path.basename(str(name).replace("\\", "/").rstrip("/")) or name)+ hits = [(len(stem), b) for b, stem in stems if stem and stem in folded]+ if hits:+ return known.get(max(hits)[1])+ return None+++def _family_int8_base(+ media: str,+ fam: Any,+ base_repo: Optional[str],+ model_path: Optional[str] = None,+ filename: Optional[str] = None,+) -> Optional[str]:+ """None unless the pick provably names it: a different size, version or distill must never load in its place."""+ names = [n for n in (model_path, filename) if n]+ if media == "video":+ return _video_int8_base(fam, base_repo, names)+ explicit = str(base_repo or "").strip()+ if explicit:+ return explicit+ return _named_base(fam, names)+++def _name_tokens(names: Iterable[str]) -> set:+ return {+ t for n in names for t in re.split(r"[^a-z0-9.]+", os.path.basename(str(n)).lower()) if t+ }+++def _video_int8_base(fam: Any, base_repo: Optional[str], names: list) -> Optional[str]:+ """LTX-2.5 pack is distilled-only; ``ltx-2`` spans 2.0-2.3 on a 2.0 pipeline, so never replaced."""+ name = str(getattr(fam, "name", "") or "")+ pack = str(getattr(fam, "base_repo", "") or "").strip()+ if not pack:+ return None+ if name == "ltx-2.5":+ return pack if "distilled" in _name_tokens(names) else None+ if name == "ltx-2":+ return None+ named = _named_base(fam, names)+ if named is None or named.lower() != pack.lower():+ return None+ return str(base_repo or "").strip() or pack+++def _int8_denied(fam_name: Optional[str], base_repo: Optional[str]) -> bool:+ try:+ from .diffusion_transformer_quant import TQ_INT8, _family_denied+ return bool(_family_denied(fam_name, TQ_INT8, base_repo))+ except Exception: # noqa: BLE001+ return False+++def _turing_int8_enabled() -> bool:+ try:+ from .diffusion_transformer_quant import fp16_card_int8_enabled+ return bool(fp16_card_int8_enabled())+ except Exception: # noqa: BLE001+ return False+++def _dit_target(media: str, capability: Optional[tuple]) -> str:+ """Video INT8 needs bf16 (sm_80+); image INT8 also runs on Turing via the fp16 int8 linear."""+ if capability is None:+ return AUTO+ if capability >= BF16_INT8_CAPABILITY:+ return INT8+ if media != "video" and capability >= TURING_CAPABILITY and _turing_int8_enabled():+ return INT8+ return AUTO+++def _is_auto(value: Optional[str]) -> bool:+ return value is None or str(value).strip().lower() in ("", AUTO)+++def plan_nvfp4_route(+ *,+ media: str = "image",+ model_path: Optional[str] = None,+ gguf_filename: Optional[str] = None,+ model_kind: Optional[str] = None,+ base_repo: Optional[str] = None,+ family_override: Optional[str] = None,+ transformer_quant: Optional[str] = None,+ text_encoder_quant: Optional[str] = None,+ transformer_prequant_path: Optional[str] = None,+ gpu_ordinal: Optional[int] = None,+ gpu_ids: Optional[Iterable[int]] = None,+ component_files: bool = False,+ replace_checkpoint: bool = True,+ allow_cuda_init: Any = True,+ profile: Optional[DeviceProfile] = None,+ log: bool = True,+) -> Optional[Nvfp4Route]:+ """None when left as is. ``component_files`` / ``replace_checkpoint=False`` keep the checkpoint, rerouting precision only."""+ if not route_enabled():+ return None+ from .diffusion_nvfp4_flag import nvfp4_diffusion_enabled++ # NVFP4 disabled: its 400 stands on every GPU; this route never turns it into a load.+ enabled = nvfp4_diffusion_enabled()+ dit_pick = enabled and is_nvfp4(transformer_quant)+ te_pick = enabled and is_nvfp4(text_encoder_quant)+ model_path, gguf_filename = _normalized_pick(model_path, gguf_filename)+ # Picks first: an ordinary request never reads the device.+ prequant_pick = (+ enabled+ and bool(transformer_prequant_path)+ and checkpoint_is_nvfp4(transformer_prequant_path)+ )+ ckpt_pick = bool(model_path) and checkpoint_is_nvfp4(model_path, gguf_filename)+ if ckpt_pick and not enabled and _switch_refuses_checkpoint(model_path, base_repo):+ ckpt_pick = False+ if not (dit_pick or te_pick or prequant_pick or ckpt_pick):+ return None+ profile = profile or device_profile(allow_cuda_init = allow_cuda_init)+ capability = None+ if profile.kind == NVIDIA:+ capability, routes = load_capability(profile, gpu_ordinal, gpu_ids)+ if not routes:+ return None+ dit_target = _dit_target(media, capability)+ te_target = INT8 if capability is not None and capability >= BF16_INT8_CAPABILITY else AUTO+ elif profile.kind in (ROCM, XPU, MPS, CPU):+ dit_target = te_target = AUTO+ else:+ return None+ where = f"{profile.kind}" + (f" sm_{capability[0]}{capability[1]}" if capability else "")++ updates: dict = {}+ requested: dict = {}+ reasons: dict = {}+ replaced = None+ kept: list = []++ def _dit(fam_name: Optional[str], base: Optional[str]) -> str:+ if dit_target == INT8 and _int8_denied(fam_name, base):+ return AUTO+ return dit_target++ if ckpt_pick:+ name = gguf_filename or model_path+ fam = base = None+ why = None+ if component_files:+ why = "it names its own text-encoder / VAE files, which the family pipeline would drop"+ elif not replace_checkpoint:+ why = "this load was not picked by hand"+ else:+ hosted = hosted_nvfp4_repo_base(+ model_path, media, filename = gguf_filename, family_override = family_override+ )+ if hosted is not None:+ fam, base = hosted+ else:+ fam = _detect_family(+ media, str(model_path), gguf_filename, family_override, model_kind+ )+ base = (+ _family_int8_base(media, fam, base_repo, str(model_path), gguf_filename)+ if fam+ else None+ )+ if fam is None or not base:+ why = (+ "Studio cannot tell which model it is, so there is no INT8 build of it to load"+ )+ if why is None:+ target = _dit(getattr(fam, "name", None), base)+ replaced = f"nvfp4:{name}"+ updates.update(+ model_path = base,+ gguf_filename = None,+ model_kind = "pipeline",+ base_repo = None,+ display_repo_id = None,+ )+ if not family_override:+ updates["family_override"] = getattr(fam, "name", None)+ word = "INT8" if target == INT8 else "Auto"+ if dit_pick or _is_auto(transformer_quant):+ requested[TRANSFORMER_QUANT] = transformer_quant if dit_pick else "nvfp4"+ updates[TRANSFORMER_QUANT] = target+ reasons[TRANSFORMER_QUANT] = (+ f"{REASON_INT8 if target == INT8 else REASON_AUTO} from {base} instead of {name}"+ )+ else:+ reasons[TRANSFORMER_QUANT] = (+ f"NVFP4 needs a Blackwell GPU; loading {base} instead of {name}"+ )+ word = str(transformer_quant)+ if log:+ logger.info("diffusion.nvfp4_route: %s -> %s (%s) on %s", name, base, word, where)+ else:+ kept.append(name)+ dit_pick = prequant_pick = False+ if log:+ logger.info("diffusion.nvfp4_route: kept %s as picked on %s: %s", name, where, why)+ fam_name = updates.get("family_override") or family_override+ if fam_name is None and (dit_pick or prequant_pick) and model_path:+ fam_name = getattr(+ _detect_family(media, str(model_path), gguf_filename, None, model_kind), "name", None+ )+ if dit_pick and TRANSFORMER_QUANT not in updates:+ target = _dit(fam_name, base_repo)+ requested[TRANSFORMER_QUANT] = transformer_quant+ updates[TRANSFORMER_QUANT] = target+ reasons[TRANSFORMER_QUANT] = REASON_INT8 if target == INT8 else REASON_AUTO+ if prequant_pick:+ # An NVFP4 artifact is never handed to the INT8 path.+ updates["transformer_prequant_path"] = None+ if TRANSFORMER_QUANT not in updates and _is_auto(transformer_quant):+ target = _dit(fam_name, base_repo)+ requested[TRANSFORMER_QUANT] = "nvfp4"+ updates[TRANSFORMER_QUANT] = target+ reasons[TRANSFORMER_QUANT] = REASON_INT8 if target == INT8 else REASON_AUTO+ elif TRANSFORMER_QUANT not in reasons:+ reasons[TRANSFORMER_QUANT] = (+ "NVFP4 needs a Blackwell GPU; the NVFP4 prequant file is not used"+ )+ if te_pick:+ requested[TEXT_ENCODER_QUANT] = text_encoder_quant+ updates[TEXT_ENCODER_QUANT] = te_target+ reasons[TEXT_ENCODER_QUANT] = REASON_INT8 if te_target == INT8 else REASON_AUTO+ if not updates:+ return None+ route = Nvfp4Route(+ updates = updates,+ requested = requested,+ reasons = reasons,+ device = profile.kind,+ capability = capability,+ replaced = replaced,+ kept = tuple(kept),+ )+ if log and requested:+ logger.info(+ "diffusion.nvfp4_route: %s on %s: %s",+ ", ".join(f"{k}={v!r}->{updates.get(k)!r}" for k, v in requested.items()),+ where,+ route.reason,+ )+ return route+++def _has_component_files(request: Any) -> bool:+ for name in ("text_encoder_file", "text_encoder_files", "vae_file"):+ value = getattr(request, name, None)+ if value:+ return True+ return False+++def route_load_request(+ request: Any,+ *,+ media: str = "image",+ gpu_ordinal: Optional[int] = None,+ replace_checkpoint: bool = True,+ allow_cuda_init: Any = True,+) -> tuple:+ route = plan_nvfp4_route(+ media = media,+ model_path = getattr(request, "model_path", None),+ gguf_filename = getattr(request, "gguf_filename", None),+ model_kind = getattr(request, "model_kind", None),+ base_repo = getattr(request, "base_repo", None),+ family_override = getattr(request, "family_override", None),+ transformer_quant = getattr(request, "transformer_quant", None),+ text_encoder_quant = getattr(request, "text_encoder_quant", None),+ transformer_prequant_path = getattr(request, "transformer_prequant_path", None),+ gpu_ordinal = gpu_ordinal,+ gpu_ids = getattr(request, "gpu_ids", None),+ component_files = _has_component_files(request),+ replace_checkpoint = replace_checkpoint,+ allow_cuda_init = allow_cuda_init,+ )+ if route is None:+ return request, None+ fields = getattr(type(request), "model_fields", None) or {}+ update = {k: v for k, v in route.updates.items() if not fields or k in fields}+ return request.model_copy(update = update), route+++_ACTIVE_ROUTE: contextvars.ContextVar = contextvars.ContextVar("unsloth_nvfp4_route", default = None)++ROUTE_KWARG = "_nvfp4_route"+++def with_route_scope(fn: Callable) -> Callable:+ @functools.wraps(fn)+ def wrapper(*args: Any, **kwargs: Any) -> Any:+ route = kwargs.pop(ROUTE_KWARG, None)+ token = _ACTIVE_ROUTE.set(route)+ try:+ return fn(*args, **kwargs)+ finally:+ _ACTIVE_ROUTE.reset(token)++ return wrapper+++def active_route() -> Optional[Nvfp4Route]:+ return _ACTIVE_ROUTE.get()+++def annotate_resolved(record: Optional[dict], route: Optional[Nvfp4Route] = None) -> Optional[dict]:+ route = route if route is not None else active_route()+ if route is None or not isinstance(record, dict):+ return record+ for control in dict.fromkeys((*route.requested, *route.reasons)):+ entry = record.get(control)+ if not isinstance(entry, dict):+ continue+ reason = route.reasons.get(control) or route.reason+ prior = str(entry.get("reason") or "").strip()+ if control in route.requested:+ asked = route.requested[control]+ entry["requested"] = asked if asked is not None else "nvfp4"+ entry["source"] = "explicit"+ entry["status"] = "fell_back"+ if reason:+ entry["reason"] = (+ f"{reason}; {prior}" if prior and reason not in prior else (prior or reason)+ )+ if control == TRANSFORMER_QUANT and route.replaced and not entry.get("replaced"):+ entry["replaced"] = route.replaced+ return recorddiff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 8fed4fb8a94..a4626a7d6fa 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -201,6 +201,7 @@ from .diffusion_auto_policy import (precision_refusal_message,)from .diffusion_nvfp4_flag import nvfp4_diffusion_enabled+from .diffusion_nvfp4_route import with_route_scopefrom .diffusion_nvfp4_install import nvfp4_backend_fields as _nvfp4_backend_fieldsfrom .diffusion_transformer_quant import (TQ_AUTO,@@ -5688,9 +5689,37 @@ class VideoBackend:# The ordinal the ROUTE already ranked, so the preflight and the load agree on one cardgpu_ordinal: Optional[int] = None,allow_oversized_load: bool = False,+ nvfp4_route: Any = None,) -> dict[str, Any]:"""Validate, then run the (slow) load on a daemon thread. Returns at once."""hf_token = (hf_token.strip() if isinstance(hf_token, str) else hf_token) or None+ from .diffusion_nvfp4_route import ROUTE_UNCHANGED, plan_nvfp4_route++ if nvfp4_route is ROUTE_UNCHANGED:+ nvfp4_route = None+ elif nvfp4_route is None:+ nvfp4_route = plan_nvfp4_route(+ media = "video",+ model_path = repo_id,+ gguf_filename = gguf_filename,+ model_kind = model_kind,+ base_repo = base_repo,+ family_override = family_override,+ transformer_quant = transformer_quant,+ text_encoder_quant = text_encoder_quant,+ gpu_ordinal = gpu_ordinal,+ gpu_ids = gpu_ids,+ )+ if nvfp4_route is not None:+ updates = nvfp4_route.updates+ repo_id = updates.get("model_path", repo_id)+ display_repo_id = updates.get("display_repo_id", display_repo_id)+ gguf_filename = updates.get("gguf_filename", gguf_filename)+ model_kind = updates.get("model_kind", model_kind)+ base_repo = updates.get("base_repo", base_repo)+ family_override = updates.get("family_override", family_override)+ transformer_quant = updates.get("transformer_quant", transformer_quant)+ text_encoder_quant = updates.get("text_encoder_quant", text_encoder_quant)# Resolved ONCE, here, and carried to the worker: outside it so a bad pick is the route's 400 rather than a load# that dies tens of GB later, and only once so free VRAM cannot re-rank the choice after the weights land. Gated# on the resolved backend, since XPU / MPS / CPU ignore physical ids and would otherwise 400 a selection the@@ -5810,11 +5839,14 @@ class VideoBackend:_load_token = token,_cancel_event = cancel_event,_gpu_ordinals = gpu_ordinals,+ _nvfp4_route = nvfp4_route,),daemon = True,).start()return self.status()+ # Outermost, so the resolved record reports the NVFP4 ask it replaced.+ @with_route_scope@scoped_allow_oversized_load# The multi-GPU selection (begin_load's ``_gpu_ordinals``) is visible to this load's planner and placement only.@with_load_selectiondiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 59b8d662c73..e53d2a1329d 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -48398,6 +48398,45 @@ async def _selected_gpu_ordinal(gpu_ids, *, allow_ranking: bool = True) -> Optio)+async def _route_nvfp4_request(+ request: Any,+ media: str = "image",+ *,+ user_initiated: bool = True,+) -> tuple:+ """Runs after authorization, before any check or download plan reads the request."""+ from core.inference.diffusion_nvfp4_route import route_load_request++ # Before the training interlock: cards are then read without a CUDA context.+ routed, route = await asyncio.to_thread(+ route_load_request,+ request,+ media = media,+ replace_checkpoint = user_initiated,+ allow_cuda_init = lambda: not _training_is_active(),+ )+ if (+ route is not None+ and routed.model_path != request.model_path+ and account_access.managed_account()+ ):+ await asyncio.to_thread(account_access.require_model_access, routed.model_path)+ return routed, route+++def _nvfp4_route_kwarg(begin_load: Any, route: Any) -> dict:+ """Unchanged decisions are passed too so the backend does not re-decide; native engines take no such argument."""+ from core.inference.diffusion_nvfp4_route import ROUTE_UNCHANGED++ try:+ import inspect+ if "nvfp4_route" in inspect.signature(begin_load).parameters:+ return {"nvfp4_route": route if route is not None else ROUTE_UNCHANGED}+ except (TypeError, ValueError):+ pass+ return {}++def _refuse_disabled_nvfp4_request(request: Any) -> None:"""Refuses NVFP4 with 400 while UNSLOTH_NVFP4_DIFFUSION is off, ahead of any precision fallback."""from core.inference.diffusion_nvfp4_flag import refuse_disabled_nvfp4@@ -48498,6 +48537,7 @@ async def diffusion_download_plan(update = {"hf_token": account_access.account_hf_token(request.hf_token)})await _refuse_disabled_nvfp4_checkpoint(request)+ request, _ = await _route_nvfp4_request(request, "image")from core.inference.diffusion import (get_diffusion_backend,split_local_checkpoint_path,@@ -48790,6 +48830,9 @@ async def load_diffusion_model_gated(update = {"hf_token": account_access.account_hf_token(request.hf_token)})await _refuse_disabled_nvfp4_checkpoint(request)+ request, nvfp4_route = await _route_nvfp4_request(+ request, "image", user_initiated = user_initiated+ )# Tested at ENTRY since begin_load returns early; the write waits, as validation can 400 first_media_repos_to_record = [ref@@ -49194,6 +49237,7 @@ async def load_diffusion_model_gated(engine.begin_load,_mlx_fallback_load_gate(request, gpu_ordinal, multi_model_mode),),+ **_nvfp4_route_kwarg(engine.begin_load, nvfp4_route),)media_load_ids.admitted("diffusion", engine, request.load_token, prior_load)# A warm start that took the generation slot between the stop above and begin_load publishing the load woulddiff --git a/studio/backend/routes/video.py b/studio/backend/routes/video.pyindex 60e41f42107..acebe202d63 100644--- a/studio/backend/routes/video.py+++ b/studio/backend/routes/video.py@@ -158,6 +158,7 @@ async def video_download_plan(from routes.inference import (_refuse_disabled_nvfp4_checkpoint,_refuse_disabled_nvfp4_request,+ _route_nvfp4_request,)_refuse_disabled_nvfp4_request(request)@@ -173,6 +174,7 @@ async def video_download_plan(update = {"hf_token": account_access.account_hf_token(request.hf_token)})await _refuse_disabled_nvfp4_checkpoint(request)+ request, _ = await _route_nvfp4_request(request, "video")from core.inference.diffusion import split_local_checkpoint_pathfrom core.inference.diffusion_local_files import resolve_local_single_filefrom core.inference.video import (@@ -307,8 +309,10 @@ async def load_video_model_gated(route so the idle unload can tell an API-loaded pipeline from one the user picked on the Video page."""from routes.inference import (+ _nvfp4_route_kwarg,_refuse_disabled_nvfp4_checkpoint,_refuse_disabled_nvfp4_request,+ _route_nvfp4_request,)_refuse_disabled_nvfp4_request(request)@@ -325,6 +329,9 @@ async def load_video_model_gated(update = {"hf_token": account_access.account_hf_token(request.hf_token)})await _refuse_disabled_nvfp4_checkpoint(request)+ request, nvfp4_route = await _route_nvfp4_request(+ request, "video", user_initiated = user_initiated+ )# Tested at entry (begin_load returns early) and written at launch (validation may 400 first).from routes.inference import (_note_load_fetched_with_a_request_token,@@ -460,6 +467,7 @@ async def load_video_model_gated(# The already-ranked card, so free VRAM drift cannot change the pick.gpu_ordinal = gpu_ordinal,allow_oversized_load = request.allow_oversized_load,+ **_nvfp4_route_kwarg(backend.begin_load, nvfp4_route),)media_load_ids.admitted("video", backend, request.load_token, prior)return starteddiff --git a/studio/backend/tests/test_diffusion_nvfp4_route.py b/studio/backend/tests/test_diffusion_nvfp4_route.pynew file mode 100644index 00000000000..02b81acabf5--- /dev/null+++ b/studio/backend/tests/test_diffusion_nvfp4_route.py@@ -0,0 +1,821 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Pre-Blackwell NVFP4 picks load INT8 (or Auto off NVIDIA); Blackwell and the kill switch keep today's behaviour."""++from __future__ import annotations++import asyncio+import types++import pytest++from core.inference import diffusion_nvfp4_route as route+from core.inference.diffusion_nvfp4_route import DeviceProfile++CAPS = [(7, 5), (8, 0), (8, 6), (8, 9), (9, 0), (10, 0), (12, 0)]+DEVICES = ["cuda", "rocm", "mps", "cpu", "xpu"]+PICKS = ["dit", "te", "hosted_source", "hosted_repo", "ltx_packed", "local_unknown", "auto"]++LTX_FILE = "diffusion_models/ltx-2.5-22b-distilled-transformer-nvfp4.safetensors"++[email protected](autouse = True)+def _nvfp4_on(monkeypatch):+ monkeypatch.setenv("UNSLOTH_NVFP4_DIFFUSION", "1")+ monkeypatch.delenv(route.ROUTE_ENV, raising = False)+ yield+++def _profile(device, cap):+ if device == "cuda":+ return DeviceProfile("nvidia", (cap,))+ if device == "rocm":+ # gfx versions come through the same call: RDNA 3 reads 11.x, which must never count as Blackwell.+ return DeviceProfile("rocm", ((11, 0),))+ return DeviceProfile(device, ())+++def _fake_device(monkeypatch, device, cap):+ monkeypatch.setattr(route, "device_profile", lambda **kw: _profile(device, cap))+++def _ltx_folder(tmp_path):+ path = tmp_path / "cm" / LTX_FILE+ path.parent.mkdir(parents = True)+ path.write_bytes(b"\0" * 64)+ return str(tmp_path / "cm")+++def _unknown_file(tmp_path):+ folder = tmp_path / "my_models"+ folder.mkdir(parents = True)+ (folder / "mystery-model-nvfp4.safetensors").write_bytes(b"\0" * 64)+ return str(folder), "mystery-model-nvfp4.safetensors"+++def _pick(kind, tmp_path):+ if kind == "dit":+ return "image", dict(model_path = "Tongyi-MAI/Z-Image-Turbo", transformer_quant = "nvfp4")+ if kind == "te":+ return "image", dict(model_path = "Qwen/Qwen-Image-2.1", text_encoder_quant = "nvfp4")+ if kind == "hosted_source":+ # A family with a hosted NVFP4 prequant repo: the scheme decides which hosted file is fetched.+ return "image", dict(model_path = "Qwen/Qwen-Image-2.1", transformer_quant = "nvfp4")+ if kind == "hosted_repo":+ return "image", dict(model_path = "unsloth/Qwen-Image-2.1-NVFP4")+ if kind == "ltx_packed":+ return "video", dict(+ model_path = _ltx_folder(tmp_path),+ gguf_filename = LTX_FILE,+ model_kind = "single_file",+ base_repo = "Lightricks/LTX-2.5-Diffusers",+ family_override = "ltx-2.5",+ )+ if kind == "local_unknown":+ folder, name = _unknown_file(tmp_path)+ return "image", dict(model_path = folder, gguf_filename = name, model_kind = "single_file")+ return "image", dict(model_path = "Tongyi-MAI/Z-Image-Turbo", transformer_quant = "auto")+++def _expected(device, cap, kind):+ blackwell = device == "cuda" and cap[0] >= 10+ if kind in ("auto", "local_unknown") or blackwell:+ return None+ nvidia = device == "cuda"+ floor = (8, 0) if kind == "ltx_packed" else (7, 5)+ dit = "int8" if nvidia and cap >= floor else "auto"+ te = "int8" if nvidia and cap[0] >= 8 else "auto"+ if kind == "dit" or kind == "hosted_source":+ return {"transformer_quant": dit}+ if kind == "te":+ return {"text_encoder_quant": te}+ if kind == "hosted_repo":+ return {+ "model_path": "Qwen/Qwen-Image-2.1",+ "model_kind": "pipeline",+ "gguf_filename": None,+ "transformer_quant": dit,+ }+ if kind == "ltx_packed":+ return {+ "model_path": "Lightricks/LTX-2.5-Diffusers",+ "model_kind": "pipeline",+ "gguf_filename": None,+ "base_repo": None,+ "transformer_quant": dit,+ }+ raise AssertionError(kind)++[email protected]("kind", PICKS)[email protected]("device", DEVICES)[email protected]("cap", CAPS, ids = lambda c: f"sm{c[0]}{c[1]}")+def test_routing_matrix(monkeypatch, tmp_path, cap, device, kind):+ _fake_device(monkeypatch, device, cap)+ media, kwargs = _pick(kind, tmp_path)+ got = route.plan_nvfp4_route(media = media, **kwargs)+ want = _expected(device, cap, kind)+ if want is None:+ assert got is None+ return+ assert got is not None+ for key, value in want.items():+ assert got.updates[key] == value, (key, got.updates)+ assert got.reason.startswith("NVFP4 needs a Blackwell GPU; using ")+ expected_word = (+ "INT8"+ if want.get("transformer_quant", want.get("text_encoder_quant")) == "int8"+ else "Auto"+ )+ assert f"using {expected_word}" in got.reason+ if "transformer_quant" in want:+ assert got.requested["transformer_quant"] == "nvfp4"+ if kind in ("hosted_repo", "ltx_packed"):+ assert got.replaced.startswith("nvfp4:")++[email protected]("kind", PICKS)+def test_kill_switch_restores_todays_request(monkeypatch, tmp_path, kind):+ _fake_device(monkeypatch, "cuda", (8, 9))+ monkeypatch.setenv(route.ROUTE_ENV, "0")+ media, kwargs = _pick(kind, tmp_path)+ assert route.plan_nvfp4_route(media = media, **kwargs) is None+++def test_the_nvfp4_switch_off_keeps_the_400_for_an_nvfp4_scheme(monkeypatch, tmp_path):+ """The master switch decides whether NVFP4 exists; the route never turns its 400 into a load."""+ _fake_device(monkeypatch, "cuda", (8, 9))+ monkeypatch.setenv("UNSLOTH_NVFP4_DIFFUSION", "0")+ for kind in ("dit", "te", "hosted_source", "hosted_repo"):+ media, kwargs = _pick(kind, tmp_path)+ assert route.plan_nvfp4_route(media = media, **kwargs) is None, kind+ # The packed single-file path loads today with the switch off, so it is still routed.+ media, kwargs = _pick("ltx_packed", tmp_path)+ assert route.plan_nvfp4_route(media = media, **kwargs).updates["transformer_quant"] == "int8"+++def test_an_unknown_nvfp4_file_keeps_its_dit_precision_but_not_its_te_pick(+ monkeypatch, tmp_path, caplog+):+ _fake_device(monkeypatch, "cuda", (8, 9))+ folder, name = _unknown_file(tmp_path)+ with caplog.at_level("INFO", logger = route.logger.name):+ got = route.plan_nvfp4_route(+ model_path = folder,+ gguf_filename = name,+ model_kind = "single_file",+ transformer_quant = "nvfp4",+ text_encoder_quant = "nvfp4",+ )+ assert dict(got.updates) == {"text_encoder_quant": "int8"}+ assert got.kept == (name,)+ assert any("kept" in r.getMessage() and name in r.getMessage() for r in caplog.records)+++ "name,base",+ [+ ("FLUX.2-klein-9B-NVFP4.safetensors", "black-forest-labs/FLUX.2-klein-9B"),+ ("flux-2-klein-4b-nvfp4.safetensors", "black-forest-labs/FLUX.2-klein-4B"),+ ("qwen-image-2.1-turbo-nvfp4.safetensors", "Qwen/Qwen-Image-2.1-Turbo"),+ ("flux1-dev-nvfp4.safetensors", "black-forest-labs/FLUX.1-dev"),+ # Spells a variant whose canonical spelling the family never states: kept, never another model.+ ("flux1-krea-dev-nvfp4.safetensors", None),+ ],+)+def test_a_known_family_file_keeps_its_variant(monkeypatch, tmp_path, name, base):+ _fake_device(monkeypatch, "cuda", (8, 9))+ folder = tmp_path / "models"+ folder.mkdir()+ (folder / name).write_bytes(b"\0" * 64)+ got = route.plan_nvfp4_route(+ model_path = str(folder), gguf_filename = name, model_kind = "single_file"+ )+ if base is None:+ assert got is None+ else:+ assert got.updates["model_path"] == base+ assert got.updates["transformer_quant"] == "int8"+++ "name,override,base",+ [+ (+ "ltx-2.5-22b-distilled-transformer-nvfp4.safetensors",+ "ltx-2.5",+ "Lightricks/LTX-2.5-Diffusers",+ ),+ # The pack runs only its distilled DiT: a dev file is a different model.+ ("ltx-2.5-22b-dev-nvfp4.safetensors", "ltx-2.5", None),+ # The ltx-2 family spans 2.0 to 2.3 on a 2.0 pipeline.+ ("ltx-2.3-22b-distilled-nvfp4.safetensors", None, None),+ ("Wan2.2-TI2V-5B-nvfp4.safetensors", None, "Wan-AI/Wan2.2-TI2V-5B-Diffusers"),+ ],+)+def test_a_video_file_is_replaced_only_by_the_same_model(+ monkeypatch, tmp_path, name, override, base+):+ _fake_device(monkeypatch, "cuda", (8, 0))+ folder = tmp_path / "videos"+ folder.mkdir()+ (folder / name).write_bytes(b"\0" * 64)+ got = route.plan_nvfp4_route(+ media = "video",+ model_path = str(folder),+ gguf_filename = name,+ model_kind = "single_file",+ family_override = override,+ )+ if base is None:+ assert got is None+ else:+ assert got.updates["model_path"] == base+ assert got.updates["transformer_quant"] == "int8"+++def test_a_family_that_denies_int8_gets_auto(monkeypatch):+ from core.inference import diffusion_transformer_quant as tq++ _fake_device(monkeypatch, "cuda", (8, 9))+ monkeypatch.setattr(tq, "_FAMILY_SCHEME_DENY", {"z-image": frozenset({"int8"})})+ got = route.plan_nvfp4_route(model_path = "Tongyi-MAI/Z-Image-Turbo", transformer_quant = "nvfp4")+ assert got.updates["transformer_quant"] == "auto"+++def test_an_nvfp4_prequant_path_is_never_handed_to_int8(monkeypatch, tmp_path):+ _fake_device(monkeypatch, "cuda", (8, 0))+ art = tmp_path / "Z-Image-Turbo-NVFP4.safetensors"+ art.write_bytes(b"\0" * 64)+ got = route.plan_nvfp4_route(+ model_path = "Tongyi-MAI/Z-Image-Turbo",+ transformer_quant = "nvfp4",+ transformer_prequant_path = str(art),+ )+ assert got.updates["transformer_prequant_path"] is None+ assert got.updates["transformer_quant"] == "int8"+++ "caps,ordinal,routes",+ [+ (((10, 0), (8, 0)), None, False), # auto may land on the B200: keep NVFP4+ (((10, 0), (8, 0)), 1, True), # pinned to the A100+ (((10, 0), (8, 0)), 0, False), # pinned to the B200+ (((8, 9), (8, 9)), None, True),+ (((12, 0),), None, False),+ ],+)+def test_mixed_boxes_follow_the_card_the_load_uses(caps, ordinal, routes):+ profile = DeviceProfile("nvidia", caps)+ got = route.plan_nvfp4_route(+ model_path = "Tongyi-MAI/Z-Image-Turbo",+ transformer_quant = "nvfp4",+ gpu_ordinal = ordinal,+ profile = profile,+ )+ assert (got is not None) is routes+++def test_an_ordinary_request_never_reads_the_device(monkeypatch):+ monkeypatch.setattr(route, "device_profile", lambda **kw: pytest.fail("read the device"))+ for kwargs in (+ dict(model_path = "Tongyi-MAI/Z-Image-Turbo"),+ dict(+ model_path = "Tongyi-MAI/Z-Image-Turbo",+ transformer_quant = "auto",+ text_encoder_quant = "int8",+ ),+ dict(model_path = "unsloth/Z-Image-Turbo-GGUF", gguf_filename = "z-image-turbo-Q4_K_M.gguf"),+ ):+ assert route.plan_nvfp4_route(**kwargs) is None+++def test_nvidia_smi_answers_without_initialising_cuda(monkeypatch):+ """A cold process reads the cards from nvidia-smi, never torch.cuda (training may be running beside it)."""+ import torch++ from utils.hardware import hardware, nvidia++ route.reset_device_profile()+ monkeypatch.setattr(torch.cuda, "is_initialized", lambda: False)+ monkeypatch.setattr(+ torch.cuda, "get_device_capability", lambda *a: pytest.fail("initialised CUDA")+ )+ monkeypatch.setattr(torch.cuda, "is_available", lambda: pytest.fail("asked torch"))+ monkeypatch.setattr(torch.version, "hip", None)+ monkeypatch.setattr(torch, "__version__", "2.9.0+cu130")+ monkeypatch.setattr(+ nvidia, "get_compute_capabilities", lambda: {0: (8, 9), 1: (8, 9), 2: (12, 0)}+ )+ monkeypatch.setattr(hardware, "get_parent_visible_gpu_ids", lambda: [0, 1])+ try:+ assert route.device_profile() == DeviceProfile("nvidia", ((8, 9), (8, 9)))+ finally:+ route.reset_device_profile()+ # Mixed cards: nvidia-smi rows are not torch ordinals, so it cannot answer.+ for caps in ({0: (8, 9), 1: (12, 0)}, {0: (8, 9), 1: (7, 5)}):+ monkeypatch.setattr(nvidia, "get_compute_capabilities", lambda caps = caps: caps)+ monkeypatch.setattr(hardware, "get_parent_visible_gpu_ids", lambda: [0, 1])+ assert route._smi_visible_capabilities(torch) == ()+++def test_training_never_initialises_cuda_for_the_route(monkeypatch):+ """Mixed cards (nvidia-smi cannot answer) while training owns the GPU: left as is, nothing cached."""+ import torch++ route.reset_device_profile()+ monkeypatch.setattr(route, "_smi_visible_capabilities", lambda torch: ())+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "is_initialized", lambda: False)+ monkeypatch.setattr(+ torch.cuda, "get_device_capability", lambda *a: pytest.fail("initialised CUDA")+ )+ monkeypatch.setattr(torch.version, "hip", None)+ monkeypatch.setattr(torch, "__version__", "2.9.0+cu130")+ try:+ got = route.plan_nvfp4_route(+ model_path = "Tongyi-MAI/Z-Image-Turbo", transformer_quant = "nvfp4", allow_cuda_init = False+ )+ assert got is None+ assert route._PROFILE == []+ finally:+ route.reset_device_profile()+++def test_the_route_reads_the_cards_without_cuda_while_training(monkeypatch):+ from models.inference import DiffusionLoadRequest+ from routes import inference as image_routes++ seen = {}++ def _plan(**kwargs):+ seen.update(kwargs)+ return None++ monkeypatch.setattr(route, "plan_nvfp4_route", _plan)+ monkeypatch.setattr(image_routes, "_training_is_active", lambda: True)+ pick = DiffusionLoadRequest(model_path = "Tongyi-MAI/Z-Image-Turbo", transformer_quant = "nvfp4")+ asyncio.run(image_routes._route_nvfp4_request(pick, "image"))+ assert seen["allow_cuda_init"]() is False+++def test_the_device_is_read_once(monkeypatch):+ import torch++ calls = []+ route.reset_device_profile()+ monkeypatch.setattr(route, "_smi_visible_capabilities", lambda torch: ())+ monkeypatch.setattr(torch.cuda, "is_available", lambda: calls.append("avail") or True)+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 1)+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda i = None: (8, 9))+ monkeypatch.setattr(torch.version, "hip", None)+ try:+ assert route.device_profile() == DeviceProfile("nvidia", ((8, 9),))+ assert route.device_profile() == DeviceProfile("nvidia", ((8, 9),))+ assert calls == ["avail"]+ finally:+ route.reset_device_profile()+++ "hip,version",+ [+ ("7.0", "2.9.0+rocm7.0"),+ (None, "2.9.0+rocm7.0"),+ ], # AMD SDK / Radeon wheels leave torch.version.hip unset+)+def test_rocm_never_reads_as_blackwell(monkeypatch, hip, version):+ import torch++ route.reset_device_profile()+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 1)+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda i = None: (12, 0))+ monkeypatch.setattr(torch.version, "hip", hip)+ monkeypatch.setattr(torch, "__version__", version)+ try:+ got = route.plan_nvfp4_route(+ model_path = "Tongyi-MAI/Z-Image-Turbo", transformer_quant = "nvfp4"+ )+ assert got.updates["transformer_quant"] == "auto"+ assert got.device == "rocm"+ finally:+ route.reset_device_profile()+++def test_the_resolved_record_reports_the_rerouted_ask(monkeypatch):+ from core.inference.diffusion_auto_policy import build_resolved_record++ _fake_device(monkeypatch, "cuda", (8, 9))+ got = route.plan_nvfp4_route(+ model_path = "Qwen/Qwen-Image-2.1", transformer_quant = "nvfp4", text_encoder_quant = "nvfp4"+ )+ controls = {+ "transformer_quant": ("int8", "int8", "seeded from the hosted checkpoint unsloth/x"),+ "text_encoder_quant": ("int8", "int8", "int8 ConvRot encoder"),+ "memory_mode": (None, "none", "fits"),+ }++ @route.with_route_scope+ def _load(**kwargs):+ assert route.ROUTE_KWARG not in kwargs+ return build_resolved_record(controls)++ record = _load(_nvfp4_route = got, repo_id = "Qwen/Qwen-Image-2.1")+ tq = record["transformer_quant"]+ assert tq["value"] == "int8"+ assert tq["requested"] == "nvfp4"+ assert tq["status"] == "fell_back"+ assert tq["source"] == "explicit"+ assert tq["reason"].startswith("NVFP4 needs a Blackwell GPU; using INT8")+ assert "seeded from the hosted checkpoint" in tq["reason"]+ assert record["text_encoder_quant"]["requested"] == "nvfp4"+ assert record["memory_mode"]["status"] == "applied"+ plain = build_resolved_record(controls)+ assert plain["transformer_quant"]["requested"] == "int8"+ assert plain["transformer_quant"]["status"] == "applied"+++def test_the_resolved_record_reports_a_replaced_checkpoint(monkeypatch, tmp_path):+ from core.inference.diffusion_auto_policy import build_resolved_record++ _fake_device(monkeypatch, "cuda", (8, 0))+ media, kwargs = _pick("ltx_packed", tmp_path)+ got = route.plan_nvfp4_route(media = media, **kwargs)+ record = route.annotate_resolved(+ build_resolved_record({"transformer_quant": ("int8", "int8", "hosted int8")}), got+ )+ assert record["transformer_quant"]["replaced"] == f"nvfp4:{LTX_FILE}"+ assert "from Lightricks/LTX-2.5-Diffusers instead of" in record["transformer_quant"]["reason"]+++class _Seen(Exception):+ pass++[email protected]("field", ["transformer_quant", "text_encoder_quant"])[email protected]("cap,want", [((8, 9), "int8"), ((10, 0), "nvfp4")])+def test_every_load_and_plan_route_reroutes_before_its_checks(monkeypatch, field, cap, want):+ """All four entries reroute after the disabled-NVFP4 and account refusals, before anything else reads the request."""+ from models.inference import DiffusionLoadRequest, VideoLoadRequest+ from routes import inference as image_routes+ from routes import video as video_routes++ _fake_device(monkeypatch, "cuda", cap)+ real = image_routes._route_nvfp4_request+ seen = []++ async def _spy(+ request,+ media = "image",+ **kwargs,+ ):+ routed, got = await real(request, media, **kwargs)+ seen.append((media, getattr(routed, field), kwargs.get("user_initiated", True)))+ raise _Seen()++ monkeypatch.setattr(image_routes, "_route_nvfp4_request", _spy)+ image = DiffusionLoadRequest(model_path = "Tongyi-MAI/Z-Image-Turbo", **{field: "nvfp4"})+ video = VideoLoadRequest(model_path = "Wan-AI/Wan2.2-TI2V-5B-Diffusers", **{field: "nvfp4"})+ for call in (+ image_routes.diffusion_download_plan(image, current_subject = "u"),+ image_routes.load_diffusion_model_gated(image, "u", user_initiated = True),+ video_routes.video_download_plan(video, current_subject = "u"),+ video_routes.load_video_model_gated(video, "u"),+ ):+ with pytest.raises(_Seen):+ asyncio.run(call)+ assert seen == [+ ("image", want, True),+ ("image", want, True),+ ("video", want, True),+ ("video", want, False),+ ]+++def test_a_load_nobody_picked_by_hand_keeps_its_checkpoint(monkeypatch, tmp_path):+ """Media auto-switch tracks the model by the path it asked for, so only precision is rerouted there."""+ from models.inference import VideoLoadRequest++ _fake_device(monkeypatch, "cuda", (8, 0))+ media, kwargs = _pick("ltx_packed", tmp_path)+ pick = VideoLoadRequest(**kwargs)+ same, got = route.route_load_request(pick, media = media, replace_checkpoint = False)+ assert got is None and same is pick+ swapped, got = route.route_load_request(pick, media = media)+ assert swapped.model_path == "Lightricks/LTX-2.5-Diffusers"+++def test_a_pick_with_its_own_components_keeps_its_checkpoint(monkeypatch, tmp_path):+ _fake_device(monkeypatch, "cuda", (8, 9))+ folder = tmp_path / "models"+ folder.mkdir()+ (folder / "flux-2-klein-4b-nvfp4.safetensors").write_bytes(b"\0" * 64)+ got = route.plan_nvfp4_route(+ model_path = str(folder),+ gguf_filename = "flux-2-klein-4b-nvfp4.safetensors",+ model_kind = "single_file",+ component_files = True,+ )+ assert got is None+++def test_a_bare_folder_or_file_path_decides_like_its_folder_and_file(monkeypatch, tmp_path):+ _fake_device(monkeypatch, "cuda", (8, 0))+ folder = tmp_path / "ltx"+ folder.mkdir()+ name = "ltx-2.5-22b-distilled-transformer-nvfp4.safetensors"+ (folder / name).write_bytes(b"\0" * 64)+ pair = route.plan_nvfp4_route(media = "video", model_path = str(folder), gguf_filename = name)+ bare = route.plan_nvfp4_route(media = "video", model_path = str(folder))+ whole = route.plan_nvfp4_route(media = "video", model_path = str(folder / name))+ assert pair.updates == bare.updates == whole.updates+ assert pair.updates["model_path"] == "Lightricks/LTX-2.5-Diffusers"+++def test_a_missing_local_file_is_not_a_pick(monkeypatch, tmp_path):+ _fake_device(monkeypatch, "cuda", (8, 9))+ assert not route.checkpoint_is_nvfp4(+ str(tmp_path / "nope"), "flux-2-klein-4b-nvfp4.safetensors"+ )+ assert (+ route.plan_nvfp4_route(+ model_path = str(tmp_path / "nope"), gguf_filename = "flux-2-klein-4b-nvfp4.safetensors"+ )+ is None+ )+++def test_a_recorded_header_wins_over_the_name_and_pickles_are_never_opened(monkeypatch, tmp_path):+ from core.inference import diffusion_prequant++ opened = []+ monkeypatch.setattr(+ diffusion_prequant, "local_prequant_scheme", lambda path: opened.append(path) or "int8"+ )+ art = tmp_path / "my-finetune-from-nvfp4-int8.safetensors"+ art.write_bytes(b"\0" * 64)+ assert not route.checkpoint_is_nvfp4(str(art))+ pickle = tmp_path / "flux-2-klein-4b-nvfp4.pt"+ pickle.write_bytes(b"\0" * 64)+ assert route.checkpoint_is_nvfp4(str(pickle))+ assert opened == [str(art)]+++def test_an_unreadable_device_is_not_cached_and_leaves_the_request(monkeypatch):+ calls = []++ def _boom(*args, **kwargs):+ calls.append(1)+ raise RuntimeError("driver hiccup")++ route.reset_device_profile()+ monkeypatch.setattr(route, "_probe_device_profile", _boom)+ try:+ assert route.device_profile().kind == route.UNKNOWN+ assert route.device_profile().kind == route.UNKNOWN+ assert len(calls) == 2+ got = route.plan_nvfp4_route(+ model_path = "Tongyi-MAI/Z-Image-Turbo", transformer_quant = "nvfp4"+ )+ assert got is None+ finally:+ route.reset_device_profile()+++ "cap,media,turing_on,want",+ [+ ((7, 5), "image", True, "int8"),+ ((7, 5), "image", False, "auto"),+ ((7, 5), "video", True, "auto"), # video INT8 needs bf16+ ((8, 0), "video", True, "int8"),+ ((6, 1), "image", True, "auto"),+ ],+)+def test_the_int8_target_follows_what_the_card_runs(monkeypatch, cap, media, turing_on, want):+ from core.inference import diffusion_transformer_quant as tq++ monkeypatch.setenv(tq.FP16_CARD_INT8_ENV, "1" if turing_on else "0")+ _fake_device(monkeypatch, "cuda", cap)+ repo = "Tongyi-MAI/Z-Image-Turbo" if media == "image" else "Wan-AI/Wan2.2-TI2V-5B-Diffusers"+ got = route.plan_nvfp4_route(media = media, model_path = repo, transformer_quant = "nvfp4")+ assert got.updates["transformer_quant"] == want+++def test_a_selection_counts_every_card_it_places_work_on(monkeypatch):+ from core.inference import diffusion_device++ monkeypatch.setattr(diffusion_device, "resolve_selected_cuda_ordinals", lambda ids: [0, 1])+ profile = DeviceProfile("nvidia", ((10, 0), (8, 0)))+ # Primary B200 ranked by the route, A100 also selected: the A100 cannot run NVFP4.+ got = route.plan_nvfp4_route(+ model_path = "Tongyi-MAI/Z-Image-Turbo",+ transformer_quant = "nvfp4",+ gpu_ordinal = 0,+ gpu_ids = [0, 1],+ profile = profile,+ )+ assert got is not None and got.updates["transformer_quant"] == "int8"+++def test_hosted_repo_lookup_is_unambiguous_and_canonical(monkeypatch):+ _fake_device(monkeypatch, "cuda", (8, 9))+ # HunyuanVideo-1.5 480p and 720p share one NVFP4 repo: nothing tells them apart, so it is kept.+ assert route.hosted_nvfp4_repo_base("unsloth/HunyuanVideo-1.5-NVFP4", "video") is None+ fam, base = route.hosted_nvfp4_repo_base(+ "unsloth/HunyuanVideo-1.5-NVFP4", "video", family_override = "hunyuanvideo-1.5-720p"+ )+ assert fam.name == "hunyuanvideo-1.5-720p" and base == fam.base_repo+ fam, base = route.hosted_nvfp4_repo_base(+ "unsloth/HunyuanVideo-1.5-NVFP4",+ "video",+ filename = "HunyuanVideo-1.5-Diffusers-720p_t2v-NVFP4.safetensors",+ )+ assert fam.name == "hunyuanvideo-1.5-720p"+ # A variant row's base is a lowercase key: returned only in a spelling the family states in full.+ got = route.hosted_nvfp4_repo_base("unsloth/Qwen-Image-2512-NVFP4", "image")+ assert got is None or got[1] != got[1].lower()+++def test_the_route_hands_the_reroute_only_to_a_backend_that_records_it():+ from routes.inference import _nvfp4_route_kwarg++ def native(repo_id, **kwargs):+ pass++ def diffusers(repo_id, *, nvfp4_route = None):+ pass++ marker = object()+ assert _nvfp4_route_kwarg(native, marker) == {}+ assert _nvfp4_route_kwarg(diffusers, marker) == {"nvfp4_route": marker}+ # An unchanged decision is handed over too, so the backend does not decide again on another card.+ assert _nvfp4_route_kwarg(diffusers, None) == {"nvfp4_route": route.ROUTE_UNCHANGED}+++ "backend_name,repo,base",+ [+ ("image", "unsloth/Qwen-Image-2.1-NVFP4", "Qwen/Qwen-Image-2.1"),+ ("video", "unsloth/Wan2.2-T2V-A14B-NVFP4", "Wan-AI/Wan2.2-T2V-A14B-Diffusers"),+ ],+)+def test_begin_load_reroutes_a_direct_caller(monkeypatch, backend_name, repo, base):+ """Direct callers (no route) are rerouted in ``begin_load`` before validation reads the pick."""+ _fake_device(monkeypatch, "cuda", (8, 6))+ if backend_name == "image":+ from core.inference.diffusion import DiffusionBackend as Backend+ else:+ from core.inference.video import VideoBackend as Backend+ seen = {}++ def _validate(self, repo_id, **kwargs):+ seen["repo_id"] = repo_id+ seen.update(kwargs)+ raise _Seen()++ monkeypatch.setattr(Backend, "validate_load_request", _validate)+ with pytest.raises(_Seen):+ Backend().begin_load(repo, transformer_quant = "nvfp4")+ assert seen["repo_id"] == base+ assert seen.get("gguf_filename") is None+ monkeypatch.setenv(route.ROUTE_ENV, "0")+ with pytest.raises(_Seen):+ Backend().begin_load(repo, transformer_quant = "nvfp4")+ assert seen["repo_id"] == repo+++_WAN_T2V = "Wan-AI/Wan2.2-T2V-A14B-Diffusers"+++class _RecordingApi:+ def __init__(self, repos):+ self.repos = repos+ self.asked: list = []++ def model_info(+ self,+ repo_id,+ files_metadata = False,+ token = None,+ ):+ self.asked.append(repo_id)+ return types.SimpleNamespace(siblings = self.repos[repo_id])+++def _sib(name, size):+ return types.SimpleNamespace(rfilename = name, size = size)+++_WAN_FILES = [+ _sib("model_index.json", 1000),+ _sib("transformer/config.json", 1000),+ _sib("transformer/diffusion_pytorch_model.safetensors", 28_000_000_000),+ _sib("transformer_2/config.json", 1000),+ _sib("transformer_2/diffusion_pytorch_model.safetensors", 28_000_000_000),+ _sib("text_encoder/model-00001-of-00001.safetensors", 11_000_000_000),+ _sib("vae/diffusion_pytorch_model.safetensors", 500_000_000),+]+_WAN_SIBLINGS = {+ _WAN_T2V: _WAN_FILES,+ "unsloth/Wan2.2-T2V-A14B-FP8": _WAN_FILES+ + [+ _sib("Wan2.2-T2V-A14B-INT8.pt", 14_000_000_000),+ _sib("Wan2.2-T2V-A14B-INT8-2.pt", 14_000_000_000),+ ],+ "unsloth/Wan2.2-T2V-A14B-NVFP4": [+ _sib("Wan2.2-T2V-A14B-NVFP4.safetensors", 8_000_000_000),+ _sib("Wan2.2-T2V-A14B-transformer_2-NVFP4.safetensors", 8_100_000_000),+ ],+}+++def test_the_rerouted_video_plan_asks_no_nvfp4_repo_but_the_kill_switch_does(monkeypatch):+ """The routed request (int8) stages no NVFP4 file; the same pick under the kill switch would stage both."""+ from models.inference import VideoLoadRequest++ import core.inference.video as video_mod+ from core.inference import diffusion_prequant+ from core.inference.diffusion import DiffusionBackend+ from core.inference.video import VideoBackend++ def _plan_for(request):+ api = _RecordingApi(_WAN_SIBLINGS)+ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: api)+ monkeypatch.setattr(+ DiffusionBackend,+ "_hub_file_is_cached",+ staticmethod(lambda repo_id, filename, revision = None, expected_size = None, **kw: False),+ )+ monkeypatch.setattr(+ video_mod,+ "select_transformer_quant_scheme",+ lambda target, requested, *a, **k: requested,+ )+ monkeypatch.setattr(+ diffusion_prequant, "restricted_prequant_load_supported", lambda *a, **k: True+ )+ monkeypatch.setattr(video_mod, "_video_seed_stays_resident", lambda fam, **kw: True)+ monkeypatch.setattr(+ video_mod,+ "resolve_diffusion_device_target",+ lambda *a, **k: types.SimpleNamespace(backend = "cuda", device = "cuda", dtype = None),+ )+ plan = VideoBackend().download_plan(+ request.model_path, model_kind = "pipeline", transformer_quant = request.transformer_quant+ )+ return api.asked, {f for e in plan["entries"] for f in e["files"]}++ _fake_device(monkeypatch, "cuda", (8, 9))+ pick = VideoLoadRequest(model_path = _WAN_T2V, transformer_quant = "nvfp4")+ routed, got = route.route_load_request(pick, media = "video")+ assert routed.transformer_quant == "int8" and got is not None+ asked, staged = _plan_for(routed)+ assert not any(repo.lower().endswith("-nvfp4") for repo in asked), asked+ assert not any("NVFP4" in f for f in staged), staged++ monkeypatch.setenv(route.ROUTE_ENV, "0")+ kept, none = route.route_load_request(pick, media = "video")+ assert none is None and kept.transformer_quant == "nvfp4"+ asked, staged = _plan_for(kept)+ assert "unsloth/Wan2.2-T2V-A14B-NVFP4" in asked+++def _all_family_names():+ from core.inference.diffusion_families import _FAMILIES as image+ from core.inference.video_families import _FAMILIES as video+ return sorted({f.name for f in (*image, *video)})++[email protected]("cap", CAPS, ids = lambda c: f"sm{c[0]}{c[1]}")+def test_auto_never_orders_nvfp4_below_blackwell(monkeypatch, cap):+ from core.inference import diffusion_nvfp4_gate as gate+ from core.inference import diffusion_transformer_quant as tq++ monkeypatch.setattr(tq, "_nvfp4_gate_passed", lambda *a, **k: True)+ monkeypatch.setattr(tq, "_nvfp4_gate_backend_ok", lambda *a, **k: True)+ monkeypatch.setattr(tq, "_nvfp4_backend_is", lambda *a, **k: True)+ monkeypatch.setattr(tq, "_is_consumer_gpu", lambda device = None: False)+ monkeypatch.setattr(gate, "nvfp4_gate_passed", lambda *a, **k: True)+ for family in _all_family_names():+ order = tq._auto_scheme_order(family, "cuda", cap)+ if cap[0] < 10:+ assert "nvfp4" not in order, (family, cap, order)+++def test_blackwell_requests_are_returned_untouched(monkeypatch, tmp_path):+ for cap in ((10, 0), (10, 3), (11, 0), (12, 0), (12, 1)):+ _fake_device(monkeypatch, "cuda", cap)+ for kind in PICKS:+ media, kwargs = _pick(kind, tmp_path / f"{cap[0]}{cap[1]}{kind}")+ assert route.plan_nvfp4_route(media = media, **kwargs) is None, (cap, kind)+ from models.inference import DiffusionLoadRequest++ pick = DiffusionLoadRequest(+ model_path = "Tongyi-MAI/Z-Image-Turbo", transformer_quant = "nvfp4"+ )+ same, none = route.route_load_request(pick)+ assert same is pick and none is Nonediff --git a/studio/backend/tests/test_video_routes.py b/studio/backend/tests/test_video_routes.pyindex 46ee0f18342..bd4b3acaec1 100644--- a/studio/backend/tests/test_video_routes.py+++ b/studio/backend/tests/test_video_routes.py@@ -33,6 +33,14 @@ def _shared_setup_1(client):)+def _nvfp4_not_rerouted(monkeypatch):+ """Blackwell host: explicit nvfp4 still reaches the precision gates."""+ from core.inference import diffusion_nvfp4_route as nvfp4_route+ monkeypatch.setattr(+ nvfp4_route, "device_profile", lambda **kw: nvfp4_route.DeviceProfile("nvidia", ((10, 0),))+ )++def _shared_setup_2(monkeypatch):backend = video_module.get_video_backend()monkeypatch.setattr(@@ -1587,6 +1595,7 @@ def test_video_download_plan_forwards_the_h3_partition(client, monkeypatch):def test_video_download_plan_judges_a_quantized_reference_pick_per_partition(client, monkeypatch):+ _nvfp4_not_rerouted(monkeypatch)# Stub the host precision gate so the partition refusal is tested on CPU CI too.monkeypatch.setattr(video_module, "assert_video_precision_available", lambda fam, **kw: None, raising = False@@ -1651,6 +1660,7 @@ def test_video_download_plan_refuses_an_unsupported_combination_before_staging(cdef test_video_download_plan_refuses_an_unavailable_transformer_quant(client, monkeypatch):+ _nvfp4_not_rerouted(monkeypatch)backend = _shared_setup_2(monkeypatch)monkeypatch.setattr(backend,@@ -1673,6 +1683,7 @@ def test_video_download_plan_refuses_an_unavailable_transformer_quant(client, modef test_video_download_plan_refuses_a_quantized_reference_task(client, monkeypatch):+ _nvfp4_not_rerouted(monkeypatch)backend = _shared_setup_2(monkeypatch)monkeypatch.setattr(backend,