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: install flashinfer on demand for NVFP4 without moving torch (#11730)
Daniel Han11282f1de419
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 1a313e72fdf..32b476e412d 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -230,6 +230,8 @@ from .diffusion_auto_policy import (resident_bytes_from_declared,resolve_dense_quant_candidate,)+from .diffusion_nvfp4_flag import nvfp4_diffusion_enabled+from .diffusion_nvfp4_install import nvfp4_backend_fields as _nvfp4_backend_fieldsfrom .diffusion_transformer_quant import (TQ_AUTO,TQ_NVFP4,@@ -3555,6 +3557,43 @@ class DiffusionBackend:)return None+ def _nvfp4_checkpoint_will_load(+ self,+ fam: Any,+ base: Optional[str],+ path_override: Optional[str],+ hf_token: Optional[str],+ *,+ local_files_only: bool = False,+ loras: Any = None,+ ) -> bool:+ """Whether an NVFP4 load opens a pre-quantised checkpoint (the only FlashInfer path); unanswerable -> False."""+ if not nvfp4_diffusion_enabled():+ return False+ try:+ if _has_active_lora(loras):+ return False+ source = usable_prequant_source(+ fam, TQ_NVFP4, path_override = path_override, base_repo = base+ )+ if source is None:+ return False+ if getattr(source, "kind", None) != "repo":+ return True+ if prequant_checkpoint_cached(source, cache_dir = hub_cache_dir()):+ return True+ if local_files_only:+ return False+ return self._prequant_source_hub_entry(source, hf_token, scheme = TQ_NVFP4) is not None+ except Exception as exc: # noqa: BLE001 -- a refused or unreachable listing is no checkpoint+ logger.info(+ "diffusion.nvfp4_install: no reachable NVFP4 checkpoint for %s, so the load runs on "+ "torchao and FlashInfer is not installed (%s)",+ base,+ type(exc).__name__,+ )+ return False+@staticmethoddef _estimate_download_bytes(repo_id: str,@@ -4762,6 +4801,52 @@ class DiffusionBackend:_ensure_attention_backend_installed(preinstall_backend, logger)except Exception: # noqa: BLE001 - the locked path re-resolves and validatespass+ # Install FlashInfer only when a pre-quantised checkpoint will load: the on-the-fly build is torchao.+ if (+ dense_quant_supported_kind(kind)+ and nvfp4_diffusion_enabled()+ and TQ_NVFP4+ in (+ normalize_transformer_quant(transformer_quant),+ _pipeline_prequant_planned,+ )+ # A declined seed loads the released denoiser (torchao or no quant), so no checkpoint for FlashInfer.+ and _pipeline_prequant_planned != PIPELINE_SEED_DECLINED+ and (+ _pipeline_prequant_planned == TQ_NVFP4+ or self._nvfp4_checkpoint_will_load(+ fam,+ base,+ transformer_prequant_path,+ hf_token,+ local_files_only = local_files_only,+ loras = loras,+ )+ )+ # The locked re-plan (after teardown) may drop the capacity-settled seed; ask it now with teardown memory credited.+ and not (+ kind == "pipeline"+ and _pipeline_prequant_planned == TQ_NVFP4+ and not self._seed_plan_stays_resident(+ TQ_NVFP4,+ target,+ base,+ fam,+ memory_mode,+ cpu_offload,+ repo_id = repo_id,+ base_local_dir = _base_local_dir,+ fetch_base = fetch_base,+ text_encoder_quant = text_encoder_quant,+ )+ )+ ):+ from .diffusion_nvfp4_install import ensure_flashinfer_for_nvfp4+ _nvfp4_install_outcome = ensure_flashinfer_for_nvfp4(+ device, logger = logger, local_files_only = local_files_only+ )+ else:+ _nvfp4_install_outcome = Nonewith self._lock:self._raise_if_load_cancelled(_load_token)@@ -4777,6 +4862,10 @@ class DiffusionBackend:self._unload_locked()finally:self._release_teardown_locked()+ # Bind even when the gate skipped, so no stale install reason survives.+ from .diffusion_nvfp4_install import record_install_reason++ record_install_reason(self, *(_nvfp4_install_outcome or (True, None)), device)# Single-file kinds resolve a checkpoint path; the pipeline kind has none.single_file_path = (@@ -4816,31 +4905,17 @@ class DiffusionBackend:PIPELINE_SEED_DECLINED,):pipeline_seed_scheme = _pipeline_prequant_planned- seed_estimate = estimate_dense_quant(- fam, pipeline_seed_scheme, base_repo = base, prequant_available = True- )- seeded_plan = (- self._plan_memory(- target,- single_file_path,- base,- fam,- memory_mode,- cpu_offload,- kind = kind,- repo_id = repo_id,- base_local_dir = _base_local_dir,- fetch_base = fetch_base,- transformer_resident_override_mib = (- seed_estimate.steady_transformer_mib- ),- **self._candidate_companion_overrides(- seed_estimate, fam, base, target, text_encoder_quant- ),- text_encoder_quant = text_encoder_quant,- )- if seed_estimate is not None- else None+ seeded_plan = self._seeded_pipeline_plan(+ pipeline_seed_scheme,+ target,+ base,+ fam,+ memory_mode,+ cpu_offload,+ repo_id = repo_id,+ base_local_dir = _base_local_dir,+ fetch_base = fetch_base,+ text_encoder_quant = text_encoder_quant,)if seeded_plan is None or not plan_keeps_transformer_resident(seeded_plan):# Offload hooks use Module.to(), which torchao tensors reject, and live free@@ -7074,6 +7149,68 @@ class DiffusionBackend:except Exception: # noqa: BLE001 -- sizing aid only; the dense total still refuses safelyreturn int(companions)+ def _seeded_pipeline_plan(+ self,+ scheme: str,+ target: Any,+ base: str,+ fam: Any,+ memory_mode: Optional[str],+ cpu_offload: bool,+ *,+ repo_id: str,+ base_local_dir: Optional[str],+ fetch_base: Optional[str],+ device_memory_override: Optional[DeviceMemory] = None,+ text_encoder_quant: Optional[str] = None,+ ):+ """Full-pipeline plan priced on the pre-quantised ``scheme`` seed, or None when the family table cannot size it."""+ seed_estimate = estimate_dense_quant(fam, scheme, base_repo = base, prequant_available = True)+ if seed_estimate is None:+ return None+ return self._plan_memory(+ target,+ None,+ base,+ fam,+ memory_mode,+ cpu_offload,+ kind = "pipeline",+ repo_id = repo_id,+ base_local_dir = base_local_dir,+ fetch_base = fetch_base,+ transformer_resident_override_mib = seed_estimate.steady_transformer_mib,+ **self._candidate_companion_overrides(+ seed_estimate, fam, base, target, text_encoder_quant+ ),+ device_memory_override = device_memory_override,+ text_encoder_quant = text_encoder_quant,+ )++ def _seed_plan_stays_resident(+ self, scheme: str, target: Any, *args: Any, **kwargs: Any+ ) -> bool:+ """Whether the post-teardown seeded plan keeps ``scheme``, asked before teardown with this process's allocation+ credited as free (errs toward keeping the seed). Unanswerable keeps it."""+ try:+ memory = snapshot_device_memory(target)+ if getattr(target, "device", None) == "cuda" and memory.free_mib is not None:+ import torch++ free = int(memory.free_mib) + int(torch.cuda.memory_reserved()) // (1024 * 1024)+ if memory.total_mib is not None:+ free = min(free, int(memory.total_mib))+ memory = DeviceMemory(+ memory.backend, memory.device, memory.memory_kind, free, memory.total_mib+ )+ plan = self._seeded_pipeline_plan(+ scheme, target, *args, device_memory_override = memory, **kwargs+ )+ except Exception as exc: # noqa: BLE001 - a gate on an optional install must not fail the load+ logger.debug("diffusion.nvfp4_install: seed plan preview skipped: %r", exc)+ return True+ return plan is not None and plan.offload_policy == OFFLOAD_NONE+def _resident_sized_plan(self,plan: Any,@@ -8810,6 +8947,7 @@ class DiffusionBackend:"text_encoder_quant": None,"transformer_quant": None,"transformer_quant_backend": None,+ "transformer_quant_backend_reason": None,"attention_backend": None,"transformer_cache": None,"transformer_cache_stats": None,@@ -8847,7 +8985,7 @@ class DiffusionBackend:"speed_optims": speed_optims,"text_encoder_quant": state.text_encoder_quant,"transformer_quant": state.transformer_quant,- "transformer_quant_backend": _transformer_quant_backend(state),+ **_nvfp4_backend_fields(_transformer_quant_backend(state), owner = self),"attention_backend": state.attention_backend,"transformer_cache": state.transformer_cache,"transformer_cache_stats": static_skip_stats(state.pipe),diff --git a/studio/backend/core/inference/diffusion_nvfp4_dispatch.py b/studio/backend/core/inference/diffusion_nvfp4_dispatch.pyindex 230cf768df3..0221ad6fc59 100644--- a/studio/backend/core/inference/diffusion_nvfp4_dispatch.py+++ b/studio/backend/core/inference/diffusion_nvfp4_dispatch.py@@ -284,6 +284,13 @@ def _build_plan(key: tuple, device: Any, operands: list):return _GEMM_PLAN.setdefault(key, plan)+def forget_availability() -> None:+ """Re-probe on the next ``available()``."""+ global _AVAILABLE+ with _LOCK:+ _AVAILABLE = None++def reset() -> None:"""Called on unload: the transposed views would pin a freed model."""global _AVAILABLEdiff --git a/studio/backend/core/inference/diffusion_nvfp4_install.py b/studio/backend/core/inference/diffusion_nvfp4_install.pynew file mode 100644index 00000000000..a626dd25711--- /dev/null+++ b/studio/backend/core/inference/diffusion_nvfp4_install.py@@ -0,0 +1,1142 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Install FlashInfer on demand for an NVFP4 load, without ever moving the resident torch stack.++Pinned flashinfer-python plus the CUDA-matched jit-cache; every installed distribution is constrained to its+exact version, verified in a fresh interpreter, and rolled back on any drift.+"""++from __future__ import annotations++import ast+import contextlib+import importlib+import os+import shutil+import subprocess+import weakref+import sys+import tempfile+import threading+from typing import Any, Callable, Optional++# auto (default) / 1 installs flashinfer when an NVFP4 load needs it; 0 never installs.+FLASHINFER_INSTALL_ENV = "UNSLOTH_NVFP4_FLASHINFER_INSTALL"++# The version the dispatch allowlist and the op fakes were read against. Exact, never a floor.+FLASHINFER_VERSION = "0.6.6"+FLASHINFER_PACKAGE = "flashinfer-python"+FLASHINFER_JIT_CACHE_PACKAGE = "flashinfer-jit-cache"+FLASHINFER_CUBIN_PACKAGE = "flashinfer-cubin"+FLASHINFER_JIT_CACHE_INDEX = "https://flashinfer.ai/whl/{tag}"+FLASHINFER_JIT_CACHE_CUDA = ((12, 8), (12, 9), (13, 0))++# Short-timeout HEAD: a host with no route refuses in seconds, not minutes of pip retries.+_PYPI_PROBE_URL = "https://pypi.org/simple/flashinfer-python/"+_CUSTOM_INDEX_ENVS = ("UV_INDEX_URL", "UV_DEFAULT_INDEX", "PIP_INDEX_URL")+# uv ranks these above its default index and stops at the first that has a package; pip never reads them.+_UV_INDEX_ENVS = ("UV_INDEX", "UV_EXTRA_INDEX_URL", "UV_FIND_LINKS")+_PIP_EXTRA_INDEX_ENVS = ("PIP_EXTRA_INDEX_URL", "PIP_FIND_LINKS")++_INSTALL_TIMEOUT_S = 1800+_VERIFY_TIMEOUT_S = 300++_INSTALL_LOCK = threading.Lock()+# Outcome of this process's one install; policy refusals are not recorded, so a changed env can still install.+_OUTCOME: Optional[tuple[bool, str]] = None+_LAST_REASON: Optional[str] = None+# Per backend object, so each status route reports its own model's reason.+_REASONS: "weakref.WeakKeyDictionary[Any, Optional[str]]" = weakref.WeakKeyDictionary()++StatusCb = Optional[Callable[[str], None]]+++def install_env() -> str:+ raw = os.environ.get(FLASHINFER_INSTALL_ENV, "auto").strip().lower()+ return "0" if raw in ("0", "false", "no", "off") else "auto"+++def last_install_reason() -> Optional[str]:+ """Why flashinfer is not serving NVFP4 here, as the last ensure call saw it; None when it is."""+ return _LAST_REASON+++def _cached_preflight_failure(index: Optional[int] = None) -> Optional[str]:+ """A memoised failed preflight, without running one; ``index`` limits it to that device."""+ try:+ from . import diffusion_nvfp4_ops as ops+ with ops._PREFLIGHT_LOCK:+ records = (+ [ops._PREFLIGHT.get(index)] if index is not None else list(ops._PREFLIGHT.values())+ )+ except Exception: # noqa: BLE001+ return None+ for record in records:+ if isinstance(record, dict) and not record.get("ok"):+ return f"flashinfer preflight failed: {record.get('reason', 'unknown')}"+ # A transient (allocation) failure is not memoised, yet it may be what put the resident model on torchao.+ transient = (+ [ops._PREFLIGHT_TRANSIENT.get(index)]+ if index is not None+ else list(ops._PREFLIGHT_TRANSIENT.values())+ )+ for record in transient:+ if isinstance(record, dict):+ return f"flashinfer preflight failed: {record.get('reason', 'unknown')}"+ return None+++def _cuda_index(device: Any) -> Optional[int]:+ """The CUDA index a load targets, or None when it cannot be told without guessing."""+ if isinstance(device, int):+ return device+ try:+ import torch+ dev = torch.device(device) if device is not None else None+ except Exception: # noqa: BLE001+ return None+ if dev is None or dev.type != "cuda":+ return None+ if dev.index is not None:+ return int(dev.index)+ try:+ return int(torch.cuda.current_device())+ except Exception: # noqa: BLE001+ return None+++def record_install_reason(+ owner: Any,+ ok: bool,+ reason: Optional[str],+ device: Any = None,+) -> None:+ """Bind an ensure outcome to ``owner``; call after the swap so a cancelled load cannot relabel it."""+ if owner is None:+ return+ try:+ _REASONS[owner] = (None if ok else reason, _cuda_index(device))+ except TypeError: # not weak-referenceable: the process-wide reason stands in+ pass+++def nvfp4_backend_fields(backend: Optional[str], owner: Any = None) -> dict:+ """Status keys for a loaded NVFP4 denoiser: its backend and, on torchao, why flashinfer is not serving it."""+ reason = None+ from .diffusion_nvfp4_flag import nvfp4_diffusion_enabled++ if backend == "torchao" and nvfp4_diffusion_enabled():+ if owner is not None and owner in _REASONS:+ own, index = _REASONS[owner]+ reason = own or _cached_preflight_failure(index)+ else:+ reason = (_LAST_REASON if owner is None else None) or _cached_preflight_failure()+ return {"transformer_quant_backend": backend, "transformer_quant_backend_reason": reason}+++def reset_install_state() -> None:+ """Forget the per-process outcome. For tests."""+ global _OUTCOME, _LAST_REASON+ with _INSTALL_LOCK:+ _OUTCOME = None+ _LAST_REASON = None+ _REASONS.clear()+++def _emit(+ logger: Any,+ status_cb: StatusCb,+ message: str,+ *,+ warn: bool = False,+) -> None:+ if logger is not None:+ (logger.warning if warn else logger.info)("nvfp4.flashinfer: %s", message)+ if status_cb is not None:+ try:+ status_cb(message)+ except Exception: # noqa: BLE001 - status is best-effort; never fail a load over a UI message+ pass+++def _finish(+ ok: bool,+ reason: str,+ logger: Any,+ status_cb: StatusCb,+ *,+ warn: Optional[bool] = None,+) -> tuple[bool, str]:+ global _LAST_REASON+ _LAST_REASON = None if ok else reason+ _emit(logger, status_cb, reason, warn = (not ok) if warn is None else warn)+ return ok, reason+++ENV_LOCK_TIMEOUT_S = 900.0+++def _env_lock_path() -> str:+ """One lock file per environment: next to its site-packages when writable, else in the temp dir."""+ import hashlib++ name = ".unsloth-flashinfer-install.lock"+ if os.access(sys.prefix, os.W_OK):+ return os.path.join(sys.prefix, name)+ digest = hashlib.sha256(os.path.realpath(sys.prefix).encode()).hexdigest()[:16]+ return os.path.join(tempfile.gettempdir(), f"{name}.{digest}")+++def _env_install_lock(timeout: float = ENV_LOCK_TIMEOUT_S):+ """Hold the cross-process install lock; False on timeout, True unlocked when filelock is missing."""+ try:+ from filelock import FileLock, Timeout+ except ImportError:+ yield True+ return+ lock = FileLock(_env_lock_path())+ try:+ lock.acquire(timeout = timeout)+ except Timeout:+ yield False+ return+ try:+ yield True+ finally:+ lock.release()+++def _await_inflight_install(wait: bool = True) -> bool:+ """Wait out another process's flashinfer install here: importing mid-install misses the jit-cache for life.+ False when it outlived the wait; ``wait=False`` tries once."""+ if "flashinfer" in sys.modules:+ return True+ installed = _dist_version(FLASHINFER_PACKAGE)+ if installed is None or installed.split("+", 1)[0] != FLASHINFER_VERSION:+ return True+ with _env_install_lock() if wait else _env_install_lock(0) as held:+ return held+++def _import_flashinfer() -> tuple[bool, str]:+ from .diffusion_nvfp4_ops import _flashinfer_available+ importlib.invalidate_caches()+ return _flashinfer_available()+++def _dist_version(name: str) -> Optional[str]:+ from importlib.metadata import PackageNotFoundError, version+ try:+ return version(name)+ except PackageNotFoundError:+ return None+ except Exception: # noqa: BLE001 - unreadable metadata reads as absent+ return None+++def _canonical(name: str) -> str:+ return name.strip().lower().replace("_", "-").replace(".", "-")+++def installed_distributions() -> dict[str, str]:+ """``{canonical name: version}`` for every distribution this interpreter can see."""+ from importlib.metadata import distributions++ importlib.invalidate_caches()+ found: dict[str, str] = {}+ for dist in distributions():+ try:+ name = dist.metadata["Name"]+ version = dist.version+ except Exception: # noqa: BLE001 - a corrupt dist-info is skipped, not fatal+ continue+ if name and version:+ # The first entry on sys.path wins at import time, so it is the one to pin.+ found.setdefault(_canonical(name), str(version))+ return found+++def _host_refusal(device: Any) -> Optional[str]:+ """Why this host cannot run the flashinfer NVFP4 kernels at all, or None."""+ if not sys.platform.startswith("linux"):+ return f"flashinfer publishes Linux wheels only (this host is {sys.platform})"+ try:+ import torch+ except Exception as exc: # noqa: BLE001+ return f"torch is not importable ({type(exc).__name__})"+ if getattr(torch.version, "hip", None):+ return "flashinfer NVFP4 kernels are CUDA only (this torch is a ROCm build)"+ if not getattr(torch.version, "cuda", None):+ return "flashinfer NVFP4 kernels need a CUDA build of torch"+ from .diffusion_nvfp4_ops import NVFP4_FLASHINFER_CAPS, _device_capability++ capability = _device_capability(device)+ if capability is None:+ return "no CUDA device capability to check"+ if tuple(capability) not in NVFP4_FLASHINFER_CAPS:+ return "sm_%d%d is not in the flashinfer NVFP4 set %s" % (+ capability[0],+ capability[1],+ ", ".join(sorted("sm_%d%d" % c for c in NVFP4_FLASHINFER_CAPS)),+ )+ return None+++def _parse_cuda(version: Optional[str]) -> Optional[tuple[int, int]]:+ try:+ major, minor = str(version).split(".")[:2]+ return int(major), int(minor)+ except Exception: # noqa: BLE001+ return None+++def jit_cache_tag(cuda_version: Optional[str]) -> Optional[str]:+ """The ``cuXYZ`` jit-cache index: same major, newest minor <= running (minor compat only), or None."""+ running = _parse_cuda(cuda_version)+ if running is None:+ return None+ usable = [c for c in FLASHINFER_JIT_CACHE_CUDA if c[0] == running[0] and c[1] <= running[1]]+ if not usable:+ return None+ major, minor = max(usable)+ return f"cu{major}{minor}"+++def _jit_cache_version(tag: Optional[str]) -> Optional[str]:+ """The exact ``flashinfer-jit-cache`` version for a ``cuXYZ`` tag, local segment included."""+ return None if tag is None else f"{FLASHINFER_VERSION}+{tag}"+++def _same_version(a: Optional[str], b: Optional[str]) -> bool:+ if a is None or b is None:+ return False+ try:+ from packaging.version import Version+ return Version(a) == Version(b)+ except Exception: # noqa: BLE001+ return a.strip().lower() == b.strip().lower()+++def _nvcc_available() -> bool:+ """What flashinfer's JIT would find: CUDA_HOME first, then PATH, then the default toolkit."""+ for root in (os.environ.get("CUDA_HOME"), os.environ.get("CUDA_PATH")):+ if root and os.path.isfile(os.path.join(root, "bin", "nvcc")):+ return True+ return bool(shutil.which("nvcc")) or os.path.isfile("/usr/local/cuda/bin/nvcc")+++def _reachable(url: str) -> bool:+ """A HEAD answered; a failed TLS handshake still proves a route (the installer's trust settings decide TLS)."""+ import ssl+ import urllib.error+ import urllib.request++ try:+ with urllib.request.urlopen(urllib.request.Request(url, method = "HEAD"), timeout = 10):+ return True+ except urllib.error.HTTPError:+ return False+ except urllib.error.URLError as exc:+ return isinstance(exc.reason, ssl.SSLError)+ except Exception: # noqa: BLE001 - an unanswerable probe means no network+ return False+++def _torch_probe(timeout: int = 60) -> Optional[dict]:+ """The resident torch as a FRESH interpreter sees it; the running one would never show drift."""+ try:+ from utils.wheel_utils import probe_torch_wheel_env+ return probe_torch_wheel_env(timeout = timeout)+ except Exception: # noqa: BLE001+ return None+++def _uv_executable() -> Optional[str]:+ try:+ from utils.mlx_repair import _uv_executable as find_uv+ return find_uv()+ except Exception: # noqa: BLE001+ return shutil.which("uv")+++def _child_env() -> dict[str, str]:+ try:+ from utils.child_stdio import utf8_child_env+ from utils.native_path_leases import child_env_without_native_path_secret+ return utf8_child_env(child_env_without_native_path_secret())+ except Exception: # noqa: BLE001+ env = dict(os.environ)+ env["PYTHONIOENCODING"] = "utf-8"+ return env+++_TRUE = ("1", "y", "yes", "t", "true", "on")+_FALSE = ("0", "n", "no", "f", "false", "off")+++def _flag(value: Any) -> Optional[bool]:+ """A pip / uv boolean setting; None when unset or unreadable."""+ if isinstance(value, bool):+ return value+ text = str(value if value is not None else "").strip().lower()+ return True if text in _TRUE else False if text in _FALSE else None+++def _pip_settings(run: Callable[..., Any]) -> dict[str, str]:+ """pip's effective ``install`` options (env over ``[install]`` over ``[global]``); empty when pip cannot answer."""+ try:+ result = run(+ [sys.executable, "-m", "pip", "config", "list"],+ stdout = subprocess.PIPE,+ stderr = subprocess.DEVNULL,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ timeout = 60,+ env = _child_env(),+ )+ except Exception: # noqa: BLE001+ return {}+ if getattr(result, "returncode", 1) != 0:+ return {}+ layers: dict[str, dict[str, str]] = {"global": {}, "install": {}, ":env:": {}}+ for line in str(getattr(result, "stdout", "") or "").splitlines():+ key, sep, raw = line.partition("=")+ section, dot, name = key.strip().partition(".")+ if not sep or not dot or section not in layers:+ continue+ try:+ value = ast.literal_eval(raw.strip())+ except Exception: # noqa: BLE001+ value = raw.strip()+ layers[section][name.strip().lower().replace("_", "-")] = str(value)+ merged: dict[str, str] = {}+ for section in ("global", "install", ":env:"):+ merged.update(layers[section])+ return merged+++class _Unreadable(Exception):+ pass+++def _uv_config_tables() -> Optional[list[tuple[dict, dict]]]:+ """``(top level, [pip])`` per uv config file ``uv pip install`` reads, highest priority first; None if unparseable."""+ explicit = (os.environ.get("UV_CONFIG_FILE") or "").strip()+ if not explicit and _flag(os.environ.get("UV_NO_CONFIG")):+ return []+ try:+ # novermin -- 3.11; the tomli / None fallback below is the guard, which vermin cannot see.+ import tomllib # novermin+ except ImportError:+ try:+ import tomli as tomllib # type: ignore[no-redef]+ except ImportError:+ tomllib = None++ def _load(path: str, pyproject: bool = False) -> Optional[dict]:+ if not os.path.isfile(path):+ return None+ if tomllib is None:+ raise _Unreadable(path)+ try:+ with open(path, "rb") as fh:+ data = tomllib.load(fh)+ except Exception as exc: # noqa: BLE001+ raise _Unreadable(path) from exc+ if pyproject:+ data = (data.get("tool") or {}).get("uv")+ return data if isinstance(data, dict) else None++ found: list[Optional[dict]] = []+ try:+ if explicit:+ found.append(_load(explicit))+ else:+ try:+ directory = os.getcwd()+ except OSError:+ directory = ""+ while directory:+ if os.path.isfile(os.path.join(directory, "uv.toml")):+ found.append(_load(os.path.join(directory, "uv.toml")))+ break+ # A pyproject.toml without [tool.uv] does not stop the search, as in uv.+ project = _load(os.path.join(directory, "pyproject.toml"), pyproject = True)+ if project is not None:+ found.append(project)+ break+ parent = os.path.dirname(directory)+ directory = "" if parent == directory else parent+ home = os.environ.get("XDG_CONFIG_HOME") or ""+ if not os.path.isabs(home):+ home = os.path.join(os.path.expanduser("~"), ".config")+ found.append(_load(os.path.join(home, "uv", "uv.toml")))+ system = "/etc/uv/uv.toml"+ for root in (os.environ.get("XDG_CONFIG_DIRS") or "/etc/xdg").split(":"):+ if not root:+ break+ if os.path.isfile(os.path.join(root, "uv", "uv.toml")):+ system = os.path.join(root, "uv", "uv.toml")+ break+ found.append(_load(system))+ except _Unreadable:+ return None+ tables = []+ for data in found:+ if data is not None:+ pip = data.get("pip")+ tables.append((data, pip if isinstance(pip, dict) else {}))+ return tables+++_CONFIG_INDEX_KEYS = ("index", "index-url", "extra-index-url", "find-links")+++def _installer_config(uv: Optional[str], run: Callable[..., Any]) -> dict[str, Any]:+ """Installer config beyond our flags (env + files): ``refusal`` an unhonorable setting, ``mirror`` pypi.org may+ not be the index, ``own_index`` a default index of its own, ``unprobed`` a proxy the probe would not use."""+ config: dict[str, Any] = {+ "refusal": None,+ "mirror": False,+ "own_index": False,+ "unprobed": False,+ }+ if os.environ.get("ALL_PROXY", os.environ.get("all_proxy")) and not (+ os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy")+ ):+ # uv and pip route through ALL_PROXY; urllib ignores it.+ config["unprobed"] = True+ if uv:+ config["mirror"] = any(os.environ.get(v) for v in _CUSTOM_INDEX_ENVS + _UV_INDEX_ENVS)+ tables = _uv_config_tables()+ if tables is None:+ # A config file this interpreter cannot read may name a mirror; the installer decides, not pypi.org.+ config["mirror"] = True+ return config++ def _first(key: str) -> Any:+ for section in (1, 0):+ for table in tables:+ if key in table[section]:+ return table[section][key]+ return None++ def _default(entry: Any) -> bool:+ return isinstance(entry, dict) and bool(entry.get("default"))++ for top, pip in tables:+ for table in (top, pip):+ if any(table.get(k) for k in _CONFIG_INDEX_KEYS):+ config["mirror"] = True+ entries = table.get("index")+ if table.get("index-url") or (+ isinstance(entries, list) and any(_default(i) for i in entries)+ ):+ config["own_index"] = True+ offline = _flag(os.environ.get("UV_OFFLINE"))+ checks = (+ (_flag(_first("offline")) if offline is None else offline, "uv is configured offline"),+ (_flag(_first("no-index")), "uv is configured with no-index"),+ (+ _flag(_first("no-deps")),+ "uv is configured with no-deps, and flashinfer needs its dependencies",+ ),+ (+ _first("target"),+ "uv is configured to install into a target directory, not this environment",+ ),+ (_first("prefix"), "uv is configured to install into a prefix, not this environment"),+ # A same-version replacement is invisible to the version-only drift check, so it cannot be rolled back.+ (+ _flag(_first("reinstall")) or _first("reinstall-package"),+ "uv is configured to reinstall packages, which could replace installed ones unchecked",+ ),+ )+ config["refusal"] = next((why for hit, why in checks if hit), None)+ return config++ settings = _pip_settings(run)+ config["pip_settings"] = settings+ # pip still installs from an extra index or find-links when pypi.org is unreachable.+ config["mirror"] = any(+ os.environ.get(v) for v in _CUSTOM_INDEX_ENVS + _PIP_EXTRA_INDEX_ENVS+ ) or any(settings.get(k) for k in ("index-url", "extra-index-url", "find-links"))+ config["own_index"] = bool(settings.get("index-url"))+ if settings.get("proxy"):+ config["unprobed"] = True+ in_venv = sys.prefix != getattr(sys, "base_prefix", sys.prefix)+ checks = (+ (_flag(settings.get("no-index")), "pip is configured with no-index"),+ (+ _flag(settings.get("no-deps")),+ "pip is configured with no-deps, and flashinfer needs its dependencies",+ ),+ (+ settings.get("target"),+ "pip is configured to install into a target directory, not this environment",+ ),+ (+ settings.get("prefix"),+ "pip is configured to install into a prefix, not this environment",+ ),+ (+ settings.get("root"),+ "pip is configured to install under another root, not this environment",+ ),+ (+ _flag(settings.get("force-reinstall")) or _flag(settings.get("ignore-installed")),+ "pip is configured to force-reinstall or ignore installed packages, which could replace them unchecked",+ ),+ (+ _flag(settings.get("require-virtualenv")) and not in_venv,+ "pip requires a virtualenv and this interpreter is not in one",+ ),+ )+ config["refusal"] = next((why for hit, why in checks if hit), None)+ return config+++def _installer_prefix(+ uv: Optional[str],+ index_url: Optional[str] = None,+ *,+ own_index: bool = False,+) -> list[str]:+ """The install command up to its packages; ``index_url`` replaces any mirror (uv refuses a repeated --index-url)."""+ if uv:+ cmd = [uv, "pip", "install", "--python", sys.executable]+ # uv ignores pip-only mirrors (and pip uv's, below); the preflight skipped pypi.org because one is configured.+ pip_index = (os.environ.get("PIP_INDEX_URL") or "").strip()+ if (+ index_url is None+ and pip_index+ and not own_index+ and not (os.environ.get("UV_INDEX_URL") or os.environ.get("UV_DEFAULT_INDEX"))+ ):+ cmd += ["--index-url", pip_index]+ else:+ cmd = [sys.executable, "-m", "pip", "install", "--disable-pip-version-check"]+ uv_index = (+ os.environ.get("UV_DEFAULT_INDEX") or os.environ.get("UV_INDEX_URL") or ""+ ).strip()+ if (+ index_url is None+ and uv_index+ and not own_index+ and not (os.environ.get("PIP_INDEX_URL") or "").strip()+ ):+ cmd += ["--index-url", uv_index]+ if index_url is not None:+ cmd += ["--index-url", index_url]+ if uv:+ # --index outranks configured indexes; under uv's first-index strategy one listing jit-cache hides ours.+ cmd += ["--index", index_url]+ return cmd+++def _uninstall_cmd(uv: Optional[str], names: list[str]) -> list[str]:+ if uv:+ return [uv, "pip", "uninstall", "--python", sys.executable, *names]+ return [sys.executable, "-m", "pip", "uninstall", "-y", *names]+++def _pinnable(dists: dict[str, str]) -> dict[str, str]:+ """Distributions a constraints file can hold; non-PEP 440 versions are dropped so the file stays valid."""+ try:+ from packaging.version import InvalidVersion, Version+ except Exception: # noqa: BLE001+ return dict(dists)+ pins = {}+ for name, version in dists.items():+ try:+ Version(version)+ except InvalidVersion:+ continue+ pins[name] = version+ return pins+++def _write_constraints(pins: dict[str, str]) -> str:+ """Every installed distribution at its exact version (see ``_pinnable``)."""+ lines = [f"{name}=={version}\n" for name, version in sorted(_pinnable(pins).items())]+ fd, path = tempfile.mkstemp(prefix = "unsloth_flashinfer_", suffix = ".txt")+ with os.fdopen(fd, "w", encoding = "utf-8") as fh:+ fh.writelines(lines)+ try:+ from utils.uv_path_safety import uv_safe_path+ return uv_safe_path(path)+ except Exception: # noqa: BLE001+ return path+++# Env index sources the jit-cache step drops: under uv's first-index strategy they can hide the pinned index.+_INDEX_SOURCE_ENVS = (+ "UV_INDEX",+ "UV_EXTRA_INDEX_URL",+ "UV_FIND_LINKS",+ "UV_INDEX_URL",+ "UV_DEFAULT_INDEX",+ "PIP_INDEX_URL",+ "PIP_EXTRA_INDEX_URL",+ "PIP_FIND_LINKS",+)+++# pip transport settings (proxy, CA) the jit-cache step keeps once pip.conf is skipped.+_PIP_TRANSPORT_SETTINGS = ("proxy", "cert", "client-cert", "trusted-host", "timeout", "retries")+++def _pinned_index_env(pip_settings: Optional[dict[str, str]] = None) -> dict[str, str]:+ """The jit-cache step's env: pip.conf is skipped (its extra indexes could beat the pinned one) and the transport+ settings in ``pip_settings`` are re-exported."""+ env = _child_env()+ for name in _INDEX_SOURCE_ENVS:+ env.pop(name, None)+ if pip_settings is not None:+ env["PIP_CONFIG_FILE"] = os.devnull+ for key in _PIP_TRANSPORT_SETTINGS:+ name = "PIP_" + key.upper().replace("-", "_")+ value = pip_settings.get(key)+ if value and name not in env:+ env[name] = value+ return env+++def _run(+ run: Callable[..., Any],+ cmd: list[str],+ timeout: int,+ env: Optional[dict[str, str]] = None,+) -> tuple[bool, str]:+ try:+ result = run(+ cmd,+ stdout = subprocess.PIPE,+ stderr = subprocess.STDOUT,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ timeout = timeout,+ env = _child_env() if env is None else env,+ )+ except subprocess.TimeoutExpired:+ return False, f"timed out after {timeout}s"+ except Exception as exc: # noqa: BLE001+ return False, f"{type(exc).__name__}: {exc}"+ output = str(getattr(result, "stdout", "") or "")+ return getattr(result, "returncode", 1) == 0, output.strip()[-2000:]+++def _verify_child(run: Callable[..., Any]) -> tuple[bool, str]:+ """``import flashinfer`` in a fresh interpreter, which is where the next process will do it."""+ code = (+ "import flashinfer, sys; "+ "sys.stdout.write(str(getattr(flashinfer, '__version__', 'unknown')))"+ )+ ok, output = _run(run, [sys.executable, "-c", code], _VERIFY_TIMEOUT_S)+ if not ok:+ return False, f"import flashinfer failed after the install: {_quoted(output, 300)}"+ version = output.strip().splitlines()[-1] if output.strip() else ""+ if version != FLASHINFER_VERSION:+ return (+ False,+ f"flashinfer imported as {version or 'unknown'}, expected {FLASHINFER_VERSION}",+ )+ return True, version+++def _drift(before: dict[str, str], after: dict[str, str]) -> dict[str, tuple[str, Optional[str]]]:+ return {name: (old, after.get(name)) for name, old in before.items() if after.get(name) != old}+++def _reported_installs(output: str) -> set[str]:+ """Canonical names the installer says it installed: uv's `` + name==version`` lines, pip's+ ``Successfully installed name-version ...``."""+ names: set[str] = set()+ for line in output.splitlines():+ line = line.strip()+ if line.startswith("+ ") and "==" in line:+ names.add(_canonical(line[2:].split("==", 1)[0]))+ elif line.startswith("Successfully installed "):+ for item in line[len("Successfully installed ") :].split():+ if "-" in item:+ names.add(_canonical(item.rsplit("-", 1)[0]))+ return names+++def _requirement_closure(roots: set[str], candidates: set[str]) -> set[str]:+ """``roots`` plus installed dependencies within ``candidates``, for an install that reported nothing."""+ from importlib.metadata import distribution++ try:+ from packaging.requirements import Requirement+ except Exception: # noqa: BLE001+ Requirement = None+ found: set[str] = set()+ pending = [name for name in roots if name in candidates]+ while pending:+ name = pending.pop()+ if name in found:+ continue+ found.add(name)+ try:+ requires = distribution(name).requires or []+ except Exception: # noqa: BLE001 - absent or unreadable metadata adds nothing+ continue+ for spec in requires:+ try:+ if Requirement is None:+ continue+ req = Requirement(spec)+ if req.marker is not None and not req.marker.evaluate({"extra": ""}):+ continue+ except Exception: # noqa: BLE001+ continue+ dep = _canonical(req.name)+ if dep in candidates and dep not in found:+ pending.append(dep)+ return found+++def _quoted(output: str, limit: int) -> str:+ """Installer output for a reason or log line: index URLs can carry credentials the user must not see."""+ from utils.log_redaction import redact_log_text+ return redact_log_text(" ".join(str(output).split())[-limit:])+++def _rollback(+ run: Callable[..., Any],+ uv: Optional[str],+ before: dict[str, str],+ logger: Any,+ own_index: bool = False,+ reported: Optional[set[str]] = None,+ unreported_step: bool = False,+) -> str:+ """Remove what this install reported adding and restore what it moved; returns a one-line summary."""+ after = installed_distributions()+ new = set(after) - set(before)+ ours = set(reported or ()) & new+ if not ours or unreported_step:+ # A step that died without its summary may have half-installed what no report names.+ ours |= _requirement_closure({FLASHINFER_PACKAGE, FLASHINFER_JIT_CACHE_PACKAGE}, new)+ added = sorted(ours)+ if new - ours and logger is not None:+ logger.info(+ "nvfp4.flashinfer: rollback leaves %s (not installed by this transaction)",+ ", ".join(sorted(new - ours)),+ )+ moved = _drift(before, after)+ if reported and not unreported_step:+ # Revert only what our installer reported: concurrent changes by another installer are not ours.+ moved = {name: change for name, change in moved.items() if name in reported}+ elif unreported_step:+ # No report: constraints pinned everything, so only unpinnable packages can be ours.+ pinned = _pinnable(before)+ moved = {name: change for name, change in moved.items() if name not in pinned}+ notes = []+ if added:+ ok, output = _run(run, _uninstall_cmd(uv, added), _VERIFY_TIMEOUT_S)+ notes.append(f"{'removed' if ok else 'could not remove'} {len(added)} added package(s)")+ if logger is not None:+ logger.warning(+ "nvfp4.flashinfer: rollback %s %s%s",+ "removed" if ok else "could not remove",+ ", ".join(added),+ "" if ok else f": {_quoted(output, 500)}",+ )+ if moved:+ # --no-deps: restore exactly these, and nothing a resolver would pull back in.+ specs = [f"{name}=={old}" for name, (old, _new) in sorted(moved.items())]+ ok, output = _run(+ run,+ _installer_prefix(uv, own_index = own_index) + ["--no-deps", *specs],+ _INSTALL_TIMEOUT_S,+ )+ notes.append(("restored " if ok else "could not restore ") + ", ".join(specs))+ if not ok and logger is not None:+ logger.warning("nvfp4.flashinfer: rollback restore failed: %s", _quoted(output, 500))+ return "; ".join(notes) or "nothing to roll back"+++def _install(+ device: Any, logger: Any, status_cb: StatusCb, run: Callable[..., Any]+) -> tuple[bool, str, bool]:+ """The install itself, called under ``_INSTALL_LOCK``. ``(ok, reason, memoise)``."""+ torch_before = _torch_probe()+ if not torch_before or not torch_before.get("cuda_version"):+ # Transient on a loaded box (the probe has a timeout), so not memoised.+ return False, "flashinfer not installed: the resident torch could not be probed", False+ tag = jit_cache_tag(torch_before.get("cuda_version"))+ if tag is None and not _nvcc_available():+ return (+ False,+ f"flashinfer not installed: no prebuilt {FLASHINFER_JIT_CACHE_PACKAGE} "+ f"{FLASHINFER_VERSION} for CUDA {torch_before.get('cuda_version')} and no nvcc to "+ "JIT-compile its kernels",+ True,+ )+ # A stray jit-cache or cubin of another version breaks `import flashinfer`; not ours to replace.+ for extra in (FLASHINFER_JIT_CACHE_PACKAGE, FLASHINFER_CUBIN_PACKAGE):+ present = _dist_version(extra)+ if present is not None and present.split("+", 1)[0] != FLASHINFER_VERSION:+ return (+ False,+ f"flashinfer not installed: {extra} {present} is already installed and "+ f"flashinfer-python {FLASHINFER_VERSION} would refuse to import beside it",+ True,+ )+ # flashinfer checks only the public version, so a jit-cache for another CUDA would be kept; not ours to replace.+ cache = _dist_version(FLASHINFER_JIT_CACHE_PACKAGE)+ if cache is not None and not _same_version(cache, _jit_cache_version(tag)):+ return (+ False,+ f"flashinfer not installed: {FLASHINFER_JIT_CACHE_PACKAGE} {cache} is already installed and "+ f"does not match CUDA {torch_before.get('cuda_version')}"+ + (f" (expected {_jit_cache_version(tag)})" if tag else ""),+ True,+ )+ uv = _uv_executable()+ config = _installer_config(uv, run)+ if config["refusal"]:+ # Configuration, not a failure: not memoised, so a later load after it changes can still install.+ return False, f"flashinfer not installed: {config['refusal']}", False+ # A configured mirror is the installer's to reach; probe pypi.org only when it is the index (and not proxied).+ probes = [] if config["mirror"] else [_PYPI_PROBE_URL]+ if tag is not None:+ probes.append(+ FLASHINFER_JIT_CACHE_INDEX.format(tag = tag) + f"/{FLASHINFER_JIT_CACHE_PACKAGE}/"+ )+ if config["unprobed"]:+ probes = []+ for url in probes:+ if not _reachable(url):+ return False, f"flashinfer not installed: {url} is not reachable", False++ before = installed_distributions()+ constraints = _write_constraints(before)+ size_hint = " (about 1.5 GB of prebuilt kernels)" if tag else ""+ _emit(+ logger,+ status_cb,+ f"installing {FLASHINFER_PACKAGE} {FLASHINFER_VERSION}"+ f"{f' with {FLASHINFER_JIT_CACHE_PACKAGE} for {tag}' if tag else ''} for NVFP4{size_hint}",+ )+ reported: set[str] = set()+ try:+ steps = []+ # jit-cache FIRST: an interrupted install must not leave an importable flashinfer that reads as installed.+ if tag is not None:+ steps.append(+ (+ _installer_prefix(uv, FLASHINFER_JIT_CACHE_INDEX.format(tag = tag))+ + [+ "--only-binary",+ ":all:",+ "--no-deps",+ # The full local version: `==0.6.6` would accept a cache built for another CUDA.+ f"{FLASHINFER_JIT_CACHE_PACKAGE}=={_jit_cache_version(tag)}",+ ],+ _pinned_index_env(None if uv else config.get("pip_settings", {})),+ )+ )+ steps.append(+ # Constrained, not --no-deps: flashinfer needs apache-tvm-ffi; constraints keep everything present immovable.+ (+ _installer_prefix(uv, own_index = config["own_index"])+ + [+ "--only-binary",+ ":all:",+ "-c",+ constraints,+ f"{FLASHINFER_PACKAGE}=={FLASHINFER_VERSION}",+ ],+ None,+ )+ )+ failure = None+ unreported_step = False+ for cmd, step_env in steps:+ ok, output = _run(run, cmd, _INSTALL_TIMEOUT_S, step_env)+ step_reported = _reported_installs(output)+ reported |= step_reported+ if not ok:+ failure = "the installer failed: " + _quoted(output, 400)+ unreported_step = not step_reported+ break+ finally:+ try:+ os.unlink(constraints)+ except OSError:+ pass++ if failure is None:+ moved = _drift(before, installed_distributions())+ torch_after = _torch_probe()+ if moved:+ failure = "the install changed " + ", ".join(+ f"{name} {old} -> {new or 'removed'}" for name, (old, new) in sorted(moved.items())+ )+ elif not torch_after or (+ torch_after.get("torch_version"),+ torch_after.get("cuda_version"),+ ) != (torch_before.get("torch_version"), torch_before.get("cuda_version")):+ failure = "torch reads differently after the install (%s CUDA %s -> %s)" % (+ torch_before.get("torch_version"),+ torch_before.get("cuda_version"),+ "unreadable"+ if not torch_after+ else f"{torch_after.get('torch_version')} CUDA {torch_after.get('cuda_version')}",+ )+ else:+ ok, detail = _verify_child(run)+ if not ok:+ failure = detail++ if failure is not None:+ rolled = _rollback(+ run, uv, before, logger, config["own_index"], reported, unreported_step = unreported_step+ )+ return False, f"flashinfer install rolled back ({rolled}): {failure}", True++ # The dispatch fast path memoises "flashinfer missing"; forget it now that it is not.+ try:+ from . import diffusion_nvfp4_dispatch, diffusion_nvfp4_ops+ diffusion_nvfp4_dispatch.forget_availability()+ diffusion_nvfp4_ops.reset_preflight_cache()+ except Exception: # noqa: BLE001+ pass+ ok, detail = _import_flashinfer()+ if not ok:+ return False, f"flashinfer installed but does not import in this process ({detail})", True+ return True, f"installed flashinfer {detail} for NVFP4", True+++def ensure_flashinfer_for_nvfp4(+ device: Any = None,+ *,+ logger: Any = None,+ status_cb: StatusCb = None,+ run: Callable[..., Any] = subprocess.run,+ local_files_only: bool = False,+ owner: Any = None,+) -> tuple[bool, str]:+ """See ``_ensure``. ``owner`` keys the status reason (a cancellable loader passes none and calls+ ``record_install_reason`` after the swap). Switch off: returns at once, no import, lock, subprocess or network."""+ from .diffusion_nvfp4_flag import nvfp4_diffusion_enabled++ if not nvfp4_diffusion_enabled():+ return False, "NVFP4 is disabled in this build"+ ok, reason = _ensure(+ device, logger = logger, status_cb = status_cb, run = run, local_files_only = local_files_only+ )+ record_install_reason(owner, ok, reason, device)+ return ok, reason+++def _ensure(+ device: Any = None,+ *,+ logger: Any = None,+ status_cb: StatusCb = None,+ run: Callable[..., Any] = subprocess.run,+ local_files_only: bool = False,+) -> tuple[bool, str]:+ """Make ``import flashinfer`` work for an NVFP4 load on ``device``. ``(ok, reason)``; never raises; False leaves+ ``select_nvfp4_backend`` on torchao."""+ global _OUTCOME+ try:+ from .diffusion_nvfp4_ops import BACKEND_TORCHAO, nvfp4_backend_env++ if nvfp4_backend_env() == BACKEND_TORCHAO:+ return _finish(False, "UNSLOTH_NVFP4_BACKEND=torchao", None, None)+ # A load that may not install checks the lock once instead of waiting behind another process's download.+ declined = (+ "local-only load"+ if local_files_only+ else f"{FLASHINFER_INSTALL_ENV}=0"+ if install_env() == "0"+ else None+ )+ if not _await_inflight_install(wait = declined is None):+ # Not memoised: a later load imports once that install has finished.+ return _finish(+ False,+ "flashinfer not ready: another process is still installing it into this environment"+ + (f" ({declined}: not waiting for it)" if declined else ""),+ logger,+ status_cb,+ )+ present, detail = _import_flashinfer()+ if present:+ return _finish(True, f"flashinfer {detail} already installed", None, None)+ installed = _dist_version(FLASHINFER_PACKAGE)+ if installed is not None:+ # Present but broken is not repaired: the user may have built or pinned it.+ return _finish(+ False,+ f"flashinfer-python {installed} is installed but does not import ({detail})",+ logger,+ status_cb,+ )+ if local_files_only:+ return _finish(+ False, "local-only load: flashinfer is not downloaded", logger, status_cb+ )+ if install_env() == "0":+ return _finish(+ False,+ f"flashinfer is not installed and {FLASHINFER_INSTALL_ENV}=0",+ logger,+ status_cb,+ warn = False,+ )+ refusal = _host_refusal(device)+ if refusal is not None:+ return _finish(False, f"flashinfer not installed: {refusal}", logger, None, warn = False)+ cached = _OUTCOME+ if cached is not None:+ return _finish(cached[0], cached[1], None, None)+ from utils.utils import hf_env_offline++ # UV_OFFLINE too: the install probes PyPI and the flashinfer index before uv ever runs.+ if hf_env_offline() or os.environ.get("UV_OFFLINE", "").strip().lower() in (+ "1",+ "true",+ "yes",+ "on",+ ):+ return _finish(+ False,+ "flashinfer is not installed and Unsloth is in offline mode",+ logger,+ status_cb,+ )+ with _INSTALL_LOCK:+ # A concurrent load may have installed it while this one waited.+ if _OUTCOME is not None:+ return _finish(_OUTCOME[0], _OUTCOME[1], None, None)+ # The rollback diffs a snapshot, so also exclude other Studio processes installing here.+ with _env_install_lock() as held:+ if not held:+ return _finish(+ False,+ "flashinfer not installed: another process is installing into this "+ "environment",+ logger,+ status_cb,+ )+ present, detail = _import_flashinfer()+ if present:+ return _finish(True, f"flashinfer {detail} already installed", None, None)+ ok, reason, memoise = _install(device, logger, status_cb, run)+ if memoise:+ _OUTCOME = (ok, reason)+ return _finish(ok, reason, logger, status_cb)+ except Exception as exc: # noqa: BLE001 - an install helper must never break a model load+ return _finish(+ False, f"flashinfer install skipped ({type(exc).__name__}: {exc})", logger, None+ )diff --git a/studio/backend/core/inference/diffusion_nvfp4_ops.py b/studio/backend/core/inference/diffusion_nvfp4_ops.pyindex 3e4e65a46f2..a36d78bb98f 100644--- a/studio/backend/core/inference/diffusion_nvfp4_ops.py+++ b/studio/backend/core/inference/diffusion_nvfp4_ops.py@@ -34,6 +34,8 @@ _REGISTER_LOCK = threading.Lock()_REGISTERED = False_PREFLIGHT_LOCK = threading.Lock()_PREFLIGHT: dict[int, dict] = {}+# Last transient preflight failure per device index: reporting only, never used to pick a backend.+_PREFLIGHT_TRANSIENT: dict[int, dict] = {}_WARNED: set = set()_BARRIER_LOCK = threading.Lock()@@ -366,6 +368,7 @@ def nvfp4_preflight(device: Any = None, *, refresh: bool = False) -> dict:}with _PREFLIGHT_LOCK:_PREFLIGHT[index] = rec+ _PREFLIGHT_TRANSIENT.pop(index, None)return dict(rec)rec = {"ok": False, "reason": "", "capability": capability, "name": name}@@ -382,10 +385,14 @@ def nvfp4_preflight(device: Any = None, *, refresh: bool = False) -> dict:except Exception as exc: # noqa: BLE001 - every failure mode here means "use torchao"rec["reason"] = f"{type(exc).__name__}: {str(exc)[:200]}"if _transient_preflight_failure(exc):+ # Not memoised: a model about to be evicted may own the card, so OOM means "not now".+ with _PREFLIGHT_LOCK:+ _PREFLIGHT_TRANSIENT[index] = dict(rec)return dict(rec)with _PREFLIGHT_LOCK:_PREFLIGHT[index] = rec+ _PREFLIGHT_TRANSIENT.pop(index, None)return dict(rec)@@ -430,6 +437,7 @@ def _transient_preflight_failure(exc: BaseException) -> bool:def reset_preflight_cache() -> None:with _PREFLIGHT_LOCK:_PREFLIGHT.clear()+ _PREFLIGHT_TRANSIENT.clear()_WARNED.clear()diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex cbdbce4b578..9f7965f18e9 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -119,6 +119,8 @@ from .diffusion_auto_policy import (precision_fallback_allowed,precision_refusal_message,)+from .diffusion_nvfp4_flag import nvfp4_diffusion_enabled+from .diffusion_nvfp4_install import nvfp4_backend_fields as _nvfp4_backend_fieldsfrom .diffusion_transformer_quant import (TQ_AUTO,TQ_INT8,@@ -2948,6 +2950,65 @@ class VideoBackend:)return repo is not None+ @staticmethod+ def _install_flashinfer_for_seed(+ wanted: bool,+ seed_scheme: Optional[str],+ device: Any,+ *,+ local_files_only: bool = False,+ ) -> Optional[tuple[bool, str]]:+ """FlashInfer install for a conventional load, only when the settled plan kept the NVFP4 seed."""+ if not wanted or seed_scheme != "nvfp4":+ return None+ from .diffusion_nvfp4_install import ensure_flashinfer_for_nvfp4++ return ensure_flashinfer_for_nvfp4(device, logger = logger, local_files_only = local_files_only)++ def _nvfp4_denoiser_checkpoint_will_load(+ self,+ fam: Any,+ base: Optional[str],+ h3_task: Optional[str],+ hf_token: Optional[str],+ *,+ local_files_only: bool = False,+ kind: str = "pipeline",+ planned: Optional[str] = None,+ ) -> bool:+ """Whether an NVFP4 video load opens hosted pre-quantised denoisers (the only FlashInfer path); unanswerable -> False."""+ if not nvfp4_diffusion_enabled():+ return False+ try:+ modular = bool(getattr(fam, "modular_workflow", None))+ if planned == DENOISER_SEED_DECLINED and not modular:+ return False+ task = (h3_task or getattr(fam, "modular_workflow", None)) if modular else h3_task+ if not self._denoiser_prequant_covered(fam, "nvfp4", base, task, kind = kind):+ return False+ from .diffusion_prequant import restricted_prequant_load_supported++ if not restricted_prequant_load_supported("nvfp4"):+ return False+ if self._denoiser_prequant_cached_repo(fam, "nvfp4", base, task) is not None:+ return True+ if local_files_only:+ return False+ from huggingface_hub import HfApi++ repo, _files = self._denoiser_prequant_hub_files(+ fam, "nvfp4", base, HfApi(token = hf_token or None), task+ )+ return repo is not None+ except Exception as exc: # noqa: BLE001 -- a refused or unreachable listing is no checkpoint+ logger.info(+ "video.nvfp4_install: no reachable NVFP4 checkpoint for %s, so the load runs on "+ "torchao and FlashInfer is not installed (%s)",+ base,+ type(exc).__name__,+ )+ return False+def _h3_planned_auto_denoiser_scheme(self,fam: Any,@@ -4417,6 +4478,31 @@ class VideoBackend:target = self._device_target(gpu_ordinal)device = target.device+ # FlashInfer only serves hosted pre-quantised denoisers. Modular H3 installs below; a conventional load installs+ # after its live-memory plan keeps the seed (a capacity-settled seed can still be dropped).+ _nvfp4_install_wanted = (+ kind == "pipeline"+ and nvfp4_diffusion_enabled()+ and "nvfp4"+ in (+ normalize_transformer_quant(transformer_quant),+ _video_auto_denoiser_planned,+ )+ and (+ _video_auto_denoiser_planned == "nvfp4"+ or self._nvfp4_denoiser_checkpoint_will_load(+ fam,+ base,+ h3_task,+ hf_token,+ local_files_only = local_files_only,+ kind = kind,+ planned = _video_auto_denoiser_planned,+ )+ )+ )+ # Bound only at the commit past the token check: a superseded load may return from the install late.+ _nvfp4_install_outcome: Optional[tuple[bool, str]] = None# Video DiTs are bf16-native; fp16 overflows, so a resolved fp16 promotes to float32.dtype = target.dtypeif fam.fp16_incompatible and dtype is torch.float16:@@ -4425,6 +4511,11 @@ class VideoBackend:dtype_scale = 2.0 if device != "cpu" and dtype is torch.float32 else 1.0if fam.modular_workflow:+ if _nvfp4_install_wanted:+ from .diffusion_nvfp4_install import ensure_flashinfer_for_nvfp4+ _nvfp4_install_outcome = ensure_flashinfer_for_nvfp4(+ device, logger = logger, local_files_only = local_files_only+ )return self._load_h3_modular_pipeline(diffusers = diffusers,torch = torch,@@ -4449,6 +4540,7 @@ class VideoBackend:_base_local_dir = _base_local_dir,# Settled before the pull when the pull acted on it; None when it did not._h3_auto_denoiser_planned = _h3_auto_denoiser_planned,+ _nvfp4_install_outcome = _nvfp4_install_outcome,transformer_cache = transformer_cache,)@@ -4688,6 +4780,9 @@ class VideoBackend:denoiser_seed_scheme = Nonedenoiser_seed_gb = Noneplan, bf16_plan, quant_replanned = _plan_for_te_scale(settled_te_scale, log = False)+ _nvfp4_install_outcome = self._install_flashinfer_for_seed(+ _nvfp4_install_wanted, denoiser_seed_scheme, device, local_files_only = local_files_only+ )denoiser_injected: dict[str, Any] = {}if denoiser_seed_scheme is not None:from .video_denoiser_prequant import denoiser_prequant_pipe_kwargs@@ -5278,6 +5373,9 @@ class VideoBackend:del pipeclear_gpu_cache()raise RuntimeError("Video load was cancelled or superseded.")+ from .diffusion_nvfp4_install import record_install_reason++ record_install_reason(self, *(_nvfp4_install_outcome or (True, None)), device)self._state = _VideoLoadState(pipe = pipe,family = fam,@@ -5395,6 +5493,7 @@ class VideoBackend:_load_token: Optional[int] = None,_base_local_dir: Optional[str] = None,_h3_auto_denoiser_planned: Optional[str] = None,+ _nvfp4_install_outcome: Optional[tuple[bool, str]] = None,local_files_only: bool = False,transformer_cache: Optional[str] = None,) -> dict[str, Any]:@@ -6049,6 +6148,9 @@ class VideoBackend:del pipeclear_gpu_cache()raise RuntimeError("Video load was cancelled or superseded.")+ from .diffusion_nvfp4_install import record_install_reason++ record_install_reason(self, *(_nvfp4_install_outcome or (True, None)), device)self._state = _VideoLoadState(pipe = pipe,family = fam,@@ -7696,6 +7798,7 @@ class VideoBackend:"transformer_cache_stats": None,"transformer_quant": None,"transformer_quant_backend": None,+ "transformer_quant_backend_reason": None,"text_encoder_quant": None,"has_audio": False,"supports_cfg": True,@@ -7747,7 +7850,7 @@ class VideoBackend:static_skip_stats(state.pipe) if state.transformer_cache == TC_STATIC else None),"transformer_quant": state.transformer_quant,- "transformer_quant_backend": _video_transformer_quant_backend(state),+ **_nvfp4_backend_fields(_video_transformer_quant_backend(state), owner = self),"text_encoder_quant": state.text_encoder_quant,"has_audio": fam.has_audio,"supports_cfg": fam.supports_cfg,diff --git a/studio/backend/hub/utils/host_paths.py b/studio/backend/hub/utils/host_paths.pyindex eb356990bfe..7f37ece7042 100644--- a/studio/backend/hub/utils/host_paths.py+++ b/studio/backend/hub/utils/host_paths.py@@ -53,7 +53,9 @@ HOST_PATH_HANDLE_FIELDS = frozenset()# Scrubbed, not blanked: the only account of WHY a run failed.-HOST_PATH_TEXT_FIELDS = frozenset({"error_message", "error", "detail", "message"})+HOST_PATH_TEXT_FIELDS = frozenset(+ {"error_message", "error", "detail", "message", "transformer_quant_backend_reason"}+)# The same text, one per entry. A run's warnings quote the file they are about ("missing# <path>/tokenizer.json"), and the singular fields above do not reach a list.diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 69a1782afc0..5c68f364a8d 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -4519,6 +4519,12 @@ class DiffusionStatusResponse(BaseModel):"flashinfer is selected per device and falls back to torchao on a preflight failure, so ""this is the only place a render's speed can be attributed to the backend that served it.",)+ transformer_quant_backend_reason: Optional[str] = Field(+ None,+ description = "Why flashinfer is not serving an NVFP4 load that runs torchao: the on-demand "+ "install was refused (offline, opt-out, ineligible host) or failed and was rolled back. "+ "null when the backend is flashinfer, the scheme is not nvfp4, or no reason was recorded.",+ )attention_backend: Optional[str] = Field(None,description = "Attention backend engaged via the diffusers dispatcher (e.g. "@@ -5362,6 +5368,12 @@ class VideoStatusResponse(BaseModel):description = "Which NVFP4 kernel path the loaded DiT(s) run: flashinfer | torchao | null ""(null for every scheme but nvfp4).",)+ transformer_quant_backend_reason: Optional[str] = Field(+ None,+ description = "Why flashinfer is not serving an NVFP4 load that runs torchao: the on-demand "+ "install was refused (offline, opt-out, ineligible host) or failed and was rolled back. "+ "null when the backend is flashinfer, the scheme is not nvfp4, or no reason was recorded.",+ )text_encoder_quant: Optional[str] = Field(None,description = "Text-encoder quant engaged: fp8 | fp8_dynamic | int8 | nvfp4 | null "diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 2a02c35e608..07017bce540 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -12495,6 +12495,224 @@ def test_a_prequant_repo_missing_its_artifact_marks_the_plan_incomplete(monkeypaassert "prequant artifact missing" in str(failures[0])+class _StopAfterInstallGate(Exception):+ """Raised just past the FlashInfer pre-install hop."""+++def _hub_refusal(cls):+ # response is optional in huggingface_hub 0.x but required in 1.x; a stub works on either.+ return cls(+ "401 Client Error. Repository Not Found for url: "+ "https://huggingface.co/api/models/unsloth/Z-Image-Turbo-NVFP4",+ response = types.SimpleNamespace(headers = {}, request = None),+ )+++def _nvfp4_install_probe(+ monkeypatch,+ *,+ listing = None,+ refusal = None,+ cached = False,+):+ """Record FlashInfer installs and Hub listings; ``refusal`` is raised instead of ``listing``."""+ import core.inference.diffusion as diffusion_mod+ import core.inference.diffusion_prequant as prequant_mod+ from core.inference import diffusion_nvfp4_install as inst++ installs: list = []+ listed: list = []++ def _ensure(device, **kwargs):+ installs.append((device, kwargs.get("local_files_only")))+ return True, "installed flashinfer for NVFP4"++ class _Api:+ def model_info(+ self,+ repo_id,+ files_metadata = False,+ token = None,+ ):+ listed.append(repo_id)+ if refusal is not None:+ raise refusal+ return _FakeInfo(list(listing or []))++ monkeypatch.setattr(inst, "ensure_flashinfer_for_nvfp4", _ensure)+ monkeypatch.setattr("huggingface_hub.HfApi", lambda *a, **k: _Api())+ monkeypatch.setattr(+ prequant_mod, "restricted_prequant_load_supported", lambda scheme = None, filename = None: True+ )+ monkeypatch.setattr(diffusion_mod, "prequant_checkpoint_cached", lambda *a, **k: cached)+ monkeypatch.setattr(+ DiffusionBackend,+ "_target_for_ordinal",+ lambda self, fam, ordinal: types.SimpleNamespace(device = "cuda", dtype = None, ordinal = 0),+ )+ monkeypatch.setattr(diffusion_mod, "apply_diffusion_device_ordinal", lambda target: None)+ monkeypatch.setattr(diffusion_mod, "select_attention_backend", lambda *a, **k: None)++ def _stop(self):+ raise _StopAfterInstallGate()++ monkeypatch.setattr(DiffusionBackend, "_reserve_teardown_locked", _stop)+ return installs, listed+++def _load_to_the_install_gate(+ repo_id = "Tongyi-MAI/Z-Image-Turbo",+ family = "z-image",+ **overrides,+):+ kwargs = dict(+ model_kind = "pipeline",+ family_override = family,+ transformer_quant = "nvfp4",+ _fetch_base = repo_id,+ )+ kwargs.update(overrides)+ with pytest.raises(_StopAfterInstallGate):+ DiffusionBackend().load_pipeline(repo_id, **kwargs)++[email protected]("error", ["RepositoryNotFoundError", "GatedRepoError"])+def test_an_nvfp4_checkpoint_the_hub_refuses_installs_no_flashinfer(+ fake_runtime, monkeypatch, error+):+ # Private / gated repo: on-the-fly torchao build, FlashInfer unused.+ import huggingface_hub.errors as hub_errors++ installs, listed = _nvfp4_install_probe(+ monkeypatch, refusal = _hub_refusal(getattr(hub_errors, error))+ )+ _load_to_the_install_gate()+ assert installs == []+ assert listed == ["unsloth/Z-Image-Turbo-NVFP4"]+++def test_an_nvfp4_repo_missing_the_checkpoint_installs_no_flashinfer(fake_runtime, monkeypatch):+ installs, listed = _nvfp4_install_probe(monkeypatch, listing = [_FakeSibling("README.md", 10)])+ _load_to_the_install_gate()+ assert installs == []+ assert listed == ["unsloth/Z-Image-Turbo-NVFP4"]+++def test_a_family_with_no_hosted_nvfp4_checkpoint_installs_no_flashinfer(fake_runtime, monkeypatch):+ installs, listed = _nvfp4_install_probe(monkeypatch)+ _load_to_the_install_gate("Qwen/Qwen-Image", family = "qwen-image")+ assert installs == []+ assert listed == [], "nothing hosted, so there is nothing to ask the Hub about"+++def test_a_gguf_nvfp4_load_whose_checkpoint_the_hub_refuses_installs_no_flashinfer(+ fake_runtime, monkeypatch, tmp_path+):+ from huggingface_hub.errors import RepositoryNotFoundError++ installs, listed = _nvfp4_install_probe(+ monkeypatch, refusal = _hub_refusal(RepositoryNotFoundError)+ )+ (tmp_path / "model.gguf").write_bytes(b"weights")+ with pytest.raises(_StopAfterInstallGate):+ DiffusionBackend().load_pipeline(+ str(tmp_path),+ gguf_filename = "model.gguf",+ base_repo = "Tongyi-MAI/Z-Image-Turbo",+ family_override = "z-image",+ transformer_quant = "nvfp4",+ _fetch_base = "Tongyi-MAI/Z-Image-Turbo",+ )+ assert installs == []+ assert listed == ["unsloth/Z-Image-Turbo-NVFP4"]+++def test_a_reachable_nvfp4_checkpoint_still_installs_flashinfer(fake_runtime, monkeypatch):+ installs, listed = _nvfp4_install_probe(+ monkeypatch, listing = [_FakeSibling("Z-Image-Turbo-NVFP4.safetensors", 6 * GB)]+ )+ _load_to_the_install_gate()+ assert listed == ["unsloth/Z-Image-Turbo-NVFP4"]+ assert installs == [("cuda", False)]+++def test_with_the_nvfp4_switch_off_a_reachable_checkpoint_installs_nothing(+ fake_runtime, monkeypatch+):+ # conftest sets UNSLOTH_NVFP4_DIFFUSION=1; unset for the shipped default.+ monkeypatch.delenv("UNSLOTH_NVFP4_DIFFUSION", raising = False)+ installs, listed = _nvfp4_install_probe(+ monkeypatch, listing = [_FakeSibling("Z-Image-Turbo-NVFP4.safetensors", 6 * GB)]+ )+ _load_to_the_install_gate(transformer_quant = None, _pipeline_prequant_planned = "nvfp4")+ assert installs == []+ assert listed == [], "no Hub request to a *-NVFP4 repo while the switch is off"+ with pytest.raises(ValueError, match = "NVFP4 is disabled in this build"):+ DiffusionBackend().load_pipeline(+ "Tongyi-MAI/Z-Image-Turbo",+ model_kind = "pipeline",+ family_override = "z-image",+ transformer_quant = "nvfp4",+ _fetch_base = "Tongyi-MAI/Z-Image-Turbo",+ )+ assert installs == [] and listed == []+++def test_a_plan_that_settled_nvfp4_installs_without_asking_the_hub_again(fake_runtime, monkeypatch):+ installs, listed = _nvfp4_install_probe(+ monkeypatch, refusal = RuntimeError("no request expected")+ )+ _load_to_the_install_gate(transformer_quant = None, _pipeline_prequant_planned = "nvfp4")+ assert listed == []+ assert installs == [("cuda", False)]++[email protected]("reserved_gb, installs_expected", [(0, False), (60, True)])+def test_a_settled_nvfp4_seed_the_live_memory_plan_would_drop_installs_no_flashinfer(+ fake_runtime, monkeypatch, reserved_gb, installs_expected+):+ import core.inference.diffusion as diffusion_mod+ from core.inference.diffusion_memory import DeviceMemory++ installs, listed = _nvfp4_install_probe(+ monkeypatch, refusal = RuntimeError("no request expected")+ )+ monkeypatch.setattr(+ DiffusionBackend,+ "_target_for_ordinal",+ lambda self, fam, ordinal: types.SimpleNamespace(+ device = "cuda", dtype = None, ordinal = 0, supports_model_cpu_offload = True+ ),+ )+ monkeypatch.setattr(+ diffusion_mod,+ "snapshot_device_memory",+ lambda target: DeviceMemory("cuda", "cuda", "discrete_vram", 2 * 1024, 80 * 1024),+ )+ sys.modules["torch"].cuda.memory_reserved = lambda: reserved_gb * 1024**3+ _load_to_the_install_gate(transformer_quant = None, _pipeline_prequant_planned = "nvfp4")+ assert listed == []+ assert installs == ([("cuda", False)] if installs_expected else [])+++def test_an_nvfp4_lora_bake_installs_no_flashinfer(fake_runtime, monkeypatch):+ installs, listed = _nvfp4_install_probe(+ monkeypatch, listing = [_FakeSibling("Z-Image-Turbo-NVFP4.safetensors", 6 * GB)]+ )+ _load_to_the_install_gate(loras = [("some/lora", 1.0)])+ assert installs == []++[email protected]("cached", [False, True])+def test_an_offline_nvfp4_load_asks_only_the_cache(fake_runtime, monkeypatch, cached):+ installs, listed = _nvfp4_install_probe(+ monkeypatch, refusal = RuntimeError("an offline load made a Hub request"), cached = cached+ )+ _load_to_the_install_gate(local_files_only = True)+ assert listed == []+ assert installs == ([("cuda", True)] if cached else [])++def test_plan_memory_prices_the_hosted_precast_text_encoder(monkeypatch, tmp_path):snapshot = _base_snapshot_with_sizes(tmp_path, monkeypatch, {"vae/diffusion_pytorch_model.safetensors": 50}diff --git a/studio/backend/tests/test_diffusion_nvfp4_install.py b/studio/backend/tests/test_diffusion_nvfp4_install.pynew file mode 100644index 00000000000..5a149c010ce--- /dev/null+++ b/studio/backend/tests/test_diffusion_nvfp4_install.py@@ -0,0 +1,1517 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Hermetic tests for the on-demand FlashInfer install behind NVFP4: installer, torch probe and venv are fakes."""++from __future__ import annotations++import os+import pathlib+import re+import sys+import threading+import time+import types++import pytest++from core.inference import diffusion_nvfp4_dispatch as dispatch+from core.inference import diffusion_nvfp4_install as inst+from core.inference import diffusion_nvfp4_ops as ops++_INFERENCE_DIR = pathlib.Path(inst.__file__).resolve().parent++_BASE_DISTS = {+ "torch": "2.12.1+cu130",+ "triton": "3.7.1",+ "nvidia-cublas": "13.1.0.3",+ "numpy": "2.3.5",+ "packaging": "25.0",+}+_ADDED_BY_INSTALL = {+ "flashinfer-python": "0.6.6",+ "apache-tvm-ffi": "0.1.9",+ "nvidia-cutlass-dsl": "4.4.2",+}+++class _Result:+ def __init__(+ self,+ returncode = 0,+ stdout = "",+ ):+ self.returncode = returncode+ self.stdout = stdout+++class _FakeEnv:+ """The venv as the installer sees it: a distribution table, a torch probe, and a subprocess."""++ def __init__(+ self,+ *,+ cuda = "13.0",+ fail_install = False,+ install_moves = None,+ install_delay = 0.0,+ concurrent_add = None,+ ):+ self.dists = dict(_BASE_DISTS)+ self.cuda = cuda+ self.torch_version = self.dists["torch"]+ self.importable = False+ self.fail_install = fail_install+ self.fail_verify = False+ self.install_moves = install_moves or {}+ self.install_delay = install_delay+ self.concurrent_add = concurrent_add or {}+ self.commands: list[list[str]] = []+ self.constraints_seen: list[str] = []+ self.lock = threading.Lock()++ def probe(self, timeout = 60):+ return {"torch_version": self.torch_version, "cuda_version": self.cuda}++ def run(self, cmd, **kwargs):+ cmd = [str(c) for c in cmd]+ with self.lock:+ self.commands.append(cmd)+ if cmd[1:3] == ["-c", cmd[2]] and "import flashinfer" in cmd[2]:+ good = self.importable and not self.fail_verify+ return _Result(0 if good else 1, "0.6.6" if good else "ImportError")+ if "uninstall" in cmd:+ for name in cmd[cmd.index("uninstall") + 1 :]:+ self.dists.pop(name, None)+ self.importable = "flashinfer-python" in self.dists+ return _Result(0)+ if "install" in cmd:+ if "-c" in cmd:+ path = cmd[cmd.index("-c") + 1]+ with open(path, encoding = "utf-8") as fh:+ self.constraints_seen.append(fh.read())+ if self.install_delay:+ time.sleep(self.install_delay)+ self.dists.update(self.concurrent_add)+ if self.fail_install and any(a.startswith("flashinfer-jit-cache==") for a in cmd):+ return _Result(1, "ERROR: no matching distribution")+ if any(a.startswith("flashinfer-python==") for a in cmd):+ self.dists.update(_ADDED_BY_INSTALL)+ for name, version in self.install_moves.items():+ self.dists[name] = version+ if name == "torch":+ self.torch_version = version+ self.importable = not self.install_moves+ # uv reports an upgrade or downgrade as `- name==old` then `+ name==new`, like an addition.+ return _Result(+ 0,+ f"Installed {len(_ADDED_BY_INSTALL)} packages in 1.2s\n"+ + "\n".join(+ f" + {n}=={v}"+ for n, v in {**_ADDED_BY_INSTALL, **self.install_moves}.items()+ ),+ )+ elif any(a.startswith("flashinfer-jit-cache==") for a in cmd):+ spec = next(a for a in cmd if a.startswith("flashinfer-jit-cache=="))+ self.dists["flashinfer-jit-cache"] = spec.split("==", 1)[1]+ return _Result(0, f"Installed 1 package in 3.1s\n + {spec}")+ else:+ for spec in cmd:+ if "==" in spec:+ name, version = spec.split("==", 1)+ self.dists[name] = version+ if name == "torch":+ self.torch_version = version+ return _Result(0)+ return _Result(1, "unexpected command")++ def installs(self):+ return [c for c in self.commands if "install" in c and "uninstall" not in c]+++def _fake_torch(*, cuda = "13.0", hip = None):+ torch = types.ModuleType("torch")+ torch.version = types.SimpleNamespace(cuda = cuda, hip = hip)+ return torch++[email protected](autouse = True)+def _clean(monkeypatch, tmp_path):+ monkeypatch.setattr(inst, "_env_lock_path", lambda: str(tmp_path / "install.lock"))+ monkeypatch.delenv(inst.FLASHINFER_INSTALL_ENV, raising = False)+ monkeypatch.delenv(ops.NVFP4_BACKEND_ENV, raising = False)+ for name in (+ *inst._CUSTOM_INDEX_ENVS,+ "UV_INDEX",+ "UV_EXTRA_INDEX_URL",+ *inst._PIP_EXTRA_INDEX_ENVS,+ "UV_OFFLINE",+ "UV_CONFIG_FILE",+ "ALL_PROXY",+ "all_proxy",+ ):+ monkeypatch.delenv(name, raising = False)+ monkeypatch.setenv("UV_NO_CONFIG", "1")+ inst.reset_install_state()+ yield+ inst.reset_install_state()+++def env(monkeypatch):+ """An eligible host (Linux, CUDA 13.0 torch, sm_100) with flashinfer absent."""+ fake = _FakeEnv()+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.setitem(sys.modules, "torch", _fake_torch())+ monkeypatch.setattr(ops, "_device_capability", lambda device = None: (10, 0))+ monkeypatch.setattr(+ inst,+ "_import_flashinfer",+ lambda: (True, "0.6.6") if fake.importable else (False, "ModuleNotFoundError: flashinfer"),+ )+ monkeypatch.setattr(inst, "_dist_version", lambda name: fake.dists.get(name))+ monkeypatch.setattr(inst, "installed_distributions", lambda: dict(fake.dists))+ monkeypatch.setattr(inst, "_torch_probe", fake.probe)+ monkeypatch.setattr(inst, "_reachable", lambda url: True)+ monkeypatch.setattr(inst, "_uv_executable", lambda: "uv")+ monkeypatch.setattr(inst, "_nvcc_available", lambda: False)+ import utils.utils as uu++ monkeypatch.setattr(uu, "hf_env_offline", lambda: False)+ return fake+++def _steps(installs):+ """``(main, jit)`` by content, whichever order the transaction runs them in."""+ main = next(c for c in installs if "flashinfer-python==0.6.6" in c)+ jit = next(c for c in installs if any(a.startswith("flashinfer-jit-cache==") for a in c))+ return main, jit+++def _ensure(fake, device = 0):+ return inst.ensure_flashinfer_for_nvfp4(device, run = fake.run)+++def test_installs_pinned_flashinfer_and_matching_jit_cache_when_missing(env):+ ok, reason = _ensure(env)+ assert ok, reason+ installs = env.installs()+ assert len(installs) == 2+ main, jit = _steps(installs)+ assert "flashinfer-python==0.6.6" in main and "--only-binary" in main+ assert "--no-deps" not in main # tvm-ffi and friends are real import deps+ assert "flashinfer-jit-cache==0.6.6+cu130" in jit and "--no-deps" in jit+ assert jit[jit.index("--index-url") + 1] == "https://flashinfer.ai/whl/cu130"+ assert jit[jit.index("--index") + 1] == "https://flashinfer.ai/whl/cu130"+ assert env.dists["flashinfer-jit-cache"] == "0.6.6+cu130"+ pins = env.constraints_seen[0].splitlines()+ for name, version in _BASE_DISTS.items():+ assert f"{name}=={version}" in pins+ assert inst.last_install_reason() is None+++def test_constraints_file_is_deleted_after_the_install(env, monkeypatch):+ written = []+ real = inst._write_constraints++ def _spy(pins):+ path = real(pins)+ written.append(path)+ return path++ monkeypatch.setattr(inst, "_write_constraints", _spy)+ _ensure(env)+ assert written and not os.path.exists(written[0])+++def test_already_installed_runs_nothing(env):+ env.importable = True+ ok, reason = _ensure(env)+ assert ok and "already installed" in reason+ assert env.commands == []+++def test_installed_but_broken_is_not_repaired(env):+ env.dists["flashinfer-python"] = "0.5.3"+ ok, reason = _ensure(env)+ assert not ok and "does not import" in reason+ assert env.commands == []+++ "setup, needle",+ [+ (lambda mp: mp.setattr(sys, "platform", "darwin"), "Linux wheels only"),+ (lambda mp: mp.setattr(sys, "platform", "win32"), "Linux wheels only"),+ (lambda mp: mp.setitem(sys.modules, "torch", _fake_torch(cuda = None, hip = "6.4")), "ROCm"),+ (lambda mp: mp.setitem(sys.modules, "torch", _fake_torch(cuda = None)), "CUDA build"),+ (lambda mp: mp.setattr(ops, "_device_capability", lambda device = None: (9, 0)), "sm_90"),+ (lambda mp: mp.setattr(ops, "_device_capability", lambda device = None: (8, 9)), "sm_89"),+ (lambda mp: mp.setattr(ops, "_device_capability", lambda device = None: None), "capability"),+ ],+)+def test_never_installs_on_an_ineligible_host(env, monkeypatch, setup, needle):+ setup(monkeypatch)+ ok, reason = _ensure(env)+ assert not ok and needle in reason+ assert env.commands == []+++def test_torch_version_change_rolls_back_and_refuses(env):+ env.install_moves = {"torch": "2.13.0+cu130"}+ ok, reason = _ensure(env)+ assert not ok and "rolled back" in reason and "torch 2.12.1+cu130 -> 2.13.0+cu130" in reason+ assert env.dists == _BASE_DISTS+ uninstall = [c for c in env.commands if "uninstall" in c]+ assert uninstall and set(_ADDED_BY_INSTALL) <= set(uninstall[0])+ assert any("torch==2.12.1+cu130" in c and "--no-deps" in c for c in env.installs())+ assert inst.last_install_reason() == reason+++def test_torch_probe_drift_without_metadata_drift_also_rolls_back(env, monkeypatch):+ probes = iter(+ [+ {"torch_version": "2.12.1+cu130", "cuda_version": "13.0"},+ {"torch_version": "2.12.1+cu130", "cuda_version": "12.8"},+ ]+ )+ monkeypatch.setattr(inst, "_torch_probe", lambda timeout = 60: next(probes))+ ok, reason = _ensure(env)+ assert not ok and "rolled back" in reason and "torch reads differently" in reason+ assert env.dists == _BASE_DISTS+++def test_failed_jit_cache_step_rolls_back_the_first_step(env):+ env.fail_install = True+ ok, reason = _ensure(env)+ assert not ok and "rolled back" in reason and "installer failed" in reason+ assert env.dists == _BASE_DISTS+++def test_rollback_leaves_packages_another_installer_added_meanwhile(env):+ env.fail_verify = True+ env.concurrent_add = {"requests": "2.32.3", "rich": "14.0.0"}+ ok, reason = _ensure(env)+ assert not ok and "rolled back" in reason+ for name in _ADDED_BY_INSTALL:+ assert name not in env.dists+ assert env.dists.get("requests") == "2.32.3" and env.dists.get("rich") == "14.0.0", (+ reason,+ env.commands,+ )+ uninstall = next(c for c in env.commands if "uninstall" in c)+ assert "requests" not in uninstall and "rich" not in uninstall+++def test_reported_installs_reads_uv_and_pip_output():+ uv_out = "Resolved 5 packages\nInstalled 2 packages in 9ms\n + Apache_TVM_FFI==0.1.9\n + flashinfer-python==0.6.6\n ~ numpy==2.3.5"+ assert inst._reported_installs(uv_out) == {"apache-tvm-ffi", "flashinfer-python"}+ pip_out = (+ "Collecting x\nSuccessfully installed apache-tvm-ffi-0.1.9 flashinfer-jit-cache-0.6.6+cu130"+ )+ assert inst._reported_installs(pip_out) == {"apache-tvm-ffi", "flashinfer-jit-cache"}+ assert inst._reported_installs("ERROR: no matching distribution") == set()+++def test_rollback_without_installer_output_follows_the_flashinfer_dependency_tree(monkeypatch):+ import importlib.metadata as md++ requires = {+ "flashinfer-python": [+ "apache-tvm-ffi>=0.1",+ "nvidia-cutlass-dsl; python_version >= '3'",+ "pytest; extra == 'test'",+ ],+ "apache-tvm-ffi": [],+ "nvidia-cutlass-dsl": [],+ }++ def _distribution(name):+ if name not in requires:+ raise md.PackageNotFoundError(name)+ return types.SimpleNamespace(requires = requires[name])++ monkeypatch.setattr(md, "distribution", _distribution)+ before = dict(_BASE_DISTS)+ after = {**before, **_ADDED_BY_INSTALL, "pytest": "8.0.0", "requests": "2.32.3"}+ monkeypatch.setattr(inst, "installed_distributions", lambda: dict(after))+ commands = []++ def run(cmd, **kwargs):+ commands.append([str(c) for c in cmd])+ return _Result(0)++ inst._rollback(run, "uv", before, None, reported = set())+ assert len(commands) == 1+ removed = set(commands[0][commands[0].index(sys.executable) + 1 :])+ assert removed == set(_ADDED_BY_INSTALL)+++def test_failed_import_after_install_rolls_back(env, monkeypatch):+ real_run = env.run++ def _run(cmd, **kwargs):+ result = real_run(cmd, **kwargs)+ if "import flashinfer" in " ".join(map(str, cmd)):+ return _Result(1, "ImportError: libcudart.so.13")+ return result++ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = _run)+ assert not ok and "import flashinfer failed" in reason+ assert env.dists == _BASE_DISTS+++def test_offline_refuses_with_a_reason_and_is_not_memoised(env, monkeypatch):+ import utils.utils as uu++ monkeypatch.setattr(uu, "hf_env_offline", lambda: True)+ ok, reason = _ensure(env)+ assert not ok and "offline" in reason+ assert env.commands == []+ assert inst.last_install_reason() == reason+ monkeypatch.setattr(uu, "hf_env_offline", lambda: False)+ assert _ensure(env)[0]+++def test_uv_offline_refuses_before_any_index_probe(env, monkeypatch):+ probes: list = []+ monkeypatch.setattr(inst, "_reachable", lambda url: probes.append(url) or True)+ monkeypatch.setenv("UV_OFFLINE", "1")+ ok, reason = _ensure(env)+ assert not ok and "offline" in reason+ assert probes == [] and env.commands == []+ monkeypatch.delenv("UV_OFFLINE")+ assert _ensure(env)[0]+++def test_another_process_holding_the_env_lock_blocks_the_install(env, monkeypatch):+ filelock = pytest.importorskip("filelock")+ monkeypatch.setattr(inst, "ENV_LOCK_TIMEOUT_S", 0.05)+ real = inst._env_install_lock+ monkeypatch.setattr(inst, "_env_install_lock", lambda timeout = 0.05: real(timeout))+ # A second FileLock on its own file handle, held from a thread, stands in for another process.+ other = filelock.FileLock(inst._env_lock_path(), thread_local = False)+ import threading++ held, release = threading.Event(), threading.Event()++ def _hold():+ with other:+ held.set()+ release.wait(5)++ t = threading.Thread(target = _hold)+ t.start()+ held.wait(5)+ try:+ ok, reason = _ensure(env)+ finally:+ release.set()+ t.join()+ assert not ok and "another process" in reason+ assert env.commands == []+ assert _ensure(env)[0]+++def test_unreachable_index_refuses_without_running_the_installer(env, monkeypatch):+ monkeypatch.setattr(inst, "_reachable", lambda url: False)+ ok, reason = _ensure(env)+ assert not ok and "is not reachable" in reason+ assert env.installs() == []+ monkeypatch.setattr(inst, "_reachable", lambda url: True)+ assert _ensure(env)[0]++[email protected]("value", ["0", "off", "false", "no"])+def test_opt_out_env_refuses(env, monkeypatch, value):+ monkeypatch.setenv(inst.FLASHINFER_INSTALL_ENV, value)+ ok, reason = _ensure(env)+ assert not ok and inst.FLASHINFER_INSTALL_ENV in reason+ assert env.commands == []+++def test_explicit_torchao_backend_never_installs(env, monkeypatch):+ monkeypatch.setenv(ops.NVFP4_BACKEND_ENV, "torchao")+ ok, reason = _ensure(env)+ assert not ok and "torchao" in reason+ assert env.commands == []+++def test_concurrent_loads_install_once(env):+ env.install_delay = 0.3+ results = []+ barrier = threading.Barrier(4)++ def _worker():+ barrier.wait()+ results.append(_ensure(env))++ threads = [threading.Thread(target = _worker) for _ in range(4)]+ for t in threads:+ t.start()+ for t in threads:+ t.join(10)+ assert len(results) == 4 and all(ok for ok, _ in results)+ assert sum(1 for c in env.installs() if "flashinfer-python==0.6.6" in c) == 1+++def test_a_failed_install_is_attempted_once_per_process(env):+ env.fail_install = True+ assert not _ensure(env)[0]+ count = len(env.installs())+ assert not _ensure(env)[0]+ assert len(env.installs()) == count+++def test_no_jit_cache_and_no_nvcc_refuses(env):+ env.cuda = "12.6"+ ok, reason = _ensure(env)+ assert not ok and "no nvcc" in reason and "12.6" in reason+ assert env.installs() == []+++def test_no_jit_cache_with_nvcc_installs_flashinfer_only(env, monkeypatch):+ env.cuda = "14.0"+ monkeypatch.setattr(inst, "_nvcc_available", lambda: True)+ ok, reason = _ensure(env)+ assert ok, reason+ assert [c for c in env.installs() if any("jit-cache" in a for a in c)] == []+++def test_stray_jit_cache_of_another_version_refuses(env):+ env.dists["flashinfer-jit-cache"] = "0.6.4+cu130"+ ok, reason = _ensure(env)+ assert not ok and "flashinfer-jit-cache 0.6.4+cu130" in reason+ assert env.installs() == []+++def test_success_forgets_the_dispatch_availability_memo(env, monkeypatch):+ monkeypatch.setattr(dispatch, "_AVAILABLE", (False, "ModuleNotFoundError"))+ assert _ensure(env)[0]+ assert dispatch._AVAILABLE is None+++ "cuda, tag",+ [+ ("12.8", "cu128"),+ ("12.9", "cu129"),+ ("13.0", "cu130"),+ ("13.2", "cu130"),+ ("12.6", None),+ ("14.0", None),+ (None, None),+ ("garbage", None),+ ],+)+def test_jit_cache_tag_matches_the_running_cuda(cuda, tag):+ assert inst.jit_cache_tag(cuda) == tag+++def test_status_fields_carry_the_reason_only_for_torchao(env, monkeypatch):+ monkeypatch.setenv(inst.FLASHINFER_INSTALL_ENV, "0")+ _ensure(env)+ assert inst.nvfp4_backend_fields("torchao")["transformer_quant_backend_reason"]+ assert inst.nvfp4_backend_fields("flashinfer") == {+ "transformer_quant_backend": "flashinfer",+ "transformer_quant_backend_reason": None,+ }+ assert inst.nvfp4_backend_fields(None)["transformer_quant_backend_reason"] is None+++def test_never_raises(env, monkeypatch):+ def _boom(device):+ raise RuntimeError("probe exploded")++ monkeypatch.setattr(inst, "_host_refusal", _boom)+ ok, reason = _ensure(env)+ assert not ok and "probe exploded" in reason+++def _load_pipeline_body(path: pathlib.Path) -> str:+ source = path.read_text(encoding = "utf-8")+ start = source.index(" def load_pipeline(")+ return source[start : source.index("\n def ", start + 10)]+++def _flat(text: str) -> str:+ """Whitespace-insensitive, so a formatter re-wrapping the condition does not fail the test."""+ return re.sub(r"[\s,]+", " ", text).replace("( ", "(").replace(" )", ")")+++def test_image_loader_installs_before_the_load_locks():+ body = _load_pipeline_body(_INFERENCE_DIR / "diffusion.py")+ call = body.index("ensure_flashinfer_for_nvfp4(")+ assert call < body.index("with self._lock:")+ assert _flat(+ "TQ_NVFP4 in (normalize_transformer_quant(transformer_quant), _pipeline_prequant_planned)"+ ) in _flat(body)+++def test_video_loader_installs_after_teardown_and_outside_the_locks():+ body = _load_pipeline_body(_INFERENCE_DIR / "video.py")+ teardown = body.index("self._teardown_state_locked()")+ modular = body.index("ensure_flashinfer_for_nvfp4(")+ conventional = body.index("self._install_flashinfer_for_seed(")+ assert body.count("ensure_flashinfer_for_nvfp4(") == 1+ for call, indent in ((modular, 16), (conventional, 8)):+ assert teardown < call+ line = body[body.rindex("\n", 0, call) + 1 : call]+ assert line == " " * indent + "_nvfp4_install_outcome = "+ assert _flat(+ '"nvfp4" in (normalize_transformer_quant(transformer_quant), _video_auto_denoiser_planned)'+ ) in _flat(body)+++def test_video_loader_installs_only_for_a_seed_the_live_memory_plan_kept():+ from core.inference.video import VideoBackend++ body = _load_pipeline_body(_INFERENCE_DIR / "video.py")+ conventional = body.index("self._install_flashinfer_for_seed(")+ injection = body.index("denoiser_prequant_pipe_kwargs(")+ assert body.rindex("denoiser_seed_scheme = None", 0, injection) < conventional < injection+ assert _flat("_nvfp4_install_wanted denoiser_seed_scheme device") in _flat(+ body[conventional : body.index(")", conventional)]+ )+ modular = body.index("ensure_flashinfer_for_nvfp4(")+ assert (+ body.index("if fam.modular_workflow:")+ < modular+ < body.index("self._load_h3_modular_pipeline(")+ )++ calls = []+ import core.inference.diffusion_nvfp4_install as inst_mod++ original = inst_mod.ensure_flashinfer_for_nvfp4+ inst_mod.ensure_flashinfer_for_nvfp4 = lambda device, **kw: calls.append(device) or (True, "ok")+ try:+ assert VideoBackend._install_flashinfer_for_seed(True, None, "cuda") is None+ assert VideoBackend._install_flashinfer_for_seed(True, "int8", "cuda") is None+ assert VideoBackend._install_flashinfer_for_seed(False, "nvfp4", "cuda") is None+ assert calls == []+ assert VideoBackend._install_flashinfer_for_seed(True, "nvfp4", "cuda") == (True, "ok")+ assert calls == ["cuda"]+ finally:+ inst_mod.ensure_flashinfer_for_nvfp4 = original+++def test_image_loader_gates_the_install_on_the_seed_plan_it_will_rerun():+ import inspect++ from core.inference import diffusion++ body = _load_pipeline_body(_INFERENCE_DIR / "diffusion.py")+ call = body.index("ensure_flashinfer_for_nvfp4(")+ assert "self._seed_plan_stays_resident(" in body[:call]+ locked = body[body.index("with self._lock:") :]+ assert "self._seeded_pipeline_plan(" in locked+ helper = inspect.getsource(diffusion.DiffusionBackend._seed_plan_stays_resident)+ assert "self._seeded_pipeline_plan(" in helper+++class _FakePlan:+ def __init__(self, offload_policy):+ self.offload_policy = offload_policy+++def _seed_gate(+ monkeypatch,+ *,+ free_mib,+ reserved_mib,+ need_mib,+ total_mib = 100_000,+):+ from core.inference import diffusion+ from core.inference.diffusion_memory import DeviceMemory++ seen = []+ monkeypatch.setattr(+ diffusion,+ "snapshot_device_memory",+ lambda target: DeviceMemory("cuda", "cuda", "discrete_vram", free_mib, total_mib),+ )+ torch = types.ModuleType("torch")+ torch.cuda = types.SimpleNamespace(memory_reserved = lambda: reserved_mib * 1024 * 1024)+ monkeypatch.setitem(sys.modules, "torch", torch)+ monkeypatch.setattr(+ diffusion,+ "estimate_dense_quant",+ lambda fam, scheme, base_repo = None, prequant_available = False: types.SimpleNamespace(+ steady_transformer_mib = need_mib, companions_mib = 0, text_encoders_mib = 0+ ),+ )++ def _plan_memory(self, target, single_file_path, base, fam, memory_mode, cpu_offload, **kw):+ seen.append(kw)+ memory = kw["device_memory_override"]+ return _FakePlan("none" if memory.free_mib >= need_mib else "model")++ monkeypatch.setattr(diffusion.DiffusionBackend, "_plan_memory", _plan_memory)+ backend = object.__new__(diffusion.DiffusionBackend)+ ok = backend._seed_plan_stays_resident(+ "nvfp4",+ types.SimpleNamespace(device = "cuda"),+ "org/base",+ object(),+ None,+ False,+ repo_id = "org/base",+ base_local_dir = None,+ fetch_base = None,+ )+ return ok, seen+++def test_seed_gate_refuses_when_live_memory_would_offload_the_seed(monkeypatch):+ ok, seen = _seed_gate(monkeypatch, free_mib = 10_000, reserved_mib = 0, need_mib = 40_000)+ assert ok is False+ assert seen and seen[0]["transformer_resident_override_mib"] == 40_000+++def test_seed_gate_credits_what_the_teardown_frees(monkeypatch):+ ok, _ = _seed_gate(monkeypatch, free_mib = 10_000, reserved_mib = 35_000, need_mib = 40_000)+ assert ok is True+++def test_seed_gate_unanswerable_keeps_the_old_answer(monkeypatch):+ from core.inference import diffusion++ monkeypatch.setattr(+ diffusion,+ "snapshot_device_memory",+ lambda target: (_ for _ in ()).throw(RuntimeError("probe")),+ )+ backend = object.__new__(diffusion.DiffusionBackend)+ assert (+ backend._seed_plan_stays_resident(+ "nvfp4",+ types.SimpleNamespace(device = "cuda"),+ "b",+ object(),+ None,+ False,+ repo_id = "b",+ base_local_dir = None,+ fetch_base = None,+ )+ is True+ )+++def test_a_configured_mirror_skips_the_pypi_probe_but_not_the_jit_cache_one(env, monkeypatch):+ probed = []+ monkeypatch.setattr(inst, "_reachable", lambda url: probed.append(url) or True)+ monkeypatch.setenv("UV_INDEX_URL", "https://mirror.example/simple")+ assert _ensure(env)[0]+ assert probed == ["https://flashinfer.ai/whl/cu130/flashinfer-jit-cache/"]+++def test_a_pip_only_mirror_is_handed_to_uv(env, monkeypatch):+ monkeypatch.setattr(inst, "_reachable", lambda url: True)+ monkeypatch.setenv("PIP_INDEX_URL", "https://pip-mirror.example/simple")+ assert _ensure(env)[0]+ installs = [c for c in env.commands if c[:3] == ["uv", "pip", "install"]]+ assert installs and "https://pip-mirror.example/simple" in _steps(installs)[0]+ monkeypatch.setenv("UV_INDEX_URL", "https://uv-mirror.example/simple")+ assert "--index-url" not in inst._installer_prefix("uv")+ assert "--index-url" not in inst._installer_prefix(None)+++def test_a_uv_only_mirror_is_handed_to_the_pip_fallback(env, monkeypatch):+ monkeypatch.setattr(inst, "_uv_executable", lambda: None)+ for name in ("PIP_INDEX_URL", "UV_DEFAULT_INDEX"):+ monkeypatch.delenv(name, raising = False)+ monkeypatch.setenv("UV_INDEX_URL", "https://uv-mirror.example/simple")+ main = inst._installer_prefix(None)+ assert main[main.index("--index-url") + 1] == "https://uv-mirror.example/simple"+ monkeypatch.setenv("UV_DEFAULT_INDEX", "https://uv-default.example/simple")+ main = inst._installer_prefix(None)+ assert main[main.index("--index-url") + 1] == "https://uv-default.example/simple"+ jit = inst._installer_prefix(None, "https://flashinfer.ai/whl/cu130")+ assert jit.count("--index-url") == 1 and jit[-1] == "https://flashinfer.ai/whl/cu130"+ monkeypatch.setenv("PIP_INDEX_URL", "https://pip-mirror.example/simple")+ assert "--index-url" not in inst._installer_prefix(None)+++def test_a_pip_only_mirror_never_gives_uv_two_index_urls(env, monkeypatch):+ monkeypatch.setenv("PIP_INDEX_URL", "https://pip-mirror.example/simple")+ assert _ensure(env)[0]+ main, jit = _steps(env.installs())+ assert main.count("--index-url") == 1+ assert main[main.index("--index-url") + 1] == "https://pip-mirror.example/simple"+ assert jit.count("--index-url") == 1+ assert jit[jit.index("--index-url") + 1] == "https://flashinfer.ai/whl/cu130"+ pip_jit = inst._installer_prefix(None, "https://flashinfer.ai/whl/cu130")+ assert pip_jit.count("--index-url") == 1+++def test_status_reason_reports_a_transient_preflight_failure(monkeypatch):+ torch = pytest.importorskip("torch")+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device = None: (10, 0))+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda device = None: "stub B200")+ ops.reset_preflight_cache()++ def _oom(dev):+ raise torch.cuda.OutOfMemoryError("CUDA out of memory. Tried to allocate 64.00 MiB")++ class _Backend:+ pass++ image = _Backend()+ inst.record_install_reason(image, True, "already installed", 0)+ monkeypatch.setattr(ops, "_preflight_probe", _oom)+ assert ops.nvfp4_preflight(0)["ok"] is False+ assert 0 not in ops._PREFLIGHT+ reason = inst.nvfp4_backend_fields("torchao", owner = image)["transformer_quant_backend_reason"]+ assert reason and "out of memory" in reason.lower()+ assert (+ "out of memory"+ in inst.nvfp4_backend_fields("torchao")["transformer_quant_backend_reason"].lower()+ )+ monkeypatch.setattr(ops, "_preflight_probe", lambda dev: False)+ ops.nvfp4_preflight(0)+ assert (+ inst.nvfp4_backend_fields("torchao", owner = image)["transformer_quant_backend_reason"]+ == "flashinfer preflight failed: mm_fp4 produced a non-finite result"+ )+ ops.reset_preflight_cache()+++def test_status_reason_falls_back_to_a_cached_preflight_failure(monkeypatch):+ monkeypatch.setitem(ops._PREFLIGHT, 0, {"ok": False, "reason": "JIT build failed"})+ fields = inst.nvfp4_backend_fields("torchao")+ assert (+ fields["transformer_quant_backend_reason"]+ == "flashinfer preflight failed: JIT build failed"+ )+++class _Logger:+ def __init__(self):+ self.records = []++ def info(self, fmt, *args):+ self.records.append(("info", fmt % args))++ def warning(self, fmt, *args):+ self.records.append(("warning", fmt % args))+++def test_policy_refusals_log_at_info_and_failures_at_warning(env, monkeypatch):+ logger = _Logger()+ monkeypatch.setattr(ops, "_device_capability", lambda device = None: (9, 0))+ inst.ensure_flashinfer_for_nvfp4(0, logger = logger, run = env.run)+ assert logger.records[-1][0] == "info"+ monkeypatch.setattr(ops, "_device_capability", lambda device = None: (10, 0))+ env.fail_install = True+ inst.ensure_flashinfer_for_nvfp4(0, logger = logger, run = env.run)+ assert logger.records[-1][0] == "warning" and "rolled back" in logger.records[-1][1]+++def test_status_callback_sees_the_install_and_its_outcome(env):+ seen = []+ ok, _ = inst.ensure_flashinfer_for_nvfp4(0, status_cb = seen.append, run = env.run)+ assert ok+ assert seen[0].startswith("installing flashinfer-python 0.6.6") and "cu130" in seen[0]+ assert seen[-1] == "installed flashinfer 0.6.6 for NVFP4"+++def test_local_only_load_never_installs(env):+ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = env.run, local_files_only = True)+ assert not ok and "local-only" in reason+ assert env.installs() == []+++def test_status_reason_is_bound_to_the_backend_that_loaded():+ class _Backend:+ pass++ image, video = _Backend(), _Backend()+ inst.reset_install_state()+ inst.record_install_reason(image, False, "offline: flashinfer is not downloaded", 0)+ inst.record_install_reason(video, True, "installed", 1)+ assert inst.nvfp4_backend_fields("torchao", owner = image)[+ "transformer_quant_backend_reason"+ ] == ("offline: flashinfer is not downloaded")+ assert (+ inst.nvfp4_backend_fields("flashinfer", owner = image)["transformer_quant_backend_reason"]+ is None+ )+ inst.reset_install_state()+++def test_status_preflight_reason_is_the_loaded_device_only(monkeypatch):+ class _Backend:+ pass++ image, video = _Backend(), _Backend()+ inst.reset_install_state()+ monkeypatch.setitem(ops._PREFLIGHT, 0, {"ok": False, "reason": "JIT build failed"})+ monkeypatch.setitem(ops._PREFLIGHT, 1, {"ok": False, "reason": "sm_120 unsupported"})+ inst.record_install_reason(image, True, "already installed", 0)+ inst.record_install_reason(video, True, "already installed", "cuda:1")+ assert (+ inst.nvfp4_backend_fields("torchao", owner = image)["transformer_quant_backend_reason"]+ == "flashinfer preflight failed: JIT build failed"+ )+ assert (+ inst.nvfp4_backend_fields("torchao", owner = video)["transformer_quant_backend_reason"]+ == "flashinfer preflight failed: sm_120 unsupported"+ )+ inst.reset_install_state()+++def test_image_loader_skips_the_install_when_the_plan_declined_the_seed():+ # A declined seed loads the released denoiser, and the Hub probe alone would still buy the install.+ body = _load_pipeline_body(_INFERENCE_DIR / "diffusion.py")+ gate = body[: body.index("ensure_flashinfer_for_nvfp4(")].rsplit("if (", 1)[-1]+ declined = gate.index("_pipeline_prequant_planned != PIPELINE_SEED_DECLINED")+ assert declined < gate.index("self._nvfp4_checkpoint_will_load(")+++def test_image_loader_binds_the_reason_only_after_the_resident_model_is_unloaded():+ import inspect++ from core.inference import diffusion++ src = inspect.getsource(diffusion.DiffusionBackend)+ ensure_at = src.index("ensure_flashinfer_for_nvfp4(")+ call = src[ensure_at : src.index(")", ensure_at)]+ assert "owner" not in call+ unload_at = src.index("self._unload_locked()", ensure_at)+ assert src.index("record_install_reason(self", ensure_at) > unload_at+++def test_video_loader_binds_the_reason_only_at_the_commit():+ import inspect++ from core.inference import video++ src = inspect.getsource(video.VideoBackend)+ ensure_at = src.index("ensure_flashinfer_for_nvfp4(")+ call = src[ensure_at : src.index(")", ensure_at)]+ assert "owner" not in call+ commits = [m.start() for m in re.finditer(r"self\._state = _VideoLoadState\(", src)]+ binds = [m.start() for m in re.finditer(r"record_install_reason\(self", src)]+ assert len(binds) == 2+ for bind in binds:+ commit = min(c for c in commits if c > bind)+ cancel = src.rindex("Video load was cancelled or superseded.", 0, bind)+ assert src.index("self._state = _VideoLoadState(", cancel) == commit+++def test_every_loader_commit_binds_a_reason_even_when_the_install_gate_skipped():+ import inspect++ from core.inference import diffusion, video+ for cls in (diffusion.DiffusionBackend, video.VideoBackend):+ src = inspect.getsource(cls)+ assert "if _nvfp4_install_outcome is not None" not in src+ binds = re.findall(+ r"record_install_reason\(self, \*\(_nvfp4_install_outcome or \(True, None\)\)", src+ )+ assert len(binds) == (1 if cls is diffusion.DiffusionBackend else 2)+++def test_install_gates_skip_kinds_the_dense_quant_path_cannot_reach():+ import inspect++ from core.inference import diffusion, video++ img = inspect.getsource(diffusion.DiffusionBackend)+ gate = img[: img.index("ensure_flashinfer_for_nvfp4(")].rsplit("if ", 1)[-1]+ assert gate.lstrip("( \n").startswith("dense_quant_supported_kind(kind)")+ vid = inspect.getsource(video.VideoBackend)+ gate = vid[vid.index("_nvfp4_install_wanted = (") + len("_nvfp4_install_wanted = (") :]+ assert gate.lstrip("( \n").startswith('kind == "pipeline"')+ body = _load_pipeline_body(_INFERENCE_DIR / "video.py")+ modular = body.index("ensure_flashinfer_for_nvfp4(")+ assert "if _nvfp4_install_wanted:" in body[body.index("if fam.modular_workflow:") : modular]+ hop = body[body.index("self._install_flashinfer_for_seed(") :]+ assert hop[: hop.index(")")].split("(", 1)[1].split(",")[0].strip() == "_nvfp4_install_wanted"+++def test_jit_cache_step_drops_extra_index_sources_from_the_environment(env, monkeypatch):+ extra = {+ "UV_INDEX": "https://corp.example/simple",+ "UV_EXTRA_INDEX_URL": "https://corp.example/extra",+ "PIP_EXTRA_INDEX_URL": "https://corp.example/pip-extra",+ "UV_FIND_LINKS": "https://corp.example/links",+ }+ for name, value in extra.items():+ monkeypatch.setenv(name, value)+ seen = []+ real = env.run++ def _run(cmd, **kwargs):+ seen.append(([str(c) for c in cmd], kwargs.get("env")))+ return real(cmd, **kwargs)++ assert inst.ensure_flashinfer_for_nvfp4(0, run = _run)[0]+ envs = {+ "main" if any(c.startswith("flashinfer-python==") for c in cmd) else "jit": child+ for cmd, child in seen+ if "install" in cmd and "uninstall" not in cmd+ }+ for name, value in extra.items():+ assert envs["main"].get(name) == value # the user's mirrors still serve the main step+ assert name not in envs["jit"]+++def test_pip_jit_cache_step_reads_no_pip_conf_but_keeps_its_transport(env, monkeypatch):+ monkeypatch.setattr(inst, "_uv_executable", lambda: None)+ monkeypatch.setenv("PIP_TIMEOUT", "30")+ lines = [+ "global.extra-index-url='https://corp.example/extra'",+ "install.find-links='https://corp.example/links'",+ "global.proxy='http://proxy.corp.example:3128'",+ "global.cert='/etc/ssl/corp.pem'",+ "global.trusted-host='a.corp.example\\nb.corp.example'",+ "global.timeout='120'",+ ":env:.timeout='30'",+ ]+ seen = []+ config_run = _pip_config(env, lines)++ def _run(cmd, **kwargs):+ seen.append(([str(c) for c in cmd], kwargs.get("env")))+ return config_run(cmd, **kwargs)++ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = _run)+ assert ok, reason+ installs = {+ "main" if any(c.startswith("flashinfer-python==") for c in cmd) else "jit": (cmd, child)+ for cmd, child in seen+ if "install" in cmd and "uninstall" not in cmd and "config" not in cmd+ }+ main_cmd, main_env = installs["main"]+ jit_cmd, jit_env = installs["jit"]+ assert main_env is None or main_env.get("PIP_CONFIG_FILE") != os.devnull+ assert jit_env["PIP_CONFIG_FILE"] == os.devnull+ assert jit_cmd[jit_cmd.index("--index-url") + 1] == "https://flashinfer.ai/whl/cu130"+ assert jit_env["PIP_PROXY"] == "http://proxy.corp.example:3128"+ assert jit_env["PIP_CERT"] == "/etc/ssl/corp.pem"+ assert jit_env["PIP_TRUSTED_HOST"].split() == ["a.corp.example", "b.corp.example"]+ assert jit_env["PIP_TIMEOUT"] == "30" # the caller's own environment still wins+ assert not any(k in jit_env for k in ("PIP_EXTRA_INDEX_URL", "PIP_FIND_LINKS"))+++def test_uv_jit_cache_step_leaves_pip_config_alone(env, monkeypatch):+ seen = []+ real = env.run++ def _run(cmd, **kwargs):+ seen.append(([str(c) for c in cmd], kwargs.get("env")))+ return real(cmd, **kwargs)++ assert inst.ensure_flashinfer_for_nvfp4(0, run = _run)[0]+ jit_env = next(+ child for cmd, child in seen if any(c.startswith("flashinfer-jit-cache==") for c in cmd)+ )+ assert jit_env.get("PIP_CONFIG_FILE") == os.environ.get("PIP_CONFIG_FILE")+++def _hold_env_lock(release_after):+ filelock = pytest.importorskip("filelock")+ other = filelock.FileLock(inst._env_lock_path(), thread_local = False)+ held = threading.Event()++ def _hold():+ with other:+ held.set()+ time.sleep(release_after)++ t = threading.Thread(target = _hold)+ t.start()+ held.wait(5)+ return t+++def _track_imports(env, monkeypatch):+ stamps = []+ monkeypatch.setattr(+ inst,+ "_import_flashinfer",+ lambda: stamps.append(time.monotonic())+ or ((True, "0.6.6") if env.importable else (False, "ModuleNotFoundError: flashinfer")),+ )+ monkeypatch.delitem(sys.modules, "flashinfer", raising = False)+ return stamps+++def test_an_in_flight_install_by_another_process_is_waited_for_before_importing(env, monkeypatch):+ env.dists["flashinfer-python"] = "0.6.6"+ env.importable = True+ stamps = _track_imports(env, monkeypatch)+ start = time.monotonic()+ t = _hold_env_lock(0.5)+ try:+ ok, reason = _ensure(env)+ finally:+ t.join()+ assert ok and "already installed" in reason+ assert stamps and stamps[0] - start >= 0.45+ assert env.commands == []+++def test_a_complete_install_still_holding_the_lock_is_waited_for_in_case_it_rolls_back(+ env, monkeypatch+):+ env.dists.update({"flashinfer-python": "0.6.6", "flashinfer-jit-cache": "0.6.6+cu130"})+ env.importable = True+ stamps = _track_imports(env, monkeypatch)+ filelock = pytest.importorskip("filelock")+ other = filelock.FileLock(inst._env_lock_path(), thread_local = False)+ held, rolled_back = threading.Event(), []++ def _hold():+ with other:+ held.set()+ time.sleep(0.5)+ env.dists.pop("flashinfer-python")+ env.dists.pop("flashinfer-jit-cache")+ env.importable = False+ # Imports seen before the rollback: ordering by count, not by clock.+ rolled_back.append(len(stamps))++ t = threading.Thread(target = _hold)+ t.start()+ held.wait(5)+ try:+ ok, reason = _ensure(env)+ finally:+ t.join()+ assert rolled_back == [0] and stamps+ assert "already installed" not in reason+++def test_a_user_flashinfer_never_waits_on_the_lock(env, monkeypatch):+ env.dists["flashinfer-python"] = "0.5.3"+ env.importable = True+ stamps = _track_imports(env, monkeypatch)+ start = time.monotonic()+ t = _hold_env_lock(1.0)+ try:+ ok, _ = _ensure(env)+ finally:+ t.join()+ assert ok and stamps[0] - start < 0.5+ assert env.commands == []+++def test_a_timed_out_wait_for_an_in_flight_install_does_not_import(env, monkeypatch):+ env.dists["flashinfer-python"] = "0.6.6"+ env.importable = True+ real = inst._env_install_lock+ monkeypatch.setattr(inst, "_env_install_lock", lambda timeout = 0.05: real(timeout))+ stamps = _track_imports(env, monkeypatch)+ t = _hold_env_lock(0.5)+ try:+ ok, reason = _ensure(env)+ finally:+ t.join()+ assert not ok and "another process" in reason+ assert stamps == [] and env.commands == []+ ok, reason = _ensure(env)+ assert ok and "already installed" in reason++[email protected]("uv", ["uv", None])[email protected]("name", ["UV_INDEX", "UV_EXTRA_INDEX_URL", "UV_FIND_LINKS"])+def test_a_uv_index_skips_the_pypi_probe_only_when_uv_installs(env, monkeypatch, name, uv):+ probed = []+ monkeypatch.setattr(inst, "_reachable", lambda url: probed.append(url) or True)+ monkeypatch.setattr(inst, "_uv_executable", lambda: uv)+ monkeypatch.setenv(name, "https://uv-mirror.example/simple")+ assert _ensure(env)[0]+ assert (inst._PYPI_PROBE_URL in probed) == (uv is None)+++ "cuda, cache, nvcc",+ [+ ("13.0", "0.6.6+cu128", False), # left over from a cu128 torch+ ("13.0", "0.6.6", False), # no local tag: the CUDA it was built for cannot be told+ ("14.0", "0.6.6+cu130", True), # no published build fits, yet a cache is present+ ],+)+def test_a_jit_cache_built_for_another_cuda_refuses(env, monkeypatch, cuda, cache, nvcc):+ env.cuda = cuda+ env.dists["flashinfer-jit-cache"] = cache+ monkeypatch.setattr(inst, "_nvcc_available", lambda: nvcc)+ ok, reason = _ensure(env)+ assert not ok and f"flashinfer-jit-cache {cache}" in reason and "does not match CUDA" in reason+ assert env.installs() == []+++def test_a_jit_cache_of_the_running_cuda_is_kept(env):+ env.dists["flashinfer-jit-cache"] = "0.6.6+cu130"+ ok, reason = _ensure(env)+ assert ok, reason++[email protected]("policy", ["local_files_only", "opt_out"])+def test_a_load_that_declined_installs_does_not_wait_on_another_install(env, monkeypatch, policy):+ env.dists["flashinfer-python"] = "0.6.6"+ env.importable = True+ stamps = _track_imports(env, monkeypatch)+ kwargs = {}+ if policy == "local_files_only":+ kwargs["local_files_only"] = True+ else:+ monkeypatch.setenv(inst.FLASHINFER_INSTALL_ENV, "0")+ t = _hold_env_lock(2.0)+ start = time.monotonic()+ try:+ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = env.run, **kwargs)+ elapsed = time.monotonic() - start+ finally:+ t.join()+ assert elapsed < 1.0+ assert not ok and "another process is still installing" in reason+ assert stamps == [] # never imported mid-transaction+ assert env.commands == []+++def test_a_load_that_declined_installs_still_imports_a_finished_install(env, monkeypatch):+ env.dists.update({"flashinfer-python": "0.6.6", "flashinfer-jit-cache": "0.6.6+cu130"})+ env.importable = True+ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = env.run, local_files_only = True)+ assert ok and "already installed" in reason+++def _pip_config(env, lines):+ """``env.run`` that also answers ``pip config list`` with ``lines``, as pip prints them."""+ calls = []++ def _run(cmd, **kwargs):+ cmd = [str(c) for c in cmd]+ if cmd[1:] == ["-m", "pip", "config", "list"]:+ calls.append(cmd)+ return _Result(0, "".join(f"{line}\n" for line in lines))+ return env.run(cmd, **kwargs)++ _run.calls = calls+ return _run+++def test_a_pip_conf_mirror_skips_the_pypi_probe_for_the_pip_fallback(env, monkeypatch):+ probed = []+ monkeypatch.setattr(inst, "_reachable", lambda url: probed.append(url) or True)+ monkeypatch.setattr(inst, "_uv_executable", lambda: None)+ run = _pip_config(env, ["global.index-url='https://corp.example/simple'"])+ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = run)+ assert ok, reason+ assert probed == ["https://flashinfer.ai/whl/cu130/flashinfer-jit-cache/"]+++ "lines, envvar",+ [+ ([":env:.extra-index-url='https://corp.example/simple'"], None),+ (["global.extra-index-url='https://corp.example/simple'"], None),+ (["install.find-links='https://corp.example/links'"], None),+ ([], "PIP_EXTRA_INDEX_URL"),+ ([], "PIP_FIND_LINKS"),+ ],+)+def test_a_pip_extra_index_skips_the_pypi_probe_for_the_pip_fallback(+ env, monkeypatch, lines, envvar+):+ probed = []+ monkeypatch.setattr(+ inst, "_reachable", lambda url: probed.append(url) or url != inst._PYPI_PROBE_URL+ )+ monkeypatch.setattr(inst, "_uv_executable", lambda: None)+ if envvar:+ monkeypatch.setenv(envvar, "https://corp.example/simple")+ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = _pip_config(env, lines))+ assert ok, reason+ assert inst._PYPI_PROBE_URL not in probed+++def test_a_pip_conf_mirror_is_not_overridden_by_a_uv_one(env, monkeypatch):+ monkeypatch.setattr(inst, "_uv_executable", lambda: None)+ monkeypatch.setenv("UV_INDEX_URL", "https://uv-mirror.example/simple")+ run = _pip_config(env, ["install.index-url='https://corp.example/simple'"])+ assert inst.ensure_flashinfer_for_nvfp4(0, run = run)[0]+ main = _steps(env.installs())[0]+ assert "--index-url" not in main # pip reads its own pip.conf mirror+++def test_pip_config_is_only_read_when_pip_installs(env):+ run = _pip_config(env, [":env:.no-index='1'"])+ assert inst.ensure_flashinfer_for_nvfp4(0, run = run)[0]+ assert (+ run.calls == []+ ) # uv ignores pip's settings, and the installed path never pays for the subprocess+++ "line, needle",+ [+ (":env:.no-index='1'", "no-index"),+ ("global.no-index='true'", "no-index"),+ (":env:.no-deps='yes'", "no-deps"),+ ("install.target='/opt/elsewhere'", "target directory"),+ (":env:.prefix='/opt/elsewhere'", "prefix"),+ ("install.root='/chroot'", "another root"),+ (":env:.force-reinstall='1'", "force-reinstall"),+ ("install.force-reinstall='true'", "force-reinstall"),+ (":env:.ignore-installed='yes'", "ignore installed"),+ ("global.ignore-installed='true'", "ignore installed"),+ ],+)+def test_pip_settings_it_cannot_honor_refuse_before_installing(env, monkeypatch, line, needle):+ probed = []+ monkeypatch.setattr(inst, "_reachable", lambda url: probed.append(url) or True)+ monkeypatch.setattr(inst, "_uv_executable", lambda: None)+ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = _pip_config(env, [line]))+ assert not ok and needle in reason+ assert env.installs() == [] and probed == []+ assert inst.ensure_flashinfer_for_nvfp4(0, run = _pip_config(env, []))[0]+++def test_pip_require_virtualenv_refuses_only_outside_a_venv(env, monkeypatch):+ monkeypatch.setattr(inst, "_uv_executable", lambda: None)+ run = _pip_config(env, [":env:.require-virtualenv='1'"])+ monkeypatch.setattr(sys, "base_prefix", sys.prefix)+ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = run)+ assert not ok and "virtualenv" in reason and env.installs() == []+ monkeypatch.setattr(sys, "base_prefix", sys.prefix + "-base")+ assert inst.ensure_flashinfer_for_nvfp4(0, run = run)[0]+++def _uv_toml(monkeypatch, tmp_path, text):+ path = tmp_path / "uv.toml"+ path.write_text(text, encoding = "utf-8")+ monkeypatch.setenv("UV_CONFIG_FILE", str(path))+ return path+++ "text, needle",+ [+ ("offline = true\n", "offline"),+ ("no-index = true\n", "no-index"),+ ("[pip]\nno-index = true\n", "no-index"),+ ("[pip]\nno-deps = true\n", "no-deps"),+ ('[pip]\ntarget = "/opt/elsewhere"\n', "target directory"),+ ('[pip]\nprefix = "/opt/elsewhere"\n', "prefix"),+ ("reinstall = true\n", "reinstall"),+ ("[pip]\nreinstall = true\n", "reinstall"),+ ('[pip]\nreinstall-package = ["torch"]\n', "reinstall"),+ ],+)+def test_uv_config_settings_it_cannot_honor_refuse_before_installing(+ env, monkeypatch, tmp_path, text, needle+):+ probed = []+ monkeypatch.setattr(inst, "_reachable", lambda url: probed.append(url) or True)+ _uv_toml(monkeypatch, tmp_path, text)+ ok, reason = _ensure(env)+ assert not ok and needle in reason+ assert env.installs() == [] and probed == []+ monkeypatch.delenv("UV_CONFIG_FILE")+ assert _ensure(env)[0]+++def test_uv_offline_env_false_overrides_a_config_offline(env, monkeypatch, tmp_path):+ _uv_toml(monkeypatch, tmp_path, "offline = true\n")+ monkeypatch.setenv("UV_OFFLINE", "0")+ assert _ensure(env)[0]+++def test_pip_section_overrides_the_top_level_in_uv_config(env, monkeypatch, tmp_path):+ _uv_toml(monkeypatch, tmp_path, "no-index = true\n[pip]\nno-index = false\n")+ assert _ensure(env)[0]+++ "text",+ [+ 'index-url = "https://corp.example/simple"\n',+ '[[index]]\nurl = "https://corp.example/simple"\n',+ '[pip]\nextra-index-url = ["https://corp.example/simple"]\n',+ "this is not toml = = \n", # unreadable here: the installer decides, not pypi.org+ ],+)+def test_a_uv_config_mirror_skips_the_pypi_probe(env, monkeypatch, tmp_path, text):+ probed = []+ monkeypatch.setattr(inst, "_reachable", lambda url: probed.append(url) or True)+ _uv_toml(monkeypatch, tmp_path, text)+ assert _ensure(env)[0]+ assert probed == ["https://flashinfer.ai/whl/cu130/flashinfer-jit-cache/"]+++def test_uv_config_discovery_finds_the_project_file_and_honors_no_config(+ env, monkeypatch, tmp_path+):+ project = tmp_path / "proj" / "sub"+ project.mkdir(parents = True)+ (tmp_path / "proj" / "pyproject.toml").write_text(+ '[project]\nname = "x"\n[tool.uv]\nindex-url = "https://corp.example/simple"\n',+ encoding = "utf-8",+ )+ (project / "pyproject.toml").write_text('[project]\nname = "y"\n', encoding = "utf-8")+ monkeypatch.chdir(project)+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))+ monkeypatch.setenv("XDG_CONFIG_DIRS", str(tmp_path / "xdg-sys"))+ monkeypatch.delenv("UV_NO_CONFIG")+ config = inst._installer_config("uv", env.run)+ assert config["mirror"] and config["own_index"]+ monkeypatch.setenv("PIP_INDEX_URL", "https://pip-mirror.example/simple")+ assert "--index-url" not in inst._installer_prefix("uv", own_index = config["own_index"])+ monkeypatch.setenv("UV_NO_CONFIG", "1")+ assert not inst._installer_config("uv", env.run)["own_index"]+ monkeypatch.delenv("UV_NO_CONFIG")+ monkeypatch.chdir(tmp_path)+ (tmp_path / "xdg" / "uv").mkdir(parents = True)+ (tmp_path / "xdg" / "uv" / "uv.toml").write_text("offline = true\n", encoding = "utf-8")+ assert "offline" in inst._installer_config("uv", env.run)["refusal"]++[email protected]("uv", ["uv", None])+def test_a_proxy_the_probe_cannot_use_skips_the_probes(env, monkeypatch, uv):+ monkeypatch.setattr(inst, "_reachable", lambda url: False)+ monkeypatch.setattr(inst, "_uv_executable", lambda: uv)+ monkeypatch.setenv("ALL_PROXY", "socks5h://proxy.example:1080")+ assert inst.ensure_flashinfer_for_nvfp4(0, run = _pip_config(env, []))[0]+++def test_pips_own_proxy_setting_skips_the_probes(env, monkeypatch):+ monkeypatch.setattr(inst, "_reachable", lambda url: False)+ monkeypatch.setattr(inst, "_uv_executable", lambda: None)+ run = _pip_config(env, ["global.proxy='http://proxy.example:3128'"])+ assert inst.ensure_flashinfer_for_nvfp4(0, run = run)[0]+++def test_reachability_counts_a_tls_failure_as_a_route(monkeypatch):+ import ssl+ import urllib.error+ import urllib.request++ def _raise(exc):+ def _urlopen(*args, **kwargs):+ raise exc++ return _urlopen++ cases = [+ (urllib.error.URLError(ssl.SSLCertVerificationError(1, "self-signed certificate")), True),+ (urllib.error.URLError(OSError(101, "Network is unreachable")), False),+ (urllib.error.HTTPError("https://x", 404, "Not Found", {}, None), False),+ (TimeoutError("timed out"), False),+ ]+ for exc, expected in cases:+ monkeypatch.setattr(urllib.request, "urlopen", _raise(exc))+ assert inst._reachable("https://pypi.org/simple/flashinfer-python/") is expected+++def test_an_install_killed_between_its_steps_completes_on_the_next_load(env):+ # Killed between steps: the next load must finish the install, not treat jit-cache-less flashinfer as done.+ real_run = env.run+ calls = {"n": 0}++ def dies_on_second_install(cmd, **kwargs):+ if "install" in cmd and "uninstall" not in cmd:+ calls["n"] += 1+ if calls["n"] == 2:+ raise SystemExit("killed mid-install")+ return real_run(cmd, **kwargs)++ with pytest.raises(SystemExit):+ inst.ensure_flashinfer_for_nvfp4(0, run = dies_on_second_install)+ inst.reset_install_state()+ env.importable = "flashinfer-python" in env.dists+ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = env.run)+ assert ok, reason+ assert env.dists.get("flashinfer-python") == "0.6.6"+ assert env.dists.get("flashinfer-jit-cache") == "0.6.6+cu130", reason++[email protected]("model", ["DiffusionStatusResponse", "VideoStatusResponse"])+def test_the_status_reason_hides_host_paths_from_api_key_callers(model):+ # Host paths must stay redacted for API-key callers.+ from hub.utils.host_paths import redact_host_paths+ from models import inference as models++ secret = "/home/alice/.unsloth/studio/venv"+ reason = f"flashinfer install rolled back: the installer failed: Using Python environment at: {secret} error"+ status = getattr(models, model)(+ loaded = True, transformer_quant_backend = "torchao", transformer_quant_backend_reason = reason+ )+ seen = redact_host_paths(status, via_api_key = True)+ seen = seen if isinstance(seen, dict) else seen.model_dump()+ assert secret not in str(seen["transformer_quant_backend_reason"])+ assert "rolled back" in seen["transformer_quant_backend_reason"]+ own = redact_host_paths(status, via_api_key = False)+ own = own if isinstance(own, dict) else own.model_dump()+ assert secret in own["transformer_quant_backend_reason"]+++def test_a_concurrent_upgrade_by_another_installer_is_not_reverted(env):+ # A concurrent terminal upgrade fails drift but must not be downgraded by the rollback.+ env.concurrent_add = {"packaging": "26.0"}+ ok, reason = _ensure(env)+ assert not ok and "rolled back" in reason+ assert env.dists["packaging"] == "26.0", reason+ assert not [c for c in env.commands if "packaging==25.0" in c]+++def test_a_later_step_that_dies_unreported_is_still_rolled_back(env):+ real_run = env.run++ def run(cmd, **kwargs):+ result = real_run(cmd, **kwargs)+ steps = [c for c in env.installs() if any(a.startswith("flashinfer") for a in c)]+ if "install" in cmd and "uninstall" not in cmd and len(steps) == 2:+ return _Result(1, "")+ return result++ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = run)+ assert not ok and "rolled back" in reason+ assert "flashinfer-python" not in env.dists, reason+ assert "flashinfer-jit-cache" not in env.dists, reason+++def test_a_failed_install_does_not_quote_index_credentials(env):+ real_run = env.run++ def run(cmd, **kwargs):+ if "install" in cmd and "uninstall" not in cmd:+ return _Result(+ 1,+ "error: https://__token__:[email protected]/simple/ ?token=SECRET2 returned 401",+ )+ return real_run(cmd, **kwargs)++ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = run)+ assert not ok and "the installer failed" in reason+ assert "SECRET" not in reason+++def test_an_unreported_failure_does_not_revert_a_concurrent_upgrade(env):+ # No report: constraints held everything, so a concurrent terminal upgrade stays.+ env.concurrent_add = {"packaging": "26.0"}+ real_run = env.run++ def run(cmd, **kwargs):+ result = real_run(cmd, **kwargs)+ if (+ "install" in cmd+ and "uninstall" not in cmd+ and any(a.startswith("flashinfer-python==") for a in cmd)+ ):+ return _Result(1, "")+ return result++ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = run)+ assert not ok and "rolled back" in reason+ assert "flashinfer-python" not in env.dists, reason+ assert env.dists["packaging"] == "26.0", reason+ assert not [c for c in env.commands if "packaging==25.0" in c]diff --git a/studio/backend/tests/test_nvfp4_diffusion_flag.py b/studio/backend/tests/test_nvfp4_diffusion_flag.pyindex 5e93188a691..fde4ba70ff8 100644--- a/studio/backend/tests/test_nvfp4_diffusion_flag.py+++ b/studio/backend/tests/test_nvfp4_diffusion_flag.py@@ -564,6 +564,60 @@ def test_the_fast_dispatch_is_never_probed_or_verified(monkeypatch):assert touched == []+def test_no_flashinfer_install_is_attempted(monkeypatch):+ from core.inference import diffusion_nvfp4_install as inst++ inst.reset_install_state()+ touched = []+ monkeypatch.setattr(inst, "_ensure", lambda *a, **k: touched.append("ensure") or (True, None))+ monkeypatch.setattr(inst, "_import_flashinfer", lambda *a, **k: touched.append("import"))+ commands = []+ ok, reason = inst.ensure_flashinfer_for_nvfp4(+ 0, run = lambda *a, **k: commands.append(a), owner = object()+ )+ assert ok is False and DISABLED in reason+ assert touched == [] and commands == []+ assert inst.last_install_reason() is None+ assert inst.nvfp4_backend_fields("torchao") == {+ "transformer_quant_backend": "torchao",+ "transformer_quant_backend_reason": None,+ }+++def test_the_loaders_never_ask_whether_an_nvfp4_checkpoint_will_load(monkeypatch):+ from core.inference.diffusion import DiffusionBackend+ from core.inference.video import VideoBackend++ asked = []+ monkeypatch.setattr(+ "huggingface_hub.HfApi", lambda *a, **k: types.SimpleNamespace(model_info = asked.append)+ )+ assert (+ DiffusionBackend._nvfp4_checkpoint_will_load(+ object(), None, "Tongyi-MAI/Z-Image-Turbo", None, None+ )+ is False+ )+ assert (+ VideoBackend._nvfp4_denoiser_checkpoint_will_load(+ object(), _wan_a14b(), _WAN_T2V, None, None+ )+ is False+ )+ assert asked == []+++def test_enabled_the_install_gate_is_reached(monkeypatch):+ _enable(monkeypatch)+ from core.inference import diffusion_nvfp4_install as inst++ inst.reset_install_state()+ seen = []+ monkeypatch.setattr(inst, "_ensure", lambda *a, **k: seen.append("ensure") or (True, None))+ assert inst.ensure_flashinfer_for_nvfp4(0) == (True, None)+ assert seen == ["ensure"]++def _prequant_dir(root, name, scheme):"""A directory holding one tiny safetensors pre-quant artifact that records ``scheme``."""import jsondiff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.pyindex 0409fd9c8df..246ec23806e 100644--- a/studio/backend/tests/test_video_backend.py+++ b/studio/backend/tests/test_video_backend.py@@ -9351,6 +9351,100 @@ def test_a_checkpoint_that_will_not_load_falls_back_to_the_dense_quant(fake_runtassert "unsloth/" not in status["resolved"]["transformer_quant"]["reason"]+def test_a_superseded_nvfp4_load_cannot_overwrite_the_install_reason(fake_runtime, monkeypatch):+ # A superseded load returning from the install must not overwrite the newer load's reason.+ import threading++ import core.inference.video as video_mod+ from core.inference import diffusion_nvfp4_install as inst++ monkeypatch.setattr(video_mod, "dense_transformer_supported", lambda target: True)+ monkeypatch.setattr(video_mod, "quantize_transformer", lambda *a, **k: "nvfp4")+ _stub_denoiser_seed(monkeypatch, seeded = False)++ old_entered, release_old = threading.Event(), threading.Event()++ def _ensure(+ device,+ *,+ logger = None,+ local_files_only = False,+ owner = None,+ **kw,+ ):+ if threading.current_thread() is not threading.main_thread():+ old_entered.set()+ assert release_old.wait(timeout = 10), "test never released the old load"+ outcome = (False, "old load: flashinfer install refused")+ else:+ outcome = (True, "installed flashinfer for NVFP4")+ inst.record_install_reason(owner, *outcome, device)+ return outcome++ monkeypatch.setattr(inst, "ensure_flashinfer_for_nvfp4", _ensure)+ monkeypatch.setattr(+ VideoBackend, "_nvfp4_denoiser_checkpoint_will_load", lambda self, *a, **k: True+ )+ inst.reset_install_state()+ backend = VideoBackend()+ kwargs = dict(model_kind = "pipeline", transformer_quant = "nvfp4")++ old_exc = []++ def _old_load():+ try:+ backend.load_pipeline("Wan-AI/Wan2.2-T2V-A14B-Diffusers", _load_token = 1, **kwargs)+ except Exception as exc: # noqa: BLE001 - superseded by the newer load+ old_exc.append(exc)++ backend._load_token = 1+ old = threading.Thread(target = _old_load)+ old.start()+ try:+ assert old_entered.wait(timeout = 10), "old load never reached the FlashInfer install"+ backend._load_token = 2+ backend.load_pipeline("Wan-AI/Wan2.2-T2V-A14B-Diffusers", _load_token = 2, **kwargs)+ committed = backend._state+ assert inst._REASONS[backend][0] is None+ finally:+ release_old.set()+ old.join(timeout = 10)+ assert old_exc and "superseded" in str(old_exc[0])+ assert backend._state is committed+ assert inst._REASONS[backend][0] is None, "the superseded load relabelled the resident model"+ inst.reset_install_state()+++def test_an_on_the_fly_nvfp4_load_clears_the_previous_install_reason(fake_runtime, monkeypatch):+ # A skipped install must still clear the previous model's reason.+ import core.inference.video as video_mod+ from core.inference import diffusion_nvfp4_install as inst++ monkeypatch.setattr(video_mod, "dense_transformer_supported", lambda target: True)+ monkeypatch.setattr(video_mod, "quantize_transformer", lambda *a, **k: "nvfp4")+ _stub_denoiser_seed(monkeypatch, seeded = False)++ def _ensure(*a, **k):+ raise AssertionError("the gate should have skipped the install")++ monkeypatch.setattr(inst, "ensure_flashinfer_for_nvfp4", _ensure)+ monkeypatch.setattr(+ VideoBackend, "_nvfp4_denoiser_checkpoint_will_load", lambda self, *a, **k: False+ )+ inst.reset_install_state()+ backend = VideoBackend()+ inst.record_install_reason(backend, False, "offline: flashinfer is not downloaded", 0)+ backend.load_pipeline(+ "Wan-AI/Wan2.2-T2V-A14B-Diffusers", model_kind = "pipeline", transformer_quant = "nvfp4"+ )+ assert inst._REASONS[backend][0] is None+ assert (+ inst.nvfp4_backend_fields("torchao", owner = backend)["transformer_quant_backend_reason"]+ != "offline: flashinfer is not downloaded"+ )+ inst.reset_install_state()++def test_seeding_is_skipped_entirely_under_offload(fake_runtime, monkeypatch):import core.inference.video as video_mod@@ -10478,6 +10572,292 @@ def test_a_failed_replacement_keeps_the_resident_models_nvfp4_state(monkeypatch,assert resets == ([] if resident else [True])+class _StopAfterInstallGate(Exception):+ """Raised just past the FlashInfer pre-install hop."""+++class _Sibling:+ def __init__(+ self,+ rfilename,+ size = 1,+ ):+ self.rfilename = rfilename+ self.size = size+++def _hub_refusal(cls, repo = "unsloth/Wan2.2-T2V-A14B-NVFP4"):+ # response is optional in huggingface_hub 0.x but required in 1.x; a stub works on either.+ return cls(+ f"401 Client Error. Repository Not Found for url: https://huggingface.co/api/models/{repo}",+ response = types.SimpleNamespace(headers = {}, request = None),+ )+++def _video_install_probe(+ monkeypatch,+ *,+ listing = None,+ refusal = None,+ cached = False,+ free_mib = 180_000,+):+ """Record FlashInfer installs and Hub listings, stopping after the hop."""+ import core.inference.video as video_mod+ from core.inference import diffusion_nvfp4_install as inst+ from core.inference.diffusion import DiffusionBackend++ installs: list = []+ listed: list = []+ dispatched: list = []++ def _ensure(device, **kwargs):+ installs.append((device, kwargs.get("local_files_only")))+ return True, "installed flashinfer for NVFP4"++ real_hop = VideoBackend._install_flashinfer_for_seed++ def _hop(*args, **kwargs):+ real_hop(*args, **kwargs)+ raise _StopAfterInstallGate()++ class _Api:+ def __init__(self, *a, **k):+ pass++ def model_info(+ self,+ repo_id,+ files_metadata = False,+ token = None,+ ):+ listed.append(repo_id)+ if refusal is not None:+ raise refusal+ return types.SimpleNamespace(siblings = [_Sibling(n) for n in (listing or [])])++ def _modular(self, **kwargs):+ dispatched.append(kwargs.get("_nvfp4_install_outcome"))+ raise _StopAfterInstallGate()++ monkeypatch.setattr(inst, "ensure_flashinfer_for_nvfp4", _ensure)+ monkeypatch.setattr("huggingface_hub.HfApi", _Api)+ monkeypatch.setattr(+ DiffusionBackend, "_hub_file_is_cached", staticmethod(lambda repo, name, *a, **k: cached)+ )+ monkeypatch.setattr(+ VideoBackend,+ "_device_target",+ lambda self, ordinal = None: types.SimpleNamespace(device = "cuda", dtype = None, ordinal = 0),+ )+ from core.inference.diffusion_memory import DeviceMemory++ monkeypatch.setattr(+ video_mod,+ "settled_snapshot_device_memory",+ lambda target: DeviceMemory("cuda", "cuda", "discrete_vram", free_mib, 183_000),+ )+ monkeypatch.setattr(+ video_mod,+ "_video_auto_denoiser_scheme",+ lambda fam, *, requested = None, **kw: "nvfp4" if requested == "nvfp4" else None,+ )+ monkeypatch.setattr(VideoBackend, "_load_h3_modular_pipeline", _modular)+ monkeypatch.setattr(VideoBackend, "_install_flashinfer_for_seed", staticmethod(_hop))+ return installs, listed, dispatched+++def _video_load_to_the_install_gate(repo_id = "Wan-AI/Wan2.2-T2V-A14B-Diffusers", **overrides):+ kwargs = dict(model_kind = "pipeline", transformer_quant = "nvfp4")+ kwargs.update(overrides)+ with pytest.raises(_StopAfterInstallGate):+ VideoBackend().load_pipeline(repo_id, **kwargs)++[email protected]("error", ["RepositoryNotFoundError", "GatedRepoError"])+ "repo_id, hosted",+ [+ ("Wan-AI/Wan2.2-T2V-A14B-Diffusers", "unsloth/Wan2.2-T2V-A14B-NVFP4"),+ ("Wan-AI/Wan2.2-TI2V-5B-Diffusers", "unsloth/Wan2.2-TI2V-5B-NVFP4"),+ ],+)+def test_an_nvfp4_video_checkpoint_the_hub_refuses_installs_no_flashinfer(+ fake_runtime, monkeypatch, error, repo_id, hosted+):+ # Private / gated repo: on-the-fly torchao build, FlashInfer unused.+ import huggingface_hub.errors as hub_errors++ installs, listed, _ = _video_install_probe(+ monkeypatch, refusal = _hub_refusal(getattr(hub_errors, error), hosted)+ )+ _video_load_to_the_install_gate(repo_id)+ assert installs == []+ assert listed == [hosted]+++def test_an_nvfp4_video_repo_missing_a_denoiser_installs_no_flashinfer(fake_runtime, monkeypatch):+ # A14B needs BOTH denoisers.+ installs, listed, _ = _video_install_probe(monkeypatch, listing = ["Wan2.2-T2V-A14B-NVFP4.pt"])+ _video_load_to_the_install_gate()+ assert installs == []+ assert listed == ["unsloth/Wan2.2-T2V-A14B-NVFP4"]+++def test_an_nvfp4_video_family_with_no_hosted_checkpoint_installs_no_flashinfer(+ fake_runtime, monkeypatch+):+ import core.inference.video_denoiser_prequant as dq++ installs, listed, _ = _video_install_probe(monkeypatch)+ monkeypatch.setattr(dq, "denoiser_prequant_sources", lambda fam, scheme, base: None)+ _video_load_to_the_install_gate()+ assert installs == []+ assert listed == []+++def test_a_reachable_nvfp4_video_checkpoint_still_installs_flashinfer(fake_runtime, monkeypatch):+ installs, listed, _ = _video_install_probe(+ monkeypatch,+ listing = ["Wan2.2-T2V-A14B-NVFP4.pt", "Wan2.2-T2V-A14B-transformer_2-NVFP4.pt"],+ )+ _video_load_to_the_install_gate()+ assert listed == ["unsloth/Wan2.2-T2V-A14B-NVFP4"]+ assert installs == [("cuda", False)]+++def test_with_the_nvfp4_switch_off_a_reachable_video_checkpoint_installs_nothing(+ fake_runtime, monkeypatch+):+ monkeypatch.delenv("UNSLOTH_NVFP4_DIFFUSION", raising = False)+ installs, listed, _ = _video_install_probe(+ monkeypatch,+ listing = ["Wan2.2-T2V-A14B-NVFP4.pt", "Wan2.2-T2V-A14B-transformer_2-NVFP4.pt"],+ )+ _video_load_to_the_install_gate(transformer_quant = None, _video_auto_denoiser_planned = "nvfp4")+ assert installs == []+ assert listed == [], "no Hub request to a *-NVFP4 repo while the switch is off"+++def test_a_video_plan_that_settled_nvfp4_installs_without_asking_the_hub_again(+ fake_runtime, monkeypatch+):+ installs, listed, _ = _video_install_probe(+ monkeypatch, refusal = RuntimeError("no request expected")+ )+ _video_load_to_the_install_gate(transformer_quant = None, _video_auto_denoiser_planned = "nvfp4")+ assert listed == []+ assert installs == [("cuda", False)]+++def test_a_video_seed_the_plan_declined_installs_no_flashinfer(fake_runtime, monkeypatch):+ from core.inference.video import DENOISER_SEED_DECLINED++ installs, listed, _ = _video_install_probe(+ monkeypatch,+ listing = ["Wan2.2-T2V-A14B-NVFP4.pt", "Wan2.2-T2V-A14B-transformer_2-NVFP4.pt"],+ )+ _video_load_to_the_install_gate(_video_auto_denoiser_planned = DENOISER_SEED_DECLINED)+ assert installs == []+ assert listed == []+++def test_a_video_seed_the_live_memory_plan_drops_installs_no_flashinfer(fake_runtime, monkeypatch):+ # Live free memory short: the plan offloads and drops the capacity-settled seed, so no install.+ installs, listed, _ = _video_install_probe(+ monkeypatch, refusal = RuntimeError("no request expected"), free_mib = 4_000+ )+ monkeypatch.setattr(+ VideoBackend,+ "_device_target",+ lambda self, ordinal = None: types.SimpleNamespace(+ device = "cuda", dtype = None, ordinal = 0, supports_model_cpu_offload = True+ ),+ )+ _video_load_to_the_install_gate(transformer_quant = None, _video_auto_denoiser_planned = "nvfp4")+ assert installs == []+ assert listed == []++[email protected]("cached", [False, True])+def test_an_offline_nvfp4_video_load_asks_only_the_cache(fake_runtime, monkeypatch, cached):+ installs, listed, _ = _video_install_probe(+ monkeypatch, refusal = RuntimeError("an offline load made a Hub request"), cached = cached+ )+ _video_load_to_the_install_gate(local_files_only = True)+ assert listed == []+ assert installs == ([("cuda", True)] if cached else [])+++def _stub_h3_nvfp4_checkpoint(monkeypatch):+ """Register a fake hosted NVFP4 MiniMax-H3 denoiser; records each lookup's task."""+ import core.inference.diffusion_prequant as prequant_mod+ import core.inference.video as video_mod++ tasks: list = []++ def _available(+ fam,+ scheme,+ task = None,+ base_repo = None,+ ):+ tasks.append(task)+ return scheme == "nvfp4"++ def _resolve(+ fam,+ scheme,+ *,+ path_override = None,+ base_repo = None,+ task = None,+ ):+ return types.SimpleNamespace(+ kind = "repo",+ location = "unsloth/MiniMax-H3-NVFP4",+ filename = f"MiniMax-H3-{task}-NVFP4.pt",+ fallback_filenames = (),+ )++ monkeypatch.setattr(video_mod, "video_family_prequant_available", _available)+ monkeypatch.setattr(prequant_mod, "resolve_prequant_source", _resolve)+ diffusers = sys.modules["diffusers"]+ monkeypatch.setattr(diffusers, "ModularPipeline", _FakeModularPipeline, raising = False)+ fam = _detect_load_family("MiniMaxAI/MiniMax-H3", None, "minimax-h3")+ monkeypatch.setattr(diffusers, fam.transformer_class, _FakeTransformer, raising = False)+ return tasks+++def test_the_minimax_h3_modular_path_skips_the_install_for_a_refused_checkpoint(+ fake_runtime, monkeypatch+):+ from huggingface_hub.errors import RepositoryNotFoundError++ installs, listed, dispatched = _video_install_probe(+ monkeypatch, refusal = _hub_refusal(RepositoryNotFoundError, "unsloth/MiniMax-H3-NVFP4")+ )+ tasks = _stub_h3_nvfp4_checkpoint(monkeypatch)+ _video_load_to_the_install_gate("MiniMaxAI/MiniMax-H3", family_override = "minimax-h3")+ assert installs == []+ assert listed == ["unsloth/MiniMax-H3-NVFP4"]+ assert dispatched == [None], "the modular load was handed an install outcome it never earned"+ assert "fl2va" in tasks+++def test_the_minimax_h3_modular_path_installs_for_a_reachable_checkpoint(fake_runtime, monkeypatch):+ installs, listed, dispatched = _video_install_probe(+ monkeypatch, listing = ["MiniMax-H3-ref2va-NVFP4.pt"]+ )+ _stub_h3_nvfp4_checkpoint(monkeypatch)+ _video_load_to_the_install_gate(+ "MiniMaxAI/MiniMax-H3", family_override = "minimax-h3", h3_task = "ref2va"+ )+ assert listed == ["unsloth/MiniMax-H3-NVFP4"]+ assert installs == [("cuda", False)]+ assert dispatched == [(True, "installed flashinfer for NVFP4")]++@pytest.mark.parametrize("scheme", ["int8", "fp8"])def test_an_explicit_video_scheme_on_amd_runs_weight_only_without_forcing_compile(fake_runtime, monkeypatch, schemediff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex d8bb22b4c4d..469172b66ad 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -43,6 +43,7 @@ export interface DiffusionStatus {// ("int8" / "fp8" / ...), null = the GGUF ran as-is.transformer_quant?: string | null;transformer_quant_backend?: string | null;+ transformer_quant_backend_reason?: string | null;// Text-encoder quant engaged ("fp8" | "fp8_dynamic" | "int8" | "nvfp4"), null = dense bf16.text_encoder_quant?: string | null;// Memory mode the load ran under: "auto" | "fast" | "balanced" | "low_vram".diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.tsindex 4a5d7f7bba0..3fec394faf0 100644--- a/studio/frontend/src/features/video/api.ts+++ b/studio/frontend/src/features/video/api.ts@@ -78,6 +78,7 @@ export interface VideoStatus {// Dense DiT precision actually engaged ("int8" | "fp8" | ...) or null for bf16.transformer_quant?: string | null;transformer_quant_backend?: string | null;+ transformer_quant_backend_reason?: string | null;// Text-encoder quant actually engaged ("fp8" | "fp8_dynamic" | "int8" | "nvfp4") or null for dense bf16.text_encoder_quant?: string | null;// Whether the loaded family produces a synchronized audio track.