Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: NVFP4 flashinfer backend kernel items (device guard, persistent barrier, bias path, cached dispatch) (#10731)

Daniel Han4a45ad4a68c0
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index de20ca91cf9..1a313e72fdf 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -5596,6 +5596,12 @@ class DiffusionBackend:
f"the quantised transformer build failed ({exc})"
)
_clear_exception_frames(exc)
+ # The NVFP4 caches hold VIEWS of the failed transformer, which clear_gpu_cache() cannot free.
+ try:
+ from .diffusion_nvfp4_linear import reset_nvfp4_state
+ reset_nvfp4_state()
+ except Exception: # noqa: BLE001 - cleanup is best effort
+ pass
try:
clear_gpu_cache()
except Exception: # noqa: BLE001
@@ -6568,6 +6574,12 @@ class DiffusionBackend:
gguf_compile.uninstall_all() # idempotent
cuda_graph.uninstall_all(getattr(pipe, "_unsloth_cuda_graphs", ()) or ())
uninstall_static_step_skip(pipe)
+ # After the graphs: the NVFP4 caches hold views that would pin the aborted transformer.
+ try:
+ from .diffusion_nvfp4_linear import reset_nvfp4_state
+ reset_nvfp4_state()
+ except Exception: # noqa: BLE001 - teardown is best effort
+ pass
if eager_patched:
uninstall_patches()
uninstall_arch_patches()
@@ -8745,6 +8757,11 @@ class DiffusionBackend:
for aux in (*self._aux_pipes.values(), *self._cn_pipes.values()):
prompt_cache.release(aux)
gguf_compile.uninstall_all()
+ try:
+ from .diffusion_nvfp4_linear import reset_nvfp4_state
+ reset_nvfp4_state()
+ except Exception: # noqa: BLE001 - teardown is best effort
+ pass
if state.eager_patched:
# Lazy import to keep diffusion.py torch-free to import.
from .diffusion_eager_patches import uninstall_patches
diff --git a/studio/backend/core/inference/diffusion_nvfp4_bias.py b/studio/backend/core/inference/diffusion_nvfp4_bias.py
new file mode 100644
index 00000000000..3b53607bbc2
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_nvfp4_bias.py
@@ -0,0 +1,79 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Eager bias add for the NVFP4 output, bit-identical to ``add_`` (compile defers to ``add_``). CUTLASS's
+fused FP4 bias epilogue is WRONG here: it adds into the fp32 accumulator before the rounding."""
+
+from __future__ import annotations
+
+import os
+from typing import Any
+
+try:
+ import triton
+ import triton.language as tl
+ _HAVE_TRITON = True
+except Exception: # noqa: BLE001 - no triton means the torch add, not a crash
+ _HAVE_TRITON = False
+
+NVFP4_FAST_BIAS_ENV = "UNSLOTH_NVFP4_FAST_BIAS"
+
+_TRUE_TOKENS = ("1", "true", "yes", "on")
+_FALSE_TOKENS = ("0", "false", "no", "off")
+
+_BLOCK = 4096
+_FAST_BIAS_MIN_NUMEL = 12 * 1024 * 1024
+# The kernel indexes with int32 offsets.
+_FAST_BIAS_MAX_NUMEL = 2**31 - 1
+
+
+if _HAVE_TRITON:
+
+ @triton.jit
+ def _bias_add_kernel(ptr, bias_ptr, n_elements, n_cols: "tl.constexpr", BLOCK: "tl.constexpr"):
+ pid = tl.program_id(0)
+ offsets = pid * BLOCK + tl.arange(0, BLOCK)
+ mask = offsets < n_elements
+ x = tl.load(ptr + offsets, mask = mask)
+ b = tl.load(bias_ptr + (offsets % n_cols), mask = mask)
+ # fp32 accumulate, one round on store: matches torch's bf16 add exactly.
+ tl.store(ptr + offsets, (x.to(tl.float32) + b.to(tl.float32)).to(x.dtype), mask = mask)
+
+
+def fast_bias_enabled() -> bool:
+ raw = os.environ.get(NVFP4_FAST_BIAS_ENV, "").strip().lower()
+ if raw in _FALSE_TOKENS:
+ return False
+ return True
+
+
+def _eligible(out: Any, bias: Any) -> bool:
+ """Each clause is a case the flat 1-D indexing gets WRONG, or a size that does not pay."""
+ import torch
+ return (
+ _HAVE_TRITON
+ and _FAST_BIAS_MIN_NUMEL <= out.numel() <= _FAST_BIAS_MAX_NUMEL
+ and out.is_cuda
+ and out.is_contiguous()
+ and bias.is_contiguous()
+ and bias.dim() == 1
+ and out.shape[-1] == bias.shape[0]
+ and out.dtype == bias.dtype
+ and out.dtype in (torch.bfloat16, torch.float16)
+ )
+
+
+def fused_bias_add_(out: Any, bias: Any):
+ """The device guard is load-bearing: Triton takes its device from the CURRENT context."""
+ import torch
+
+ if torch.compiler.is_compiling() or not fast_bias_enabled() or not _eligible(out, bias):
+ return out.add_(bias)
+
+ n_elements = out.numel()
+ if n_elements == 0:
+ return out
+ grid = (triton.cdiv(n_elements, _BLOCK),)
+ with torch.cuda.device(out.device):
+ _bias_add_kernel[grid](out, bias, n_elements, out.shape[-1], _BLOCK, num_warps = 8)
+ return out
diff --git a/studio/backend/core/inference/diffusion_nvfp4_dispatch.py b/studio/backend/core/inference/diffusion_nvfp4_dispatch.py
new file mode 100644
index 00000000000..230cf768df3
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_nvfp4_dispatch.py
@@ -0,0 +1,305 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""FlashInfer's per-call dispatch work, cached. Every private import is HERE, fenced by an EXACT version
+allowlist, ONE all-or-nothing try, and a per-device bit-identity ``verify()`` (a symbol can change meaning)."""
+
+from __future__ import annotations
+
+import os
+import threading
+import weakref
+from functools import partial
+from typing import Any, Optional
+
+# The only versions whose private layout was read and verified. Exact, never a minimum.
+_SUPPORTED = ("0.6.6",)
+
+NVFP4_FAST_DISPATCH_ENV = "UNSLOTH_NVFP4_FAST_DISPATCH"
+
+# Weights only: an activation view would be unbounded.
+_TRANSPOSE_CACHE_MAX = 4096
+
+_LOCK = threading.Lock()
+_AVAILABLE: Optional[tuple] = None
+_VERIFIED: dict[int, tuple] = {}
+_QUANT_FN: dict[int, tuple] = {}
+_GEMM_PLAN: dict = {}
+_TRANSPOSED: dict = {}
+
+
+def fast_dispatch_env() -> str:
+ """``auto`` (default), ``0`` (never), ``1`` (skip the version check, nothing else)."""
+ raw = os.environ.get(NVFP4_FAST_DISPATCH_ENV, "").strip().lower()
+ return raw if raw in ("auto", "0", "1") else "auto"
+
+
+def _probe() -> tuple:
+ env = fast_dispatch_env()
+ if env == "0":
+ return False, f"{NVFP4_FAST_DISPATCH_ENV}=0"
+ try:
+ import flashinfer
+
+ version = str(getattr(flashinfer, "__version__", "unknown"))
+ if env != "1" and version not in _SUPPORTED:
+ return False, (
+ f"flashinfer {version} is not in the verified set "
+ f"{', '.join(_SUPPORTED)}; using the public API"
+ )
+ from flashinfer.autotuner import AutoTuner # noqa: F401
+ from flashinfer.fp4_quantization import get_fp4_quantization_module # noqa: F401
+ from flashinfer.gemm.gemm_base import ( # noqa: F401
+ DEFAULT_WORKSPACE_SIZE,
+ _MM_FP4_TUNING_CONFIG_128x4,
+ _get_cache_buf,
+ get_cutlass_fp4_gemm_module,
+ )
+ from flashinfer.utils import device_support_pdl, get_compute_capability # noqa: F401
+ except Exception as exc: # noqa: BLE001 - any failure means the public API, never a raise
+ return False, f"{type(exc).__name__}: {str(exc)[:160]}"
+ return True, f"flashinfer {version} private dispatch symbols present"
+
+
+def available() -> tuple:
+ global _AVAILABLE
+ cached = _AVAILABLE
+ if cached is not None:
+ return cached
+ result = _probe()
+ with _LOCK:
+ _AVAILABLE = result
+ return result
+
+
+def enabled(device: Any) -> bool:
+ from .diffusion_nvfp4_ops import _device_index
+ record = _VERIFIED.get(_device_index(device))
+ return bool(record and record[0])
+
+
+def verify(device: Any) -> tuple:
+ from .diffusion_nvfp4_ops import _device_index
+
+ index = _device_index(device)
+ cached = _VERIFIED.get(index)
+ if cached is not None:
+ return cached
+ ok, reason = available()
+ record = _run_verify(device) if ok else (False, reason)
+ with _LOCK:
+ _VERIFIED[index] = record
+ return record
+
+
+def _run_verify(device: Any) -> tuple:
+ import torch
+ try:
+ import flashinfer
+ with torch.cuda.device(device):
+ x = torch.randn(256, 512, device = device, dtype = torch.bfloat16) * 0.05
+ w = torch.randn(128, 512, device = device, dtype = torch.bfloat16) * 0.02
+ a_gsf = _global_scale(x)
+ w_gsf = _global_scale(w)
+ alpha = (1.0 / (a_gsf * w_gsf)).float()
+
+ want_q, want_sf = flashinfer.nvfp4_quantize(x, a_gsf, do_shuffle = False)
+ wq, w_sf = flashinfer.nvfp4_quantize(w, w_gsf, do_shuffle = False)
+ got_q, got_sf = _fast_quantize(x, a_gsf, force = True)
+ if got_q is None:
+ return False, "the cached quantiser refused this device"
+ if not (torch.equal(want_q, got_q) and torch.equal(want_sf, got_sf)):
+ return False, "the cached quantiser is not bit-identical to nvfp4_quantize"
+
+ want = torch.empty(256, 128, device = device, dtype = torch.bfloat16)
+ flashinfer.mm_fp4(
+ want_q,
+ wq.T,
+ want_sf,
+ w_sf.T,
+ alpha,
+ torch.bfloat16,
+ out = want,
+ backend = "cutlass",
+ )
+ got = torch.empty(256, 128, device = device, dtype = torch.bfloat16)
+ plan = gemm_plan(want_q, wq.T, want_sf, w_sf.T, alpha, got, 128, "cutlass", force = True)
+ if plan is None:
+ return False, "no cached GEMM plan could be built"
+ runner, tactic, workspace = plan
+ runner(
+ inputs = [
+ want_q,
+ wq.T,
+ want_sf,
+ w_sf.T,
+ alpha,
+ torch.bfloat16,
+ got,
+ 16,
+ True,
+ workspace,
+ ],
+ tactic = tactic,
+ )
+ torch.cuda.synchronize(device)
+ if not torch.equal(want, got):
+ return False, "the cached GEMM is not bit-identical to mm_fp4"
+ except Exception as exc: # noqa: BLE001 - a raise is a failed verify
+ return False, f"{type(exc).__name__}: {str(exc)[:160]}"
+ return True, "verified bit-identical against the public API"
+
+
+def _global_scale(t: Any):
+ return (6.0 * 448.0 / t.float().abs().amax().clamp(min = 1e-8)).reshape(1).to(t.device)
+
+
+def quant_fn(device: Any, *, force: bool = False):
+ from .diffusion_nvfp4_ops import _device_index
+
+ # Gate before the cache read: verify() forces this entry BEFORE it knows it is bit-identical.
+ if not (force or enabled(device)):
+ return None
+ index = _device_index(device)
+ got = _QUANT_FN.get(index)
+ if got is not None:
+ return got
+ try:
+ return _build_quant_fn(device, index)
+ except Exception: # noqa: BLE001 - no quantiser means the public API
+ return None
+
+
+def _build_quant_fn(device: Any, index: int):
+ import torch
+
+ from flashinfer.fp4_quantization import get_fp4_quantization_module
+ from flashinfer.utils import device_support_pdl, get_compute_capability
+
+ with torch.cuda.device(device):
+ major, minor = get_compute_capability(device)
+ got = (
+ get_fp4_quantization_module(f"{major}{minor}").fp4_quantize_sm100,
+ device_support_pdl(device),
+ )
+ with _LOCK:
+ return _QUANT_FN.setdefault(index, got)
+
+
+def _fast_quantize(
+ x: Any,
+ global_sf: Any,
+ *,
+ force: bool = False,
+):
+ if not x.is_contiguous():
+ return None, None
+ got = quant_fn(x.device, force = force)
+ if got is None:
+ return None, None
+ fn, pdl = got
+ xq, sf = fn(x, global_sf, 16, False, True, False, pdl)
+ return xq, sf.reshape((-1, x.shape[-1] // 16))
+
+
+def _drop_transposed(key: int, ref: Any) -> None:
+ """Lock-free: a collection can land on a thread already holding the lock."""
+ entry = _TRANSPOSED.get(key)
+ if entry is not None and entry[0] is ref:
+ _TRANSPOSED.pop(key, None)
+
+
+def transposed(t: Any):
+ """A ``.T`` released with the weight. Over ``t.detach()``: ``t.T`` keeps ``t`` alive via ``_base``,
+ so the weakref would never fire."""
+ key = id(t)
+ stamp = (t.data_ptr(), tuple(t.shape))
+ entry = _TRANSPOSED.get(key)
+ if entry is not None and entry[0]() is t and entry[1] == stamp:
+ return entry[2]
+ with _LOCK:
+ entry = _TRANSPOSED.get(key)
+ if entry is not None and entry[0]() is t and entry[1] == stamp:
+ return entry[2]
+ if len(_TRANSPOSED) >= _TRANSPOSE_CACHE_MAX:
+ _TRANSPOSED.clear()
+ view = t.detach().T
+ # partial, never a closure over ``t``: a callback holding the weight would pin it forever.
+ _TRANSPOSED[key] = (weakref.ref(t, partial(_drop_transposed, key)), stamp, view)
+ return view
+
+
+def gemm_plan(
+ xq: Any,
+ wq_t: Any,
+ x_sf: Any,
+ w_sf_t: Any,
+ alpha: Any,
+ out: Any,
+ n: int,
+ backend: str,
+ *,
+ force: bool = False,
+):
+ """None (use ``mm_fp4``) for a COLD key under capture, where ``choose_one`` may profile into the graph."""
+ from .diffusion_nvfp4_ops import _device_index, _is_capturing
+
+ device = xq.device
+ key = (xq.shape[0], xq.shape[1], n, backend, _device_index(device))
+ got = _GEMM_PLAN.get(key)
+ if got is not None:
+ return got
+ if backend != "cutlass" or not (force or enabled(device)) or _is_capturing():
+ return None
+ try:
+ return _build_plan(key, device, [xq, wq_t, x_sf, w_sf_t, alpha, out])
+ except Exception: # noqa: BLE001 - no plan means the public API
+ return None
+
+
+def _build_plan(key: tuple, device: Any, operands: list):
+ import torch
+
+ from flashinfer.autotuner import AutoTuner
+ from flashinfer.gemm.gemm_base import (
+ DEFAULT_WORKSPACE_SIZE,
+ _MM_FP4_TUNING_CONFIG_128x4,
+ _get_cache_buf,
+ get_cutlass_fp4_gemm_module,
+ )
+ from flashinfer.utils import get_compute_capability
+
+ # The guard spans the whole builder: both allocation and profiling hit the CURRENT device.
+ with torch.cuda.device(device):
+ workspace = _get_cache_buf("mm_fp4_workspace", DEFAULT_WORKSPACE_SIZE, device)
+ major, minor = get_compute_capability(device)
+ runner = get_cutlass_fp4_gemm_module(major, minor).cutlass_fp4_gemm_runner()
+ xq, wq_t, x_sf, w_sf_t, alpha, out = operands
+ inputs = [xq, wq_t, x_sf, w_sf_t, alpha, torch.bfloat16, out, 16, True, workspace]
+ _, tactic = AutoTuner.get().choose_one(
+ "fp4_gemm", [runner], _MM_FP4_TUNING_CONFIG_128x4, inputs
+ )
+ plan = (runner, tactic, workspace)
+ with _LOCK:
+ return _GEMM_PLAN.setdefault(key, plan)
+
+
+def reset() -> None:
+ """Called on unload: the transposed views would pin a freed model."""
+ global _AVAILABLE
+ with _LOCK:
+ _AVAILABLE = None
+ _VERIFIED.clear()
+ _QUANT_FN.clear()
+ _GEMM_PLAN.clear()
+ _TRANSPOSED.clear()
+
+
+def describe() -> dict:
+ return {
+ "available": available()[0],
+ "reason": available()[1],
+ "verified_devices": sorted(index for index, rec in _VERIFIED.items() if rec[0]),
+ "plans": len(_GEMM_PLAN),
+ "transposed": len(_TRANSPOSED),
+ }
diff --git a/studio/backend/core/inference/diffusion_nvfp4_linear.py b/studio/backend/core/inference/diffusion_nvfp4_linear.py
index 6d604e3f38f..0fa5801233e 100644
--- a/studio/backend/core/inference/diffusion_nvfp4_linear.py
+++ b/studio/backend/core/inference/diffusion_nvfp4_linear.py
@@ -35,12 +35,25 @@ def reset_tuned_shapes() -> None:
_TUNED_SHAPES.clear()
+def reset_nvfp4_state() -> None:
+ from . import diffusion_nvfp4_dispatch as _dispatch
+ from . import diffusion_nvfp4_ops as _ops
+
+ reset_tuned_shapes()
+ _ops.reset_barriers()
+ _dispatch.reset()
+ # verify() runs only in the preflight, so a memoised one would leave _VERIFIED empty next load.
+ _ops.reset_preflight_cache()
+
+
@lru_cache(maxsize = 1)
def nvfp4_linear_class():
import torch
from torch import nn
from torch.nn import functional as F
+ from .diffusion_nvfp4_bias import fused_bias_add_
+
class NVFP4FlashInferLinear(nn.Module):
"""Runs inside a captured CUDA graph: no host synchronize, no device-value branch."""
@@ -94,6 +107,7 @@ def nvfp4_linear_class():
)
out = F.linear(flat, weight)
else:
+ # Zero graph breaks under compile; without it a flashinfer launch can hit the wrong card.
with _device_guard(flat):
xq, x_sf = torch.ops.unsloth_nvfp4.quantize(flat, self.a_gsf)
out = torch.ops.unsloth_nvfp4.mm(
@@ -101,7 +115,7 @@ def nvfp4_linear_class():
)
out = out.to(out_dtype)
if self.bias is not None:
- out.add_(self.bias)
+ fused_bias_add_(out, self.bias)
return out.reshape(*shape[:-1], self.out_features)
def extra_repr(self) -> str: # pragma: no cover - debug aid
diff --git a/studio/backend/core/inference/diffusion_nvfp4_ops.py b/studio/backend/core/inference/diffusion_nvfp4_ops.py
index 9d58f26561c..3e4e65a46f2 100644
--- a/studio/backend/core/inference/diffusion_nvfp4_ops.py
+++ b/studio/backend/core/inference/diffusion_nvfp4_ops.py
@@ -36,6 +36,9 @@ _PREFLIGHT_LOCK = threading.Lock()
_PREFLIGHT: dict[int, dict] = {}
_WARNED: set = set()
+_BARRIER_LOCK = threading.Lock()
+_BARRIERS: dict[int, Any] = {}
+
def _swizzled_sf_numel(
rows: int,
@@ -56,31 +59,82 @@ def _zero_buffer_enabled() -> bool:
return os.environ.get(NVFP4_ZERO_BUFFER_ENV, "").strip().lower() in _TRUE_TOKENS
+def _device_index(device: Any) -> int:
+ import torch
+ index = getattr(device, "index", None)
+ return torch.cuda.current_device() if index is None else int(index)
+
+
+def _is_capturing() -> bool:
+ try:
+ import torch
+ return bool(torch.cuda.is_current_stream_capturing())
+ except Exception: # noqa: BLE001 - a torch without the query cannot be capturing
+ return False
+
+
+def _barrier(device: Any):
+ """Per-device 1-element buffer, UNCACHED under capture: an allocation made in a capture dies with the graph."""
+ import torch
+
+ index = _device_index(device)
+ buf = _BARRIERS.get(index)
+ if buf is not None:
+ return buf
+ fresh = torch.empty(1, device = device, dtype = torch.bfloat16)
+ if _is_capturing():
+ return fresh
+ with _BARRIER_LOCK:
+ return _BARRIERS.setdefault(index, fresh)
+
+
+def _fire_barrier(device: Any):
+ buf = _barrier(device)
+ buf.zero_()
+ return buf
+
+
+def reset_barriers() -> None:
+ """One allocated under a model's allocator state must not reach the next model's graph pool."""
+ with _BARRIER_LOCK:
+ _BARRIERS.clear()
+
+
def global_scale(t: Any):
return (FP4_MAX * FP8_MAX / t.float().abs().amax().clamp(min = 1e-8)).reshape(1).to(t.device)
def _quantize_impl(x: Any, global_sf: Any):
import flashinfer
+
+ from . import diffusion_nvfp4_dispatch as dispatch
with _device_guard(x):
+ xq, sf = dispatch._fast_quantize(x, global_sf)
+ if xq is not None:
+ return xq, sf
return flashinfer.nvfp4_quantize(x, global_sf, do_shuffle = False)
def _mm_impl(xq: Any, wq: Any, x_sf: Any, w_sf: Any, alpha: Any, n: int, backend: str):
- """Weight row-major, transposed inside (a ``.T`` input is an alias). A KERNEL must run between
- the quantiser and this GEMM (cutlass PDL without griddepcontrol reads unfinished operands):
- ``torch.zeros(1)`` per call works, ``torch.empty`` does NOT."""
+ """NVFP4 GEMM on a row-major ``[N, K/2]`` weight (a ``.T`` input would be an alias Dynamo must track).
+
+ A kernel MUST run between the activation quantiser and this GEMM: cutlass launches with PDL but its
+ ``griddepcontrol`` is compiled out, so ``torch.empty`` alone is NOT enough; a one-element fill is.
+ """
import flashinfer
import torch
+ from . import diffusion_nvfp4_dispatch as dispatch
+
with _device_guard(xq):
m = xq.shape[0]
if _zero_buffer_enabled():
out = torch.zeros(m, n, device = xq.device, dtype = torch.bfloat16)
else:
out = torch.empty(m, n, device = xq.device, dtype = torch.bfloat16)
- torch.zeros(1, device = xq.device, dtype = torch.bfloat16)
+ _fire_barrier(xq.device)
if _claim_first_call_tune(m, xq.shape[1] * 2, n):
+ # Before the dispatch plan, which caches whatever tactic FlashInfer holds on its first build.
try:
with flashinfer.autotune(True):
return flashinfer.mm_fp4(
@@ -88,19 +142,41 @@ def _mm_impl(xq: Any, wq: Any, x_sf: Any, w_sf: Any, alpha: Any, n: int, backend
)
except Exception: # noqa: BLE001 - claimed, so it is not retried; run it untuned
pass
+ if dispatch.enabled(xq.device):
+ wq_t, w_sf_t = dispatch.transposed(wq), dispatch.transposed(w_sf)
+ plan = dispatch.gemm_plan(xq, wq_t, x_sf, w_sf_t, alpha, out, n, backend)
+ if plan is not None:
+ runner, tactic, workspace = plan
+ runner(
+ inputs = [
+ xq,
+ wq_t,
+ x_sf,
+ w_sf_t,
+ alpha,
+ torch.bfloat16,
+ out,
+ 16,
+ True,
+ workspace,
+ ],
+ tactic = tactic,
+ )
+ return out
return flashinfer.mm_fp4(
xq, wq.T, x_sf, w_sf.T, alpha, torch.bfloat16, out = out, backend = backend
)
def _claim_first_call_tune(m: int, k: int, n: int) -> bool:
- """True once per untuned ``(M, K, N)``, never under graph capture (profiling is illegal there)."""
- import torch
-
+ """True exactly once per ``(M, K, N)`` not yet autotuned, and only outside a CUDA graph
+ capture, where profiling is illegal (the warm-up before a capture is eager, so a graphed
+ shape tunes there). Shares ``nvfp4_prewarm``'s process-wide set, so a prewarmed shape is
+ never profiled twice."""
from .diffusion_nvfp4_linear import _TUNED_SHAPES
key = (int(m), int(k), int(n))
- if key in _TUNED_SHAPES or torch.cuda.is_current_stream_capturing():
+ if key in _TUNED_SHAPES or _is_capturing():
return False
_TUNED_SHAPES.add(key)
return True
@@ -297,6 +373,12 @@ def nvfp4_preflight(device: Any = None, *, refresh: bool = False) -> dict:
finite = _preflight_probe(dev)
rec["ok"] = finite
rec["reason"] = "ok" if finite else "mm_fp4 produced a non-finite result"
+ if finite:
+ from . import diffusion_nvfp4_dispatch as dispatch
+
+ fast_ok, fast_reason = dispatch.verify(dev)
+ rec["fast_dispatch"] = fast_ok
+ rec["fast_dispatch_reason"] = fast_reason
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):
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 2998cb5cb8f..cbdbce4b578 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -2276,6 +2276,13 @@ class VideoBackend:
restore_owner_account(VIDEO)
restore_resident_metadata(VIDEO)
# Free the debris of a failed construction: nothing was committed, so nothing else releases the VRAM.
+ # NVFP4 caches pin the denoiser, but a failed replacement keeps the old model, whose graph still uses them.
+ if self._state is None:
+ try:
+ from .diffusion_nvfp4_linear import reset_nvfp4_state
+ reset_nvfp4_state()
+ except Exception: # noqa: BLE001 -- cleanup is best-effort
+ pass
try:
clear_gpu_cache()
except Exception: # noqa: BLE001 -- cleanup is best-effort
@@ -7618,6 +7625,11 @@ class VideoBackend:
getattr(getattr(state, "pipe", None), "_unsloth_cuda_graphs", ()) or ()
)
uninstall_static_step_skip(getattr(state, "pipe", None))
+ try:
+ from .diffusion_nvfp4_linear import reset_nvfp4_state
+ reset_nvfp4_state()
+ except Exception: # noqa: BLE001 - teardown is best effort
+ pass
del state
try:
clear_gpu_cache()
diff --git a/studio/backend/tests/test_diffusion_nvfp4_backend.py b/studio/backend/tests/test_diffusion_nvfp4_backend.py
index 85f05662927..67579e222f3 100644
--- a/studio/backend/tests/test_diffusion_nvfp4_backend.py
+++ b/studio/backend/tests/test_diffusion_nvfp4_backend.py
@@ -146,12 +146,31 @@ def _is_guard(node: ast.AST) -> bool:
return name.endswith("torch.cuda.device") or name.endswith("_device_guard")
+# FlashInfer PRIVATE entry points: imported by name, so a prefix check cannot see them.
+_PRIVATE_LAUNCHES = frozenset(
+ {
+ "choose_one",
+ "cutlass_fp4_gemm_runner",
+ "get_cutlass_fp4_gemm_module",
+ "_get_cache_buf",
+ "fp4_quantize_sm100",
+ "get_fp4_quantization_module",
+ }
+)
+
+
def _is_launch(node: ast.Call) -> str:
+ # A Triton launch is a Call on a SUBSCRIPT (``kernel[grid](...)``), on the CURRENT device.
+ if isinstance(node.func, ast.Subscript):
+ name = _dotted(node.func.value)
+ return name if name.endswith("_kernel") else ""
name = _dotted(node.func)
if name.startswith("flashinfer.") or name.startswith("_fi."):
return name
if "torch.ops.unsloth_nvfp4" in name:
return name
+ if name.rsplit(".", 1)[-1] in _PRIVATE_LAUNCHES:
+ return name
return ""
@@ -195,12 +214,18 @@ def test_the_guard_visitor_catches_an_unguarded_launch():
" flashinfer.mm_fp4(x)\n"
" flashinfer.nvfp4_quantize(x)\n"
" torch.ops.unsloth_nvfp4.mm(x)\n"
+ " _bias_add_kernel[grid](x)\n"
+ " with torch.cuda.device(x.device):\n"
+ " _bias_add_kernel[grid](x)\n"
+ " _get_cache_buf('ws', 1, x.device)\n"
)
visitor = _LaunchVisitor()
visitor.visit(tree)
assert [name for _, name in visitor.unguarded] == [
"flashinfer.nvfp4_quantize",
"torch.ops.unsloth_nvfp4.mm",
+ "_bias_add_kernel",
+ "_get_cache_buf",
]
@@ -218,9 +243,34 @@ def test_every_flashinfer_launch_in_the_nvfp4_modules_sits_inside_a_device_guard
assert not offences, "\n".join(offences)
-def test_the_modules_never_set_the_current_stream():
+_STREAM_BANNED = ("set_stream", "set_device", "setDevice")
+
+
+def _banned_stream_calls(source: str) -> list[tuple[int, str]]:
+ """``set_stream`` silently sets the current DEVICE; ``set_device`` moves what the guard restores."""
+ found: list[tuple[int, str]] = []
+ for node in ast.walk(ast.parse(source)):
+ if isinstance(node, ast.Attribute) and node.attr in _STREAM_BANNED:
+ found.append((node.lineno, _dotted(node) or node.attr))
+ elif isinstance(node, ast.Name) and node.id in _STREAM_BANNED:
+ found.append((node.lineno, node.id))
+ return found
+
+
+def test_the_banned_call_detector_sees_an_aliased_set_stream():
+ assert _banned_stream_calls("import torch\ncuda = torch.cuda\ncuda.set_stream(s)\n")
+ assert _banned_stream_calls("from torch.cuda import set_device\nset_device(1)\n")
+ assert not _banned_stream_calls("def reset_stream_cache():\n return None\n")
+
+
+def test_the_modules_never_set_the_current_stream_or_device():
+ offences: list[str] = []
for path in _nvfp4_sources():
- assert "set_stream" not in path.read_text(encoding = "utf-8"), path.name
+ offences += [
+ f"{path.name}:{line}: {name} switches the current device behind the guard"
+ for line, name in _banned_stream_calls(path.read_text(encoding = "utf-8"))
+ ]
+ assert not offences, "\n".join(offences)
@pytest.mark.parametrize(
@@ -409,6 +459,10 @@ def test_an_unprewarmed_gemm_shape_autotunes_on_its_first_eager_call_only(monkey
fake.mm_fp4 = _mm_fp4
monkeypatch.setitem(sys.modules, "flashinfer", fake)
monkeypatch.setattr(ops, "_device_guard", lambda t: contextlib.nullcontext())
+ monkeypatch.setattr(ops, "_fire_barrier", lambda device: None)
+ from core.inference import diffusion_nvfp4_dispatch as dispatch
+
+ monkeypatch.setattr(dispatch, "enabled", lambda device: False)
monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: state["capturing"])
nl.reset_tuned_shapes()
try:
@@ -429,3 +483,57 @@ def test_an_unprewarmed_gemm_shape_autotunes_on_its_first_eager_call_only(monkey
assert (8192, 32, 64) not in nl._TUNED_SHAPES
finally:
nl.reset_tuned_shapes()
+
+
+def test_the_first_call_tune_runs_before_the_cached_dispatch_plan_is_built(monkeypatch):
+ """``gemm_plan`` snapshots the tactic on its first build, so a plan before the tune pins the fallback."""
+ import contextlib
+ import sys
+ import types
+
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_nvfp4_dispatch as dispatch
+ from core.inference import diffusion_nvfp4_linear as nl
+
+ events = []
+ tuning = {"on": False}
+
+ @contextlib.contextmanager
+ def _autotune(flag = True):
+ tuning["on"] = flag
+ try:
+ yield
+ finally:
+ tuning["on"] = False
+
+ def _mm_fp4(
+ *args,
+ out = None,
+ **kwargs,
+ ):
+ events.append(("mm_fp4", tuning["on"]))
+ return out
+
+ def _plan(xq, *args, **kwargs):
+ events.append(("plan_built", tuning["on"]))
+ return (lambda inputs, tactic: events.append(("plan_run", tactic)), 7, None)
+
+ fake = types.ModuleType("flashinfer")
+ fake.autotune = _autotune
+ fake.mm_fp4 = _mm_fp4
+ monkeypatch.setitem(sys.modules, "flashinfer", fake)
+ monkeypatch.setattr(ops, "_device_guard", lambda t: contextlib.nullcontext())
+ monkeypatch.setattr(ops, "_fire_barrier", lambda device: None)
+ monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: False)
+ monkeypatch.setattr(dispatch, "enabled", lambda device: True)
+ monkeypatch.setattr(dispatch, "transposed", lambda t: t)
+ monkeypatch.setattr(dispatch, "gemm_plan", _plan)
+ nl.reset_tuned_shapes()
+ try:
+ wq = torch.zeros(64, 16, dtype = torch.uint8)
+ xq = torch.zeros(4352, 16, dtype = torch.uint8)
+ ops._mm_impl(xq, wq, None, wq, None, 64, "cutlass")
+ ops._mm_impl(xq, wq, None, wq, None, 64, "cutlass")
+ assert events == [("mm_fp4", True), ("plan_built", False), ("plan_run", 7)]
+ finally:
+ nl.reset_tuned_shapes()
diff --git a/studio/backend/tests/test_diffusion_nvfp4_dispatch.py b/studio/backend/tests/test_diffusion_nvfp4_dispatch.py
new file mode 100644
index 00000000000..ff2197bbb19
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_nvfp4_dispatch.py
@@ -0,0 +1,442 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+
+from __future__ import annotations
+
+import sys
+import types
+
+import pytest
+
+from core.inference import diffusion_nvfp4_dispatch as dispatch
+from core.inference import diffusion_nvfp4_ops as ops
+
+_PRIVATE = {
+ "flashinfer.autotuner": ("AutoTuner",),
+ "flashinfer.fp4_quantization": ("get_fp4_quantization_module",),
+ "flashinfer.gemm.gemm_base": (
+ "DEFAULT_WORKSPACE_SIZE",
+ "_MM_FP4_TUNING_CONFIG_128x4",
+ "_get_cache_buf",
+ "get_cutlass_fp4_gemm_module",
+ ),
+ "flashinfer.utils": ("device_support_pdl", "get_compute_capability"),
+}
+
+
[email protected](autouse = True)
+def _clean_dispatch():
+ dispatch.reset()
+ yield
+ dispatch.reset()
+
+
+def _fake_flashinfer(
+ monkeypatch,
+ *,
+ version = "0.6.6",
+ drop = (),
+):
+ root = types.ModuleType("flashinfer")
+ root.__version__ = version
+ root.__path__ = []
+ monkeypatch.setitem(sys.modules, "flashinfer", root)
+ gemm = types.ModuleType("flashinfer.gemm")
+ gemm.__path__ = []
+ monkeypatch.setitem(sys.modules, "flashinfer.gemm", gemm)
+ for name, symbols in _PRIVATE.items():
+ module = types.ModuleType(name)
+ for symbol in symbols:
+ if symbol not in drop:
+ setattr(module, symbol, object())
+ monkeypatch.setitem(sys.modules, name, module)
+ return root
+
+
+def test_the_allowlisted_version_with_every_symbol_is_available(monkeypatch):
+ _fake_flashinfer(monkeypatch)
+ ok, reason = dispatch.available()
+ assert ok is True, reason
+ assert "0.6.6" in reason
+
+
[email protected]("version", ["0.6.5", "0.6.7", "0.7.0", "unknown"])
+def test_an_unlisted_version_refuses_even_when_every_symbol_is_there(monkeypatch, version):
+ """Exact, not a minimum: a private symbol that moves in 0.6.7 is not a bug in 0.6.7."""
+ _fake_flashinfer(monkeypatch, version = version)
+ ok, reason = dispatch.available()
+ assert ok is False
+ assert version in reason and "public API" in reason
+
+
+ "missing",
+ ["AutoTuner", "_get_cache_buf", "_MM_FP4_TUNING_CONFIG_128x4", "get_cutlass_fp4_gemm_module"],
+)
+def test_one_missing_private_symbol_takes_the_whole_fast_path_down(monkeypatch, missing):
+ _fake_flashinfer(monkeypatch, drop = (missing,))
+ ok, reason = dispatch.available()
+ assert ok is False
+ assert "ImportError" in reason and missing in reason
+
+
+def test_the_env_switch_refuses_before_it_imports_anything(monkeypatch):
+ def _boom(*_a, **_kw): # pragma: no cover - reached only on a regression
+ raise AssertionError("the probe imported flashinfer under FAST_DISPATCH=0")
+
+ monkeypatch.setitem(sys.modules, "flashinfer", property(_boom))
+ monkeypatch.setenv(dispatch.NVFP4_FAST_DISPATCH_ENV, "0")
+ ok, reason = dispatch.available()
+ assert ok is False and reason.endswith("=0")
+
+
+def test_env_one_skips_the_version_check_and_nothing_else(monkeypatch):
+ monkeypatch.setenv(dispatch.NVFP4_FAST_DISPATCH_ENV, "1")
+ _fake_flashinfer(monkeypatch, version = "0.7.0")
+ assert dispatch.available()[0] is True
+
+ dispatch.reset()
+ _fake_flashinfer(monkeypatch, version = "0.7.0", drop = ("AutoTuner",))
+ ok, reason = dispatch.available()
+ assert ok is False and "AutoTuner" in reason
+
+
[email protected]("value", ["", "auto", "AUTO", "yes", "2"])
+def test_an_unrecognised_env_value_reads_as_auto(monkeypatch, value):
+ monkeypatch.setenv(dispatch.NVFP4_FAST_DISPATCH_ENV, value)
+ assert dispatch.fast_dispatch_env() == "auto"
+
+
+def test_nothing_is_enabled_until_verify_has_passed_on_that_device(monkeypatch):
+ _fake_flashinfer(monkeypatch)
+ monkeypatch.setattr(ops, "_device_index", lambda device: int(device))
+ assert dispatch.available()[0] is True
+ assert dispatch.enabled(0) is False
+ assert dispatch.quant_fn(0) is None
+
+
+def test_a_failed_verify_is_remembered_and_never_retried(monkeypatch):
+ _fake_flashinfer(monkeypatch)
+ monkeypatch.setattr(ops, "_device_index", lambda device: int(device))
+ calls = []
+
+ def _fail(device):
+ calls.append(device)
+ return False, "stub failure"
+
+ monkeypatch.setattr(dispatch, "_run_verify", _fail)
+ assert dispatch.verify(0) == (False, "stub failure")
+ assert dispatch.verify(0) == (False, "stub failure")
+ assert len(calls) == 1
+ assert dispatch.enabled(0) is False
+
+
+def test_verify_does_not_run_the_gemm_when_the_library_is_wrong(monkeypatch):
+ _fake_flashinfer(monkeypatch, version = "0.7.0")
+ monkeypatch.setattr(ops, "_device_index", lambda device: int(device))
+
+ def _boom(_device): # pragma: no cover - reached only on a regression
+ raise AssertionError("verify ran the GEMM on an unlisted version")
+
+ monkeypatch.setattr(dispatch, "_run_verify", _boom)
+ ok, reason = dispatch.verify(0)
+ assert ok is False and "0.7.0" in reason
+
+
+class _Ptr:
+ def __init__(
+ self,
+ pointer,
+ shape = (8, 4),
+ ):
+ self._pointer = pointer
+ self.shape = shape
+
+ def data_ptr(self):
+ return self._pointer
+
+ def detach(self):
+ return self
+
+ @property
+ def T(self):
+ return ("view", self._pointer, self.shape)
+
+
+def test_a_cold_plan_is_never_built_during_a_capture(monkeypatch):
+ """``choose_one`` may PROFILE, and a profiling launch inside a capture is in the graph forever."""
+ _fake_flashinfer(monkeypatch)
+ monkeypatch.setattr(ops, "_device_index", lambda device: 0)
+ monkeypatch.setattr(dispatch, "enabled", lambda device: True)
+ monkeypatch.setattr(ops, "_is_capturing", lambda: True)
+
+ def _boom(*_a, **_kw): # pragma: no cover - reached only on a regression
+ raise AssertionError("a plan was built inside a capture")
+
+ monkeypatch.setattr(dispatch, "_build_plan", _boom)
+ xq = types.SimpleNamespace(device = 0, shape = (512, 1536))
+ assert dispatch.gemm_plan(xq, None, None, None, None, None, 3072, "cutlass") is None
+
+ dispatch._GEMM_PLAN[(512, 1536, 3072, "cutlass", 0)] = ("runner", 7, "ws")
+ assert dispatch.gemm_plan(xq, None, None, None, None, None, 3072, "cutlass") == (
+ "runner",
+ 7,
+ "ws",
+ )
+
+
+def test_a_backend_other_than_cutlass_has_no_cached_plan(monkeypatch):
+ monkeypatch.setattr(ops, "_device_index", lambda device: 0)
+ monkeypatch.setattr(dispatch, "enabled", lambda device: True)
+ monkeypatch.setattr(ops, "_is_capturing", lambda: False)
+ xq = types.SimpleNamespace(device = 0, shape = (512, 1536))
+ assert dispatch.gemm_plan(xq, None, None, None, None, None, 3072, "trtllm") is None
+
+
+def test_the_transpose_cache_holds_the_view_and_revalidates_pointer_and_shape():
+ weight = _Ptr(1024)
+ view = dispatch.transposed(weight)
+ assert dispatch.transposed(weight) is view
+ # A reallocated buffer at the same address with a new shape must not get the old view.
+ other = _Ptr(1024, shape = (4, 8))
+ assert dispatch.transposed(other) is not view
+ weight._pointer = 2048
+ assert dispatch.transposed(weight) is not view
+
+
+def test_the_transpose_cache_is_bounded():
+ held = [_Ptr(pointer) for pointer in range(dispatch._TRANSPOSE_CACHE_MAX)]
+ for weight in held:
+ dispatch.transposed(weight)
+ assert len(dispatch._TRANSPOSED) == dispatch._TRANSPOSE_CACHE_MAX
+ last = _Ptr(10**9)
+ dispatch.transposed(last)
+ assert len(dispatch._TRANSPOSED) == 1
+
+
+def test_the_transpose_cache_releases_a_weight_that_was_collected():
+ """A superseded load never resets, so only the cache letting go can free its weights."""
+ import gc
+
+ weight = _Ptr(4096)
+ dispatch.transposed(weight)
+ assert len(dispatch._TRANSPOSED) == 1
+ del weight
+ gc.collect()
+ assert dispatch._TRANSPOSED == {}
+
+
+def test_a_live_weight_survives_a_superseded_loads_collection():
+ import gc
+
+ live = _Ptr(64)
+ live_view = dispatch.transposed(live)
+ stale = _Ptr(128)
+ dispatch.transposed(stale)
+ del stale
+ gc.collect()
+ assert len(dispatch._TRANSPOSED) == 1
+ assert dispatch.transposed(live) is live_view
+
+
+def test_reset_clears_every_cache(monkeypatch):
+ _fake_flashinfer(monkeypatch)
+ monkeypatch.setattr(ops, "_device_index", lambda device: int(device))
+ dispatch.available()
+ held = _Ptr(7)
+ dispatch.transposed(held)
+ dispatch._GEMM_PLAN[("k",)] = ("runner", 0, "ws")
+ dispatch._QUANT_FN[0] = ("fn", True)
+ dispatch._VERIFIED[0] = (True, "ok")
+ assert dispatch.enabled(0) is True
+
+ dispatch.reset()
+ assert dispatch._AVAILABLE is None
+ assert not dispatch._GEMM_PLAN and not dispatch._QUANT_FN
+ assert not dispatch._TRANSPOSED and not dispatch._VERIFIED
+ assert dispatch.enabled(0) is False
+
+
+def test_describe_reports_what_is_cached(monkeypatch):
+ _fake_flashinfer(monkeypatch)
+ monkeypatch.setattr(ops, "_device_index", lambda device: int(device))
+ dispatch._VERIFIED[1] = (True, "ok")
+ dispatch._VERIFIED[2] = (False, "nope")
+ held = _Ptr(3)
+ dispatch.transposed(held)
+ record = dispatch.describe()
+ assert record["available"] is True
+ assert record["verified_devices"] == [1]
+ assert record["transposed"] == 1
+
+
+def test_a_quantiser_built_for_a_failed_verify_is_never_handed_out(monkeypatch):
+ """A cache read ahead of the gate would hand a failed device the quantiser its verify rejected."""
+ _fake_flashinfer(monkeypatch)
+ monkeypatch.setattr(ops, "_device_index", lambda device: int(device))
+ dispatch._QUANT_FN[0] = ("fn", True)
+ dispatch._VERIFIED[0] = (False, "the cached quantiser is not bit-identical to nvfp4_quantize")
+ assert dispatch.enabled(0) is False
+ assert dispatch.quant_fn(0) is None
+ x = types.SimpleNamespace(device = 0, is_contiguous = lambda: True)
+ assert dispatch._fast_quantize(x, None) == (None, None)
+
+
+def test_the_unload_reset_also_forgets_the_preflight_that_ran_verify():
+ from core.inference import diffusion_nvfp4_linear as nl
+ try:
+ ops._PREFLIGHT[0] = {"ok": True, "fast_dispatch": True}
+ dispatch._VERIFIED[0] = (True, "ok")
+ nl.reset_nvfp4_state()
+ assert not ops._PREFLIGHT
+ assert not dispatch._VERIFIED
+ finally:
+ ops.reset_preflight_cache()
+
+
+def _block_after(source: str, marker: str, lines: int) -> str:
+ return "\n".join(source[source.index(marker) :].splitlines()[:lines])
+
+
+def test_an_aborted_load_drops_the_caches_that_pin_the_failed_model():
+ import inspect
+
+ from core.inference.diffusion import DiffusionBackend
+ from core.inference.video import VideoBackend
+
+ load = inspect.getsource(DiffusionBackend.load_pipeline)
+ assert "reset_nvfp4_state()" in _block_after(load, "diffusion.transformer_quant_fallback", 30)
+ assert "reset_nvfp4_state()" in _block_after(load, "if not state_committed:", 20)
+ assert "reset_nvfp4_state()" in _block_after(
+ inspect.getsource(VideoBackend._run_load), "video.load_failed", 15
+ )
+
+
+CUDA_SHAPES = (
+ (32, 2560, 3840),
+ (1056, 3840, 3840),
+ (1056, 3840, 10240),
+ (4128, 3840, 10240),
+ (27280, 3072, 14336),
+)
+
+
+def _cuda_or_skip():
+ torch = pytest.importorskip("torch")
+ if not getattr(torch, "cuda", None) or not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ if tuple(torch.cuda.get_device_capability(0)) not in ops.NVFP4_FLASHINFER_CAPS:
+ pytest.skip("this device has no flashinfer NVFP4 kernels")
+ pytest.importorskip("flashinfer")
+ return torch
+
+
+def test_the_real_flashinfer_verifies_bit_identical():
+ torch = _cuda_or_skip()
+ import flashinfer
+
+ if flashinfer.__version__ not in dispatch._SUPPORTED:
+ pytest.skip(f"flashinfer {flashinfer.__version__} is outside the allowlist by design")
+ ok, reason = dispatch.verify(torch.device("cuda", 0))
+ assert ok is True, reason
+ assert dispatch.enabled(torch.device("cuda", 0)) is True
+
+
[email protected]("m,k,n", CUDA_SHAPES)
+def test_the_cached_dispatch_matches_the_public_api_exactly(m, k, n):
+ torch = _cuda_or_skip()
+ import flashinfer
+
+ if flashinfer.__version__ not in dispatch._SUPPORTED:
+ pytest.skip(f"flashinfer {flashinfer.__version__} is outside the allowlist by design")
+
+ device = torch.device("cuda", 0)
+ torch.manual_seed(m + k + n)
+ with torch.cuda.device(device), torch.inference_mode():
+ x = torch.randn(m, k, device = device, dtype = torch.bfloat16) * 0.05
+ w = torch.randn(n, k, device = device, dtype = torch.bfloat16) * 0.02
+ a_gsf, w_gsf = ops.global_scale(x), ops.global_scale(w)
+ wq, w_sf = flashinfer.nvfp4_quantize(w, w_gsf, do_shuffle = False)
+ alpha = (1.0 / (a_gsf * w_gsf)).float()
+
+ dispatch.reset()
+ assert dispatch.enabled(device) is False
+ want_q, want_sf = ops._quantize_impl(x, a_gsf)
+ want = ops._mm_impl(want_q, wq, want_sf, w_sf, alpha, n, ops.DEFAULT_MM_BACKEND)
+
+ assert dispatch.verify(device)[0] is True
+ got_q, got_sf = ops._quantize_impl(x, a_gsf)
+ got = ops._mm_impl(got_q, wq, got_sf, w_sf, alpha, n, ops.DEFAULT_MM_BACKEND)
+ torch.cuda.synchronize(device)
+
+ assert torch.equal(want_q, got_q) and torch.equal(want_sf, got_sf)
+ assert torch.equal(want, got), float((want.float() - got.float()).abs().max())
+ assert (m, k // 2, n, ops.DEFAULT_MM_BACKEND, 0) in dispatch._GEMM_PLAN
+
+
+def test_the_preflight_unlocks_the_fast_dispatch_and_says_so():
+ torch = _cuda_or_skip()
+ import flashinfer
+
+ if flashinfer.__version__ not in dispatch._SUPPORTED:
+ pytest.skip(f"flashinfer {flashinfer.__version__} is outside the allowlist by design")
+
+ ops.reset_preflight_cache()
+ dispatch.reset()
+ record = ops.nvfp4_preflight(0, refresh = True)
+ assert record["ok"] is True, record["reason"]
+ assert record["fast_dispatch"] is True, record["fast_dispatch_reason"]
+ assert dispatch.enabled(torch.device("cuda", 0)) is True
+ ops.reset_preflight_cache()
+
+
+def test_a_collected_layer_takes_its_cached_weights_and_their_vram_with_it():
+ torch = _cuda_or_skip()
+ import gc
+
+ import flashinfer
+
+ from core.inference import diffusion_nvfp4_linear as nl
+
+ if flashinfer.__version__ not in dispatch._SUPPORTED:
+ pytest.skip(f"flashinfer {flashinfer.__version__} is outside the allowlist by design")
+
+ device = torch.device("cuda", 0)
+ dispatch.reset()
+ assert dispatch.verify(device)[0] is True
+ ops.register_ops()
+
+ in_features, out_features = 3072, 18432
+ torch.manual_seed(0)
+ with torch.cuda.device(device), torch.inference_mode():
+ w = torch.randn(out_features, in_features, device = device, dtype = torch.bfloat16) * 0.02
+ x = torch.randn(64, in_features, device = device, dtype = torch.bfloat16) * 0.05
+ a_gsf, w_gsf = ops.global_scale(x), ops.global_scale(w)
+ wq, w_sf = flashinfer.nvfp4_quantize(w, w_gsf, do_shuffle = False)
+ layer = nl.nvfp4_linear_class()(
+ in_features,
+ out_features,
+ wq = wq.clone(),
+ w_sf = w_sf.clone(),
+ alpha = (1.0 / (a_gsf * w_gsf)).float(),
+ a_gsf = a_gsf,
+ )
+ del wq, w_sf, w
+ gc.collect()
+ torch.cuda.empty_cache()
+ before = torch.cuda.memory_allocated(device)
+ nl._TUNED_SHAPES.add((x.shape[0], in_features, out_features))
+ layer(x)
+ torch.cuda.synchronize(device)
+
+ assert len(dispatch._TRANSPOSED) == 2
+ assert {id(layer.wq), id(layer.w_sf)} == set(dispatch._TRANSPOSED)
+ weight_bytes = layer.wq.numel() + layer.w_sf.numel()
+
+ del layer
+ gc.collect()
+ assert dispatch._TRANSPOSED == {}
+ torch.cuda.empty_cache()
+ freed = before - torch.cuda.memory_allocated(device)
+ assert freed >= weight_bytes, f"{freed} bytes released, expected at least {weight_bytes}"
diff --git a/studio/backend/tests/test_diffusion_nvfp4_speed.py b/studio/backend/tests/test_diffusion_nvfp4_speed.py
new file mode 100644
index 00000000000..3412035bd79
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_nvfp4_speed.py
@@ -0,0 +1,676 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""NVFP4 flashinfer device guard and ordering barrier. Stubs ``torch`` and ``flashinfer``: neither the
+launch device nor the call ORDER inside an opaque custom op is observable on one GPU."""
+
+from __future__ import annotations
+
+import contextlib
+import sys
+import types
+
+import pytest
+
+from core.inference import diffusion_nvfp4_dispatch as dispatch
+from core.inference import diffusion_nvfp4_linear as nl
+from core.inference import diffusion_nvfp4_ops as ops
+
+
+class _FakeDevice:
+ def __init__(
+ self,
+ index,
+ kind = "cuda",
+ ):
+ self.type = kind
+ self.index = index
+
+ def __eq__(self, other):
+ return isinstance(other, _FakeDevice) and (self.type, self.index) == (
+ other.type,
+ other.index,
+ )
+
+ def __hash__(self):
+ return hash((self.type, self.index))
+
+ def __repr__(self): # pragma: no cover - debug aid
+ return f"cuda:{self.index}"
+
+
+class _FakeTensor:
+ def __init__(
+ self,
+ shape = (1,),
+ device = None,
+ dtype = None,
+ ):
+ self.shape = tuple(shape)
+ self.device = device if device is not None else _FakeDevice(0)
+ self.dtype = dtype
+
+ def _same(self, shape = None):
+ return _FakeTensor(self.shape if shape is None else shape, self.device, self.dtype)
+
+ def float(self):
+ return self._same()
+
+ def abs(self):
+ return self._same()
+
+ def amax(self):
+ return self._same((1,))
+
+ def clamp(self, **_kw):
+ return self._same((1,))
+
+ def all(self):
+ return self._same((1,))
+
+ def item(self):
+ return True
+
+ def reshape(self, *shape):
+ flat = shape[0] if len(shape) == 1 and isinstance(shape[0], (tuple, list)) else shape
+ return self._same(tuple(flat) if not isinstance(flat, int) else (flat,))
+
+ def contiguous(self):
+ return self
+
+ def is_contiguous(self):
+ return True
+
+ def to(
+ self,
+ device = None,
+ **_kw,
+ ):
+ out = self._same()
+ if isinstance(device, _FakeDevice):
+ out.device = device
+ return out
+
+ def zero_(self):
+ _RECORDER.launches.append(("zero_", _RECORDER.current))
+ return self
+
+ def add_(self, _other):
+ return self
+
+ @property
+ def T(self):
+ return self._same(tuple(reversed(self.shape)))
+
+ def __mul__(self, _other):
+ return self._same()
+
+ __rmul__ = __mul__
+
+ def __truediv__(self, _other):
+ return self._same()
+
+ def __rtruediv__(self, _other):
+ return self._same()
+
+
+class _Recorder:
+ def __init__(self):
+ self.current = 0
+ self.launches: list[tuple] = []
+ self.stack: list[int] = []
+
+ def reset(self):
+ self.current = 0
+ self.launches.clear()
+ self.stack.clear()
+
+
+_RECORDER = _Recorder()
+
+
+def _fake_device_guard(device):
+ index = device.index if isinstance(device, _FakeDevice) else int(device)
+ _RECORDER.stack.append(_RECORDER.current)
+ _RECORDER.current = index
+ try:
+ yield
+ finally:
+ _RECORDER.current = _RECORDER.stack.pop()
+
+
+def _record(name):
+ def _call(*args, **kwargs):
+ _RECORDER.launches.append((name, _RECORDER.current))
+ if name == "nvfp4_quantize":
+ x = args[0]
+ return (_FakeTensor(x.shape, x.device), _FakeTensor(x.shape, x.device))
+ out = kwargs.get("out")
+ return out if out is not None else _FakeTensor((1,), _FakeDevice(_RECORDER.current))
+
+ return _call
+
+
+def _fake_alloc(name):
+ def _call(
+ *shape,
+ device = None,
+ dtype = None,
+ **_kw,
+ ):
+ flat = shape[0] if len(shape) == 1 and isinstance(shape[0], (tuple, list)) else shape
+ _RECORDER.launches.append((name, _RECORDER.current))
+ return _FakeTensor(tuple(flat), device, dtype)
+
+ return _call
+
+
+def _fake_torch():
+ torch = types.ModuleType("torch")
+ torch.bfloat16 = "bfloat16"
+ torch.float32 = "float32"
+ torch.uint8 = "uint8"
+ torch.zeros = _fake_alloc("zeros")
+ torch.empty = _fake_alloc("empty")
+ torch.randn = _fake_alloc("randn")
+ torch.isfinite = lambda t: t
+
+ def _device(kind, index = None):
+ if isinstance(kind, _FakeDevice):
+ return kind
+ if isinstance(kind, int):
+ return _FakeDevice(kind, "cuda")
+ return _FakeDevice(0 if index is None else index, str(kind))
+
+ torch.device = _device
+ torch.inference_mode = contextlib.nullcontext
+ cuda = types.SimpleNamespace(
+ is_available = lambda: True,
+ device = _fake_device_guard,
+ current_device = lambda: _RECORDER.current,
+ device_count = lambda: 2,
+ get_device_capability = lambda dev = None: (10, 0),
+ get_device_name = lambda dev = None: "stub B200",
+ synchronize = lambda dev = None: _RECORDER.launches.append(("synchronize", _RECORDER.current)),
+ is_current_stream_capturing = lambda: False,
+ )
+ torch.cuda = cuda
+ return torch
+
+
+def _fake_flashinfer():
+ fi = types.ModuleType("flashinfer")
+ fi.__version__ = "0.6.6"
+ fi.nvfp4_quantize = _record("nvfp4_quantize")
+ fi.mm_fp4 = _record("mm_fp4")
+ fi.autotune = lambda _on: contextlib.nullcontext()
+ return fi
+
+
+def stub_kernels(monkeypatch):
+ _RECORDER.reset()
+ dispatch.reset()
+ monkeypatch.setitem(sys.modules, "torch", _fake_torch())
+ monkeypatch.setitem(sys.modules, "flashinfer", _fake_flashinfer())
+ monkeypatch.setattr(ops, "register_ops", lambda: None)
+ monkeypatch.setattr(nl, "register_ops", lambda: None)
+ ops.reset_preflight_cache()
+ yield _RECORDER
+ _RECORDER.reset()
+ ops.reset_preflight_cache()
+ dispatch.reset()
+
+
+def _launch_devices(recorder, *names) -> list[int]:
+ return [device for name, device in recorder.launches if name in names]
+
+
+def test_the_stub_records_the_device_a_launch_actually_sees(stub_kernels):
+ """The detector's own control: without a guard the launch reads the CURRENT device."""
+ import flashinfer
+
+ flashinfer.mm_fp4()
+ assert _launch_devices(stub_kernels, "mm_fp4") == [0]
+
+
+def test_the_quantize_body_enters_the_tensors_device(stub_kernels):
+ x = _FakeTensor((128, 256), _FakeDevice(1))
+ ops._quantize_impl(x, _FakeTensor((1,), _FakeDevice(1)))
+ assert _launch_devices(stub_kernels, "nvfp4_quantize") == [1]
+ assert stub_kernels.current == 0
+
+
+def test_the_mm_body_enters_the_tensors_device_for_the_barrier_and_the_gemm(stub_kernels):
+ device = _FakeDevice(1)
+ ops._mm_impl(
+ _FakeTensor((4096, 1536), device),
+ _FakeTensor((12288, 1536), device),
+ _FakeTensor((4096, 192), device),
+ _FakeTensor((12288, 192), device),
+ _FakeTensor((1,), device),
+ 12288,
+ "cutlass",
+ )
+ assert set(_launch_devices(stub_kernels, "zeros", "empty", "mm_fp4")) == {1}
+ assert stub_kernels.current == 0
+
+
+def test_the_preflight_enters_the_probed_device(stub_kernels):
+ record = ops.nvfp4_preflight(_FakeDevice(1))
+ assert record["ok"] is True, record["reason"]
+ assert set(_launch_devices(stub_kernels, "nvfp4_quantize", "mm_fp4", "synchronize")) == {1}
+ assert stub_kernels.current == 0
+
+
+def test_the_prewarm_enters_each_layers_device(stub_kernels):
+ class NVFP4FlashInferLinear:
+ def __init__(self):
+ self.in_features = 1536
+ self.out_features = 12288
+ self.a_gsf = _FakeTensor((1,), _FakeDevice(1))
+ self.wq = _FakeTensor((12288, 768), _FakeDevice(1))
+ self._tuned = False
+
+ def __call__(self, _x):
+ _RECORDER.launches.append(("layer", _RECORDER.current))
+ return _FakeTensor((1,), self.wq.device)
+
+ layer = NVFP4FlashInferLinear()
+ tree = types.SimpleNamespace(named_modules = lambda: [("blocks.0.ff", layer)])
+
+ nl.reset_tuned_shapes()
+ try:
+ assert nl.nvfp4_prewarm(tree, (512,)) == 1
+ finally:
+ nl.reset_tuned_shapes()
+ assert set(_launch_devices(stub_kernels, "layer", "zeros", "synchronize")) == {1}
+ assert stub_kernels.current == 0
+
+
+def test_no_guard_is_left_open_when_a_launch_raises(stub_kernels, monkeypatch):
+ """A leaked guard is worse than no guard: it moves the whole process onto another card."""
+ import flashinfer
+
+ def _boom(*_a, **_kw):
+ raise RuntimeError("kernel refused")
+
+ monkeypatch.setattr(flashinfer, "nvfp4_quantize", _boom)
+ with pytest.raises(RuntimeError):
+ ops._quantize_impl(_FakeTensor((8, 16), _FakeDevice(1)), _FakeTensor((1,), _FakeDevice(1)))
+ assert stub_kernels.current == 0
+ assert stub_kernels.stack == []
+
+
+def test_a_layer_on_card_one_runs_correctly_while_the_current_device_is_card_zero():
+ torch = pytest.importorskip("torch")
+ if not getattr(torch, "cuda", None) or not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ if torch.cuda.device_count() < 2:
+ pytest.skip("needs two visible CUDA devices")
+ if tuple(torch.cuda.get_device_capability(1)) not in ops.NVFP4_FLASHINFER_CAPS:
+ pytest.skip("device 1 has no flashinfer NVFP4 kernels")
+ pytest.importorskip("flashinfer")
+ pytest.importorskip("torchao")
+
+ import torch.nn as nn
+ from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig
+ from torchao.quantization import quantize_
+
+ torch.manual_seed(0)
+ with torch.cuda.device(1):
+ linear = nn.Linear(3072, 3072, bias = True).to("cuda:1", torch.bfloat16)
+ quantize_(linear, NVFP4DynamicActivationNVFP4WeightConfig(use_triton_kernel = False))
+ x = torch.randn(512, 3072, device = "cuda:1", dtype = torch.bfloat16) * 0.05
+ converted = nl.nvfp4_linear_from_torchao(linear, ops.global_scale(x))
+ with torch.inference_mode():
+ want = converted(x)
+ torch.cuda.synchronize(1)
+
+ assert torch.cuda.current_device() == 0
+ with torch.inference_mode():
+ got = converted(x)
+ torch.cuda.synchronize(1)
+ assert bool(torch.isfinite(got).all())
+ assert torch.equal(got, want)
+
+
+def _mm_once(
+ device_index = 1,
+ m = 4096,
+ n = 12288,
+ k = 3072,
+):
+ device = _FakeDevice(device_index)
+ return ops._mm_impl(
+ _FakeTensor((m, k // 2), device),
+ _FakeTensor((n, k // 2), device),
+ _FakeTensor((m, k // 16), device),
+ _FakeTensor((n, k // 16), device),
+ _FakeTensor((1,), device),
+ n,
+ "cutlass",
+ )
+
+
[email protected](autouse = True)
+def _clean_barriers():
+ ops.reset_barriers()
+ yield
+ ops.reset_barriers()
+
+
+def test_the_barrier_is_allocated_once_per_device(stub_kernels):
+ for _ in range(5):
+ _mm_once(1)
+ for _ in range(5):
+ _mm_once(0)
+ barrier_allocs = [1 for name, _ in stub_kernels.launches if name == "empty"]
+ assert len(barrier_allocs) == 12, stub_kernels.launches
+ assert sorted(ops._BARRIERS) == [0, 1]
+ assert ops._BARRIERS[0] is not ops._BARRIERS[1]
+
+
+def test_the_barrier_fill_precedes_every_gemm(stub_kernels):
+ """A kernel MUST exist between the activation quantiser and the GEMM (PDL, no griddepcontrol)."""
+ for _ in range(3):
+ _mm_once(1)
+ order = [name for name, _ in stub_kernels.launches if name in ("zero_", "mm_fp4")]
+ assert order == ["zero_", "mm_fp4"] * 3
+
+
+def test_the_barrier_is_not_cached_when_the_stream_is_capturing(stub_kernels, monkeypatch):
+ monkeypatch.setattr(ops, "_is_capturing", lambda: True)
+ _mm_once(1)
+ assert ops._BARRIERS == {}
+ order = [name for name, _ in stub_kernels.launches if name in ("zero_", "mm_fp4")]
+ assert order == ["zero_", "mm_fp4"]
+
+ monkeypatch.setattr(ops, "_is_capturing", lambda: False)
+ _mm_once(1)
+ warm = ops._BARRIERS[1]
+ monkeypatch.setattr(ops, "_is_capturing", lambda: True)
+ _mm_once(1)
+ assert ops._BARRIERS[1] is warm
+
+
+def test_reset_barriers_drops_them(stub_kernels):
+ _mm_once(1)
+ assert list(ops._BARRIERS) == [1]
+ ops.reset_barriers()
+ assert ops._BARRIERS == {}
+ _mm_once(1)
+ assert list(ops._BARRIERS) == [1]
+
+
+def test_the_zero_buffer_env_restores_the_full_memset(stub_kernels, monkeypatch):
+ monkeypatch.setenv(ops.NVFP4_ZERO_BUFFER_ENV, "1")
+ _mm_once(1)
+ names = [name for name, _ in stub_kernels.launches]
+ assert "zeros" in names and "zero_" not in names
+ assert ops._BARRIERS == {}
+
+
+def test_the_barrier_is_not_an_op_argument():
+ """A mutable tensor input would go through ``auto_functionalized`` and be CLONED per call."""
+ schema = "(Tensor xq, Tensor wq, Tensor x_sf, Tensor w_sf, Tensor alpha, int n, str backend)"
+ import inspect
+
+ assert schema.count("Tensor") == 5
+ params = list(inspect.signature(ops._mm_impl).parameters)
+ assert params == ["xq", "wq", "x_sf", "w_sf", "alpha", "n", "backend"]
+
+
+def _nvfp4_cuda_or_skip():
+ torch = pytest.importorskip("torch")
+ if not getattr(torch, "cuda", None) or not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ if tuple(torch.cuda.get_device_capability(0)) not in ops.NVFP4_FLASHINFER_CAPS:
+ pytest.skip("this device has no flashinfer NVFP4 kernels")
+ pytest.importorskip("flashinfer")
+ pytest.importorskip("torchao")
+ return torch
+
+
+def _real_operands(
+ torch,
+ m,
+ k,
+ n,
+ seed = 0,
+):
+ import flashinfer
+
+ torch.manual_seed(seed)
+ with torch.cuda.device(0):
+ x = torch.randn(m, k, device = "cuda", dtype = torch.bfloat16) * 0.05
+ w = torch.randn(n, k, device = "cuda", dtype = torch.bfloat16) * 0.02
+ a_gsf, w_gsf = ops.global_scale(x), ops.global_scale(w)
+ xq, x_sf = flashinfer.nvfp4_quantize(x, a_gsf, do_shuffle = False)
+ wq, w_sf = flashinfer.nvfp4_quantize(w, w_gsf, do_shuffle = False)
+ alpha = (1.0 / (a_gsf * w_gsf)).float()
+ return xq, wq, x_sf, w_sf, alpha
+
+
+def test_the_persistent_barrier_is_bit_identical_to_the_per_call_one():
+ torch = _nvfp4_cuda_or_skip()
+ ops.reset_barriers()
+ xq, wq, x_sf, w_sf, alpha = _real_operands(torch, 4096, 3072, 12288)
+
+ with torch.inference_mode():
+ reference = None
+ for _ in range(50):
+ out = ops._mm_impl(xq, wq, x_sf, w_sf, alpha, 12288, ops.DEFAULT_MM_BACKEND)
+ assert bool(torch.isfinite(out).all())
+ if reference is None:
+ reference = out.clone()
+ else:
+ assert torch.equal(out, reference)
+ pointer = ops._BARRIERS[0].data_ptr()
+ for _ in range(10):
+ ops._mm_impl(xq, wq, x_sf, w_sf, alpha, 12288, ops.DEFAULT_MM_BACKEND)
+ assert ops._BARRIERS[0].data_ptr() == pointer
+ ops.reset_barriers()
+
+
+def test_the_barrier_pointer_is_stable_across_a_capture_and_replay():
+ """The barrier is warmed OUTSIDE the capture and must be the one the replay fires."""
+ torch = _nvfp4_cuda_or_skip()
+ ops.reset_barriers()
+ xq, wq, x_sf, w_sf, alpha = _real_operands(torch, 512, 3072, 3072, seed = 5)
+
+ with torch.cuda.device(0), torch.inference_mode():
+ eager = ops._mm_impl(xq, wq, x_sf, w_sf, alpha, 3072, ops.DEFAULT_MM_BACKEND).clone()
+ before = ops._BARRIERS[0].data_ptr()
+ torch.cuda.synchronize(0)
+
+ pool = torch.cuda.graph_pool_handle()
+ graph = torch.cuda.CUDAGraph()
+ stream = torch.cuda.Stream()
+ stream.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(stream):
+ for _ in range(3):
+ ops._mm_impl(xq, wq, x_sf, w_sf, alpha, 3072, ops.DEFAULT_MM_BACKEND)
+ torch.cuda.current_stream().wait_stream(stream)
+ with torch.cuda.graph(graph, pool = pool):
+ captured = ops._mm_impl(xq, wq, x_sf, w_sf, alpha, 3072, ops.DEFAULT_MM_BACKEND)
+ assert ops._BARRIERS[0].data_ptr() == before
+ for _ in range(5):
+ graph.replay()
+ torch.cuda.synchronize(0)
+ assert torch.equal(captured, eager)
+ assert ops._BARRIERS[0].data_ptr() == before
+ del graph
+ ops.reset_barriers()
+
+
+BIAS_SHAPES = (
+ (16384, 12288),
+ (4096, 3072),
+ (1024, 12288),
+ (333, 4096),
+ (1, 512),
+ (9304, 3072),
+ (7, 1024),
+)
+
+
+def _bias_pair(
+ torch,
+ m,
+ n,
+ dtype = None,
+ device = "cuda",
+):
+ dtype = torch.bfloat16 if dtype is None else dtype
+ torch.manual_seed(m * 31 + n)
+ out = torch.randn(m, n, device = device, dtype = dtype)
+ bias = torch.randn(n, device = device, dtype = dtype)
+ return out, bias
+
+
+def test_the_fast_bias_falls_back_without_triton(monkeypatch):
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_nvfp4_bias as fb
+
+ monkeypatch.setattr(fb, "_HAVE_TRITON", False)
+ out = torch.zeros(4, 8)
+ bias = torch.arange(8, dtype = torch.float32)
+ assert fb.fused_bias_add_(out, bias) is out
+ assert torch.equal(out[0], bias)
+
+
[email protected]("value", ["0", "off", "FALSE", " no "])
+def test_the_env_switch_takes_the_kernel_out_of_the_path(monkeypatch, value):
+ pytest.importorskip("torch")
+ from core.inference import diffusion_nvfp4_bias as fb
+
+ monkeypatch.setenv(fb.NVFP4_FAST_BIAS_ENV, value)
+ assert fb.fast_bias_enabled() is False
+
+
[email protected]("value", ["", "auto", "1", "AUTO"])
+def test_auto_and_one_both_leave_it_on(monkeypatch, value):
+ pytest.importorskip("torch")
+ from core.inference import diffusion_nvfp4_bias as fb
+
+ monkeypatch.setenv(fb.NVFP4_FAST_BIAS_ENV, value)
+ assert fb.fast_bias_enabled() is True
+
+
+def test_the_kernel_declines_a_shape_or_dtype_it_does_not_cover(monkeypatch):
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_nvfp4_bias as fb
+
+ if not fb._HAVE_TRITON:
+ pytest.skip("needs triton")
+ if not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+
+ monkeypatch.setattr(fb, "_FAST_BIAS_MIN_NUMEL", 0)
+ out, bias = _bias_pair(torch, 8, 16)
+ assert fb._eligible(out, bias)
+ assert not fb._eligible(*_bias_pair(torch, 8, 16, dtype = torch.float32))
+ assert not fb._eligible(out.T.contiguous().T, bias)
+ assert not fb._eligible(out.cpu(), bias.cpu())
+ assert not fb._eligible(out, bias[:8])
+ assert not fb._eligible(out, bias.reshape(1, 16))
+
+
+def test_the_kernel_declines_below_the_size_floor_and_above_int32(monkeypatch):
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_nvfp4_bias as fb
+
+ if not fb._HAVE_TRITON:
+ pytest.skip("needs triton")
+ if not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+
+ out, bias = _bias_pair(torch, 1024, 3840)
+ assert not fb._eligible(out, bias)
+ monkeypatch.setattr(fb, "_FAST_BIAS_MIN_NUMEL", out.numel())
+ assert fb._eligible(out, bias)
+ monkeypatch.setattr(fb, "_FAST_BIAS_MAX_NUMEL", out.numel() - 1)
+ assert not fb._eligible(out, bias)
+
+
+def test_the_kernel_declines_while_tracing(monkeypatch):
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_nvfp4_bias as fb
+
+ calls = []
+ monkeypatch.setattr(torch.compiler, "is_compiling", lambda: True)
+ monkeypatch.setattr(fb, "_eligible", lambda *a: calls.append("eligible") or True)
+ out = torch.zeros(4, 8)
+ fb.fused_bias_add_(out, torch.ones(8))
+ assert calls == []
+ assert float(out[0, 0]) == 1.0
+
+
[email protected]("m,n", BIAS_SHAPES)
+def test_the_fused_bias_is_bit_identical_to_add_(m, n, monkeypatch):
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_nvfp4_bias as fb
+
+ if not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ if not fb._HAVE_TRITON:
+ pytest.skip("needs triton")
+
+ monkeypatch.setattr(fb, "_FAST_BIAS_MIN_NUMEL", 0)
+ out, bias = _bias_pair(torch, m, n)
+ want = out.clone().add_(bias)
+ got = fb.fused_bias_add_(out, bias)
+ assert got is out
+ # Bit-identical, not close: the accuracy gates compare renders against stored references.
+ assert torch.equal(got, want), float((got.float() - want.float()).abs().max())
+
+
+def test_an_empty_output_is_left_alone():
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_nvfp4_bias as fb
+
+ if not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ out = torch.zeros(0, 32, device = "cuda", dtype = torch.bfloat16)
+ assert fb.fused_bias_add_(out, torch.ones(32, device = "cuda", dtype = torch.bfloat16)) is out
+
+
+def test_m3_the_fused_bias_against_add_at_the_bench_shapes(capsys, monkeypatch):
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_nvfp4_bias as fb
+
+ monkeypatch.setattr(fb, "_FAST_BIAS_MIN_NUMEL", 0)
+
+ if not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ if not fb._HAVE_TRITON:
+ pytest.skip("needs triton")
+ import time
+
+ lines = []
+ for m, n in ((4096, 12288), (4096, 3072), (4096, 4096), (16384, 12288)):
+ out, bias = _bias_pair(torch, m, n)
+ row = {}
+ for name, fn in (
+ ("add_", lambda: out.add_(bias)),
+ ("fused", lambda: fb.fused_bias_add_(out, bias)),
+ ):
+ for _ in range(5):
+ fn()
+ torch.cuda.synchronize()
+ best = float("inf")
+ for _ in range(5):
+ start = time.perf_counter()
+ for _ in range(20):
+ fn()
+ torch.cuda.synchronize()
+ best = min(best, (time.perf_counter() - start) / 20 * 1e3)
+ row[name] = best
+ lines.append(
+ f" bias {m}x{n}: add_ {row['add_']:.4f} ms, fused {row['fused']:.4f} ms, "
+ f"{row['add_'] / row['fused']:.2f}x"
+ )
+ with capsys.disabled():
+ print("\n" + "\n".join(lines))
diff --git a/studio/backend/tests/test_nvfp4_diffusion_flag.py b/studio/backend/tests/test_nvfp4_diffusion_flag.py
index a059a5e9922..5e93188a691 100644
--- a/studio/backend/tests/test_nvfp4_diffusion_flag.py
+++ b/studio/backend/tests/test_nvfp4_diffusion_flag.py
@@ -552,6 +552,18 @@ def test_the_per_layer_policy_factor_is_not_applied(monkeypatch):
assert policy_steady_factor("z-image", "Tongyi-MAI/Z-Image-Turbo") is not None
+def test_the_fast_dispatch_is_never_probed_or_verified(monkeypatch):
+ from core.inference import diffusion_nvfp4_dispatch as dispatch
+ from core.inference import diffusion_nvfp4_ops as ops
+
+ touched = []
+ monkeypatch.setattr(dispatch, "verify", lambda device: touched.append("verify") or (True, ""))
+ monkeypatch.setattr(dispatch, "_probe", lambda: touched.append("probe") or (True, ""))
+ assert ops.nvfp4_preflight(0, refresh = True)["ok"] is False
+ assert ops.select_nvfp4_backend(0) == ops.BACKEND_TORCHAO
+ assert touched == []
+
+
def _prequant_dir(root, name, scheme):
"""A directory holding one tiny safetensors pre-quant artifact that records ``scheme``."""
import json
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index fa79279187a..0409fd9c8df 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -10450,6 +10450,34 @@ def test_the_boundary_marker_waits_out_a_busy_capture_lock(fake_runtime, monkeyp
assert at_decode.get("phase") == "decode"
[email protected]("resident", [True, False])
+def test_a_failed_replacement_keeps_the_resident_models_nvfp4_state(monkeypatch, resident):
+ """A failed replacement keeps the old model, whose CUDA graph still uses the NVFP4 tensors."""
+ import core.inference.video as vid
+ from core.inference import diffusion_nvfp4_linear as lin
+
+ backend = VideoBackend()
+ resets: list = []
+ monkeypatch.setattr(lin, "reset_nvfp4_state", lambda: resets.append(True))
+ monkeypatch.setattr(vid, "clear_gpu_cache", lambda: None)
+
+ def _boom(*_a, **_k):
+ raise RuntimeError("metadata lookup failed")
+
+ monkeypatch.setattr(vid, "_detect_load_family", _boom)
+ if resident:
+ backend._state = types.SimpleNamespace(pipe = None)
+ import core.inference.gpu_arbiter as arbiter
+ import hub.services.models.account_access as access
+
+ monkeypatch.setattr(arbiter, "restore_owner_account", lambda *_a, **_k: None)
+ monkeypatch.setattr(access, "restore_resident_metadata", lambda *_a, **_k: None)
+ backend._load_token = 7
+ backend._run_load(repo_id = "org/model", _load_token = 7)
+
+ assert resets == ([] if resident else [True])
+
+
@pytest.mark.parametrize("scheme", ["int8", "fp8"])
def test_an_explicit_video_scheme_on_amd_runs_weight_only_without_forcing_compile(
fake_runtime, monkeypatch, scheme