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 0.7.3 prebuilt kernels for diffusion NVFP4 (#17215)
Daniel Han0a41a7af00c9
diff --git a/studio/backend/core/inference/diffusion_nvfp4_dispatch.py b/studio/backend/core/inference/diffusion_nvfp4_dispatch.pyindex b5dd11eb36f..7c96235c65d 100644--- a/studio/backend/core/inference/diffusion_nvfp4_dispatch.py+++ b/studio/backend/core/inference/diffusion_nvfp4_dispatch.py@@ -12,8 +12,8 @@ import weakreffrom functools import partialfrom typing import Any, Optional-# The only versions whose private layout was read and verified. Exact, never a minimum.-_SUPPORTED = ("0.6.6",)+# Exact versions whose private layout was read, never a minimum.+_SUPPORTED = ("0.6.6", "0.7.3")NVFP4_FAST_DISPATCH_ENV = "UNSLOTH_NVFP4_FAST_DISPATCH"@@ -203,7 +203,16 @@ def _fast_quantize(if got is None:return None, Nonefn, pdl = got- xq, sf = fn(x, global_sf, 16, False, True, False, pdl)+ # By keyword: 0.7 put ``is_global_scale_inversed`` before ``enable_pdl``; positional pdl inverts the scale.+ xq, sf = fn(+ x,+ global_sf,+ sf_vec_size = 16,+ sf_use_ue8m0 = False,+ is_sf_swizzled_layout = True,+ is_sf_8x4_layout = False,+ enable_pdl = pdl,+ )return xq, sf.reshape((-1, x.shape[-1] // 16))diff --git a/studio/backend/core/inference/diffusion_nvfp4_install.py b/studio/backend/core/inference/diffusion_nvfp4_install.pyindex 70e364ff19a..466762f2c8a 100644--- a/studio/backend/core/inference/diffusion_nvfp4_install.py+++ b/studio/backend/core/inference/diffusion_nvfp4_install.py@@ -9,25 +9,70 @@ import astimport contextlibimport importlibimport os+import reimport shutilimport subprocessimport weakrefimport sysimport tempfileimport threading+from dataclasses import dataclassfrom typing import Any, Callable, Optionalfrom .rocm_bf16 import is_rocm_torch# 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))+++@dataclass(frozen = True)+class FlashinferRelease:+ """One installable flashinfer: exact version, the CUDA tags with a prebuilt jit-cache, and its packaging."""++ version: str+ jit_cache_cuda: tuple[tuple[int, int], ...]+ # 0.7+: ``flashinfer-jit-cache`` is a shim; the kernels ship per arch as ``flashinfer-jit-cache-<arch>``.+ split_providers: bool+ # Dependencies it needs at least at these versions; one already installed below is pinned, so skip the release.+ dependency_floors: tuple[tuple[str, tuple[int, ...]], ...] = ()+ # Hold a fresh nvidia-cutlass-dsl to the hub FA4 range; only a release that accepts it can.+ holds_cutlass_dsl: bool = False+ size_hint: str = ""+++# Newest first; an install takes the first that fits this host (see ``select_release``). Exact, never floors. The+# dispatch allowlist and the op fakes were read against each one. No flashinfer-cubin: it carries the trtllm-gen+# cubins, and NVFP4 here runs only the cutlass GEMM and the fp4 quantiser, both in the jit-cache.+FLASHINFER_RELEASES = (+ FlashinferRelease(+ "0.7.3",+ ((12, 9), (13, 0), (13, 4)),+ split_providers = True,+ dependency_floors = (+ ("nvidia-cutlass-dsl", (4, 8)),+ ("apache-tvm-ffi", (0, 1, 11)),+ ("nvidia-cudnn-frontend", (1, 32)),+ ),+ size_hint = "about 350 MB",+ ),+ # No cu128 jit-cache for 0.7.x, and the only one that keeps nvidia-cutlass-dsl in the hub FA4 range.+ FlashinferRelease(+ "0.6.6",+ ((12, 8), (12, 9), (13, 0)),+ split_providers = False,+ holds_cutlass_dsl = True,+ size_hint = "about 1.5 GB",+ ),+)+FLASHINFER_VERSION = FLASHINFER_RELEASES[0].version+FLASHINFER_VERSIONS = tuple(release.version for release in FLASHINFER_RELEASES)+FLASHINFER_JIT_CACHE_CUDA = FLASHINFER_RELEASES[0].jit_cache_cuda+# Compute capability -> the split jit-cache provider that holds its NVFP4 kernels (fp4_quantization_*, fp4_gemm_*).+FLASHINFER_JIT_CACHE_ARCH = {(10, 0): "sm100a", (10, 3): "sm103a", (12, 0): "sm120f"}# 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/"@@ -213,7 +258,7 @@ def _await_inflight_install(wait: bool = True) -> bool:if "flashinfer" in sys.modules:return Trueinstalled = _dist_version(FLASHINFER_PACKAGE)- if installed is None or installed.split("+", 1)[0] != FLASHINFER_VERSION:+ if installed is None or installed.split("+", 1)[0] not in FLASHINFER_VERSIONS:return Truewith _env_install_lock() if wait else _env_install_lock(0) as held:return held@@ -291,21 +336,103 @@ def _parse_cuda(version: Optional[str]) -> Optional[tuple[int, int]]:return None-def jit_cache_tag(cuda_version: Optional[str]) -> Optional[str]:+def jit_cache_tag(+ cuda_version: Optional[str], available: tuple[tuple[int, int], ...] = FLASHINFER_JIT_CACHE_CUDA+) -> 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]]+ usable = [c for c in available if c[0] == running[0] and c[1] <= running[1]]if not usable:return Nonemajor, minor = max(usable)return f"cu{major}{minor}"-def _jit_cache_version(tag: Optional[str]) -> Optional[str]:+def _jit_cache_version(tag: Optional[str], version: str = FLASHINFER_VERSION) -> 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}"+ return None if tag is None else f"{version}+{tag}"+++def jit_cache_provider(release: FlashinferRelease, capability: Any) -> Optional[str]:+ """The ``flashinfer-jit-cache-<arch>`` distribution a split release needs on ``capability``, else None."""+ if not release.split_providers:+ return None+ try:+ arch = FLASHINFER_JIT_CACHE_ARCH.get(tuple(int(c) for c in capability))+ except Exception: # noqa: BLE001+ return None+ return f"{FLASHINFER_JIT_CACHE_PACKAGE}-{arch}" if arch else None+++def _nvfp4_capabilities(device: Any) -> list[tuple[int, int]]:+ """``device``'s capability first, then every other visible card's that runs flashinfer NVFP4: a split release+ installs each one's provider up front, since a later load on another arch finds flashinfer already importable."""+ from .diffusion_nvfp4_ops import NVFP4_FLASHINFER_CAPS, _device_capability++ caps: list[tuple[int, int]] = []+ first = _device_capability(device)+ if first is not None:+ caps.append(tuple(first))+ try:+ import torch+ count = int(torch.cuda.device_count())+ except Exception: # noqa: BLE001 - no count means only ``device``+ count = 0+ for index in range(count):+ cap = _device_capability(index)+ if cap is not None and tuple(cap) in NVFP4_FLASHINFER_CAPS and tuple(cap) not in caps:+ caps.append(tuple(cap))+ return caps+++def _version_tuple(version: Optional[str]) -> tuple[int, ...]:+ """Leading release numbers: ``4.6.2a0`` -> ``(4, 6, 2)``, ``0.1.15.post2`` -> ``(0, 1, 15)``."""+ out = []+ for part in str(version or "").split("+", 1)[0].split("."):+ match = re.match(r"\d+", part)+ if match is None:+ break+ out.append(int(match.group(0)))+ if match.end() != len(part):+ break+ return tuple(out)+++def _held_below_floor(release: FlashinferRelease, dists: dict[str, str]) -> Optional[str]:+ """The first installed dependency below ``release``'s floor (the constraints file pins it), else None."""+ for name, floor in release.dependency_floors:+ have = dists.get(name)+ if have is not None and _version_tuple(have) < floor:+ return f"{name}>={'.'.join(map(str, floor))} (installed {have})"+ return None+++def select_release(+ cuda_version: Optional[str], capability: Any, dists: dict[str, str]+) -> tuple[Optional[FlashinferRelease], Optional[str], str]:+ """``(release, jit-cache tag, note)``: the newest release with a prebuilt jit-cache for this CUDA and capability+ whose dependency floors fit ``dists``; else the newest that fits at all, with no tag (JIT); else ``(None, None,+ why)``. Installed packages are never moved, so a held dependency rules a release out rather than being raised."""+ fitting: list[FlashinferRelease] = []+ held: list[str] = []+ for release in FLASHINFER_RELEASES:+ below = _held_below_floor(release, dists)+ if below is not None:+ held.append(f"flashinfer {release.version} needs {below}")+ continue+ fitting.append(release)+ for release in fitting:+ tag = jit_cache_tag(cuda_version, release.jit_cache_cuda)+ if tag is None:+ continue+ if release.split_providers and jit_cache_provider(release, capability) is None:+ continue+ return release, tag, "; ".join(held)+ if fitting:+ return fitting[0], None, "; ".join(held)+ return None, None, "; ".join(held)def _same_version(a: Optional[str], b: Optional[str]) -> bool:@@ -733,22 +860,45 @@ def _run(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)+_VERIFY_CODE = (+ "import flashinfer, sys\n"+ "names = ''\n"+ "try:\n"+ " from flashinfer.jit import env as _env\n"+ " names = ','.join(sorted(str(p.distribution) for p in getattr(_env, 'FLASHINFER_AOT_PROVIDERS', ())))\n"+ "except Exception:\n"+ " pass\n"+ "sys.stdout.write('providers=' + names + '\\n' + str(getattr(flashinfer, '__version__', 'unknown')))\n"+)+++def _verify_child(+ run: Callable[..., Any],+ version: str = FLASHINFER_VERSION,+ providers: tuple[str, ...] = (),+) -> tuple[bool, str]:+ """``import flashinfer`` in a fresh interpreter, which is where the next process will do it. A split release+ must also list each of ``providers``: flashinfer ignores a mismatched one, and its kernels would then JIT."""+ ok, output = _run(run, [sys.executable, "-c", _VERIFY_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:+ lines = output.strip().splitlines() if output.strip() else []+ got = lines[-1].strip() if lines else ""+ if got != version:+ return (+ False,+ f"flashinfer imported as {got or 'unknown'}, expected {version}",+ )+ listed = next((ln.split("=", 1)[1] for ln in lines if ln.startswith("providers=")), "")+ loaded = {_canonical(n) for n in listed.split(",") if n}+ missing = [p for p in providers if _canonical(p) not in loaded]+ if missing:return (False,- f"flashinfer imported as {version or 'unknown'}, expected {FLASHINFER_VERSION}",+ f"flashinfer {version} imported but did not load the {', '.join(missing)} prebuilt kernels"+ f" (providers: {listed or 'none'})",)- return True, version+ return True, gotdef _drift(before: dict[str, str], after: dict[str, str]) -> dict[str, tuple[str, Optional[str]]]:@@ -818,6 +968,7 @@ def _rollback(own_index: bool = False,reported: Optional[set[str]] = None,unreported_step: bool = False,+ providers: tuple[str, ...] = (),) -> str:"""Remove what this install reported adding and restore what it moved; returns a one-line summary."""after = installed_distributions()@@ -825,7 +976,9 @@ def _rollback(ours = set(reported or ()) & newif 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)+ roots = {FLASHINFER_PACKAGE, FLASHINFER_JIT_CACHE_PACKAGE}+ roots |= {_canonical(p) for p in providers}+ ours |= _requirement_closure(roots, new)added = sorted(ours)if new - ours and logger is not None:logger.info(@@ -873,35 +1026,54 @@ def _install(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"))+ from .diffusion_nvfp4_ops import _device_capability++ capability = _device_capability(device)+ release, tag, held = select_release(+ torch_before.get("cuda_version"), capability, installed_distributions()+ )+ if release is None:+ return (+ False,+ f"flashinfer not installed: {held}; Unsloth does not move installed packages",+ True,+ )+ version = release.version+ # Every visible NVFP4 arch's provider: once flashinfer imports, a load on another card never installs again.+ providers: tuple[str, ...] = ()+ if tag is not None:+ found = (jit_cache_provider(release, cap) for cap in _nvfp4_capabilities(device))+ providers = tuple(dict.fromkeys(p for p in found if p))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 "+ f"{', '.join(FLASHINFER_VERSIONS)} 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):+ # A stray jit-cache, provider or cubin of another version shadows ours; not ours to replace.+ extras = [FLASHINFER_JIT_CACHE_PACKAGE, FLASHINFER_CUBIN_PACKAGE, *providers]+ for extra in extras:present = _dist_version(extra)- if present is not None and present.split("+", 1)[0] != FLASHINFER_VERSION:+ if present is not None and present.split("+", 1)[0] != version:return (False,f"flashinfer not installed: {extra} {present} is already installed and "- f"flashinfer-python {FLASHINFER_VERSION} would refuse to import beside it",+ f"flashinfer-python {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,- )+ for extra in [FLASHINFER_JIT_CACHE_PACKAGE, *providers]:+ cache = _dist_version(extra)+ if cache is not None and not _same_version(cache, _jit_cache_version(tag, version)):+ return (+ False,+ f"flashinfer not installed: {extra} {cache} is already installed and "+ f"does not match CUDA {torch_before.get('cuda_version')}"+ + (f" (expected {_jit_cache_version(tag, version)})" if tag else ""),+ True,+ )uv = _uv_executable()config = _installer_config(uv, run)if config["refusal"]:@@ -911,7 +1083,8 @@ def _install(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}/"+ FLASHINFER_JIT_CACHE_INDEX.format(tag = tag)+ + f"/{providers[0] if providers else FLASHINFER_JIT_CACHE_PACKAGE}/")if config["unprobed"]:probes = []@@ -921,34 +1094,33 @@ def _install(before = installed_distributions()constraints = _write_constraints(before)- if "nvidia-cutlass-dsl" not in before:+ if release.holds_cutlass_dsl and "nvidia-cutlass-dsl" not in before:try:with open(constraints, "a", encoding = "utf-8") as fh:fh.write(_CUTLASS_DSL_CONSTRAINT + "\n")except OSError:pass- size_hint = " (about 1.5 GB of prebuilt kernels)" if tag else ""+ size_hint = f" ({release.size_hint} of prebuilt kernels)" if tag and release.size_hint else ""+ kernels = ", ".join(providers) or FLASHINFER_JIT_CACHE_PACKAGE_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}",+ f"installing {FLASHINFER_PACKAGE} {version}"+ f"{f' with {kernels} 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:+ # The full local version: `==0.7.3` would accept a cache built for another CUDA. A split release's shim+ # requires every arch's provider, so --no-deps installs the shim and the visible NVFP4 archs' only.+ specs = [f"{p}=={_jit_cache_version(tag, version)}" for p in providers]+ specs.append(f"{FLASHINFER_JIT_CACHE_PACKAGE}=={_jit_cache_version(tag, version)}")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)}",- ],+ + ["--only-binary", ":all:", "--no-deps", *specs],_pinned_index_env(None if uv else config.get("pip_settings", {})),))@@ -961,7 +1133,7 @@ def _install(":all:","-c",constraints,- f"{FLASHINFER_PACKAGE}=={FLASHINFER_VERSION}",+ f"{FLASHINFER_PACKAGE}=={version}",],None,)@@ -1001,13 +1173,20 @@ def _install(else f"{torch_after.get('torch_version')} CUDA {torch_after.get('cuda_version')}",)else:- ok, detail = _verify_child(run)+ ok, detail = _verify_child(run, version, providers)if not ok:failure = detailif failure is not None:rolled = _rollback(- run, uv, before, logger, config["own_index"], reported, unreported_step = unreported_step+ run,+ uv,+ before,+ logger,+ config["own_index"],+ reported,+ unreported_step = unreported_step,+ providers = providers,)return False, f"flashinfer install rolled back ({rolled}): {failure}", Truediff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 4cd110dea76..e690132f502 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -11875,11 +11875,12 @@ def test_the_download_plan_resolves_the_same_nvfp4_rung_the_load_does(monkeypatcmonkeypatch.setattr(dmod, "prequant_checkpoint_cached", lambda source, **kw: False)monkeypatch.setattr(ops, "select_nvfp4_backend", lambda device = None: "flashinfer")from core.inference import diffusion_nvfp4_gate as gate- from core.inference.diffusion_nvfp4_install import FLASHINFER_VERSION+ from core.inference.diffusion_nvfp4_install import FLASHINFER_RELEASES- # The gate covers only the flashinfer its record was measured on; pin the version Studio installs so the- # answer does not depend on this host's flashinfer (CI runners have none).- monkeypatch.setattr(gate, "installed_flashinfer_version", lambda: FLASHINFER_VERSION)+ # Pin the covered release so the answer does not depend on this host's flashinfer.+ monkeypatch.setattr(+ gate, "installed_flashinfer_version", lambda: FLASHINFER_RELEASES[-1].version+ )target = SimpleNamespace(device = "cuda", dtype = None)assert (@@ -11891,7 +11892,14 @@ def test_the_download_plan_resolves_the_same_nvfp4_rung_the_load_does(monkeypatc== "unsloth/FLUX.1-schnell-NVFP4")- # An unreadable version is not covered: the plan and the load both drop the nvfp4 rung, so nothing fetches it.+ # An unmeasured or unreadable version: plan and load both drop the nvfp4 rung.+ from core.inference.diffusion_nvfp4_install import FLASHINFER_VERSION++ monkeypatch.setattr(gate, "installed_flashinfer_version", lambda: FLASHINFER_VERSION)+ assert (+ dmod._planned_quant_scheme(fam, target, "auto", base_repo = base, prequant_path = None)+ != "nvfp4"+ )monkeypatch.setattr(gate, "installed_flashinfer_version", lambda: None)assert (dmod._planned_quant_scheme(fam, target, "auto", base_repo = base, prequant_path = None)diff --git a/studio/backend/tests/test_diffusion_nvfp4_dispatch.py b/studio/backend/tests/test_diffusion_nvfp4_dispatch.pyindex 70f1f0524e6..25528b6eea9 100644--- a/studio/backend/tests/test_diffusion_nvfp4_dispatch.py+++ b/studio/backend/tests/test_diffusion_nvfp4_dispatch.py@@ -440,3 +440,58 @@ def test_a_collected_layer_takes_its_cached_weights_and_their_vram_with_it():torch.cuda.empty_cache()freed = before - torch.cuda.memory_allocated(device)assert freed >= weight_bytes, f"{freed} bytes released, expected at least {weight_bytes}"+++def _sig_066(+ input,+ global_scale = None,+ sf_vec_size = 16,+ sf_use_ue8m0 = False,+ is_sf_swizzled_layout = True,+ is_sf_8x4_layout = False,+ enable_pdl = None,+):+ return {+ "inversed": False,+ "pdl": enable_pdl,+ "vec": sf_vec_size,+ "swizzled": is_sf_swizzled_layout,+ }+++def _sig_073(+ input,+ global_scale = None,+ sf_vec_size = 16,+ sf_use_ue8m0 = False,+ is_sf_swizzled_layout = True,+ is_sf_8x4_layout = False,+ is_global_scale_inversed = False,+ enable_pdl = None,+ nvfp4_4over6_code = -1,+):+ return {+ "inversed": is_global_scale_inversed,+ "pdl": enable_pdl,+ "vec": sf_vec_size,+ "swizzled": is_sf_swizzled_layout,+ }++[email protected]("fn", [_sig_066, _sig_073], ids = ["0.6.6", "0.7.3"])+def test_fast_quantize_passes_pdl_by_keyword_on_both_layouts(monkeypatch, fn):+ seen = {}++ def _quant(x, gsf, *args, **kw):+ seen.update(fn(x, gsf, *args, **kw))+ return x, types.SimpleNamespace(reshape = lambda shape: "sf")++ monkeypatch.setattr(dispatch, "quant_fn", lambda device, force = False: (_quant, True))+ x = types.SimpleNamespace(is_contiguous = lambda: True, device = "cuda:0", shape = (4, 32))+ dispatch._fast_quantize(x, None)+ assert seen == {"inversed": False, "pdl": True, "vec": 16, "swizzled": True}+++def test_the_dispatch_allowlist_covers_every_release_studio_installs():+ from core.inference.diffusion_nvfp4_install import FLASHINFER_VERSIONS+ assert set(FLASHINFER_VERSIONS) <= set(dispatch._SUPPORTED)diff --git a/studio/backend/tests/test_diffusion_nvfp4_install.py b/studio/backend/tests/test_diffusion_nvfp4_install.pyindex 8f93a3d7cbe..8b7e1eef580 100644--- a/studio/backend/tests/test_diffusion_nvfp4_install.py+++ b/studio/backend/tests/test_diffusion_nvfp4_install.py@@ -20,6 +20,10 @@ from core.inference import diffusion_nvfp4_install as instfrom core.inference import diffusion_nvfp4_ops as ops_INFERENCE_DIR = pathlib.Path(inst.__file__).resolve().parent+# The default fake host (CUDA 13.0 torch, sm_100, no cutlass-dsl) takes the newest release and its sm100a provider.+V = inst.FLASHINFER_VERSION+FALLBACK = inst.FLASHINFER_RELEASES[-1].version+PROVIDER = "flashinfer-jit-cache-sm100a"_BASE_DISTS = {"torch": "2.12.1+cu130",@@ -29,7 +33,7 @@ _BASE_DISTS = {"packaging": "25.0",}_ADDED_BY_INSTALL = {- "flashinfer-python": "0.6.6",+ "flashinfer-python": V,"apache-tvm-ffi": "0.1.9","nvidia-cutlass-dsl": "4.4.2",}@@ -79,7 +83,11 @@ class _FakeEnv: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")+ providers = ",".join(+ sorted(n for n in self.dists if n.startswith("flashinfer-jit-cache-"))+ )+ got = f"providers={providers}\n{self.dists.get('flashinfer-python', V)}"+ return _Result(0 if good else 1, got if good else "ImportError")if "uninstall" in cmd:for name in cmd[cmd.index("uninstall") + 1 :]:self.dists.pop(name, None)@@ -93,10 +101,12 @@ class _FakeEnv: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):+ 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)+ spec = next(a for a in cmd if a.startswith("flashinfer-python=="))+ self.dists["flashinfer-python"] = spec.split("==", 1)[1]for name, version in self.install_moves.items():self.dists[name] = versionif name == "torch":@@ -108,13 +118,23 @@ class _FakeEnv: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()+ for n, v in {+ **_ADDED_BY_INSTALL,+ "flashinfer-python": self.dists["flashinfer-python"],+ **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}")+ elif any(a.startswith("flashinfer-jit-cache") and "==" in a for a in cmd):+ specs = [a for a in cmd if a.startswith("flashinfer-jit-cache") and "==" in a]+ for spec in specs:+ name, version = spec.split("==", 1)+ self.dists[name] = version+ return _Result(+ 0,+ f"Installed {len(specs)} package(s) in 3.1s\n"+ + "\n".join(f" + {spec}" for spec in specs),+ )else:for spec in cmd:if "==" in spec:@@ -167,7 +187,9 @@ def env(monkeypatch):monkeypatch.setattr(inst,"_import_flashinfer",- lambda: (True, "0.6.6") if fake.importable else (False, "ModuleNotFoundError: flashinfer"),+ lambda: (True, fake.dists.get("flashinfer-python", V))+ 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))@@ -183,7 +205,7 @@ def env(monkeypatch):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)+ main = next(c for c in installs if any(a.startswith("flashinfer-python==") for a in c))jit = next(c for c in installs if any(a.startswith("flashinfer-jit-cache==") for a in c))return main, jit@@ -198,12 +220,12 @@ def test_installs_pinned_flashinfer_and_matching_jit_cache_when_missing(env):installs = env.installs()assert len(installs) == 2main, jit = _steps(installs)- assert "flashinfer-python==0.6.6" in main and "--only-binary" in main+ assert f"flashinfer-python=={V}" in main and "--only-binary" in mainassert "--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 f"flashinfer-jit-cache=={V}+cu130" in jit and "--no-deps" in jitassert 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"+ assert env.dists["flashinfer-jit-cache"] == f"{V}+cu130"pins = env.constraints_seen[0].splitlines()for name, version in _BASE_DISTS.items():assert f"{name}=={version}" in pins@@ -452,7 +474,7 @@ def test_concurrent_loads_install_once(env):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+ assert sum(1 for c in env.installs() if f"flashinfer-python=={V}" in c) == 1def test_a_failed_install_is_attempted_once_per_process(env):@@ -494,7 +516,7 @@ def test_success_forgets_the_dispatch_availability_memo(env, monkeypatch):@pytest.mark.parametrize("cuda, tag",[- ("12.8", "cu128"),+ ("12.8", None), # the newest release has no cu128 jit-cache; select_release falls back("12.9", "cu129"),("13.0", "cu130"),("13.2", "cu130"),@@ -705,7 +727,7 @@ def test_a_configured_mirror_skips_the_pypi_probe_but_not_the_jit_cache_one(env,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/"]+ assert probed == [f"https://flashinfer.ai/whl/cu130/{PROVIDER}/"]def test_a_pip_only_mirror_is_handed_to_uv(env, monkeypatch):@@ -816,8 +838,8 @@ 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"+ assert seen[0].startswith(f"installing flashinfer-python {V}") and "cu130" in seen[0]+ assert seen[-1] == f"installed flashinfer {V} for NVFP4"def test_local_only_load_never_installs(env):@@ -1141,9 +1163,9 @@ def test_a_uv_index_skips_the_pypi_probe_only_when_uv_installs(env, monkeypatch,@pytest.mark.parametrize("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),+ ("13.0", f"{V}+cu129", False), # left over from a cu129 torch+ ("13.0", V, False), # no local tag: the CUDA it was built for cannot be told+ ("14.0", f"{V}+cu130", True),],)def test_a_jit_cache_built_for_another_cuda_refuses(env, monkeypatch, cuda, cache, nvcc):@@ -1156,7 +1178,7 @@ def test_a_jit_cache_built_for_another_cuda_refuses(env, monkeypatch, cuda, cachdef test_a_jit_cache_of_the_running_cuda_is_kept(env):- env.dists["flashinfer-jit-cache"] = "0.6.6+cu130"+ env.dists["flashinfer-jit-cache"] = f"{V}+cu130"ok, reason = _ensure(env)assert ok, reason@@ -1213,7 +1235,7 @@ def test_a_pip_conf_mirror_skips_the_pypi_probe_for_the_pip_fallback(env, monkeyrun = _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/"]+ assert probed == [f"https://flashinfer.ai/whl/cu130/{PROVIDER}/"]@pytest.mark.parametrize(@@ -1350,7 +1372,7 @@ def test_a_uv_config_mirror_skips_the_pypi_probe(env, monkeypatch, tmp_path, texmonkeypatch.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/"]+ assert probed == [f"https://flashinfer.ai/whl/cu130/{PROVIDER}/"]def test_uv_config_discovery_finds_the_project_file_and_honors_no_config(@@ -1435,8 +1457,9 @@ def test_an_install_killed_between_its_steps_completes_on_the_next_load(env):env.importable = "flashinfer-python" in env.distsok, 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+ assert env.dists.get("flashinfer-python") == V+ assert env.dists.get("flashinfer-jit-cache") == f"{V}+cu130", reason+ assert env.dists.get(PROVIDER) == f"{V}+cu130", reason@pytest.mark.parametrize("model", ["DiffusionStatusResponse", "VideoStatusResponse"])@@ -1520,16 +1543,176 @@ def test_an_unreported_failure_does_not_revert_a_concurrent_upgrade(env):assert not [c for c in env.commands if "packaging==25.0" in c]-def test_cutlass_dsl_is_held_to_the_flash4_range_when_absent(env):- # An unconstrained resolve lands cutlass-dsl 4.8.0, which the hub FA4 build cannot load.+def test_cutlass_dsl_is_held_to_the_flash4_range_when_absent_on_the_fallback(env):+ # An unconstrained resolve lands cutlass-dsl 4.8.0, which the hub FA4 build cannot load. Only the fallback+ # release accepts the FA4 range; a cu128 torch has no newer prebuilt jit-cache, so it takes the fallback.+ env.cuda = "12.8"ok, reason = _ensure(env)assert ok, reasonassert "nvidia-cutlass-dsl>=4.4,<4.6" in env.constraints_seen[0].splitlines()+ assert env.dists["flashinfer-python"] == FALLBACK+++def test_the_newest_release_does_not_hold_cutlass_dsl(env):+ # Its own floor (>= 4.8) is above the FA4 range, so a hold there would make every fresh install unresolvable.+ ok, reason = _ensure(env)+ assert ok, reason+ assert env.dists["flashinfer-python"] == V+ assert not any("nvidia-cutlass-dsl" in line for line in env.constraints_seen[0].splitlines())def test_an_installed_cutlass_dsl_is_pinned_not_ranged(env):+ # 4.4.2 is below the newest release's floor and is never moved, so the fallback is installed beside it.env.dists["nvidia-cutlass-dsl"] = "4.4.2"ok, reason = _ensure(env)assert ok, reasonpins = env.constraints_seen[0].splitlines()assert "nvidia-cutlass-dsl==4.4.2" in pins and "nvidia-cutlass-dsl>=4.4,<4.6" not in pins+ assert env.dists["flashinfer-python"] == FALLBACK+ assert PROVIDER not in env.dists+++ "cuda, capability, dists, version, tag",+ [+ ("13.0", (10, 0), {}, V, "cu130"),+ ("12.9", (12, 0), {}, V, "cu129"),+ ("13.2", (10, 3), {}, V, "cu130"),+ ("12.8", (10, 0), {}, FALLBACK, "cu128"),+ ("13.0", (10, 0), {"nvidia-cutlass-dsl": "4.5.0"}, FALLBACK, "cu130"),+ ("13.0", (10, 0), {"nvidia-cutlass-dsl": "4.6.2a0"}, FALLBACK, "cu130"),+ ("13.0", (10, 0), {"apache-tvm-ffi": "0.1.9"}, FALLBACK, "cu130"),+ ("13.0", (10, 0), {"nvidia-cudnn-frontend": "1.20.0"}, FALLBACK, "cu130"),+ (+ "13.0",+ (10, 0),+ {"nvidia-cutlass-dsl": "4.8.1", "apache-tvm-ffi": "0.1.15.post2"},+ V,+ "cu130",+ ),+ # No prebuilt anywhere: the newest that fits, JIT-compiled (the caller needs nvcc).+ ("12.6", (10, 0), {}, V, None),+ ("14.0", (10, 0), {}, V, None),+ ],+)+def test_select_release(cuda, capability, dists, version, tag):+ release, got_tag, _ = inst.select_release(cuda, capability, dists)+ assert (release.version, got_tag) == (version, tag)+++def test_select_release_names_the_held_dependency_when_nothing_fits(monkeypatch):+ newest = inst.FLASHINFER_RELEASES[0]+ monkeypatch.setattr(inst, "FLASHINFER_RELEASES", (newest,))+ release, tag, why = inst.select_release("13.0", (10, 0), {"nvidia-cutlass-dsl": "4.4.2"})+ assert release is None and tag is None+ assert "nvidia-cutlass-dsl>=4.8 (installed 4.4.2)" in why+++ "capability, provider",+ [+ ((10, 0), "flashinfer-jit-cache-sm100a"),+ ((10, 3), "flashinfer-jit-cache-sm103a"),+ ((12, 0), "flashinfer-jit-cache-sm120f"),+ ],+)+def test_every_nvfp4_capability_has_a_jit_cache_provider(capability, provider):+ assert tuple(capability) in ops.NVFP4_FLASHINFER_CAPS+ assert inst.jit_cache_provider(inst.FLASHINFER_RELEASES[0], capability) == provider+ assert set(inst.FLASHINFER_JIT_CACHE_ARCH) == set(ops.NVFP4_FLASHINFER_CAPS)+++def test_the_newest_release_installs_the_shim_and_this_devices_provider_only(env):+ ok, reason = _ensure(env)+ assert ok, reason+ jit = next(c for c in env.installs() if any(a.startswith("flashinfer-jit-cache") for a in c))+ specs = [a for a in jit if a.startswith("flashinfer-")]+ assert specs == [f"{PROVIDER}=={V}+cu130", f"flashinfer-jit-cache=={V}+cu130"]+ assert "--no-deps" in jit # the shim requires every arch's provider+++def test_a_split_release_whose_provider_is_not_loaded_rolls_back(env, monkeypatch):+ real_run = env.run++ def no_providers(cmd, **kwargs):+ res = real_run(cmd, **kwargs)+ if "-c" in cmd and "import flashinfer" in str(cmd[-1]) and res.returncode == 0:+ res.stdout = f"providers=\n{V}"+ return res++ ok, reason = inst.ensure_flashinfer_for_nvfp4(0, run = no_providers)+ assert (+ not ok+ and "rolled back" in reason+ and f"did not load the {PROVIDER} prebuilt kernels" in reason+ )+ assert PROVIDER not in env.dists and "flashinfer-python" not in env.dists+++def test_a_stray_provider_of_another_version_refuses(env):+ env.dists[PROVIDER] = "0.7.2+cu130"+ ok, reason = _ensure(env)+ assert not ok and f"{PROVIDER} 0.7.2+cu130" in reason+ assert env.installs() == []+++def test_the_fallback_installs_the_single_jit_cache(env):+ env.cuda = "12.8"+ ok, reason = _ensure(env)+ assert ok, reason+ jit = next(c for c in env.installs() if any(a.startswith("flashinfer-jit-cache") for a in c))+ assert [a for a in jit if a.startswith("flashinfer-")] == [+ f"flashinfer-jit-cache=={FALLBACK}+cu128"+ ]+++def test_an_installed_fallback_is_kept_not_upgraded(env):+ env.dists.update({"flashinfer-python": FALLBACK, "flashinfer-jit-cache": f"{FALLBACK}+cu130"})+ env.importable = True+ ok, reason = _ensure(env)+ assert ok and FALLBACK in reason+ assert env.installs() == []+++def test_the_verify_child_runs_the_shipped_snippet():+ import ast+ ast.parse(inst._VERIFY_CODE)+ assert inst._VERIFY_CODE.rstrip().endswith("'unknown')))")+++def _two_arch_host(monkeypatch, caps):+ torch = sys.modules["torch"]+ torch.cuda = types.SimpleNamespace(device_count = lambda: len(caps))+ monkeypatch.setattr(+ ops,+ "_device_capability",+ lambda device = None: caps[device if isinstance(device, int) else 0],+ )+++def test_a_mixed_arch_host_installs_every_visible_nvfp4_provider(env, monkeypatch):+ # A later load on the other card finds flashinfer importable and never installs again, so both go in now.+ _two_arch_host(monkeypatch, [(10, 0), (8, 0), (12, 0)])+ ok, reason = _ensure(env)+ assert ok, reason+ jit = next(c for c in env.installs() if any(a.startswith("flashinfer-jit-cache") for a in c))+ assert [a for a in jit if a.startswith("flashinfer-")] == [+ f"{PROVIDER}=={V}+cu130",+ f"flashinfer-jit-cache-sm120f=={V}+cu130",+ f"flashinfer-jit-cache=={V}+cu130",+ ]+++def test_a_mixed_arch_install_missing_one_provider_rolls_back(env, monkeypatch):+ _two_arch_host(monkeypatch, [(12, 0), (10, 0)])+ real_run = env.run++ def one_provider(cmd, **kwargs):+ res = real_run(cmd, **kwargs)+ if "-c" in cmd and "import flashinfer" in str(cmd[-1]) and res.returncode == 0:+ res.stdout = f"providers=flashinfer-jit-cache-sm120f\n{V}"+ return res++ ok, reason = inst.ensure_flashinfer_for_nvfp4(1, run = one_provider)+ assert not ok and f"did not load the {PROVIDER} prebuilt kernels" in reason+ assert "flashinfer-jit-cache-sm120f" not in env.dists and PROVIDER not in env.distsdiff --git a/studio/backend/tests/test_nvfp4_gate_coverage.py b/studio/backend/tests/test_nvfp4_gate_coverage.pyindex 1f1f32d092c..9c336ce5c39 100644--- a/studio/backend/tests/test_nvfp4_gate_coverage.py+++ b/studio/backend/tests/test_nvfp4_gate_coverage.py@@ -152,13 +152,23 @@ def _zimage_record(**versions):}-def test_the_shipped_records_cover_the_flashinfer_studio_installs():- from core.inference.diffusion_nvfp4_install import FLASHINFER_VERSION+def test_the_shipped_records_cover_the_fallback_flashinfer_and_refuse_the_unmeasured_newest():+ # A version joins flashinfer_bit_identical only with measured evidence.+ from core.inference.diffusion_nvfp4_install import FLASHINFER_RELEASESrecords = [r for r in load_gate_records() if r.get("backend") == "flashinfer"]assert records- for record in records:- assert FLASHINFER_VERSION in gate.record_flashinfer_versions(record), record["repo_id"]+ for release in FLASHINFER_RELEASES:+ covered = [release.version in gate.record_flashinfer_versions(r) for r in records]+ assert all(covered) or not any(covered), release.version+ for record in records:+ message = gate.nvfp4_gate_flashinfer_mismatch(+ record["family"], record["base_repo"], installed = release.version+ )+ assert (message is None) == all(covered), (release.version, record["repo_id"])+ assert all(+ FLASHINFER_RELEASES[-1].version in gate.record_flashinfer_versions(r) for r in records+ )def test_a_flashinfer_the_record_names_or_lists_bit_identical_is_covered(tmp_path):