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: per-layer NVFP4 image policies, flashinfer FP4 backend and a gated auto row (#10730)

Daniel Hane15d7a3c51a7
diff --git a/pyproject.toml b/pyproject.toml
index 3af32244b08..221ea4003ee 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -75,6 +75,8 @@ studio = [
# Swagger UI / ReDoc, served from this origin instead of a CDN. Without these the
# /docs and /redoc pages render blank in an installed Unsloth.
"backend/assets/docs_ui/*",
+ # Gate verdicts the auto ladder reads: missing from the wheel, nvfp4 silently leaves the ladder.
+ "backend/core/inference/nvfp4_gate_record.json",
"backend/core/data_recipe/oxc-validator/*.json",
"backend/core/data_recipe/oxc-validator/*.mjs",
"backend/core/inference/bundled_skills/**/*.md",
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 3a78f9e05b3..de20ca91cf9 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -188,6 +188,7 @@ from .diffusion_step_skip import (
static_skip_view,
uninstall_static_step_skip,
)
+from .diffusion_nvfp4_protect import protect_generation
from .diffusion_precision import (
TE_QUANT_FP8,
effective_te_quant,
@@ -231,6 +232,7 @@ from .diffusion_auto_policy import (
)
from .diffusion_transformer_quant import (
TQ_AUTO,
+ TQ_NVFP4,
TQ_INT8,
DEFAULT_MIN_LINEAR_FEATURES,
DenoiserView as _DenoiserView,
@@ -241,7 +243,9 @@ from .diffusion_transformer_quant import (
dense_transformer_unsupported_reason,
denoiser_modules,
explain_unusable_scheme,
+ family_denies_scheme,
mark_source_precision,
+ nvfp4_gated_base,
native_int8_act,
native_offload_host,
native_quant_host,
@@ -1372,6 +1376,35 @@ def _has_active_lora(loras: Any) -> bool:
return False
+def _planned_quant_scheme(
+ fam: Optional[DiffusionFamily],
+ target: Any,
+ requested: Optional[str],
+ *,
+ base_repo: Optional[str],
+ prequant_path: Optional[str],
+) -> Optional[str]:
+ """The scheme the load will resolve: without the base and the checkpoint probe, plan and load
+ pick different schemes and a second denoiser is fetched inline."""
+ return select_transformer_quant_scheme(
+ target,
+ requested,
+ family = getattr(fam, "name", None),
+ base_repo = base_repo,
+ has_prequant = _prequant_probe(fam, base_repo = base_repo, prequant_path = prequant_path),
+ )
+
+
+def _prequant_probe(
+ fam: Optional[DiffusionFamily], *, base_repo: Optional[str], prequant_path: Optional[str]
+) -> Callable[[str], bool]:
+ return lambda candidate: (
+ fam is not None
+ and usable_prequant_source(fam, candidate, path_override = prequant_path, base_repo = base_repo)
+ is not None
+ )
+
+
def _uncached_prequant_repo(
fam: Optional[DiffusionFamily],
target: Any,
@@ -1386,8 +1419,8 @@ def _uncached_prequant_repo(
instead. Shared by ``load_pipeline`` and ``_dense_quant_prefetch_needed`` so the load and the
download plan decline together. Cheap (a refs read + stat) and never raises."""
try:
- scheme = select_transformer_quant_scheme(
- target, requested, family = getattr(fam, "name", None)
+ scheme = _planned_quant_scheme(
+ fam, target, requested, base_repo = base_repo, prequant_path = prequant_path
)
if scheme is None:
return None
@@ -1514,8 +1547,8 @@ def _dense_candidate_is_prequant(
)
if candidate is not None:
return bool(candidate.prequant)
- scheme = select_transformer_quant_scheme(
- target, requested, family = getattr(fam, "name", None)
+ scheme = _planned_quant_scheme(
+ fam, target, requested, base_repo = base_repo, prequant_path = prequant_path
)
if scheme is None:
return False
@@ -1866,6 +1899,8 @@ class DiffusionBackend:
cpu_offload: bool = False,
speed_mode: Optional[str] = None,
gpu_ordinal: Optional[int] = None,
+ repo_id: Optional[str] = None,
+ base_repo: Optional[str] = None,
) -> None:
"""Raise ``RuntimeError`` (the route's 409) when an EXPLICIT precision cannot run here.
@@ -1907,6 +1942,7 @@ class DiffusionBackend:
memory_mode = memory_mode,
cpu_offload = cpu_offload,
speed_mode = speed_mode,
+ base_repo = repo_id if model_kind == "pipeline" else base_repo,
)
def _assert_precision_for_target(
@@ -1920,10 +1956,20 @@ class DiffusionBackend:
memory_mode: Optional[str],
cpu_offload: bool,
speed_mode: Optional[str] = None,
+ base_repo: Optional[str] = None,
) -> None:
"""The body of ``assert_precision_available``, run with the selected card current."""
if pinned is not None and pinned != TQ_AUTO:
reason = None
+ family_name = getattr(fam, "name", None)
+ if (
+ not base_repo
+ and model_kind != "pipeline"
+ and pinned == TQ_NVFP4
+ and family_denies_scheme(family_name, pinned)
+ ):
+ # GGUF pick without a base: judge network-free on a gate-lifted base; the loader refuses any other.
+ base_repo = nvfp4_gated_base(family_name)
if not dense_quant_supported_kind(model_kind):
reason = dense_quant_unsupported_kind_reason(model_kind)
elif getattr(fam, "denoiser_attr", "transformer") != "transformer":
@@ -1979,6 +2025,7 @@ class DiffusionBackend:
target,
pinned,
family = getattr(fam, "name", None),
+ base_repo = base_repo,
# This gate runs BEFORE the arbiter evicts the resident model, so a smoke probe that runs out of
# VRAM here has not shown the scheme unusable, only that the GPU is still full. Refusing on that
# would reject a load the eviction was about to make room for.
@@ -1987,8 +2034,9 @@ class DiffusionBackend:
is None
):
# An explicit scheme is never swapped for another, so a None here means this GPU (or this family's
- # measured deny list) rules it out.
- reason = explain_unusable_scheme(getattr(fam, "name", None), pinned)
+ # measured deny list) rules it out. The same base: a gate record that lifted the deny for it must not be
+ # blamed when it is the GPU that declined.
+ reason = explain_unusable_scheme(getattr(fam, "name", None), pinned, base_repo)
if reason is not None:
raise RuntimeError(
precision_refusal_message(
@@ -2245,9 +2293,15 @@ class DiffusionBackend:
force_dense = _has_active_lora(kwargs.get("loras")),
logger = None,
)
- # A prequant loads a small checkpoint, so widening defeats the savings and can disk-full
- if candidate is None or candidate.prequant:
+ if candidate is None:
return False
+ if candidate.prequant:
+ scheme = getattr(candidate, "scheme", None)
+ if self._hosted_prequant_reachable(fam, scheme, kwargs):
+ return False
+ kwargs["_prequant_unreachable"] = tuple(
+ dict.fromkeys((*kwargs.get("_prequant_unreachable", ()), scheme))
+ )
# Capacity gate: mirror plan_fits_total_capacity against TOTAL capacity, else load_pipeline declines the dense
# path anyway
from .diffusion_memory import (
@@ -2264,6 +2318,31 @@ class DiffusionBackend:
return False
return True
+ def _hosted_prequant_reachable(self, fam: Any, scheme: Optional[str], kwargs: dict) -> bool:
+ """Whether the prequant a candidate counts on can really be fetched. ``usable_prequant_source`` answers from
+ the family table alone, so a private, gated or unpublished repo still reads as available; the load then
+ falls back to the dense build with no shards staged and pulls them inline. Cached or local counts; a repo
+ the Hub refuses does not. Unanswerable keeps the candidate's own verdict."""
+ try:
+ source = usable_prequant_source(
+ fam,
+ scheme,
+ path_override = kwargs.get("transformer_prequant_path"),
+ base_repo = kwargs.get("base_repo"),
+ )
+ if source is None or getattr(source, "kind", None) != "repo":
+ return True
+ if prequant_checkpoint_cached(source, cache_dir = hub_cache_dir()):
+ return True
+ if kwargs.get("local_files_only"):
+ return False
+ return (
+ self._prequant_source_hub_entry(source, kwargs.get("hf_token"), scheme = scheme)
+ is not None
+ )
+ except Exception: # noqa: BLE001 -- a transient probe failure keeps the candidate's verdict
+ return True
+
@staticmethod
def _auto_prequant_retry_scheme(
target: Any,
@@ -2282,7 +2361,15 @@ class DiffusionBackend:
return None
try:
from .diffusion_transformer_quant import auto_scheme_candidates
- candidates = auto_scheme_candidates(target, getattr(fam, "name", None))
+ candidates = auto_scheme_candidates(
+ target,
+ getattr(fam, "name", None),
+ base_repo = base_repo,
+ has_prequant = lambda candidate: usable_prequant_source(
+ fam, candidate, path_override = path_override, base_repo = base_repo
+ )
+ is not None,
+ )
except Exception: # noqa: BLE001 -- no candidates is just "no retry"
return None
seen_chosen = False
@@ -2656,6 +2743,8 @@ class DiffusionBackend:
# an explicit scheme here says so before the download.
speed_mode = speed_mode,
gpu_ordinal = gpu_ordinal,
+ repo_id = repo_id,
+ base_repo = base_repo,
)
with self._lock, self._load_cancel_lock:
@@ -3201,8 +3290,12 @@ class DiffusionBackend:
)
):
return None
- scheme = select_transformer_quant_scheme(
- target, mode, family = getattr(fam, "name", None)
+ scheme = _planned_quant_scheme(
+ fam,
+ target,
+ mode,
+ base_repo = base,
+ prequant_path = transformer_prequant_path,
)
if scheme is None or scheme == TQ_AUTO:
return None
@@ -3213,7 +3306,18 @@ class DiffusionBackend:
if auto:
try:
from .diffusion_transformer_quant import auto_scheme_candidates
- below = list(auto_scheme_candidates(target, getattr(fam, "name", None)))
+ below = list(
+ auto_scheme_candidates(
+ target,
+ getattr(fam, "name", None),
+ base_repo = base,
+ has_prequant = _prequant_probe(
+ fam,
+ base_repo = base,
+ prequant_path = transformer_prequant_path,
+ ),
+ )
+ )
if scheme in below:
rungs.extend(below[below.index(scheme) + 1 :])
except Exception: # noqa: BLE001 -- no lower rungs is just "no retry"
@@ -3349,8 +3453,12 @@ class DiffusionBackend:
is not None
):
return None
- scheme = select_transformer_quant_scheme(
- target, mode, family = getattr(fam, "name", None)
+ scheme = _planned_quant_scheme(
+ fam,
+ target,
+ mode,
+ base_repo = kwargs.get("base_repo"),
+ prequant_path = kwargs.get("transformer_prequant_path"),
)
if scheme is None:
return None
@@ -3418,8 +3526,16 @@ class DiffusionBackend:
if nvfp4_blocked(scheme) or nvfp4_repo_blocked(source.location):
return None
from huggingface_hub import HfApi
+ from huggingface_hub.errors import RepositoryNotFoundError
- info = HfApi(token = hf_token or None).model_info(source.location, files_metadata = True)
+ try:
+ info = HfApi(token = hf_token or None).model_info(source.location, files_metadata = True)
+ except RepositoryNotFoundError as exc:
+ # 401/403/404 on the repo = no hosted checkpoint, not a partial listing (GatedRepoError subclasses this).
+ logger.info(
+ "diffusion.prequant_repo_unavailable: %s (%s)", source.location, type(exc).__name__
+ )
+ return None
sizes = {s.rfilename: int(getattr(s, "size", 0) or 0) for s in (info.siblings or [])}
# Every candidate, in the order the loader tries them: safetensors first, then the pickle
# spellings. Reading only two of them would miss the artifact on a repo that hosts the third.
@@ -3769,7 +3885,7 @@ class DiffusionBackend:
(
lambda companions, transformer_files: self._dense_quant_prefetch_needed(
fam,
- {**load_kwargs, "base_repo": base},
+ {**load_kwargs, "base_repo": base, "hf_token": hf_token},
companion_files = companions,
transformer_files = transformer_files,
)
@@ -4561,6 +4677,7 @@ class DiffusionBackend:
# The scheme the plan settled, or PIPELINE_SEED_DECLINED; None for a direct call, which the pull never scoped.
_pipeline_prequant_planned: Optional[str] = None,
_pipeline_prequant_skipped: tuple[str, ...] = (),
+ _prequant_unreachable: tuple[str, ...] = (),
_te_prequant_resolved: bool = True,
) -> dict[str, Any]:
with self._load_cancel_lock:
@@ -4856,15 +4973,28 @@ class DiffusionBackend:
transformer_quant_pinned is not None
and native_scheme is None
and not native_offload_forced
- and select_transformer_quant_scheme(
- target, transformer_quant_pinned, family = getattr(fam, "name", None)
+ and _planned_quant_scheme(
+ fam,
+ target,
+ transformer_quant_pinned,
+ base_repo = base,
+ prequant_path = transformer_prequant_path,
)
is None
):
- # An explicit scheme is never swapped for another
- transformer_quant_decline = (
- f"'{transformer_quant_pinned}' is not usable for family "
- f"'{getattr(fam, 'name', None)}' on this GPU"
+ transformer_quant_decline = explain_unusable_scheme(
+ getattr(fam, "name", None),
+ transformer_quant_pinned,
+ base_repo = base,
+ prequant_missing = normalize_transformer_quant(transformer_quant_pinned)
+ == TQ_NVFP4
+ and usable_prequant_source(
+ fam,
+ TQ_NVFP4,
+ path_override = transformer_prequant_path,
+ base_repo = base,
+ )
+ is None,
)
transformer_quant_decline_status = RESOLVED_UNSUPPORTED
# The GGUF-size plan can mis-budget the fast path, so preflight the real footprint pre-eviction. Also
@@ -4931,8 +5061,12 @@ class DiffusionBackend:
elif (
not _transformer_prefetched
and dense_transformer_supported(target)
- and select_transformer_quant_scheme(
- target, transformer_quant, family = getattr(fam, "name", None)
+ and _planned_quant_scheme(
+ fam,
+ target,
+ transformer_quant,
+ base_repo = base,
+ prequant_path = transformer_prequant_path,
)
is not None
and not _dense_candidate_is_prequant(
@@ -4946,8 +5080,12 @@ class DiffusionBackend:
target,
fam,
transformer_quant,
- select_transformer_quant_scheme(
- target, transformer_quant, family = getattr(fam, "name", None)
+ _planned_quant_scheme(
+ fam,
+ target,
+ transformer_quant,
+ base_repo = base,
+ prequant_path = transformer_prequant_path,
),
base_repo = base,
path_override = transformer_prequant_path,
@@ -4982,6 +5120,20 @@ class DiffusionBackend:
force_dense = _has_active_lora(loras),
logger = logger,
)
+ if (
+ candidate is not None
+ and candidate.prequant
+ and getattr(candidate, "scheme", None) in _prequant_unreachable
+ ):
+ candidate = resolve_dense_quant_candidate(
+ fam = fam,
+ target = target,
+ requested = transformer_quant,
+ base_repo = base,
+ prequant_path = transformer_prequant_path,
+ force_dense = True,
+ logger = logger,
+ )
# Defined OUTSIDE the candidate check: the retry below rebinds ``candidate`` and calls this,
# and that retry is reached precisely when the first resolve returned None. Nested, the name
@@ -5059,10 +5211,12 @@ class DiffusionBackend:
target,
fam,
transformer_quant,
- select_transformer_quant_scheme(
+ _planned_quant_scheme(
+ fam,
target,
transformer_quant,
- family = getattr(fam, "name", None),
+ base_repo = base,
+ prequant_path = transformer_prequant_path,
),
base_repo = base,
path_override = transformer_prequant_path,
@@ -5097,17 +5251,20 @@ class DiffusionBackend:
else:
# This materialises the dense bf16 transformer, so re-check the fit rather than OOMing after
# eviction (skipped for a prequant).
- scheme = select_transformer_quant_scheme(
+ scheme = _planned_quant_scheme(
+ fam,
target,
transformer_quant, # normalized above
- family = getattr(fam, "name", None),
+ base_repo = base,
+ prequant_path = transformer_prequant_path,
)
# usable_prequant_source (not resolve_): a missing/non-allowlisted local path must not skip
# the dense-fit re-check
prequant = (
# A LoRA bake skips the prequant shortcut, so gate the fast path as if no prequant existed
None
- if _has_active_lora(loras)
+ # Nor one this user cannot fetch: the loader would build dense, so the check must too
+ if _has_active_lora(loras) or scheme in _prequant_unreachable
else usable_prequant_source(
fam,
scheme,
@@ -5796,7 +5953,10 @@ class DiffusionBackend:
bf16_plan = plan
if plan.offload_policy != OFFLOAD_NONE:
preview_scheme = native_scheme or select_transformer_quant_scheme(
- target, transformer_quant, family = getattr(fam, "name", None)
+ target,
+ transformer_quant,
+ family = getattr(fam, "name", None),
+ base_repo = base,
)
# This in-memory rewrite needs no cache-space or hosted-checkpoint checks.
estimate = (
@@ -5908,6 +6068,7 @@ class DiffusionBackend:
target,
mode = transformer_quant,
family = getattr(fam, "name", None),
+ base_repo = base,
fast_accum = transformer_quant_fast_accum,
logger = logger,
**native_kwargs,
@@ -6481,7 +6642,9 @@ class DiffusionBackend:
check_cancelled()
fetch_base = fetch_base or prefer_ungated_mirror(base, hf_token)
# 1. Pre-quantized checkpoint, when one is configured for the resolved scheme.
- scheme = select_transformer_quant_scheme(target, mode, family = getattr(fam, "name", None))
+ scheme = _planned_quant_scheme(
+ fam, target, mode, base_repo = base, prequant_path = prequant_path
+ )
if scheme is None:
# Bail BEFORE the multi-GB dense download: an unsupported scheme (fp8 on Ampere, nvfp4 off Blackwell)
# would materialise the transformer only to fail at quantize, after eviction. load_pipeline falls back to
@@ -6519,6 +6682,10 @@ class DiffusionBackend:
)
check_cancelled()
if transformer is not None:
+ if scheme == TQ_NVFP4:
+ # Only M = 1 is knowable here; other shapes tune on their first eager GEMM.
+ from .diffusion_nvfp4_linear import nvfp4_prewarm
+ nvfp4_prewarm(transformer, (1,), logger = logger)
pipe = self._assemble_pipe(
pipeline_cls,
base,
@@ -6606,6 +6773,8 @@ class DiffusionBackend:
target,
mode = mode,
family = getattr(fam, "name", None),
+ # The upstream id, not ``fetch_base``: a policy is a claim about one set of weights.
+ base_repo = base,
fast_accum = fast_accum,
logger = logger,
)
@@ -8205,16 +8374,15 @@ class DiffusionBackend:
if "callback_on_step_end" in call_params:
kwargs["callback_on_step_end"] = _on_step
- # EFFECTIVE steps (img2img at strength < 1 runs fewer): the AUTO cache and the static schedule key on it.
- denoise_steps = steps
- if state.cache_auto or static_skip:
- strength_applied = effective_request_strength(
- strength,
- init_pil is not None,
- "strength" in call_params,
- call_params["strength"].default if "strength" in call_params else None,
- )
- denoise_steps = effective_denoise_steps(steps, strength_applied)
+ # EFFECTIVE steps: img2img at strength < 1 denoises a fraction of `steps`.
+ strength_applied = effective_request_strength(
+ strength,
+ init_pil is not None,
+ "strength" in call_params,
+ call_params["strength"].default if "strength" in call_params else None,
+ )
+ denoise_steps = effective_denoise_steps(steps, strength_applied)
+
# Re-check an AUTO cache decision against the ACTUAL step count; explicit choices never toggle.
if state.cache_auto:
toggled = maybe_toggle_step_cache(
@@ -8288,9 +8456,10 @@ class DiffusionBackend:
elif state.transformer_cache:
# diffusers resets FBCache only after a SUCCESSFUL __call__; a raised call leaves a stale residual.
self._reset_step_cache(state.pipe)
+ protect_ctx = protect_generation(pipe, denoise_steps, logger = logger)
try:
# inference_mode is faster than no_grad and numerically identical here.
- with torch.inference_mode():
+ with torch.inference_mode(), protect_ctx:
out = pipe(**chunk_kwargs).images
except Exception as exc: # noqa: BLE001 - reraised unless a splittable OOM
oom = is_oom_error(exc)
@@ -8623,6 +8792,7 @@ class DiffusionBackend:
"speed_optims": [],
"text_encoder_quant": None,
"transformer_quant": None,
+ "transformer_quant_backend": None,
"attention_backend": None,
"transformer_cache": None,
"transformer_cache_stats": None,
@@ -8660,6 +8830,7 @@ class DiffusionBackend:
"speed_optims": speed_optims,
"text_encoder_quant": state.text_encoder_quant,
"transformer_quant": state.transformer_quant,
+ "transformer_quant_backend": _transformer_quant_backend(state),
"attention_backend": state.attention_backend,
"transformer_cache": state.transformer_cache,
"transformer_cache_stats": static_skip_stats(state.pipe),
@@ -8688,6 +8859,29 @@ class DiffusionBackend:
}
+def _transformer_quant_backend(state: Any) -> Optional[str]:
+ """The NVFP4 kernel path read from the MODULE TREE, not the load's intent. Never raises."""
+ if getattr(state, "transformer_quant", None) != TQ_NVFP4:
+ return None
+ try:
+ pipe = getattr(state, "pipe", None)
+ denoiser_attr = getattr(getattr(state, "family", None), "denoiser_attr", "transformer")
+ denoiser = getattr(pipe, denoiser_attr or "transformer", None)
+ if denoiser is None:
+ return None
+ declared = getattr(denoiser, "_unsloth_nvfp4_backend", None)
+ if declared:
+ return str(declared)
+ from .diffusion_nvfp4_linear import is_nvfp4_flashinfer_linear
+
+ for module in denoiser.modules():
+ if is_nvfp4_flashinfer_linear(module):
+ return "flashinfer"
+ return "torchao"
+ except Exception: # noqa: BLE001 -- see the docstring: a poll must not fail on a probe
+ return None
+
+
def _family_workflows(fam: DiffusionFamily) -> list[str]:
"""The workflow ids the diffusers engine can run for ``fam`` (drives UI gating)."""
# Instruction-editing families have no txt2img mode, so expose only "edit".
diff --git a/studio/backend/core/inference/diffusion_auto_policy.py b/studio/backend/core/inference/diffusion_auto_policy.py
index 63e5c994566..ac866914efe 100644
--- a/studio/backend/core/inference/diffusion_auto_policy.py
+++ b/studio/backend/core/inference/diffusion_auto_policy.py
@@ -37,6 +37,30 @@ _QUANT_STEADY_FACTOR: dict[str, float] = {
"nvfp4": 0.33,
}
+# Measured policy residency over bf16 + ~0.04 slack; 0.33 would keep a non-fitting model resident.
+_POLICY_STEADY_FACTOR: dict[str, float] = {
+ "zimg_rg76_v1": 0.50,
+ "flux_r420_v1": 0.45,
+ "qwen21_r020_v1": 0.50,
+ "qwen2512_m120_attn8_v1": 0.42,
+ "qwen_p02_v1": 0.47,
+}
+
+
+def policy_steady_factor(family: Any, base_repo: Optional[str] = None) -> Optional[float]:
+ """None keeps the whole-model factor. Never raises: a sizing estimate must not sink a load."""
+ from .diffusion_nvfp4_flag import nvfp4_diffusion_enabled
+
+ if not nvfp4_diffusion_enabled():
+ return None
+ try:
+ from .diffusion_nvfp4_policy import resolve_policy
+ policy = resolve_policy(getattr(family, "name", family), base_repo)
+ except Exception: # noqa: BLE001 -- an unresolvable policy just means the plain factor
+ return None
+ return None if policy is None else _POLICY_STEADY_FACTOR.get(policy.policy_id)
+
+
# bf16-RESIDENT component sizes in decimal GB: (transformer, text encoders, VAE). What they occupy on device after the
# dtype cast, NOT the download size (Z-Image-Turbo ships fp32: 24.6 GB of shards -> 12.3 GB bf16). From HF sibling
# metadata.
@@ -237,6 +261,8 @@ def estimate_dense_quant(
return None
components = family_bf16_components_gb(fam, base_repo)
factor = _QUANT_STEADY_FACTOR.get(scheme)
+ if scheme == "nvfp4":
+ factor = policy_steady_factor(fam, base_repo) or factor
if components is None or factor is None:
return None
transformer_gb, text_encoders_gb, vae_gb = components
@@ -277,6 +303,20 @@ def _hf_cache_free_mib() -> Optional[int]:
return None
+def _has_usable_prequant(
+ fam: Any, scheme: str, prequant_path: Optional[str], base_repo: Optional[str]
+) -> bool:
+ """False on any failure: "cannot tell" is not "yes"."""
+ try:
+ from .diffusion_prequant import usable_prequant_source
+ return (
+ usable_prequant_source(fam, scheme, path_override = prequant_path, base_repo = base_repo)
+ is not None
+ )
+ except Exception: # noqa: BLE001 -- prequant probing must never sink the candidate
+ return False
+
+
def resolve_dense_quant_candidate(
*,
fam: Any,
@@ -301,7 +341,15 @@ def resolve_dense_quant_candidate(
return None
if not dense_transformer_supported(target):
return None
- scheme = select_transformer_quant_scheme(target, requested, family = getattr(fam, "name", None))
+ scheme = select_transformer_quant_scheme(
+ target,
+ requested,
+ family = getattr(fam, "name", None),
+ base_repo = base_repo,
+ has_prequant = lambda candidate: _has_usable_prequant(
+ fam, candidate, prequant_path, base_repo
+ ),
+ )
if scheme is None:
return None
prequant_available = False
diff --git a/studio/backend/core/inference/diffusion_cuda_graph.py b/studio/backend/core/inference/diffusion_cuda_graph.py
index ede2c4b3682..fd4b834fafe 100644
--- a/studio/backend/core/inference/diffusion_cuda_graph.py
+++ b/studio/backend/core/inference/diffusion_cuda_graph.py
@@ -196,6 +196,61 @@ def _drop_pool_if_unused() -> None:
pass
+def _nvfp4_flashinfer_linears(module: Any) -> list:
+ """Lazy import, so a build without the backend does not lose CUDA graphs over it."""
+ try:
+ from .diffusion_nvfp4_linear import is_nvfp4_flashinfer_linear
+ except Exception: # noqa: BLE001 - no backend module, no NVFP4 layers to find
+ return []
+ found: list = []
+ try:
+ for name, sub in module.named_modules():
+ if is_nvfp4_flashinfer_linear(sub):
+ found.append((name, sub))
+ except Exception: # noqa: BLE001 - an exotic module tree is simply not an NVFP4 one
+ return []
+ return found
+
+
+def _protect_keyed(module: Any) -> bool:
+ """Only when the lever is armed AND this module holds NVFP4 layers, so fp8 keeps its graph count."""
+ try:
+ from .diffusion_nvfp4_protect import module_controller
+ if not module_controller(module).armed:
+ return False
+ return bool(_nvfp4_flashinfer_linears(module))
+ except Exception: # noqa: BLE001 - a tree we cannot walk simply keys the way it always did
+ return False
+
+
+def protect_graph_key(controller: Any = None) -> tuple:
+ from .diffusion_nvfp4_protect import protect_graph_key as _key
+ return _key(controller = controller)
+
+
+def _unbaked_nvfp4_layers(layers: list) -> list:
+ """A scale still being learned would be frozen by capture. Fail closed: no answer is unbaked."""
+ return [name for name, layer in layers if not getattr(layer, "activation_scales_baked", False)]
+
+
+def _prewarm_token_counts(live: list) -> tuple:
+ """Candidate GEMM row counts (M), read off the warm-up's shapes; generous but bounded."""
+ counts = {1}
+ for tensor in live:
+ try:
+ shape = tuple(int(dim) for dim in tensor.shape)
+ except Exception: # noqa: BLE001 - not a shaped tensor, nothing to read
+ continue
+ if len(shape) < 2:
+ continue
+ rows = 1
+ for dim in shape[:-1]:
+ rows *= dim
+ if rows > 0:
+ counts.add(rows)
+ return tuple(sorted(counts)[:8])
+
+
def _warn(logger: Any, what: str, exc: Any) -> None:
if logger is not None:
logger.warning("diffusion.cuda_graph: %s failed: %s", what, exc)
@@ -260,6 +315,8 @@ class GraphedForward:
self.capture_error: Optional[dict] = None
self.cache: dict = {}
self.cap_hit = False
+ self.protect_keyed: Optional[bool] = None
+ self.protect_ctl: Any = None
self.stats = {
"captures": 0,
"replays": 0,
@@ -387,6 +444,23 @@ class GraphedForward:
try:
key = graph_key((args, kwargs))
+ if self.protect_keyed is None:
+ self.protect_keyed = _protect_keyed(self.module)
+ if self.protect_keyed:
+ from .diffusion_nvfp4_protect import module_controller
+ self.protect_ctl = module_controller(self.module)
+ if self.protect_keyed:
+ self.max_graphs *= 2
+ if self.logger is not None:
+ self.logger.info(
+ "diffusion.cuda_graph: NVFP4 per-step precision is armed on %s; graph "
+ "cap raised to %d (one graph per branch per input shape)",
+ type(self.module).__name__,
+ self.max_graphs,
+ )
+ if self.protect_keyed:
+ # One graph per branch: a W4A4 replay at a W4A16 step means the lever never fired.
+ key = key + protect_graph_key(self.protect_ctl)
entry = self.cache.get(key)
except Exception: # noqa: BLE001 - an unhashable tree is simply not capturable
self.stats["refused_object"] += 1
@@ -465,6 +539,15 @@ class GraphedForward:
f"inside a captured region is baked in at its recorded value"
)
+ nvfp4_layers = _nvfp4_flashinfer_linears(self.module)
+ unbaked = _unbaked_nvfp4_layers(nvfp4_layers)
+ if unbaked:
+ raise RuntimeError(
+ f"{len(unbaked)} NVFP4 linear(s) report unbaked activation scales "
+ f"(first: {unbaked[0]}); a scale still being calibrated would be frozen into the "
+ f"graph at whatever value this capture saw, so this load runs eager"
+ )
+
# A tensor made under ``torch.inference_mode()``, which renders run in, refuses ``copy_``.
with torch.inference_mode(False):
entry.static = [torch.empty_like(t) for t in live]
@@ -472,6 +555,11 @@ class GraphedForward:
dst.copy_(src)
static_args, static_kwargs = _rebuild(entry.in_spec, entry.static)
+ if nvfp4_layers:
+ # Before the warm-up: a captured tuning launch would bake in the default tactic.
+ from .diffusion_nvfp4_linear import nvfp4_prewarm
+ nvfp4_prewarm(self.module, _prewarm_token_counts(live), logger = self.logger)
+
# Side stream: a workspace first created DURING capture is only valid while recording.
side = torch.cuda.Stream()
side.wait_stream(torch.cuda.current_stream())
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.py
index 5713df6ee7c..a05cfebaead 100644
--- a/studio/backend/core/inference/diffusion_families.py
+++ b/studio/backend/core/inference/diffusion_families.py
@@ -215,6 +215,8 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
("black-forest-labs/flux.1-dev", "fp8", "unsloth/FLUX.1-dev-FP8"),
("black-forest-labs/flux.1-krea-dev", "int8", "unsloth/FLUX.1-Krea-dev-FP8"),
("black-forest-labs/flux.1-krea-dev", "fp8", "unsloth/FLUX.1-Krea-dev-FP8"),
+ # schnell ONLY: dev and Krea-dev would download it just for _validate_checkpoint to refuse.
+ ("black-forest-labs/flux.1-schnell", "nvfp4", "unsloth/FLUX.1-schnell-NVFP4"),
),
# Pre-cast T5-XXL (9.52 -> 5.90 GB; CLIP-L stays dense). One artifact serves schnell/dev/Krea-dev (T5 shards
# are byte-identical).
@@ -349,6 +351,8 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
prequant_variant_repos = (
("qwen/qwen-image-2512", "int8", "unsloth/Qwen-Image-2512-FP8"),
("qwen/qwen-image-2512", "fp8", "unsloth/Qwen-Image-2512-FP8"),
+ # Policy ``qwen2512_m120_attn8_v1``, 2512 only: Qwen/Qwen-Image keeps its nvfp4 deny.
+ ("qwen/qwen-image-2512", "nvfp4", "unsloth/Qwen-Image-2512-NVFP4"),
),
# Pre-cast Qwen2.5-VL-7B (16.6 -> 8.8 GB). Always was independent of the DiT scheme rules.
te_prequant_repos = (("fp8", "text_encoder", "unsloth/Qwen-Image-FP8"),),
@@ -388,6 +392,7 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
prequant_repos = (
("int8", "unsloth/Qwen-Image-2.1-FP8"),
("fp8", "unsloth/Qwen-Image-2.1-FP8"),
+ ("nvfp4", "unsloth/Qwen-Image-2.1-NVFP4"),
),
# The artifacts are safetensors, not the historical torch.save pickle, so the family has to
# NAME them: every derived fallback ends in .pt, and without these rows the loader would ask
@@ -482,6 +487,7 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (
prequant_repos = (
("int8", "unsloth/Z-Image-Turbo-FP8"),
("fp8", "unsloth/Z-Image-Turbo-FP8"),
+ ("nvfp4", "unsloth/Z-Image-Turbo-NVFP4"),
),
# Both hosted checkpoints are baked from the distilled Turbo transformer, so the undistilled base has none and
# must quantize its own dense weights.
diff --git a/studio/backend/core/inference/diffusion_inference_info.py b/studio/backend/core/inference/diffusion_inference_info.py
index 56b92c5707a..ff78f344909 100644
--- a/studio/backend/core/inference/diffusion_inference_info.py
+++ b/studio/backend/core/inference/diffusion_inference_info.py
@@ -14,7 +14,8 @@ from __future__ import annotations
from typing import Any
-from .diffusion_auto_policy import _FAMILY_BF16_GB, _QUANT_STEADY_FACTOR
+from .diffusion_auto_policy import _FAMILY_BF16_GB, _QUANT_STEADY_FACTOR, policy_steady_factor
+from .diffusion_families import _FAMILIES
from .diffusion_nvfp4_flag import nvfp4_blocked
@@ -22,6 +23,11 @@ def _round1(value: float) -> float:
return round(value, 1)
+def _family_base_repos() -> dict[str, str]:
+ """Family name -> DEFAULT base repo; a variant load prices itself via ``estimate_dense_quant``."""
+ return {fam.name.strip().lower(): fam.base_repo for fam in _FAMILIES}
+
+
def family_inference_infos() -> list[dict[str, Any]]:
"""Per-family bf16 component sizes + estimated resident footprint per quant scheme.
@@ -30,12 +36,16 @@ def family_inference_infos() -> list[dict[str, Any]]:
transformer by its steady factor and adds the same companions).
"""
infos: list[dict[str, Any]] = []
+ bases = _family_base_repos()
for name, (transformer_gb, text_encoders_gb, vae_gb) in _FAMILY_BF16_GB.items():
companions_gb = text_encoders_gb + vae_gb
estimated = {"bf16": _round1(transformer_gb + companions_gb)}
+ policy_factor = policy_steady_factor(name, bases.get(name.strip().lower()))
for scheme, factor in _QUANT_STEADY_FACTOR.items():
if nvfp4_blocked(scheme):
continue
+ if scheme == "nvfp4" and policy_factor is not None:
+ factor = policy_factor
estimated[scheme] = _round1(transformer_gb * factor + companions_gb)
infos.append(
{
diff --git a/studio/backend/core/inference/diffusion_nvfp4_gate.py b/studio/backend/core/inference/diffusion_nvfp4_gate.py
new file mode 100644
index 00000000000..1497308bd23
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_nvfp4_gate.py
@@ -0,0 +1,177 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The checked-in record of which NVFP4 checkpoints passed the accuracy gate, per family, base and
+policy. Verdicts are re-derived, never trusted as stored. Torch-free: the smoke-probe child reads it.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any, Optional
+
+GATE_RECORD_VERSION = 1
+
+GATE_RECORD_PATH = Path(__file__).with_name("nvfp4_gate_record.json")
+
+RECORD_KEY_FIELDS = ("family", "base_repo", "policy_id", "policy_version", "checkpoint_sha256")
+RECORD_FIELDS = RECORD_KEY_FIELDS + (
+ "repo_id",
+ "filename",
+ "gptq",
+ "all_pass",
+ "num_pairs",
+ "num_passed",
+ "aggregates",
+ "gates",
+ "resolutions",
+ "seeds",
+ "cuda_graphs",
+ "backend",
+ "gpu",
+ "versions",
+ "gate_script_sha256",
+ "run_date",
+ "results_path",
+)
+
+_CACHE: dict[tuple, tuple] = {}
+
+
+def _canonical(value: Any) -> str:
+ try:
+ from .diffusion_families import canonical_base
+ return canonical_base(str(value or "").strip()).strip().lower()
+ except Exception: # noqa: BLE001 -- an unimportable registry just means "no canonicalisation"
+ return str(value or "").strip().lower()
+
+
+def load_gate_records(path: Any = None) -> tuple:
+ """Never raises: an unreadable file is no evidence."""
+ target = Path(path) if path is not None else GATE_RECORD_PATH
+ try:
+ stat = target.stat()
+ key = (str(target), stat.st_mtime_ns, stat.st_size)
+ except OSError:
+ return ()
+ cached = _CACHE.get(key)
+ if cached is not None:
+ return cached
+ try:
+ parsed = json.loads(target.read_text(encoding = "utf-8"))
+ records = parsed.get("records") if isinstance(parsed, dict) else None
+ entries = tuple(record for record in (records or []) if isinstance(record, dict))
+ except Exception: # noqa: BLE001 -- see the docstring: no evidence, not an error
+ entries = ()
+ _CACHE[key] = entries
+ return entries
+
+
+def nvfp4_gate_records(
+ family: Any,
+ base_repo: Any,
+ policy_id: Optional[str] = None,
+ *,
+ path: Any = None,
+) -> tuple:
+ """Without a base there are none: a sibling base's verdict must never be inherited."""
+ fam = str(family or "").strip().lower()
+ base = _canonical(base_repo)
+ if not fam or not base:
+ return ()
+ wanted = str(policy_id).strip() if policy_id is not None else None
+ matched = []
+ for record in load_gate_records(path):
+ if str(record.get("family", "")).strip().lower() != fam:
+ continue
+ if _canonical(record.get("base_repo")) != base:
+ continue
+ if wanted is not None and str(record.get("policy_id", "")).strip() != wanted:
+ continue
+ matched.append(dict(record))
+ return tuple(matched)
+
+
+def nvfp4_gate_record(
+ family: Any,
+ base_repo: Any,
+ policy_id: Optional[str] = None,
+ *,
+ path: Any = None,
+) -> Optional[dict]:
+ """The first record only; whether nvfp4 is allowed is ``_passing_record``'s question."""
+ matched = nvfp4_gate_records(family, base_repo, policy_id, path = path)
+ return matched[0] if matched else None
+
+
+def _passing_records(
+ family: Any,
+ base_repo: Any,
+ *,
+ path: Any = None,
+) -> tuple:
+ """Every PASS at the resolved policy: one checkpoint's failure must not mask a later pass."""
+ try:
+ from .diffusion_nvfp4_policy import resolve_policy
+ policy = resolve_policy(family, base_repo)
+ except Exception: # noqa: BLE001 -- an unresolvable policy is "not gated", never a load error
+ return ()
+ if policy is None:
+ return ()
+ passing = []
+ for record in nvfp4_gate_records(family, base_repo, policy.policy_id, path = path):
+ if record.get("all_pass") is not True:
+ continue
+ try:
+ recorded = (str(record.get("policy_id", "")).strip(), int(record.get("policy_version")))
+ except (TypeError, ValueError):
+ continue
+ if recorded == (str(policy.policy_id), int(policy.version)):
+ passing.append(record)
+ return tuple(passing)
+
+
+def _passing_record(
+ family: Any,
+ base_repo: Any,
+ *,
+ path: Any = None,
+) -> Optional[dict]:
+ passing = _passing_records(family, base_repo, path = path)
+ return passing[0] if passing else None
+
+
+def nvfp4_gate_passed(
+ family: Any,
+ base_repo: Any,
+ *,
+ path: Any = None,
+) -> bool:
+ return _passing_record(family, base_repo, path = path) is not None
+
+
+def nvfp4_gate_backends(
+ family: Any,
+ base_repo: Any,
+ *,
+ path: Any = None,
+) -> tuple:
+ """Every backend a passing record was measured on: one policy can hold artifacts on either."""
+ backends: list[str] = []
+ for record in _passing_records(family, base_repo, path = path):
+ backend = str(record.get("backend") or "").strip().lower()
+ if backend and backend not in backends:
+ backends.append(backend)
+ return tuple(backends)
+
+
+def nvfp4_gate_backend(
+ family: Any,
+ base_repo: Any,
+ *,
+ path: Any = None,
+) -> Optional[str]:
+ """The first passing record's backend. Coverage wants ``nvfp4_gate_backends``."""
+ backends = nvfp4_gate_backends(family, base_repo, path = path)
+ return backends[0] if backends else None
diff --git a/studio/backend/core/inference/diffusion_nvfp4_linear.py b/studio/backend/core/inference/diffusion_nvfp4_linear.py
new file mode 100644
index 00000000000..6d604e3f38f
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_nvfp4_linear.py
@@ -0,0 +1,349 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The FlashInfer NVFP4 Linear, and the conversion that puts a hosted checkpoint onto it.
+
+Nothing requantizes: torchao's payload IS FlashInfer's, with ``per_tensor_scale == 1 / w_gsf``.
+The activation scale must be BAKED: calibrating it live is not capture-safe and latched flux to
+black frames, so a layer with no baked scale is NOT converted.
+"""
+
+from __future__ import annotations
+
+from functools import lru_cache
+from typing import Any, Iterable, Optional
+
+from .diffusion_nvfp4_ops import (
+ BACKEND_FLASHINFER,
+ DEFAULT_MM_BACKEND,
+ _device_guard,
+ dequantize_nvfp4_weight,
+ register_ops,
+ sf_matrix_shape,
+ swizzle_sf,
+)
+from .diffusion_nvfp4_protect import protect_controller
+
+ACT_SCALES_KEY = "act_global_scales"
+POLICY_KEY = "nvfp4_policy"
+POLICY_BAKED_KEY = "activation_scales_baked"
+
+_TUNED_SHAPES: set = set()
+
+
+def reset_tuned_shapes() -> None:
+ _TUNED_SHAPES.clear()
+
+
+@lru_cache(maxsize = 1)
+def nvfp4_linear_class():
+ import torch
+ from torch import nn
+ from torch.nn import functional as F
+
+ class NVFP4FlashInferLinear(nn.Module):
+ """Runs inside a captured CUDA graph: no host synchronize, no device-value branch."""
+
+ def __init__(
+ self,
+ in_features: int,
+ out_features: int,
+ *,
+ wq,
+ w_sf,
+ alpha,
+ a_gsf,
+ bias = None,
+ w_scale = None,
+ backend: str = DEFAULT_MM_BACKEND,
+ activation_scales_baked: bool = False,
+ ):
+ super().__init__()
+ self.in_features = int(in_features)
+ self.out_features = int(out_features)
+ self.backend = str(backend)
+ self.activation_scales_baked = bool(activation_scales_baked)
+ self.register_buffer("wq", wq)
+ self.register_buffer("w_sf", w_sf)
+ self.register_buffer("alpha", alpha)
+ self.register_buffer("a_gsf", a_gsf)
+ # Stored, not ``alpha * a_gsf``, which is off by a rounding: W4A16 must match bit for bit.
+ self.register_buffer(
+ "w_scale",
+ (alpha * a_gsf) if w_scale is None else w_scale,
+ )
+ self.register_buffer("bias", bias)
+ self._tuned = False
+ self.protect = protect_controller()
+ self.protect.register_layer(self)
+
+ def forward(self, x):
+ shape = x.shape
+ flat = x.reshape(-1, self.in_features)
+ # ``fp4_quantize`` raises on fp32, which Wan2.2's time embedder feeds in.
+ out_dtype = flat.dtype
+ if out_dtype not in (torch.bfloat16, torch.float16):
+ flat = flat.to(torch.bfloat16)
+ if flat.shape[0] == 0:
+ return flat.new_zeros((0, self.out_features), dtype = out_dtype).reshape(
+ *shape[:-1], self.out_features
+ )
+ if self.protect.armed and self.protect.protected:
+ weight = dequantize_nvfp4_weight(
+ self.wq, self.w_sf, self.w_scale, dtype = torch.bfloat16
+ )
+ out = F.linear(flat, weight)
+ else:
+ with _device_guard(flat):
+ xq, x_sf = torch.ops.unsloth_nvfp4.quantize(flat, self.a_gsf)
+ out = torch.ops.unsloth_nvfp4.mm(
+ xq, self.wq, x_sf, self.w_sf, self.alpha, self.out_features, self.backend
+ )
+ out = out.to(out_dtype)
+ if self.bias is not None:
+ out.add_(self.bias)
+ return out.reshape(*shape[:-1], self.out_features)
+
+ def extra_repr(self) -> str: # pragma: no cover - debug aid
+ return (
+ f"in_features={self.in_features}, out_features={self.out_features}, "
+ f"bias={self.bias is not None}, backend={self.backend}, nvfp4=flashinfer"
+ + (f", protect={self.protect.spec}" if self.protect.armed else "")
+ )
+
+ return NVFP4FlashInferLinear
+
+
+def is_nvfp4_flashinfer_linear(module: Any) -> bool:
+ return type(module).__name__ == "NVFP4FlashInferLinear" and hasattr(module, "a_gsf")
+
+
+def is_nvfp4_tensor(t: Any) -> bool:
+ return type(t).__name__ == "NVFP4Tensor" and hasattr(t, "qdata") and hasattr(t, "scale")
+
+
+def _as_scale_tensor(value: Any, *, device, dtype):
+ import torch
+ if isinstance(value, torch.Tensor):
+ return value.detach().to(device = device, dtype = dtype).reshape(1).clone()
+ return torch.tensor([float(value)], device = device, dtype = dtype)
+
+
+def nvfp4_linear_from_torchao(
+ linear: Any,
+ a_gsf: Any,
+ *,
+ backend: str = DEFAULT_MM_BACKEND,
+):
+ import torch
+
+ register_ops()
+ weight = linear.weight
+ if not is_nvfp4_tensor(weight):
+ raise TypeError(f"expected a torchao NVFP4Tensor weight, got {type(weight).__name__}")
+ per_tensor_scale = getattr(weight, "per_tensor_scale", None)
+ if per_tensor_scale is None:
+ raise ValueError(
+ "this NVFP4 weight carries no per_tensor_scale, so the GEMM alpha is undefined; the "
+ "checkpoint was built with single-level scaling and cannot run on the flashinfer path"
+ )
+
+ qdata = weight.qdata
+ wq = qdata if qdata.dtype == torch.uint8 else qdata.view(torch.uint8)
+ wq = wq.contiguous()
+ out_features, half_k = wq.shape[-2], wq.shape[-1]
+ in_features = half_k * 2
+ cols = in_features // 16
+
+ scale = weight.scale
+ if getattr(weight, "is_swizzled_scales", False):
+ flat = scale.reshape(-1)
+ w_sf = flat if flat.dtype == torch.uint8 else flat.view(torch.uint8)
+ else:
+ w_sf = swizzle_sf(scale, out_features, in_features)
+ w_sf = w_sf.reshape(sf_matrix_shape(out_features, cols)).contiguous()
+
+ device = wq.device
+ alpha = _as_scale_tensor(
+ per_tensor_scale, device = device, dtype = torch.float32
+ ) / _as_scale_tensor(a_gsf, device = device, dtype = torch.float32)
+ bias = None if linear.bias is None else linear.bias.detach().clone()
+ return nvfp4_linear_class()(
+ in_features,
+ out_features,
+ wq = wq,
+ w_sf = w_sf,
+ alpha = alpha,
+ a_gsf = _as_scale_tensor(a_gsf, device = device, dtype = torch.float32),
+ bias = bias,
+ w_scale = _as_scale_tensor(per_tensor_scale, device = device, dtype = torch.float32),
+ backend = backend,
+ activation_scales_baked = True,
+ )
+
+
+def _baked_activation_scales(metadata: Any) -> Optional[dict]:
+ if not isinstance(metadata, dict):
+ return None
+ scales = metadata.get(ACT_SCALES_KEY)
+ if not isinstance(scales, dict) or not scales:
+ return None
+ return scales
+
+
+def _declares_baked_scales(metadata: Any) -> bool:
+ if not isinstance(metadata, dict):
+ return False
+ policy = metadata.get(POLICY_KEY)
+ if isinstance(policy, dict) and policy.get(POLICY_BAKED_KEY):
+ return True
+ return bool(metadata.get(POLICY_BAKED_KEY))
+
+
+def convert_nvfp4_backend(
+ transformer: Any,
+ metadata: Any,
+ backend: str,
+ *,
+ logger: Any = None,
+) -> int:
+ """All or nothing: one missing baked scale leaves the whole tree on torchao."""
+ if backend != BACKEND_FLASHINFER:
+ return 0
+ scales = _baked_activation_scales(metadata)
+ candidates = [
+ (name, mod)
+ for name, mod in _iter_linears(transformer)
+ if is_nvfp4_tensor(getattr(mod, "weight", None))
+ ]
+ if not candidates:
+ return 0
+ if scales is None:
+ _log(
+ logger,
+ "info",
+ "[nvfp4] flashinfer backend requested but this checkpoint bakes no activation "
+ f"scales ({'flag set, scales missing' if _declares_baked_scales(metadata) else 'no ' + ACT_SCALES_KEY} "
+ f"for {len(candidates)} quantized linears); staying on torchao",
+ )
+ return 0
+ missing = [name for name, _ in candidates if name not in scales]
+ if missing:
+ _log(
+ logger,
+ "info",
+ f"[nvfp4] flashinfer backend refused: {len(missing)} of {len(candidates)} quantized "
+ f"linears have no baked activation scale (first: {missing[0]}); staying on torchao",
+ )
+ return 0
+
+ register_ops()
+ replacements = []
+ for name, module in candidates:
+ try:
+ replacements.append((name, nvfp4_linear_from_torchao(module, scales[name])))
+ except Exception as exc: # noqa: BLE001 - one unconvertible layer must not lose the model
+ _log(
+ logger,
+ "warning",
+ f"[nvfp4] {name} could not move to the flashinfer path ({type(exc).__name__}: "
+ f"{exc}); staying on torchao",
+ )
+ return 0
+ for name, replacement in replacements:
+ _replace_child(transformer, name, replacement)
+ from .diffusion_nvfp4_protect import attach_own_controller
+
+ attach_own_controller(transformer)
+ converted = len(replacements)
+ _log(logger, "info", f"[nvfp4] flashinfer backend: {converted} linears converted")
+ return converted
+
+
+def nvfp4_prewarm(
+ transformer: Any,
+ shapes: Iterable[int],
+ *,
+ logger: Any = None,
+) -> int:
+ """Must run before any capture, which would bake in ``mm_fp4``'s default tactic."""
+ from .diffusion_nvfp4_flag import nvfp4_diffusion_enabled
+
+ if not nvfp4_diffusion_enabled():
+ return 0
+ import torch
+
+ try:
+ import flashinfer
+ except Exception as exc: # noqa: BLE001 - nothing to tune without the backend
+ _log(logger, "debug", f"[nvfp4] prewarm skipped: {type(exc).__name__}: {exc}")
+ return 0
+
+ from .diffusion_nvfp4_protect import suspend_protect
+
+ register_ops()
+ modules = [mod for _, mod in _iter_linears(transformer) if is_nvfp4_flashinfer_linear(mod)]
+ counter = [0]
+ with suspend_protect(modules):
+ _prewarm_shapes(modules, shapes, logger = logger, tuned_box = counter)
+ tuned = counter[0]
+ if tuned:
+ _log(logger, "info", f"[nvfp4] prewarm tuned {tuned} GEMM shapes")
+ return tuned
+
+
+def _prewarm_shapes(modules, shapes, *, logger, tuned_box) -> None:
+ import torch
+
+ import flashinfer
+ for module in modules:
+ for m in shapes:
+ m = int(m)
+ if m <= 0:
+ continue
+ key = (m, module.in_features, module.out_features)
+ if key in _TUNED_SHAPES:
+ continue
+ device = module.wq.device
+ try:
+ with torch.inference_mode(), _device_guard(module.wq):
+ x = torch.zeros(m, module.in_features, device = device, dtype = torch.bfloat16)
+ with flashinfer.autotune(True):
+ module(x)
+ torch.cuda.synchronize(device)
+ except Exception as exc: # noqa: BLE001 - a shape that will not tune still runs
+ _log(logger, "debug", f"[nvfp4] prewarm {key} failed ({type(exc).__name__}: {exc})")
+ continue
+ _TUNED_SHAPES.add(key)
+ tuned_box[0] += 1
+ module._tuned = True
+
+
+def _iter_linears(transformer: Any):
+ """Keyed on feature counts: a converted layer has no ``weight``."""
+ for name, module in transformer.named_modules():
+ if not name:
+ continue
+ if hasattr(module, "in_features") and hasattr(module, "out_features"):
+ yield name, module
+
+
+def _replace_child(root: Any, fqn: str, replacement: Any) -> None:
+ parent = root
+ parts = fqn.split(".")
+ for part in parts[:-1]:
+ parent = getattr(parent, part) if not part.isdigit() else parent[int(part)]
+ last = parts[-1]
+ if last.isdigit() and hasattr(parent, "__setitem__"):
+ parent[int(last)] = replacement
+ else:
+ setattr(parent, last, replacement)
+
+
+def _log(logger: Any, level: str, message: str) -> None:
+ if logger is None:
+ return
+ try:
+ getattr(logger, level)(message)
+ except Exception: # noqa: BLE001 - logging is best effort
+ pass
diff --git a/studio/backend/core/inference/diffusion_nvfp4_ops.py b/studio/backend/core/inference/diffusion_nvfp4_ops.py
new file mode 100644
index 00000000000..9d58f26561c
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_nvfp4_ops.py
@@ -0,0 +1,426 @@
+# 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 NVFP4 kernels as ``torch.library`` custom ops (so ``fullgraph = True`` works), plus
+the backend decision. Fake impls must match FlashInfer's allocation EXACTLY: a wrong meta shape is
+a silently mis-sized buffer. torch and flashinfer import lazily for torch-free hosts.
+"""
+
+from __future__ import annotations
+
+import os
+import threading
+from typing import Any, Optional
+
+NVFP4_BACKEND_ENV = "UNSLOTH_NVFP4_BACKEND"
+NVFP4_BACKENDS = ("auto", "torchao", "flashinfer")
+BACKEND_TORCHAO = "torchao"
+BACKEND_FLASHINFER = "flashinfer"
+
+# Restores the full M x N memset in the GEMM op. Strictly slower and no safer; see ``_mm_impl``.
+NVFP4_ZERO_BUFFER_ENV = "UNSLOTH_NVFP4_ZERO_BUFFER"
+
+# Necessary condition only: sm_120 is listed but routinely fails the preflight on CUDA 12.8.
+NVFP4_FLASHINFER_CAPS = frozenset({(10, 0), (10, 3), (12, 0)})
+
+DEFAULT_MM_BACKEND = "cutlass"
+
+FP4_MAX = 6.0
+FP8_MAX = 448.0
+
+_TRUE_TOKENS = ("1", "true", "yes", "on")
+
+_REGISTER_LOCK = threading.Lock()
+_REGISTERED = False
+_PREFLIGHT_LOCK = threading.Lock()
+_PREFLIGHT: dict[int, dict] = {}
+_WARNED: set = set()
+
+
+def _swizzled_sf_numel(
+ rows: int,
+ cols: int,
+ row_size: int = 128,
+) -> int:
+ """Copied, not imported: a fake impl must not touch the FlashInfer JIT machinery."""
+ return ((rows + row_size - 1) // row_size * row_size) * ((cols + 3) // 4 * 4)
+
+
+def _device_guard(t: Any):
+ """EVERY flashinfer call needs this: it has no device guard, and a foreign device bricks the card."""
+ import torch
+ return torch.cuda.device(t.device)
+
+
+def _zero_buffer_enabled() -> bool:
+ return os.environ.get(NVFP4_ZERO_BUFFER_ENV, "").strip().lower() in _TRUE_TOKENS
+
+
+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
+ with _device_guard(x):
+ 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."""
+ import flashinfer
+ import torch
+
+ 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)
+ if _claim_first_call_tune(m, xq.shape[1] * 2, n):
+ try:
+ with flashinfer.autotune(True):
+ return flashinfer.mm_fp4(
+ xq, wq.T, x_sf, w_sf.T, alpha, torch.bfloat16, out = out, backend = backend
+ )
+ except Exception: # noqa: BLE001 - claimed, so it is not retried; run it untuned
+ pass
+ 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
+
+ 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():
+ return False
+ _TUNED_SHAPES.add(key)
+ return True
+
+
+def _quantize_fake(x: Any, global_sf: Any):
+ import torch
+
+ m, k = x.shape
+ cols = k // 16
+ # The leading dim is NOT m whenever the padding is non-trivial.
+ total = _swizzled_sf_numel(m, cols, 128)
+ return (
+ x.new_empty((m, k // 2), dtype = torch.uint8),
+ x.new_empty((total // cols, cols), dtype = torch.uint8),
+ )
+
+
+def _mm_fake(xq: Any, wq: Any, x_sf: Any, w_sf: Any, alpha: Any, n: int, backend: str):
+ import torch
+ return xq.new_empty((xq.shape[0], n), dtype = torch.bfloat16)
+
+
+def register_ops() -> None:
+ global _REGISTERED
+ if _REGISTERED:
+ return
+ with _REGISTER_LOCK:
+ if _REGISTERED:
+ return
+ import torch
+
+ if "unsloth_nvfp4::quantize" not in torch.library._defs:
+ quantize = torch.library.custom_op(
+ "unsloth_nvfp4::quantize",
+ _quantize_impl,
+ mutates_args = (),
+ schema = "(Tensor x, Tensor global_sf) -> (Tensor, Tensor)",
+ )
+ quantize.register_fake(_quantize_fake)
+ if "unsloth_nvfp4::mm" not in torch.library._defs:
+ mm = torch.library.custom_op(
+ "unsloth_nvfp4::mm",
+ _mm_impl,
+ mutates_args = (),
+ schema = (
+ "(Tensor xq, Tensor wq, Tensor x_sf, Tensor w_sf, Tensor alpha, "
+ "int n, str backend) -> Tensor"
+ ),
+ )
+ mm.register_fake(_mm_fake)
+ _REGISTERED = True
+
+
+def unswizzle_sf(
+ sf: Any,
+ m: int,
+ k: int,
+ vec: int = 16,
+):
+ """cutlass 128x4 swizzled block scales -> the plain ``[m, k // vec]`` e4m3 matrix."""
+ import torch
+
+ kb = k // vec
+ m_pad = (m + 127) // 128 * 128
+ k_pad = (kb + 3) // 4 * 4
+ flat = sf.reshape(-1).view(torch.float8_e4m3fn)
+ v = (
+ flat.reshape(m_pad // 128, k_pad // 4, 32, 4, 4)
+ .permute(0, 3, 2, 1, 4)
+ .reshape(m_pad, k_pad)
+ )
+ return v[:m, :kb].contiguous()
+
+
+def swizzle_sf(sf_lin: Any, m: int, k: int):
+ """Plain ``[m, k // 16]`` e4m3 block scales -> the cutlass 128x4 swizzled flat buffer."""
+ import torch
+
+ kb = k // 16
+ m_pad = (m + 127) // 128 * 128
+ k_pad = (kb + 3) // 4 * 4
+ full = torch.zeros(m_pad, k_pad, device = sf_lin.device, dtype = torch.uint8)
+ full[:m, :kb] = sf_lin.reshape(m, kb).view(torch.uint8)
+ v = full.reshape(m_pad, k_pad // 4, 4).reshape(m_pad // 128, 4, 32, k_pad // 4, 4)
+ return v.permute(0, 3, 2, 1, 4).reshape(-1).contiguous()
+
+
+_E2M1_MAGNITUDES = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0)
+_E2M1_LUT = _E2M1_MAGNITUDES + tuple(-v for v in _E2M1_MAGNITUDES)
+
+_LUT_CACHE: dict = {}
+
+
+def e2m1_lut(device: Any):
+ """Memoised so it is never ALLOCATED under a graph capture (valid only while recording)."""
+ import torch
+
+ key = (str(device.type), device.index)
+ table = _LUT_CACHE.get(key)
+ if table is None:
+ table = torch.tensor(_E2M1_LUT, device = device, dtype = torch.float32)
+ _LUT_CACHE[key] = table
+ return table
+
+
+def reset_lut_cache() -> None:
+ _LUT_CACHE.clear()
+
+
+def dequantize_nvfp4_weight(
+ wq: Any,
+ w_sf: Any,
+ per_tensor_scale: Any,
+ *,
+ dtype: Any = None,
+):
+ """Dense ``[N, K]`` weight, TRANSIENT (never cache it). Arithmetic in torchao's order, so it
+ matches the unprotected step bit for bit."""
+ import torch
+
+ if dtype is None:
+ dtype = torch.bfloat16
+ q = wq if wq.dtype == torch.uint8 else wq.view(torch.uint8)
+ rows, half_k = int(q.shape[-2]), int(q.shape[-1])
+ cols = half_k * 2
+ blocks = cols // 16
+ lut = e2m1_lut(q.device)
+ codes = q.to(torch.int32)
+ values = torch.stack((lut[codes & 0x0F], lut[codes >> 4]), dim = -1).reshape(rows, blocks, 16)
+ block_scale = unswizzle_sf(w_sf, rows, cols).to(torch.float32)
+ if not isinstance(per_tensor_scale, torch.Tensor):
+ per_tensor_scale = torch.tensor(
+ [float(per_tensor_scale)], device = q.device, dtype = torch.float32
+ )
+ step = (block_scale * per_tensor_scale.to(torch.float32).reshape(1)).reshape(rows, blocks, 1)
+ return (values * step).reshape(rows, cols).to(dtype)
+
+
+def sf_matrix_shape(rows: int, cols: int) -> tuple[int, int]:
+ padded_cols = (cols + 3) // 4 * 4
+ return (_swizzled_sf_numel(rows, cols, 128) // padded_cols, padded_cols)
+
+
+def nvfp4_preflight(device: Any = None, *, refresh: bool = False) -> dict:
+ """A tiny guarded quantise + GEMM, memoised per device: only a JIT build proves FlashInfer runs."""
+ from .diffusion_nvfp4_flag import nvfp4_diffusion_enabled
+
+ if not nvfp4_diffusion_enabled():
+ # Not memoised: turning the switch on must not inherit a verdict nobody measured.
+ return {
+ "ok": False,
+ "reason": "NVFP4 is disabled in this build",
+ "capability": None,
+ "name": "",
+ }
+ import torch
+
+ if not getattr(torch, "cuda", None) or not torch.cuda.is_available():
+ return {"ok": False, "reason": "cuda unavailable", "capability": None, "name": ""}
+ if device is None:
+ dev = torch.device("cuda", torch.cuda.current_device())
+ elif isinstance(device, int):
+ # torch.device(int) asks the accelerator API, which raises on a host without one.
+ dev = torch.device("cuda", device)
+ else:
+ dev = torch.device(device)
+ if dev.type != "cuda":
+ return {"ok": False, "reason": f"device {dev} is not cuda", "capability": None, "name": ""}
+ index = dev.index if dev.index is not None else torch.cuda.current_device()
+ dev = torch.device("cuda", index)
+ if not refresh:
+ cached = _PREFLIGHT.get(index)
+ if cached is not None:
+ return dict(cached)
+
+ try:
+ capability = tuple(torch.cuda.get_device_capability(dev))
+ name = str(torch.cuda.get_device_name(dev))
+ except Exception as exc: # noqa: BLE001 - a device that cannot be described cannot be used
+ capability, name = None, ""
+ rec = {
+ "ok": False,
+ "reason": f"{type(exc).__name__}: {str(exc)[:200]}",
+ "capability": capability,
+ "name": name,
+ }
+ with _PREFLIGHT_LOCK:
+ _PREFLIGHT[index] = rec
+ return dict(rec)
+
+ rec = {"ok": False, "reason": "", "capability": capability, "name": name}
+ try:
+ finite = _preflight_probe(dev)
+ rec["ok"] = finite
+ rec["reason"] = "ok" if finite else "mm_fp4 produced a non-finite result"
+ 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):
+ return dict(rec)
+
+ with _PREFLIGHT_LOCK:
+ _PREFLIGHT[index] = rec
+ return dict(rec)
+
+
+def _preflight_probe(dev: Any) -> bool:
+ import flashinfer
+ import torch
+ with torch.cuda.device(dev):
+ x = torch.randn(128, 256, device = dev, dtype = torch.bfloat16) * 0.05
+ w = torch.randn(128, 256, device = dev, dtype = torch.bfloat16) * 0.02
+ a_gsf, w_gsf = global_scale(x), 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)
+ out = torch.zeros(128, 128, device = dev, dtype = torch.bfloat16)
+ y = flashinfer.mm_fp4(
+ xq,
+ wq.T,
+ x_sf,
+ w_sf.T,
+ (1.0 / (a_gsf * w_gsf)).float(),
+ torch.bfloat16,
+ out = out,
+ backend = DEFAULT_MM_BACKEND,
+ )
+ torch.cuda.synchronize(dev)
+ return bool(torch.isfinite(y).all().item())
+
+
+def _transient_preflight_failure(exc: BaseException) -> bool:
+ """Allocation failures only; an import or JIT failure stays cached."""
+ if isinstance(exc, MemoryError):
+ return True
+ try:
+ import torch
+ if isinstance(exc, torch.cuda.OutOfMemoryError):
+ return True
+ except Exception: # noqa: BLE001 - no torch to ask means fall through to the text
+ pass
+ text = str(exc).lower()
+ return "out of memory" in text or "cudaerrormemoryallocation" in text
+
+
+def reset_preflight_cache() -> None:
+ with _PREFLIGHT_LOCK:
+ _PREFLIGHT.clear()
+ _WARNED.clear()
+
+
+def nvfp4_backend_env() -> str:
+ raw = os.environ.get(NVFP4_BACKEND_ENV, "").strip().lower()
+ return raw if raw in NVFP4_BACKENDS else "auto"
+
+
+def _flashinfer_available() -> tuple[bool, str]:
+ try:
+ import flashinfer
+ return True, str(getattr(flashinfer, "__version__", "unknown"))
+ except Exception as exc: # noqa: BLE001 - any import failure means torchao
+ return False, f"{type(exc).__name__}: {str(exc)[:120]}"
+
+
+def _device_capability(device: Any = None) -> Optional[tuple]:
+ try:
+ import torch
+ if not getattr(torch, "cuda", None) or not torch.cuda.is_available():
+ return None
+ return tuple(torch.cuda.get_device_capability(device))
+ except Exception: # noqa: BLE001 - an unreadable capability is not a flashinfer device
+ return None
+
+
+def _resolve_backend(device: Any = None) -> tuple[str, str]:
+ from .diffusion_nvfp4_flag import NVFP4_DIFFUSION_ENV, nvfp4_diffusion_enabled
+
+ if not nvfp4_diffusion_enabled():
+ return BACKEND_TORCHAO, (
+ f"NVFP4 is disabled in this build (set {NVFP4_DIFFUSION_ENV}=1 to enable it)"
+ )
+ requested = nvfp4_backend_env()
+ if requested == BACKEND_TORCHAO:
+ return BACKEND_TORCHAO, f"{NVFP4_BACKEND_ENV}=torchao"
+
+ available, detail = _flashinfer_available()
+ if not available:
+ return BACKEND_TORCHAO, f"flashinfer unavailable ({detail})"
+ capability = _device_capability(device)
+ if capability is None:
+ return BACKEND_TORCHAO, "no CUDA device capability to check"
+ if tuple(capability) not in NVFP4_FLASHINFER_CAPS:
+ return BACKEND_TORCHAO, (
+ "sm_%d%d is not in the flashinfer NVFP4 set %s"
+ % (
+ capability[0],
+ capability[1],
+ ", ".join(sorted("sm_%d%d" % c for c in NVFP4_FLASHINFER_CAPS)),
+ )
+ )
+ probe = nvfp4_preflight(device)
+ if not probe.get("ok"):
+ return BACKEND_TORCHAO, f"preflight failed: {probe.get('reason', 'unknown')}"
+ return BACKEND_FLASHINFER, f"flashinfer {detail} preflight ok on sm_%d%d" % tuple(capability)
+
+
+def nvfp4_backend_reason(device: Any = None) -> str:
+ return _resolve_backend(device)[1]
+
+
+def select_nvfp4_backend(device: Any = None) -> str:
+ """An explicit ``flashinfer`` that fails import, capability or preflight falls back to torchao."""
+ backend, reason = _resolve_backend(device)
+ if backend != BACKEND_FLASHINFER and nvfp4_backend_env() == BACKEND_FLASHINFER:
+ key = (str(device), reason)
+ if key not in _WARNED:
+ _WARNED.add(key)
+ import warnings
+ warnings.warn(
+ f"{NVFP4_BACKEND_ENV}=flashinfer was requested but {reason}; using torchao",
+ RuntimeWarning,
+ stacklevel = 2,
+ )
+ return backend
diff --git a/studio/backend/core/inference/diffusion_nvfp4_policy.py b/studio/backend/core/inference/diffusion_nvfp4_policy.py
new file mode 100644
index 00000000000..a661001d70f
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_nvfp4_policy.py
@@ -0,0 +1,437 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Per-layer NVFP4 policies for the image DiTs: a named set of layers at 4 bits over an fp8 model.
+
+FAILS CLOSED: layers match by exact dotted SUFFIX and every rule asserts a count, so a diffusers
+rename raises at build time instead of shipping precisions nobody measured.
+"""
+
+from __future__ import annotations
+
+from collections import Counter
+from dataclasses import dataclass, field
+from typing import Any, Mapping, Optional
+
+PRECISION_NVFP4 = "nvfp4"
+PRECISION_FP8 = "fp8"
+PRECISION_BF16 = "bf16"
+
+NVFP4_POLICY_KEY = "nvfp4_policy"
+NVFP4_POLICY_KIND = "unsloth_nvfp4_layer_policy_v1"
+
+
+class PolicyMismatch(ValueError):
+ """The model is not the one this policy was written for. Raised, never warned."""
+
+
+@dataclass(frozen = True)
+class Rule:
+ """``expect`` is asserted at assignment time; ``prefix`` narrows the rule to one subtree."""
+
+ suffix: str
+ precision: str
+ expect: int
+ prefix: str = ""
+
+ def matches(self, fqn: str) -> bool:
+ """Exact dotted suffix: ``norm.linear`` selects neither ``norm1.linear`` nor ``norm_out``."""
+ if self.prefix and not fqn.startswith(self.prefix):
+ return False
+ return fqn == self.suffix or fqn.endswith("." + self.suffix)
+
+
+@dataclass(frozen = True)
+class Admit:
+ """A linear the shared filter rejects that this policy quantises anyway, at an exact ``shape``.
+ Dropping the floor instead would admit ``t_embedder.mlp.*``, which must stay bf16
+ (``TimestepEmbedder.forward`` reads ``mlp[0].weight.dtype``)."""
+
+ suffix: str
+ shape: tuple
+ expect: int
+
+ def matches(self, fqn: str) -> bool:
+ return fqn == self.suffix or fqn.endswith("." + self.suffix)
+
+
+@dataclass(frozen = True)
+class NVFP4Policy:
+ """Keyed on lowercased ``base_repos``: a sibling checkpoint is different, ungated weights."""
+
+ policy_id: str
+ version: int
+ family: str
+ base_repos: tuple
+ default: str = PRECISION_FP8
+ rules: tuple = ()
+ admit: tuple = ()
+ expected_counts: Mapping = field(default_factory = dict)
+
+
+QWEN_P02 = NVFP4Policy(
+ policy_id = "qwen_p02_v1",
+ version = 1,
+ family = "qwen-image",
+ base_repos = ("qwen/qwen-image",),
+ rules = (
+ Rule(suffix = "img_mod.1", precision = PRECISION_NVFP4, expect = 60),
+ Rule(suffix = "txt_mod.1", precision = PRECISION_NVFP4, expect = 60),
+ ),
+ expected_counts = {PRECISION_NVFP4: 120, PRECISION_FP8: 723, PRECISION_BF16: 3},
+)
+
+
+def _per_block(suffix: str, stem: str, blocks: tuple) -> tuple:
+ """One exact rule per listed block: the storage/quality solve ranks layers per block, not per class."""
+ return tuple(
+ Rule(suffix = suffix, precision = PRECISION_NVFP4, expect = 1, prefix = f"{stem}.{block}.")
+ for block in blocks
+ )
+
+
+# Paired LPIPS(vgg) gap to fp8 < 0.05 at the upper 95% bound; artifacts at replaced policies are refused.
+ZIMG_RG76 = NVFP4Policy(
+ policy_id = "zimg_rg76_v1",
+ version = 1,
+ family = "z-image",
+ base_repos = ("tongyi-mai/z-image-turbo",),
+ rules = (
+ Rule(suffix = "attention.to_q", precision = PRECISION_NVFP4, expect = 34),
+ Rule(suffix = "attention.to_k", precision = PRECISION_NVFP4, expect = 34),
+ *_per_block("feed_forward.w1", "layers", (0, 1, 2, 3, 4, 5)),
+ Rule(
+ suffix = "feed_forward.w1", precision = PRECISION_NVFP4, expect = 2, prefix = "noise_refiner."
+ ),
+ ),
+ admit = (Admit(suffix = "adaLN_modulation.0", shape = (256, 15360), expect = 32),),
+ expected_counts = {PRECISION_NVFP4: 76, PRECISION_FP8: 195, PRECISION_BF16: 5},
+)
+
+FLUX_R420 = NVFP4Policy(
+ policy_id = "flux_r420_v1",
+ version = 1,
+ family = "flux.1",
+ # schnell only: dev and Krea-dev are separate weights and need their own gate runs.
+ base_repos = ("black-forest-labs/flux.1-schnell",),
+ rules = (
+ Rule(suffix = "norm_out.linear", precision = PRECISION_NVFP4, expect = 1),
+ *_per_block("attn.to_k", "single_transformer_blocks", tuple(range(15, 38))),
+ *_per_block("attn.to_q", "single_transformer_blocks", tuple(range(15, 38))),
+ *_per_block(
+ "attn.to_v", "single_transformer_blocks", (19, 21, 24, 26) + tuple(range(28, 38))
+ ),
+ *_per_block("norm.linear", "single_transformer_blocks", tuple(range(11, 38))),
+ *_per_block("proj_mlp", "single_transformer_blocks", tuple(range(16, 38))),
+ *_per_block("proj_out", "single_transformer_blocks", tuple(range(18, 38))),
+ *_per_block("attn.add_k_proj", "transformer_blocks", (3, 4, 6, 15)),
+ *_per_block("attn.add_q_proj", "transformer_blocks", (0, 4, 7, 9)),
+ *_per_block("attn.to_add_out", "transformer_blocks", (2,)),
+ *_per_block("attn.to_k", "transformer_blocks", (0, 4, 9)),
+ *_per_block("attn.to_q", "transformer_blocks", (0, 1, 5, 6)),
+ *_per_block("attn.to_v", "transformer_blocks", (6,)),
+ *_per_block("ff.net.0.proj", "transformer_blocks", (0, 1, 3, 4, 5)),
+ *_per_block("ff.net.2", "transformer_blocks", (0,) + tuple(range(2, 8))),
+ *_per_block("ff_context.net.0.proj", "transformer_blocks", (12, 13, 14)),
+ *_per_block(
+ "ff_context.net.2",
+ "transformer_blocks",
+ (0, 1, 2, 5, 6, 7, 10, 11, 12, 13, 14, 16, 18),
+ ),
+ *_per_block("norm1.linear", "transformer_blocks", (5,)),
+ *_per_block(
+ "norm1_context.linear",
+ "transformer_blocks",
+ (3, 4, 7, 8, 9, 12, 13, 14, 15, 16, 18),
+ ),
+ ),
+ expected_counts = {PRECISION_NVFP4: 187, PRECISION_FP8: 312, PRECISION_BF16: 3},
+)
+
+QWEN21_R020 = NVFP4Policy(
+ policy_id = "qwen21_r020_v1",
+ version = 1,
+ family = "qwen-image-2.1",
+ base_repos = ("qwen/qwen-image-2.1",),
+ rules = (
+ Rule(suffix = "norm_out.linear", precision = PRECISION_NVFP4, expect = 1),
+ *_per_block("attn.to_k", "transformer_blocks", (5, 7, 13) + tuple(range(15, 28))),
+ *_per_block("attn.to_q", "transformer_blocks", (1, 4, 18) + tuple(range(20, 28)) + (29,)),
+ *_per_block(
+ "img_mlp.gate_layer", "transformer_blocks", (8, 13, 17, 18, 19) + tuple(range(21, 29))
+ ),
+ *_per_block("img_mlp.proj", "transformer_blocks", (0, 1, 12, 13, 17, 18)),
+ ),
+ expected_counts = {PRECISION_NVFP4: 48, PRECISION_FP8: 181, PRECISION_BF16: 3},
+)
+
+# 2512 is its own weights under the qwen-image family: qwen_p02_v1 stays the Qwen/Qwen-Image policy.
+QWEN2512_M120_ATTN8 = NVFP4Policy(
+ policy_id = "qwen2512_m120_attn8_v1",
+ version = 1,
+ family = "qwen-image",
+ base_repos = ("qwen/qwen-image-2512",),
+ rules = tuple(
+ Rule(suffix = suffix, precision = PRECISION_NVFP4, expect = 60)
+ for suffix in (
+ "attn.to_k",
+ "img_mod.1",
+ "txt_mod.1",
+ "attn.to_add_out",
+ "attn.add_q_proj",
+ "attn.to_v",
+ "attn.add_k_proj",
+ "attn.to_q",
+ "attn.to_out.0",
+ "attn.add_v_proj",
+ )
+ ),
+ expected_counts = {PRECISION_NVFP4: 600, PRECISION_FP8: 243, PRECISION_BF16: 3},
+)
+
+NVFP4_POLICIES: tuple = (ZIMG_RG76, FLUX_R420, QWEN21_R020, QWEN2512_M120_ATTN8, QWEN_P02)
+
+
+def policy_by_id(policy_id: Any) -> Optional[NVFP4Policy]:
+ wanted = str(policy_id or "").strip()
+ for policy in NVFP4_POLICIES:
+ if policy.policy_id == wanted:
+ return policy
+ return None
+
+
+def policy_expected_counts(policy: NVFP4Policy) -> dict:
+ """Zero entries dropped: a Counter never records a precision no layer took."""
+ return {
+ str(key): int(value) for key, value in dict(policy.expected_counts).items() if int(value)
+ }
+
+
+def resolve_policy(family: Any, base_repo: Any = None) -> Optional[NVFP4Policy]:
+ """Keyed on the BASE: an unnamed base answers None even where the family has one policy, or a
+ second gated base would hand every anonymous load the first one's precisions."""
+ fam = str(family or "").strip().lower()
+ if not fam:
+ return None
+ candidates = [policy for policy in NVFP4_POLICIES if policy.family == fam]
+ if not candidates or not base_repo:
+ return None
+ from .diffusion_families import canonical_base
+
+ base = canonical_base(str(base_repo).strip()).strip().lower()
+ for policy in candidates:
+ if base in policy.base_repos:
+ return policy
+ return None
+
+
+def assign_precisions(
+ transformer: Any,
+ policy: NVFP4Policy,
+ *,
+ min_features: Optional[int] = None,
+ require_divisible: Optional[int] = None,
+) -> dict:
+ import torch
+
+ from .diffusion_transformer_quant import (
+ DEFAULT_MIN_LINEAR_FEATURES,
+ TQ_NVFP4,
+ divisible_for_scheme,
+ make_filter_fn,
+ )
+
+ if min_features is None:
+ min_features = DEFAULT_MIN_LINEAR_FEATURES
+ if require_divisible is None:
+ require_divisible = divisible_for_scheme(TQ_NVFP4)
+ base_filter = make_filter_fn(
+ min_features,
+ ("lora_",),
+ require_bf16 = True,
+ require_divisible = require_divisible,
+ )
+ linears = [
+ (fqn, module)
+ for fqn, module in transformer.named_modules()
+ if isinstance(module, torch.nn.Linear)
+ ]
+ modules = dict(linears)
+ admitted = {fqn for fqn, module in linears if base_filter(module, fqn)}
+ for admit in policy.admit:
+ hits = sorted(fqn for fqn, _ in linears if admit.matches(fqn))
+ if len(hits) != admit.expect:
+ raise PolicyMismatch(
+ f"policy {policy.policy_id!r} admits {admit.suffix!r} expecting "
+ f"{admit.expect} layers, found {len(hits)}"
+ )
+ for fqn in hits:
+ module = modules[fqn]
+ shape = (int(module.in_features), int(module.out_features))
+ if shape != tuple(admit.shape):
+ raise PolicyMismatch(
+ f"policy {policy.policy_id!r} admits {fqn!r} at {tuple(admit.shape)}, this "
+ f"model has {shape}"
+ )
+ admitted.update(hits)
+ assignment: dict = {}
+ for rule in policy.rules:
+ hits = sorted(fqn for fqn in admitted if fqn not in assignment and rule.matches(fqn))
+ if len(hits) != rule.expect:
+ raise PolicyMismatch(
+ f"policy {policy.policy_id!r} rule {rule.prefix}{rule.suffix!r} -> "
+ f"{rule.precision} expects {rule.expect} layers, found {len(hits)}"
+ )
+ for fqn in hits:
+ assignment[fqn] = rule.precision
+ for fqn in admitted:
+ assignment.setdefault(fqn, policy.default)
+ for fqn, _ in linears:
+ assignment.setdefault(fqn, PRECISION_BF16)
+ counts = dict(Counter(assignment.values()))
+ expected = policy_expected_counts(policy)
+ if counts != expected:
+ raise PolicyMismatch(
+ f"policy {policy.policy_id!r} assigned {counts} over {len(linears)} linears, expected "
+ f"{expected}"
+ )
+ return assignment
+
+
+def policy_metadata(
+ policy: NVFP4Policy,
+ assignment: Mapping,
+ *,
+ activation_scales_baked: bool = False,
+ gptq: bool = False,
+) -> dict:
+ """Sorted for byte-stable builds; the fqn list is recorded, not re-derived from a drifting rule."""
+ counts = Counter(assignment.values())
+ return {
+ NVFP4_POLICY_KEY: {
+ "kind": NVFP4_POLICY_KIND,
+ "policy_id": policy.policy_id,
+ "policy_version": int(policy.version),
+ "counts": {str(key): int(counts[key]) for key in sorted(counts)},
+ "nvfp4_fqns": sorted(
+ fqn for fqn, precision in assignment.items() if precision == PRECISION_NVFP4
+ ),
+ "activation_scales_baked": bool(activation_scales_baked),
+ "gptq": bool(gptq),
+ }
+ }
+
+
+def declares_policy(metadata: Any) -> bool:
+ """Keyed on the KEY: an unreadable block must refuse, not read as "no policy"."""
+ return isinstance(metadata, dict) and metadata.get(NVFP4_POLICY_KEY) not in (None, "")
+
+
+def policy_metadata_error(metadata: Any) -> Optional[str]:
+ if not declares_policy(metadata):
+ return None
+ block = metadata.get(NVFP4_POLICY_KEY)
+ if not isinstance(block, dict):
+ return f"nvfp4 policy block is {type(block).__name__}, not a dict"
+ kind = block.get("kind")
+ if kind != NVFP4_POLICY_KIND:
+ return f"unsupported nvfp4 policy {kind!r} (this build implements {NVFP4_POLICY_KIND!r})"
+ policy_id = block.get("policy_id")
+ if not isinstance(policy_id, str) or not policy_id.strip():
+ return f"nvfp4 policy records no policy_id ({policy_id!r})"
+ version = block.get("policy_version")
+ if not isinstance(version, int) or isinstance(version, bool) or version < 1:
+ return f"nvfp4 policy {policy_id!r} records policy_version {version!r}"
+ counts = block.get("counts")
+ if not isinstance(counts, dict) or not counts:
+ return f"nvfp4 policy {policy_id!r} records no counts ({counts!r})"
+ for key, value in counts.items():
+ if not isinstance(key, str) or not isinstance(value, int) or isinstance(value, bool):
+ return f"nvfp4 policy {policy_id!r} has a malformed count entry {key!r}: {value!r}"
+ fqns = block.get("nvfp4_fqns")
+ if not isinstance(fqns, (list, tuple)) or not fqns:
+ return f"nvfp4 policy {policy_id!r} records no nvfp4_fqns ({fqns!r})"
+ if not all(isinstance(fqn, str) and fqn for fqn in fqns):
+ return f"nvfp4 policy {policy_id!r} nvfp4_fqns has non-string entries"
+ if len(set(fqns)) != len(fqns):
+ return f"nvfp4 policy {policy_id!r} nvfp4_fqns has duplicates"
+ declared = counts.get(PRECISION_NVFP4)
+ if declared is not None and declared != len(fqns):
+ return (
+ f"nvfp4 policy {policy_id!r} counts {declared} nvfp4 layers but lists {len(fqns)} "
+ "nvfp4_fqns"
+ )
+ return None
+
+
+# By class NAME: torchao moves these between module paths across releases.
+_EXPECTED_WEIGHT_CLASS = {
+ PRECISION_NVFP4: "NVFP4Tensor",
+ PRECISION_FP8: "Float8Tensor",
+ PRECISION_BF16: "Parameter",
+}
+
+
+def _verify_weight_types(transformer: Any, assignment: Mapping) -> None:
+ """Raise unless every layer holds its precision's weight class: torchao skips layers silently."""
+ wrong: list = []
+ for fqn, module in transformer.named_modules():
+ precision = assignment.get(fqn)
+ if precision is None:
+ continue
+ want = _EXPECTED_WEIGHT_CLASS.get(precision)
+ if want is None:
+ continue
+ got = type(getattr(module, "weight", None)).__name__
+ if got != want:
+ wrong.append(f"{fqn}: {precision} wanted {want}, got {got}")
+ if wrong:
+ raise PolicyMismatch(
+ f"{len(wrong)} layers did not take the precision the policy assigned:\n "
+ + "\n ".join(wrong[:20])
+ )
+
+
+def quantize_with_policy(
+ transformer: Any,
+ policy: NVFP4Policy,
+ *,
+ min_features: Optional[int] = None,
+ fast_accum: Optional[bool] = None,
+ logger: Any = None,
+) -> dict:
+ """NVFP4 pass first, then fp8 over plain Parameters only. A raise leaves it partly quantised."""
+ import torch
+ from torchao.quantization import quantize_
+
+ from .diffusion_transformer_quant import TQ_FP8, TQ_NVFP4, _make_quant_config
+
+ assignment = assign_precisions(transformer, policy, min_features = min_features)
+ nvfp4_fqns = {fqn for fqn, precision in assignment.items() if precision == PRECISION_NVFP4}
+ fp8_fqns = {fqn for fqn, precision in assignment.items() if precision == PRECISION_FP8}
+
+ def nvfp4_filter(module: Any, fqn: str = "") -> bool:
+ return fqn in nvfp4_fqns
+
+ def fp8_filter(module: Any, fqn: str = "") -> bool:
+ if fqn not in fp8_fqns:
+ return False
+ weight = getattr(module, "weight", None)
+ return type(weight) is torch.nn.Parameter and weight.dtype == torch.bfloat16
+
+ quantize_(transformer, _make_quant_config(TQ_NVFP4), filter_fn = nvfp4_filter)
+ quantize_(
+ transformer,
+ _make_quant_config(TQ_FP8, fast_accum = fast_accum),
+ filter_fn = fp8_filter,
+ )
+ _verify_weight_types(transformer, assignment)
+ if logger is not None:
+ counts = Counter(assignment.values())
+ logger.info(
+ "diffusion.nvfp4_policy: %s v%d applied (%s)",
+ policy.policy_id,
+ policy.version,
+ ", ".join(f"{key} {counts[key]}" for key in sorted(counts)),
+ )
+ return assignment
diff --git a/studio/backend/core/inference/diffusion_nvfp4_protect.py b/studio/backend/core/inference/diffusion_nvfp4_protect.py
new file mode 100644
index 00000000000..74168051c7f
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_nvfp4_protect.py
@@ -0,0 +1,309 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Per-step precision for the NVFP4 backend: which denoising steps run W4A16 instead of W4A4.
+
+The step counter wraps ``pipe.scheduler.step`` (called once per step, after the forward). Off by
+default: the protected set must be MEASURED per model, a borrowed one can do worse than none.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import math
+import os
+import weakref
+from typing import Any, Optional
+
+PROTECT_STEPS_ENV = "UNSLOTH_NVFP4_PROTECT_STEPS"
+
+AUTO = "auto"
+AUTO_HEAD_FRACTION = 0.08
+
+ALL = "all"
+
+_OFF_TOKENS = ("", "off", "none", "0-none", "false", "no")
+
+
+def protect_steps_env() -> str:
+ raw = os.environ.get(PROTECT_STEPS_ENV, "").strip().lower()
+ return "" if raw in _OFF_TOKENS else raw
+
+
+def parse_protect_steps(spec: Any, total_steps: int) -> tuple:
+ """Out-of-range indices are dropped; a non-integer token DOES raise, never silently nothing."""
+ total = int(total_steps)
+ if total <= 0:
+ return ()
+ raw = "" if spec is None else str(spec).strip().lower()
+ if raw in _OFF_TOKENS:
+ return ()
+ if raw == ALL:
+ return tuple(range(total))
+ if raw == AUTO:
+ head = int(math.ceil(AUTO_HEAD_FRACTION * total))
+ wanted: list = list(range(min(head, total))) + [total - 1]
+ else:
+ wanted = []
+ for token in raw.replace(";", ",").split(","):
+ token = token.strip()
+ if not token:
+ continue
+ try:
+ wanted.append(int(token))
+ except ValueError:
+ raise ValueError(
+ f"{PROTECT_STEPS_ENV}={spec!r}: {token!r} is not a step index. Use a comma "
+ f"list of integers (negative counts from the end, e.g. '0,1,2,3,-1'), "
+ f"'{AUTO}', or leave it empty for off"
+ ) from None
+ resolved = set()
+ for index in wanted:
+ if index < 0:
+ index += total
+ if 0 <= index < total:
+ resolved.add(index)
+ return tuple(sorted(resolved))
+
+
+class NVFP4StepController:
+ """``protected`` is a plain bool, never a property: Dynamo would compile one variant per STEP."""
+
+ def __init__(self, spec: Any = None) -> None:
+ self.spec: str = ""
+ self.armed: bool = False
+ self.total: int = 0
+ self.steps: tuple = ()
+ self.index: int = 0
+ self.protected: bool = False
+ self.protected_steps_seen: int = 0
+ self.generations: int = 0
+ self._layers: "weakref.WeakSet" = weakref.WeakSet()
+ self.configure(protect_steps_env() if spec is None else spec)
+
+ def register_layer(self, layer: Any) -> None:
+ try:
+ self._layers.add(layer)
+ except TypeError: # an unweakrefable layer simply is not counted
+ pass
+
+ def capable_layers(self) -> int:
+ return len(self._layers)
+
+ def configure(self, spec: Any) -> "NVFP4StepController":
+ """``armed`` is a compile guard: configure before the first forward."""
+ raw = "" if spec is None else str(spec).strip().lower()
+ self.spec = "" if raw in _OFF_TOKENS else raw
+ self.armed = bool(self.spec)
+ self.reset()
+ return self
+
+ def describe(self) -> dict:
+ return {
+ "env": PROTECT_STEPS_ENV,
+ "spec": self.spec,
+ "armed": self.armed,
+ "total_steps": self.total,
+ "protected_steps": list(self.steps),
+ "protected_steps_seen": self.protected_steps_seen,
+ "generations": self.generations,
+ "capable_layers": self.capable_layers(),
+ }
+
+ def begin(
+ self,
+ total_steps: int,
+ *,
+ logger: Any = None,
+ ) -> tuple:
+ self.reset()
+ if not self.armed:
+ return ()
+ try:
+ self.steps = parse_protect_steps(self.spec, total_steps)
+ except ValueError as exc: # a typo must not cost a multi-minute render
+ self.steps = ()
+ if logger is not None:
+ logger.warning("[nvfp4] protect schedule ignored: %s", exc)
+ self.total = int(total_steps)
+ self.index = 0
+ self.protected = 0 in self.steps
+ self.protected_steps_seen = 1 if self.protected else 0
+ self.generations += 1
+ if logger is not None and self.steps:
+ logger.info(
+ "[nvfp4] W4A16 protect: steps %s of %d run the dequantised bf16 GEMM",
+ ",".join(str(s) for s in self.steps),
+ self.total,
+ )
+ return self.steps
+
+ def advance(self) -> int:
+ self.index += 1
+ self.protected = self.index in self.steps
+ if self.protected:
+ self.protected_steps_seen += 1
+ return self.index
+
+ def reset(self) -> "NVFP4StepController":
+ self.total = 0
+ self.steps = ()
+ self.index = 0
+ self.protected = False
+ return self
+
+
+_CONTROLLER = NVFP4StepController()
+
+
+def protect_controller() -> NVFP4StepController:
+ return _CONTROLLER
+
+
+def reset_protect_controller(spec: Any = None) -> NVFP4StepController:
+ return _CONTROLLER.configure(protect_steps_env() if spec is None else spec)
+
+
+def protect_generation(
+ pipe: Any,
+ steps: int,
+ *,
+ controller: Optional[NVFP4StepController] = None,
+ logger: Any = None,
+):
+ """A no-op when the lever is off; a pipeline with no scheduler to count protects NOTHING."""
+ ctls = [controller] if controller is not None else pipeline_controllers(pipe)
+ ctl = ctls[0]
+ if not ctl.armed:
+ yield ctl
+ return
+ if not sum(c.capable_layers() for c in ctls):
+ if logger is not None:
+ logger.warning(
+ "[nvfp4] protect schedule %r requested but no protect-capable NVFP4 layer is "
+ "loaded (the torchao backend has no W4A16 branch); the lever stays off for this "
+ "generation",
+ ctl.spec,
+ )
+ for c in ctls:
+ c.reset()
+ yield ctl
+ return
+ scheduler = getattr(pipe, "scheduler", None)
+ original = getattr(scheduler, "step", None)
+ if scheduler is None or not callable(original):
+ if logger is not None:
+ logger.warning(
+ "[nvfp4] protect schedule requested but this pipeline exposes no scheduler.step "
+ "to count denoising steps; the lever stays off for this generation"
+ )
+ for c in ctls:
+ c.reset()
+ yield ctl
+ return
+
+ for i, c in enumerate(ctls):
+ c.begin(steps, logger = logger if i == 0 else None)
+
+ def _step(*args: Any, **kwargs: Any) -> Any:
+ out = original(*args, **kwargs)
+ for c in ctls:
+ c.advance()
+ return out
+
+ # Delete, not reassign: an instance attribute would shadow the class method forever.
+ had_own = "step" in getattr(scheduler, "__dict__", {})
+ scheduler.step = _step
+ try:
+ yield ctl
+ finally:
+ if had_own:
+ scheduler.step = original
+ else:
+ try:
+ del scheduler.step
+ except (AttributeError, TypeError): # noqa: PERF203 - a slotted or proxied scheduler
+ scheduler.step = original
+ for c in ctls:
+ c.reset()
+
+
+def suspend_protect(modules: Any):
+ """The prewarm MUST suspend the lever, or it tunes the bf16 branch and marks the FP4 shape tuned."""
+ seen: dict = {}
+ for module in modules or ():
+ ctl = getattr(module, "protect", None)
+ if ctl is not None and id(ctl) not in seen:
+ seen[id(ctl)] = (ctl, bool(getattr(ctl, "armed", False)))
+ for ctl, _ in seen.values():
+ ctl.armed = False
+ try:
+ yield
+ finally:
+ for ctl, armed in seen.values():
+ ctl.armed = armed
+
+
+def protect_graph_key(
+ protected: Optional[bool] = None,
+ module: Any = None,
+ *,
+ controller: Optional[NVFP4StepController] = None,
+) -> tuple:
+ ctl = controller if controller is not None else module_controller(module)
+ if not ctl.armed:
+ return ()
+ live = ctl.protected if protected is None else bool(protected)
+ return (("nvfp4_protect", bool(live)),)
+
+
+def protect_layers(module: Any) -> list:
+ from .diffusion_nvfp4_linear import is_nvfp4_flashinfer_linear
+
+ found: list = []
+ named = getattr(module, "named_modules", None)
+ if not callable(named):
+ return found
+ for name, sub in named():
+ if is_nvfp4_flashinfer_linear(sub) and getattr(sub, "protect", None) is not None:
+ found.append((name, sub))
+ return found
+
+
+def attach_controller(module: Any, controller: NVFP4StepController) -> int:
+ layers = protect_layers(module)
+ for _, layer in layers:
+ old = layer.protect
+ if old is not controller:
+ old._layers.discard(layer)
+ layer.protect = controller
+ controller.register_layer(layer)
+ return len(layers)
+
+
+def attach_own_controller(module: Any) -> Optional[NVFP4StepController]:
+ """Per-model controller, so concurrent image and video renders never move each other's steps."""
+ ctl = NVFP4StepController(protect_controller().spec)
+ return ctl if attach_controller(module, ctl) else None
+
+
+def module_controller(module: Any) -> NVFP4StepController:
+ if module is not None:
+ for _, layer in protect_layers(module):
+ return layer.protect
+ return protect_controller()
+
+
+_DENOISER_ATTRS = ("transformer", "transformer_2", "unet")
+
+
+def pipeline_controllers(pipe: Any) -> list:
+ found: list = []
+ for attr in _DENOISER_ATTRS:
+ module = getattr(pipe, attr, None)
+ for _, layer in protect_layers(module) if module is not None else ():
+ if all(layer.protect is not c for c in found):
+ found.append(layer.protect)
+ return found or [protect_controller()]
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.py
index 2c61ce2f7a6..b00acc04427 100644
--- a/studio/backend/core/inference/diffusion_prequant.py
+++ b/studio/backend/core/inference/diffusion_prequant.py
@@ -47,15 +47,29 @@ PREQUANT_FORMAT = "unsloth_prequant_transformer_state_dict_v1"
# hand-edited tag nor a builder that forgot one half can produce something that loads.
PREQUANT_FORMAT_ROTATED = "unsloth_prequant_transformer_state_dict_v2"
-PREQUANT_FORMATS = (PREQUANT_FORMAT, PREQUANT_FORMAT_ROTATED)
+# Own tag, else an older build reads it as whole-model nvfp4. v3 MUST declare a policy, v1/v2 must NOT.
+PREQUANT_FORMAT_POLICY = "unsloth_prequant_transformer_state_dict_v3"
+
+PREQUANT_FORMATS = (PREQUANT_FORMAT, PREQUANT_FORMAT_ROTATED, PREQUANT_FORMAT_POLICY)
DEFAULT_PREQUANT_COMPONENT = "transformer"
def prequant_format_for(metadata: Any) -> str:
- """The on-disk format tag an offline builder should stamp for ``metadata``."""
+ """The on-disk format tag for ``metadata``. v2 and v3 are mutually exclusive (one tag slot)."""
from .diffusion_convrot import declares_rotation
- return PREQUANT_FORMAT_ROTATED if declares_rotation(metadata) else PREQUANT_FORMAT
+ from .diffusion_nvfp4_policy import declares_policy
+
+ rotated = declares_rotation(metadata)
+ policy = declares_policy(metadata)
+ if rotated and policy:
+ raise ValueError(
+ "a pre-quant checkpoint cannot declare both an activation rotation and a per-layer "
+ "nvfp4 policy: the format tag can only warn older builds about one of them"
+ )
+ if policy:
+ return PREQUANT_FORMAT_POLICY
+ return PREQUANT_FORMAT_ROTATED if rotated else PREQUANT_FORMAT
# A request-supplied ``kind == "path"`` is read ONLY inside an operator-configured directory ALLOWLIST: an arbitrary
@@ -128,6 +142,18 @@ _RESOLVED_SAFE_GLOBALS: set = set()
# What a checkpoint of each scheme actually NAMES, read off the artifacts with pickletools rather than assumed: every
# hosted repo the family tables list, plus a local bake of each scheme for the two nothing hosts. Only these are
# required, so dropping an unused name does not fail a scheme.
+_FP8_REQUIRED_GLOBALS: frozenset = frozenset(
+ {
+ "torchao.quantization.Float8Tensor",
+ "torchao.quantization.quantize_.workflows.float8.float8_tensor."
+ "QuantizeTensorToFloat8Kwargs",
+ "torchao.quantization.quantize_.common.kernel_preference.KernelPreference",
+ "torchao.quantization.granularity.PerRow",
+ "torchao.float8.inference.Float8MMConfig",
+ "torch.torch_version.TorchVersion",
+ }
+)
+
_SCHEME_REQUIRED_GLOBALS: dict = {
"int8": frozenset(
{
@@ -141,18 +167,7 @@ _SCHEME_REQUIRED_GLOBALS: dict = {
"torch.torch_version.TorchVersion",
}
),
- "fp8": frozenset(
- {
- # The ALIAS spelling, which is what the fp8 pickles record.
- "torchao.quantization.Float8Tensor",
- "torchao.quantization.quantize_.workflows.float8.float8_tensor."
- "QuantizeTensorToFloat8Kwargs",
- "torchao.quantization.quantize_.common.kernel_preference.KernelPreference",
- "torchao.quantization.granularity.PerRow",
- "torchao.float8.inference.Float8MMConfig",
- "torch.torch_version.TorchVersion",
- }
- ),
+ "fp8": _FP8_REQUIRED_GLOBALS,
"mxfp8": frozenset(
{
"torchao.prototype.mx_formats.mx_tensor.MXTensor",
@@ -166,7 +181,8 @@ _SCHEME_REQUIRED_GLOBALS: dict = {
"torchao.prototype.mx_formats.nvfp4_tensor.NVFP4Tensor",
"torchao.prototype.mx_formats.nvfp4_tensor.QuantizeTensorToNVFP4Kwargs",
}
- ),
+ )
+ | _FP8_REQUIRED_GLOBALS,
}
@@ -1191,7 +1207,13 @@ def load_prequantized_transformer(
apply_activation_rotation(transformer, metadata, logger = logger)
- # assign=True shares the checkpoint tensors; a live ref keeps the CPU copy past to(device).
+ if scheme == "nvfp4":
+ from .diffusion_nvfp4_linear import convert_nvfp4_backend
+ from .diffusion_nvfp4_ops import select_nvfp4_backend
+ convert_nvfp4_backend(
+ transformer, metadata, select_nvfp4_backend(device), logger = logger
+ )
+ # assign=True shares the tensors: a live reference doubles the peak on unified memory.
del state_dict
del ckpt
@@ -1210,6 +1232,12 @@ def load_prequantized_transformer(
transformer.eval()
except Exception: # noqa: BLE001 - eval() is best-effort
pass
+ if scheme == "nvfp4":
+ try:
+ from .diffusion_nvfp4_linear import nvfp4_prewarm
+ nvfp4_prewarm(transformer, (1,), logger = logger)
+ except Exception as exc: # noqa: BLE001 - an untuned layer still runs
+ _warn(logger, f"{scheme}:prewarm", exc)
try:
transformer._unsloth_runtime_quant = scheme
except Exception: # noqa: BLE001 - marker is best-effort
@@ -1421,16 +1449,20 @@ def _load_transformer_config(
raise last # type: ignore[misc]
+# By NAME: re-exported under several paths, and this check must not import torchao.
+_FLOAT8_TENSOR_CLASS = "Float8Tensor"
+
+
def _fp8_activation_floor_present(state_dict: Any, logger: Any) -> bool:
"""True unless some fp8 tensor was quantised with no activation lower bound. Only the first
- quantised tensor is inspected: the builder applies one config to the whole module, so the
- floor is uniform. A state dict with no fp8 tensor at all is left to the other checks (an
- empty or wrong-scheme artifact is their business, not this one)."""
+ FLOAT8 tensor is read: an NVFP4Tensor also has ``act_quant_kwargs`` but no ``hp_value_lb``."""
from .diffusion_transformer_quant import TQ_FP8
try:
items = state_dict.items() if hasattr(state_dict, "items") else ()
for name, tensor in items:
+ if type(tensor).__name__ != _FLOAT8_TENSOR_CLASS:
+ continue
kwargs = getattr(tensor, "act_quant_kwargs", None)
if kwargs is None:
continue
@@ -1489,6 +1521,88 @@ def _validate_activation_rotation(ckpt_format: Any, meta: Any, scheme: str, logg
return True
+def _validate_policy(ckpt_format: Any, meta: Any, scheme: str, logger: Any) -> bool:
+ """Reject a policy this build cannot reproduce EXACTLY: the weights do not say which layer got
+ which precision."""
+ from .diffusion_nvfp4_policy import (
+ NVFP4_POLICY_KEY,
+ declares_policy,
+ policy_expected_counts,
+ policy_metadata_error,
+ resolve_policy,
+ )
+ from .diffusion_transformer_quant import TQ_NVFP4
+
+ declared = declares_policy(meta)
+ tagged = ckpt_format == PREQUANT_FORMAT_POLICY
+ if declared != tagged:
+ _warn(
+ logger,
+ scheme,
+ ValueError(
+ f"checkpoint format {ckpt_format!r} and its per-layer nvfp4 policy disagree "
+ f"(declares a policy: {declared}); a policy checkpoint must be tagged "
+ f"{PREQUANT_FORMAT_POLICY!r} so older builds refuse it instead of loading it as a "
+ "whole-model artifact"
+ ),
+ )
+ return False
+ if not declared:
+ return True
+ problem = policy_metadata_error(meta)
+ if problem:
+ _warn(logger, scheme, ValueError(problem))
+ return False
+ block = meta.get(NVFP4_POLICY_KEY)
+ if scheme != TQ_NVFP4:
+ _warn(
+ logger,
+ scheme,
+ ValueError(
+ f"checkpoint declares the nvfp4 policy {block.get('policy_id')!r} but its scheme "
+ f"is {scheme!r}"
+ ),
+ )
+ return False
+ policy = resolve_policy(meta.get("family"), meta.get("base_model_id"))
+ if policy is None:
+ _warn(
+ logger,
+ scheme,
+ ValueError(
+ f"checkpoint declares the nvfp4 policy {block.get('policy_id')!r} but this build "
+ f"resolves none for family {meta.get('family')!r} on base "
+ f"{meta.get('base_model_id')!r}"
+ ),
+ )
+ return False
+ declared_id = (block.get("policy_id"), int(block.get("policy_version")))
+ expected_id = (policy.policy_id, int(policy.version))
+ if declared_id != expected_id:
+ _warn(
+ logger,
+ scheme,
+ ValueError(
+ f"checkpoint nvfp4 policy {declared_id!r} != the one this build resolves for "
+ f"{meta.get('base_model_id')!r}, {expected_id!r}"
+ ),
+ )
+ return False
+ declared_counts = {str(key): int(value) for key, value in (block.get("counts") or {}).items()}
+ expected_counts = policy_expected_counts(policy)
+ if declared_counts != expected_counts:
+ _warn(
+ logger,
+ scheme,
+ ValueError(
+ f"checkpoint nvfp4 policy {policy.policy_id!r} records {declared_counts!r}, this "
+ f"build's table expects {expected_counts!r}"
+ ),
+ )
+ return False
+ return True
+
+
def hosted_fast_accum_conflict(scheme: str, fast_accum: Optional[bool]) -> bool:
"""Whether a FORCED fp8 accumulate rules out every HOSTED checkpoint for ``scheme``.
@@ -1522,14 +1636,18 @@ def _validate_checkpoint(
meta = ckpt.get("metadata") or {}
if not _validate_activation_rotation(ckpt.get("format"), meta, scheme, logger):
return False
+ if not _validate_policy(ckpt.get("format"), meta, scheme, logger):
+ return False
if meta.get("scheme") != scheme:
_warn(logger, scheme, ValueError(f"checkpoint scheme {meta.get('scheme')!r} != {scheme!r}"))
return False
# fp8 REQUIRES per-row granularity (per-tensor collapses outlier-heavy DiTs to noise). An old checkpoint omits
# ``fp8_granularity`` or records non-per-row, so reject and let the loader re-quantise.
+ from .diffusion_nvfp4_policy import declares_policy
from .diffusion_transformer_quant import FP8_GRANULARITY, TQ_FP8
- if scheme == TQ_FP8 and meta.get("fp8_granularity") != FP8_GRANULARITY:
+ holds_fp8 = scheme == TQ_FP8 or declares_policy(meta)
+ if holds_fp8 and meta.get("fp8_granularity") != FP8_GRANULARITY:
_warn(
logger,
scheme,
@@ -1545,7 +1663,7 @@ def _validate_checkpoint(
# act_quant_kwargs.hp_value_lb, so an artifact built before the fix stays broken however it is loaded, and it
# predates any metadata field we could stamp -- and "absent is accepted for back-compat", the convention every
# check above follows, is exactly wrong here. Reading the tensors is fail-closed and needs no format bump.
- if scheme == TQ_FP8 and not _fp8_activation_floor_present(ckpt.get("state_dict"), logger):
+ if holds_fp8 and not _fp8_activation_floor_present(ckpt.get("state_dict"), logger):
return False
ckpt_base = meta.get("base_model_id")
if base:
diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.py
index 4a6fde6d338..38dd2097301 100644
--- a/studio/backend/core/inference/diffusion_speed.py
+++ b/studio/backend/core/inference/diffusion_speed.py
@@ -34,6 +34,7 @@ load bit-identical. torch imported lazily.
from __future__ import annotations
import os
+import re
import sys
import threading
from contextlib import contextmanager
@@ -516,8 +517,9 @@ def compiled_shapes_are_static(pipe: Any, speed_mode: Optional[str]) -> bool:
``max`` compiles regional DiT blocks with automatic dynamic (static until a dimension changes, then one
generalised graph; tracked by graph count, not shape) and U-Net whole-module is always static;
- ``default`` DiT compiles dynamic=True (one artifact across shapes). The compile-cache layer
- keys on this to re-save its bundle when a session hits an uncovered shape."""
+ ``default`` DiT compiles dynamic=True (one artifact across shapes) EXCEPT a stream-merging DiT,
+ static there (see ``_STREAM_MERGING_BLOCKS``). The compile-cache layer keys on this to re-save its
+ bundle when a session hits an uncovered shape."""
mode = normalize_speed_mode(speed_mode)
if mode == SPEED_MAX:
# An auto-dynamic DiT generalises a dimension once and then reuses that graph for unseen values, so a new
@@ -525,9 +527,10 @@ def compiled_shapes_are_static(pipe: Any, speed_mode: Optional[str]) -> bool:
return _denoiser_unet(pipe) is not None or not auto_dynamic_active(pipe)
if mode != SPEED_DEFAULT:
return False
- # A torchao-quantised DiT compiles with automatic dynamic: its first shapes get their own artifacts.
- return _denoiser_unet(pipe) is not None or any(
- getattr(t, "_unsloth_auto_dynamic", False) for t in _denoiser_dits(pipe)
+ return (
+ _denoiser_unet(pipe) is not None
+ or any(getattr(t, "_unsloth_auto_dynamic", False) for t in _denoiser_dits(pipe))
+ or _dits_merge_streams(_denoiser_dits(pipe))
)
@@ -544,6 +547,52 @@ def _denoiser_dits(pipe: Any) -> list:
return dits
+# Blocks MEASURED to raise inductor CantSplit under dynamic = True; measure before adding.
+_STREAM_MERGING_BLOCKS: frozenset[str] = frozenset({"FluxSingleTransformerBlock"})
+
+_STREAM_MERGE_DETECT_ENV = "UNSLOTH_STATIC_STREAM_MERGE_DETECT"
+_STREAM_MERGE_SOURCE = re.compile(
+ r"torch\.cat\(\s*\[\s*(?:encoder_hidden_states\s*,\s*hidden_states"
+ r"|hidden_states\s*,\s*encoder_hidden_states)\s*\]"
+)
+
+
+@lru_cache(maxsize = None)
+def _class_merges_streams(cls: type, broad: bool = False) -> bool:
+ """``broad`` is an argument, not an env read in the body, so the memo cannot outlive it."""
+ if cls.__name__ in _STREAM_MERGING_BLOCKS:
+ return True
+ if not broad:
+ return False
+ try:
+ import inspect # noqa: PLC0415 - only reached under the opt-in broad sweep
+ source = inspect.getsource(cls.forward)
+ except Exception: # noqa: BLE001 - no source (frozen / C ext) means fall back to the name list
+ return False
+ return bool(_STREAM_MERGE_SOURCE.search(source))
+
+
+def _dits_merge_streams(dits: list) -> bool:
+ broad = os.environ.get(_STREAM_MERGE_DETECT_ENV) == "1"
+ seen: set[type] = set()
+ for transformer in dits:
+ names = set(getattr(transformer, "_repeated_blocks", ()) or ())
+ if not names:
+ continue
+ try:
+ modules = list(transformer.named_modules())
+ except Exception: # noqa: BLE001 - a probe, never a failed load
+ continue
+ for _name, sub in modules:
+ cls = type(sub)
+ if cls.__name__ not in names or cls in seen:
+ continue
+ seen.add(cls)
+ if _class_merges_streams(cls, broad):
+ return True
+ return False
+
+
def _compile_repeated_blocks(
pipe: Any,
logger: Any,
@@ -564,9 +613,15 @@ def _compile_repeated_blocks(
# (Qwen-Image-2.1: 4-6s on about half of new prompts). Inductor's own cudagraph modes fail on the regional block --
# "accessing tensor output of CUDAGraphs that has been overwritten" -- so the tier stays on -no-cudagraphs and the
# capture is taken one level up, at the denoiser module.
+ static_shapes = (not max_autotune) and _dits_merge_streams(dits)
+ if static_shapes and logger is not None:
+ logger.info(
+ "diffusion.speed: regional compile is static; this DiT merges the text and image streams "
+ "inside its repeated block and cannot be codegen'd with dynamic sequence lengths",
+ )
kwargs: dict[str, Any] = {
"fullgraph": not (cache_active or offload_active),
- "dynamic": None if max_autotune else True,
+ "dynamic": None if max_autotune else (not static_shapes),
}
if max_autotune:
kwargs["mode"] = "max-autotune-no-cudagraphs"
@@ -609,6 +664,14 @@ def _compile_repeated_blocks(
for transformer in dits:
dit_kwargs = dict(kwargs)
dit_kwargs["dynamic"] = compile_dynamic(transformer, kwargs["dynamic"])
+ if (
+ max_autotune
+ and dit_kwargs["dynamic"] is None
+ and _carries_torchao_weights(transformer)
+ and _dits_merge_streams([transformer])
+ ):
+ # Auto dynamic hits CantSplit on torchao stream-merging blocks and drops to eager; static recompiles.
+ dit_kwargs["dynamic"] = False
# Read by auto_dynamic_active: the generalising recompile on a new text length must reach the bundle.
transformer._unsloth_auto_dynamic = dit_kwargs["dynamic"] is None
if type(transformer).__name__ == "QwenImage21Transformer2DModel":
diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.py
index a4b1a139548..0cb840fff6b 100644
--- a/studio/backend/core/inference/diffusion_transformer_quant.py
+++ b/studio/backend/core/inference/diffusion_transformer_quant.py
@@ -27,12 +27,17 @@ import re as _re
import sys as _sys
import threading as _threading
from dataclasses import dataclass
-from typing import Any, Optional
+from typing import Any, Callable, Optional
# stdlib-only module (no torch), so this stays inside the "imported lazily" promise above.
from core._torchao_stub import is_stubbed, torch_is_rocm
from .diffusion_native_quant import int8_act_disabled, int8_act_requested, is_native_linear
-from .diffusion_nvfp4_flag import nvfp4_blocked, nvfp4_disabled_message, without_nvfp4
+from .diffusion_nvfp4_flag import (
+ nvfp4_blocked,
+ nvfp4_diffusion_enabled,
+ nvfp4_disabled_message,
+ without_nvfp4,
+)
from .diffusion_torchao_patches import install_torchao_int_mm_patch
# Also runs in the spawned smoke-probe child, which imports this module and nothing else of the backend.
@@ -263,10 +268,12 @@ def divisible_for_scheme(scheme: str) -> int:
# Per-arch preference for ``auto``, best first. int8 leads every tier: it runs full-rate on consumer and
# workstation cards (which halve fp8 FP32 accumulate) and is within a few percent of fp8 elsewhere.
-# nvfp4 is explicit opt-in and kept OUT of the ladder, being slower and less accurate at DiT shapes.
+# nvfp4 stays OUT of this arch-wide table and reaches auto only via ``_FAMILY_AUTO_PREFER``.
_AUTO_LADDER: tuple[tuple[tuple[int, int], tuple[str, ...]], ...] = (
- ((10, 0), (TQ_INT8, TQ_FP8, TQ_MXFP8)), # Blackwell sm_100+ (nvfp4 is explicit opt-in only)
- # ((10, 0), (TQ_INT8, TQ_FP8, TQ_NVFP4, TQ_MXFP8)), # restore to re-enable nvfp4 under auto
+ (
+ (10, 0),
+ (TQ_INT8, TQ_FP8, TQ_MXFP8),
+ ), # Blackwell sm_100+
((8, 9), (TQ_INT8, TQ_FP8)), # Ada sm_89 / Hopper sm_90
((8, 0), (TQ_INT8,)), # Ampere sm_80 / sm_86
)
@@ -290,14 +297,35 @@ _FAMILY_SCHEME_DENY: dict[str, frozenset[str]] = {
@dataclass(frozen = True)
class _AutoPrefer:
- """Family head of the ``auto`` order; off below ``floor`` and on consumer GPUs by default."""
+ """A family's own head of the ``auto`` order, tried AHEAD of the family-blind ``_AUTO_LADDER``.
+
+ Dropped below ``floor`` and, unless ``consumer_ok``, on consumer GPUs. ``gated``: needs a
+ passing record for THIS base on this device's backend; ``backend``: needs that NVFP4 backend."""
floor: tuple[int, int]
schemes: tuple[str, ...]
consumer_ok: bool = False
-
-
-_FAMILY_AUTO_PREFER: dict[str, _AutoPrefer] = {}
+ gated: bool = False
+ backend: Optional[str] = None
+
+
+_FAMILY_AUTO_PREFER: dict[str, _AutoPrefer] = {
+ "z-image": _AutoPrefer(
+ floor = (10, 0), schemes = (TQ_INT8, TQ_FP8, TQ_NVFP4, TQ_MXFP8), gated = True
+ ),
+ "flux.1": _AutoPrefer(floor = (10, 0), schemes = (TQ_INT8, TQ_FP8, TQ_NVFP4, TQ_MXFP8), gated = True),
+ "qwen-image": _AutoPrefer(
+ floor = (10, 0), schemes = (TQ_INT8, TQ_FP8, TQ_NVFP4, TQ_MXFP8), gated = True
+ ),
+ "qwen-image-2.1": _AutoPrefer(
+ floor = (10, 0), schemes = (TQ_INT8, TQ_FP8, TQ_NVFP4, TQ_MXFP8), gated = True
+ ),
+ "wan2.2-t2v-a14b": _AutoPrefer(
+ floor = (10, 0),
+ schemes = (TQ_NVFP4, TQ_INT8, TQ_FP8, TQ_MXFP8),
+ backend = "flashinfer",
+ ),
+}
# Schemes denied for TRAINING on top of the inference table. Training holds a stricter bar because the evidence above
@@ -314,39 +342,133 @@ _FAMILY_TRAIN_SCHEME_DENY: dict[str, frozenset[str]] = {
}
-def _family_denied(family, scheme: str) -> bool:
- return scheme in _FAMILY_SCHEME_DENY.get(str(family or "").strip().lower(), ())
+def _nvfp4_gate_passed(family, base_repo) -> bool:
+ """Lazy import: the stdlib-only smoke-probe child imports this module whole."""
+ if not nvfp4_diffusion_enabled():
+ return False
+ try:
+ from .diffusion_nvfp4_gate import nvfp4_gate_passed
+ return bool(nvfp4_gate_passed(family, base_repo))
+ except Exception: # noqa: BLE001 -- see the docstring: an unanswerable gate keeps the deny
+ return False
+
+
+def _nvfp4_gate_backend_ok(family, base_repo, device: Any) -> bool:
+ if not nvfp4_diffusion_enabled():
+ return False
+ try:
+ from .diffusion_nvfp4_gate import nvfp4_gate_backends
+ from .diffusion_nvfp4_ops import select_nvfp4_backend
+ return str(select_nvfp4_backend(device)).strip().lower() in nvfp4_gate_backends(
+ family, base_repo
+ )
+ except Exception: # noqa: BLE001 -- see the docstring: an unanswerable probe keeps the deny
+ return False
-def _family_train_denied(family, scheme: str) -> bool:
- """``_family_denied`` plus the training-only additions. Every inference deny also applies to
- training (a scheme that cannot render cannot train), so this is a superset, never a bypass."""
+def _nvfp4_backend_is(device: Any, name: str) -> bool:
+ if not nvfp4_diffusion_enabled():
+ return False
+ try:
+ from .diffusion_nvfp4_ops import select_nvfp4_backend
+ return str(select_nvfp4_backend(device)) == str(name)
+ except Exception: # noqa: BLE001 -- see the docstring: an unanswerable probe drops the head
+ return False
+
+
+def _family_denied(
+ family,
+ scheme: str,
+ base_repo: Optional[str] = None,
+) -> bool:
+ """nvfp4 is the one entry a gate record can lift, per BASE: a sibling base stays denied."""
+ if scheme not in _FAMILY_SCHEME_DENY.get(str(family or "").strip().lower(), ()):
+ return False
+ if scheme == TQ_NVFP4 and _nvfp4_gate_passed(family, base_repo):
+ return False
+ return True
+
+
+_TRAIN_DENY_NVFP4_REASON = (
+ "nvfp4 is inference-only: the accuracy gate behind it measures a frozen forward at a "
+ "per-layer policy, and no training run has been measured on 4-bit frozen linears"
+)
+
+
+def _family_train_denied(
+ family,
+ scheme: str,
+ base_repo: Optional[str] = None,
+) -> bool:
+ """``_family_denied`` plus training-only additions: a superset, never a bypass."""
+ if scheme == TQ_NVFP4:
+ return True
key = str(family or "").strip().lower()
- return _family_denied(family, scheme) or scheme in _FAMILY_TRAIN_SCHEME_DENY.get(key, ())
+ return _family_denied(family, scheme, base_repo) or scheme in _FAMILY_TRAIN_SCHEME_DENY.get(
+ key, ()
+ )
+
+def nvfp4_gated_base(family: Optional[str]) -> Optional[str]:
+ """A base of ``family`` whose passing NVFP4 gate record lifts the family deny, or None. For a load whose base is
+ not known yet (a GGUF pick resolves it from its card tag at load time), so a network-free check can judge the
+ scheme the way the loader will if the pick turns out to be that base."""
+ if not family:
+ return None
+ try:
+ from .diffusion_nvfp4_gate import load_gate_records
+ records = load_gate_records()
+ except Exception: # noqa: BLE001 -- no readable record means nothing is lifted
+ return None
+ name = str(family).strip().lower()
+ for record in records:
+ base = record.get("base_repo")
+ if (
+ str(record.get("family", "")).strip().lower() == name
+ and base
+ and _nvfp4_gate_passed(name, base)
+ ):
+ return str(base)
+ return None
-def family_denies_scheme(family: Optional[str], scheme: str) -> bool:
+
+def family_denies_scheme(
+ family: Optional[str],
+ scheme: str,
+ base_repo: Optional[str] = None,
+) -> bool:
"""Whether the measured deny list rules ``scheme`` out for ``family``, regardless of hardware.
- Public so the refusal message can tell the two "no" answers apart:
- ``select_transformer_quant_scheme`` folds a family deny and a missing kernel into the same
- ``None``, and an EXPLICIT scheme now fails closed, so that single answer is the whole
- explanation the user gets."""
- return _family_denied(family, scheme)
-
-
-def explain_unusable_scheme(family: Optional[str], scheme: str) -> str:
- """Why ``select_transformer_quant_scheme`` answered None for an EXPLICIT ``scheme``. One
- ``None`` covers three different faults, and the caller turns it into a 409, so the message
- has to separate them: a family the scheme is measured to break, a torchao that cannot run at
- all in this install, and a GPU without the kernels. Only the last is a hardware limit, and
- only the last is what the message used to say."""
+ Public so the refusal message can tell a family deny from a missing kernel."""
+ return _family_denied(family, scheme, base_repo)
+
+
+def explain_unusable_scheme(
+ family: Optional[str],
+ scheme: str,
+ base_repo: Optional[str] = None,
+ *,
+ prequant_missing: bool = False,
+) -> str:
if nvfp4_blocked(scheme):
return nvfp4_disabled_message()
- if family_denies_scheme(family, scheme):
+ if family_denies_scheme(family, scheme, base_repo):
+ if scheme == TQ_NVFP4:
+ return (
+ f"'{scheme}' is ruled out for family '{family}'"
+ + (f" on base '{base_repo}'" if base_repo else "")
+ + ": no reviewed NVFP4 accuracy-gate record (core/inference/"
+ "nvfp4_gate_record.json) covers this base at the policy this build resolves, so "
+ "nothing has measured what those per-layer precisions do to the render"
+ )
return (
f"'{scheme}' is ruled out for family '{family}' by the measured accuracy gate (it "
"renders black frames or fails the quality bar on this DiT), whatever the GPU"
)
+ if prequant_missing:
+ return (
+ f"'{scheme}' needs a pre-quantized checkpoint for family '{family}' and none is "
+ "available for this model (no hosted repo for this base and no transformer_prequant_path)"
+ )
unavailable = torchao_unavailable_reason()
if unavailable is not None:
return (
@@ -798,6 +920,9 @@ def select_transformer_quant_scheme(
family: Optional[str] = None,
*,
unproven_ok: bool = False,
+ base_repo: Optional[str] = None,
+ require_prequant: frozenset[str] = frozenset({TQ_NVFP4}),
+ has_prequant: Optional[Callable[[str], bool]] = None,
) -> Optional[str]:
"""The concrete scheme to apply, or None to fall back to GGUF.
@@ -807,25 +932,25 @@ def select_transformer_quant_scheme(
measured deny list (``_FAMILY_SCHEME_DENY``): schemes that produce black frames / out-of-bar
drift are skipped by ``auto`` and refused when explicit.
- ``unproven_ok`` is for the PRE-EVICTION route gate. The smoke test allocates, so a resident
- chat/image/video model can make it fail for want of VRAM rather than for want of a kernel; the
- gate runs before the arbiter has evicted that model, so treating "could not tell" as "not
- supported" refuses a load the very next moment would have run. It answers "is this scheme
- provably unusable here", and the real selection still happens after the handoff.
+ ``base_repo`` keys the per-base nvfp4 deny lift. ``require_prequant`` schemes are offered by
+ AUTO only when ``has_prequant`` finds a hosted checkpoint; EXPLICIT opts into a build.
+
+ ``unproven_ok`` is for the PRE-EVICTION route gate: a resident model can fail the smoke test for
+ want of VRAM, so it answers only "provably unusable here".
"""
requested = normalize_transformer_quant(requested)
if requested is None or not dense_transformer_supported(target):
return None
device = str(getattr(target, "device", "cuda"))
if requested != TQ_AUTO:
- if _family_denied(family, requested):
+ if _family_denied(family, requested, base_repo):
return None
return requested if _scheme_supported(requested, device, unproven_ok = unproven_ok) else None
cap = _capability()
if cap is None:
return None
- for scheme in _auto_scheme_order(family, device, cap):
- if _family_denied(family, scheme):
+ for scheme in _auto_scheme_order(family, device, cap, base_repo):
+ if not _auto_offers_scheme(scheme, family, base_repo, require_prequant, has_prequant):
continue
if _scheme_supported(scheme, device):
return scheme
@@ -869,7 +994,33 @@ def dense_quant_host_capable(target: Any) -> bool:
return False
-def auto_scheme_candidates(target: Any, family: Optional[str] = None) -> tuple[str, ...]:
+def _auto_offers_scheme(
+ scheme: str,
+ family: Optional[str],
+ base_repo: Optional[str],
+ require_prequant: frozenset[str],
+ has_prequant: Optional[Callable[[str], bool]],
+) -> bool:
+ if _family_denied(family, scheme, base_repo):
+ return False
+ if scheme in (require_prequant or ()):
+ if has_prequant is None:
+ return False
+ try:
+ return bool(has_prequant(scheme))
+ except Exception: # noqa: BLE001 -- see the docstring: unanswerable means not offered
+ return False
+ return True
+
+
+def auto_scheme_candidates(
+ target: Any,
+ family: Optional[str] = None,
+ *,
+ base_repo: Optional[str] = None,
+ require_prequant: frozenset[str] = frozenset({TQ_NVFP4}),
+ has_prequant: Optional[Callable[[str], bool]] = None,
+) -> tuple[str, ...]:
"""Every scheme ``auto`` would accept on this device, best first.
``select_transformer_quant_scheme`` returns only the winner, which is all the load needs
until the winner turns out to have no hosted prequant AND not to fit dense. The caller then
@@ -884,13 +1035,22 @@ def auto_scheme_candidates(target: Any, family: Optional[str] = None) -> tuple[s
return ()
return tuple(
scheme
- for scheme in _auto_scheme_order(family, device, cap)
- if not _family_denied(family, scheme) and _scheme_supported(scheme, device)
+ for scheme in _auto_scheme_order(family, device, cap, base_repo)
+ if _auto_offers_scheme(scheme, family, base_repo, require_prequant, has_prequant)
+ and _scheme_supported(scheme, device)
)
-def _auto_scheme_order(family: Optional[str], device: Any, cap: tuple[int, int]) -> tuple[str, ...]:
- """``auto``'s scheme order for this family and GPU, best first; empty below every tier."""
+def _auto_scheme_order(
+ family: Optional[str],
+ device: Any,
+ cap: tuple[int, int],
+ base_repo: Optional[str] = None,
+) -> tuple[str, ...]:
+ """The schemes ``auto`` would try on this GPU for this family, best first, before the deny list
+ and the smoke probe have their say. Empty when no tier matches, head or not: a capability below
+ every tier has no dense quant path at all. Shared by ``select_transformer_quant_scheme`` and
+ ``auto_scheme_candidates`` so the two can never disagree."""
tier: tuple[str, ...] = ()
for floor, schemes in _AUTO_LADDER:
if cap >= floor:
@@ -899,10 +1059,18 @@ def _auto_scheme_order(family: Optional[str], device: Any, cap: tuple[int, int])
if not tier:
return ()
prefer = _FAMILY_AUTO_PREFER.get(str(family or "").strip().lower())
+ if prefer is not None and (prefer.gated or prefer.backend) and not nvfp4_diffusion_enabled():
+ # Switch off: drop gated/backend rows before their gate record or backend probe (imports flashinfer).
+ prefer = None
head: tuple[str, ...] = ()
if prefer is not None and cap >= prefer.floor:
if prefer.consumer_ok or not _is_consumer_gpu(device):
- head = prefer.schemes
+ if not prefer.gated or (
+ _nvfp4_gate_passed(family, base_repo)
+ and _nvfp4_gate_backend_ok(family, base_repo, device)
+ ):
+ if prefer.backend is None or _nvfp4_backend_is(device, prefer.backend):
+ head = prefer.schemes
order: list[str] = []
# Filtered here so the NVFP4 switch reaches every reader of the order.
for scheme in without_nvfp4(head + tier):
@@ -928,7 +1096,8 @@ def auto_scheme_candidates_cached(target: Any, family: Optional[str] = None) ->
return tuple(
scheme
for scheme in _auto_scheme_order(family, device, cap)
- if not _family_denied(family, scheme) and _SMOKE_CACHE.get((scheme, card), True)
+ if _auto_offers_scheme(scheme, family, None, frozenset({TQ_NVFP4}), None)
+ and _SMOKE_CACHE.get((scheme, card), True)
)
@@ -1515,6 +1684,7 @@ def quantize_transformer(
*,
mode: Optional[str],
family: Optional[str] = None,
+ base_repo: Optional[str] = None,
min_features: int = DEFAULT_MIN_LINEAR_FEATURES,
fast_accum: Optional[bool] = None,
logger: Any = None,
@@ -1525,7 +1695,7 @@ def quantize_transformer(
Returns the scheme engaged, or None when disabled / unsupported / failed (caller loads GGUF).
Best-effort: never raises for an unsupported environment (failure leaves it dense).
``fast_accum`` (fp8 only) overrides the per-GPU-class accumulate choice: None auto-detects,
- True/False force it."""
+ True/False force it. ``base_repo`` (UPSTREAM id) selects the per-layer NVFP4 policy."""
native = native_quant_scheme(target, mode, family = family, offload = offload)
if native is not None:
if act_int8 is None:
@@ -1538,7 +1708,7 @@ def quantize_transformer(
act_int8 = bool(act_int8) and native == TQ_INT8,
logger = logger,
)
- scheme = select_transformer_quant_scheme(target, mode, family = family)
+ scheme = select_transformer_quant_scheme(target, mode, family = family, base_repo = base_repo)
if scheme is None:
return None
transformer = getattr(pipe, "transformer", None)
@@ -1547,6 +1717,30 @@ def quantize_transformer(
try:
from torchao.quantization import quantize_
+ policy = None
+ if scheme == TQ_NVFP4:
+ from .diffusion_nvfp4_policy import quantize_with_policy, resolve_policy
+ policy = resolve_policy(family, base_repo)
+ if policy is not None:
+ quantize_with_policy(
+ transformer,
+ policy,
+ min_features = min_features,
+ fast_accum = fast_accum,
+ logger = logger,
+ )
+ apply_small_m_padding(transformer, scheme, family, logger = logger)
+ apply_zero_row_guard(transformer, scheme, family, logger = logger)
+ for attr, value in (
+ ("_unsloth_runtime_quant", scheme),
+ ("_unsloth_nvfp4_policy", policy.policy_id),
+ ):
+ try:
+ setattr(transformer, attr, value)
+ except Exception: # noqa: BLE001 - markers are best-effort
+ pass
+ return scheme
+
# int8 skips the M=1 projections; fp8/mxfp8 assert a bf16 weight, so on a mixed-precision DiT they must skip
# non-bf16 ones. "lora_" keeps a baked adapter's side path high precision. Runtime only: NOT part of
# exclude_tokens_for_scheme, whose list is baked into prequant metadata.
diff --git a/studio/backend/core/inference/nvfp4_gate_record.json b/studio/backend/core/inference/nvfp4_gate_record.json
new file mode 100644
index 00000000000..fbc7b13621e
--- /dev/null
+++ b/studio/backend/core/inference/nvfp4_gate_record.json
@@ -0,0 +1,314 @@
+{
+ "version": 1,
+ "comment": "Reviewed NVFP4 accuracy-gate verdicts, one entry per (family, base_repo, policy_id, policy_version, checkpoint_sha256). One entry says that ONE published checkpoint rendered the gate's prompt/resolution pairs within the recorded thresholds of its dense reference, on the backend, GPU and toolchain the entry names. Read by core/inference/diffusion_nvfp4_gate.py, which re-derives the verdict rather than trusting it as stored. Entries are measured out of band and committed after review; nothing writes this file at run time. Empty means no checkpoint has been gated yet, which keeps nvfp4 out of the auto ladder for every family.",
+ "records": [
+ {
+ "family": "z-image",
+ "base_repo": "Tongyi-MAI/Z-Image-Turbo",
+ "policy_id": "zimg_rg76_v1",
+ "policy_version": 1,
+ "checkpoint_sha256": "2453bc13d7abe5b4a49721f4a9d38a9aa16dee20085a9267f8a35867c7d9cc33",
+ "repo_id": "unsloth/Z-Image-Turbo-NVFP4",
+ "filename": "Z-Image-Turbo-NVFP4.pt",
+ "gptq": true,
+ "all_pass": true,
+ "num_pairs": 24,
+ "num_passed": 24,
+ "aggregates": {
+ "lpips_mean": 0.1581714154841999,
+ "ssim_mean": 0.8411444996904973,
+ "clip_delta_mean": 0.004930264006058375,
+ "failures": []
+ },
+ "gates": {
+ "lpips_case_max": 0.6,
+ "lpips_mean_max": 0.25,
+ "ssim_case_min": 0.3,
+ "ssim_mean_min": 0.7,
+ "clip_delta_case_max": 0.03,
+ "clip_delta_mean_max": 0.01,
+ "black_luma_min": 0.02
+ },
+ "resolutions": [
+ 512,
+ 1024
+ ],
+ "seeds": [
+ 1234,
+ 4321
+ ],
+ "cuda_graphs": true,
+ "backend": "flashinfer",
+ "gpu": "NVIDIA B200",
+ "versions": {
+ "torch": "2.12.1+cu130",
+ "torchao": "0.18.0",
+ "diffusers": "0.41.0.dev0",
+ "flashinfer": "0.6.18.post1"
+ },
+ "gate_script_sha256": "d0b423658874f8430b1508f839cbc7fe39b1ee04d73931ffe4f24c444b11d3b5",
+ "run_date": "2026-09-24",
+ "results_path": "/mnt/disks/unslothai/ubuntu/workspace_81/outputs/nvfp4_repick/zimg_zimg_rg76_v1_g32/gate/results.json",
+ "fp8_paired": {
+ "metric": "lpips_vgg(nvfp4, bf16) - lpips_vgg(fp8, bf16), per (prompt, seed)",
+ "prompts": "diffusion_bench image_24 (24 frozen prompts)",
+ "num_pairs": 48,
+ "resolution": 1024,
+ "seeds": [
+ 1234,
+ 4321
+ ],
+ "fp8_sha256": "d9ee7d97ef94f620660b0f475ee961b84a877fd99d86bfc84101d21ad3cd8dfc",
+ "d_lpips_mean": 0.0219,
+ "d_lpips_ci95": [
+ 0.0021,
+ 0.0402
+ ],
+ "d_lpips_prompt_cluster_ci95": [
+ 0.0035,
+ 0.0412
+ ],
+ "bar_upper_ci95": 0.05,
+ "ssim_vs_bf16": {
+ "fp8": 0.8275,
+ "nvfp4": 0.8028
+ },
+ "psnr_vs_bf16": {
+ "fp8": 21.79,
+ "nvfp4": 20.63
+ }
+ }
+ },
+ {
+ "family": "qwen-image-2.1",
+ "base_repo": "Qwen/Qwen-Image-2.1",
+ "policy_id": "qwen21_r020_v1",
+ "policy_version": 1,
+ "checkpoint_sha256": "37af1338c21a0c20dd0518f1908f6bc5828740c1cd12c50718552a31d753c24d",
+ "repo_id": "unsloth/Qwen-Image-2.1-NVFP4",
+ "filename": "Qwen-Image-2.1-NVFP4.pt",
+ "gptq": true,
+ "all_pass": true,
+ "num_pairs": 28,
+ "num_passed": 28,
+ "aggregates": {
+ "lpips_mean": 0.1248540869647903,
+ "ssim_mean": 0.8829234177148308,
+ "clip_delta_mean": 0.005960816783564431,
+ "failures": []
+ },
+ "gates": {
+ "lpips_case_max": 0.6,
+ "lpips_mean_max": 0.25,
+ "ssim_case_min": 0.3,
+ "ssim_mean_min": 0.7,
+ "clip_delta_case_max": 0.03,
+ "clip_delta_mean_max": 0.01,
+ "black_luma_min": 0.02
+ },
+ "resolutions": [
+ 512,
+ 1024
+ ],
+ "seeds": [
+ 1234,
+ 4321
+ ],
+ "cuda_graphs": true,
+ "backend": "flashinfer",
+ "gpu": "NVIDIA B200",
+ "versions": {
+ "torch": "2.12.1+cu130",
+ "torchao": "0.18.0",
+ "diffusers": "0.41.0.dev0",
+ "flashinfer": "0.6.18.post1"
+ },
+ "gate_script_sha256": "d0b423658874f8430b1508f839cbc7fe39b1ee04d73931ffe4f24c444b11d3b5",
+ "run_date": "2026-09-24",
+ "results_path": "/mnt/disks/unslothai/ubuntu/workspace_81/outputs/nvfp4_repick/q21_qwen21_r020_v1_g32/gate/results.json",
+ "fp8_paired": {
+ "metric": "lpips_vgg(nvfp4, bf16) - lpips_vgg(fp8, bf16), per (prompt, seed)",
+ "prompts": "diffusion_bench image_24 (24 frozen prompts)",
+ "num_pairs": 48,
+ "resolution": 1024,
+ "seeds": [
+ 1234,
+ 4321
+ ],
+ "fp8_sha256": "5ce621f4deab0fca5f4b9cd43af68f57ef0a8eb9ea0581d0229dce8612c27788",
+ "d_lpips_mean": 0.0277,
+ "d_lpips_ci95": [
+ 0.0118,
+ 0.0457
+ ],
+ "d_lpips_prompt_cluster_ci95": [
+ 0.0134,
+ 0.0432
+ ],
+ "bar_upper_ci95": 0.05,
+ "ssim_vs_bf16": {
+ "fp8": 0.9045,
+ "nvfp4": 0.8782
+ },
+ "psnr_vs_bf16": {
+ "fp8": 25.98,
+ "nvfp4": 24.37
+ }
+ }
+ },
+ {
+ "family": "flux.1",
+ "base_repo": "black-forest-labs/FLUX.1-schnell",
+ "policy_id": "flux_r420_v1",
+ "policy_version": 1,
+ "checkpoint_sha256": "d4e4c5e353374e022685f2e48dc7b38d054e36f30809dd8eb77a22a0a5d67006",
+ "repo_id": "unsloth/FLUX.1-schnell-NVFP4",
+ "filename": "FLUX.1-schnell-NVFP4.pt",
+ "gptq": true,
+ "all_pass": true,
+ "num_pairs": 24,
+ "num_passed": 24,
+ "aggregates": {
+ "lpips_mean": 0.1846515154466033,
+ "ssim_mean": 0.7870014756664174,
+ "clip_delta_mean": 0.007136411964893341,
+ "failures": []
+ },
+ "gates": {
+ "lpips_case_max": 0.6,
+ "lpips_mean_max": 0.25,
+ "ssim_case_min": 0.3,
+ "ssim_mean_min": 0.7,
+ "clip_delta_case_max": 0.03,
+ "clip_delta_mean_max": 0.01,
+ "black_luma_min": 0.02
+ },
+ "resolutions": [
+ 512,
+ 1024
+ ],
+ "seeds": [
+ 1234,
+ 4321
+ ],
+ "cuda_graphs": true,
+ "backend": "flashinfer",
+ "gpu": "NVIDIA B200",
+ "versions": {
+ "torch": "2.12.1+cu130",
+ "torchao": "0.18.0",
+ "diffusers": "0.41.0.dev0",
+ "flashinfer": "0.6.18.post1"
+ },
+ "gate_script_sha256": "d0b423658874f8430b1508f839cbc7fe39b1ee04d73931ffe4f24c444b11d3b5",
+ "run_date": "2026-09-24",
+ "results_path": "/mnt/disks/unslothai/ubuntu/workspace_81/outputs/nvfp4_repick/flux_flux_r420_v1_g32/gate/results.json",
+ "fp8_paired": {
+ "metric": "lpips_vgg(nvfp4, bf16) - lpips_vgg(fp8, bf16), per (prompt, seed)",
+ "prompts": "diffusion_bench image_24 (24 frozen prompts)",
+ "num_pairs": 48,
+ "resolution": 1024,
+ "seeds": [
+ 1234,
+ 4321
+ ],
+ "fp8_sha256": "fd619e706f2f42171864d45e5115e4410a9830bd33945837360e05e109761f76",
+ "d_lpips_mean": 0.0235,
+ "d_lpips_ci95": [
+ 0.0161,
+ 0.0307
+ ],
+ "d_lpips_prompt_cluster_ci95": [
+ 0.0163,
+ 0.0307
+ ],
+ "bar_upper_ci95": 0.05,
+ "ssim_vs_bf16": {
+ "fp8": 0.8137,
+ "nvfp4": 0.7881
+ },
+ "psnr_vs_bf16": {
+ "fp8": 22.39,
+ "nvfp4": 21.18
+ }
+ }
+ },
+ {
+ "family": "qwen-image",
+ "base_repo": "Qwen/Qwen-Image-2512",
+ "policy_id": "qwen2512_m120_attn8_v1",
+ "policy_version": 1,
+ "checkpoint_sha256": "665e8f9a12d31366cfd4ac10a93c751a32219ea2386107b55a43b0cde5955607",
+ "repo_id": "unsloth/Qwen-Image-2512-NVFP4",
+ "filename": "Qwen-Image-2512-NVFP4.pt",
+ "gptq": true,
+ "all_pass": true,
+ "num_pairs": 28,
+ "num_passed": 28,
+ "aggregates": {
+ "lpips_mean": 0.13174473800297296,
+ "ssim_mean": 0.89856672865755,
+ "clip_delta_mean": 0.005002257015023913,
+ "failures": []
+ },
+ "gates": {
+ "lpips_case_max": 0.6,
+ "lpips_mean_max": 0.25,
+ "ssim_case_min": 0.3,
+ "ssim_mean_min": 0.7,
+ "clip_delta_case_max": 0.03,
+ "clip_delta_mean_max": 0.01,
+ "black_luma_min": 0.02
+ },
+ "resolutions": [
+ 512,
+ 1024
+ ],
+ "seeds": [
+ 1234,
+ 4321
+ ],
+ "cuda_graphs": true,
+ "backend": "flashinfer",
+ "gpu": "NVIDIA B200",
+ "versions": {
+ "torch": "2.12.1+cu130",
+ "torchao": "0.18.0",
+ "diffusers": "0.41.0.dev0",
+ "flashinfer": "0.6.18.post1"
+ },
+ "gate_script_sha256": "d0b423658874f8430b1508f839cbc7fe39b1ee04d73931ffe4f24c444b11d3b5",
+ "run_date": "2026-09-24",
+ "results_path": "/mnt/disks/unslothai/ubuntu/workspace_81/outputs/nvfp4_repick/q2512_qwen2512_m120_attn8_v1_g32/gate/results.json",
+ "fp8_paired": {
+ "metric": "lpips_vgg(nvfp4, bf16) - lpips_vgg(fp8, bf16), per (prompt, seed)",
+ "prompts": "diffusion_bench image_24 (24 frozen prompts)",
+ "num_pairs": 48,
+ "resolution": 1024,
+ "seeds": [
+ 1234,
+ 4321
+ ],
+ "fp8_sha256": "d6b26b72e5925220df8e38fad8446850d35d2187f28e4164b77532cf74e80cf0",
+ "d_lpips_mean": 0.0282,
+ "d_lpips_ci95": [
+ 0.0076,
+ 0.0496
+ ],
+ "d_lpips_prompt_cluster_ci95": [
+ 0.0082,
+ 0.0493
+ ],
+ "bar_upper_ci95": 0.05,
+ "ssim_vs_bf16": {
+ "fp8": 0.906,
+ "nvfp4": 0.881
+ },
+ "psnr_vs_bf16": {
+ "fp8": 26.38,
+ "nvfp4": 24.9
+ }
+ }
+ }
+ ]
+}
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index ec7a42fda17..2998cb5cb8f 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -1262,13 +1262,19 @@ def _video_auto_denoiser_scheme(
hosted = video_family_prequant_schemes(fam)
if not hosted or (not auto and normalize_transformer_quant(requested) not in hosted):
return None
+ from .video_denoiser_prequant import denoiser_prequant_sources
+
scheme = select_transformer_quant_scheme(
- target, requested, family = getattr(fam, "name", None)
+ target,
+ requested,
+ family = getattr(fam, "name", None),
+ base_repo = base_repo,
+ has_prequant = lambda candidate: (
+ denoiser_prequant_sources(fam, candidate, base_repo) is not None
+ ),
)
if scheme is None or scheme == TQ_AUTO:
return None
- from .video_denoiser_prequant import denoiser_prequant_sources
-
# EVERY component or none: partial coverage drops shards the dense fallback then has to open.
if denoiser_prequant_sources(fam, scheme, base_repo) is None:
return None
@@ -1424,6 +1430,31 @@ def _transformer_names(pipe: Any, fam: VideoFamily) -> tuple[str, ...]:
return tuple(names)
+def _video_transformer_quant_backend(state: Any) -> Optional[str]:
+ """Read from the module tree; both experts share one backend. Never raises."""
+ if getattr(state, "transformer_quant", None) != "nvfp4":
+ return None
+ try:
+ pipe = getattr(state, "pipe", None)
+ if pipe is None:
+ return None
+ from .diffusion_nvfp4_linear import is_nvfp4_flashinfer_linear
+
+ for name in _transformer_names(pipe, state.family):
+ denoiser = getattr(pipe, name, None)
+ if denoiser is None:
+ continue
+ declared = getattr(denoiser, "_unsloth_nvfp4_backend", None)
+ if declared:
+ return str(declared)
+ for module in denoiser.modules():
+ if is_nvfp4_flashinfer_linear(module):
+ return "flashinfer"
+ return "torchao"
+ except Exception: # noqa: BLE001 -- a poll must not fail on a probe
+ return None
+
+
class _SecondDiTView:
"""A thin proxy that makes ``pipe.transformer_2`` look like ``pipe.transformer`` to a
helper that hardcodes ``getattr(pipe, "transformer")``, while every other attribute
@@ -6926,6 +6957,10 @@ class VideoBackend:
if cancel.is_set():
raise _VideoGenerationCancelled()
+ from .diffusion_nvfp4_protect import protect_generation
+
+ protect_ctx = protect_generation(pipe, steps, logger = logger)
+
has_step_callback = "callback_on_step_end" in call_params
if has_step_callback:
kwargs["callback_on_step_end"] = _on_step
@@ -6981,7 +7016,7 @@ class VideoBackend:
elif state.transformer_cache:
self._reset_step_cache(pipe)
try:
- with torch.inference_mode(), progress_ctx(), sigma_ctx:
+ with torch.inference_mode(), protect_ctx, progress_ctx(), sigma_ctx:
output = pipe(**kwargs)
except _VideoGenerationCancelled:
# Unwinding by exception skips maybe_free_model_hooks(); under offload the onloaded modules would
@@ -7648,6 +7683,7 @@ class VideoBackend:
"transformer_cache": None,
"transformer_cache_stats": None,
"transformer_quant": None,
+ "transformer_quant_backend": None,
"text_encoder_quant": None,
"has_audio": False,
"supports_cfg": True,
@@ -7699,6 +7735,7 @@ class VideoBackend:
static_skip_stats(state.pipe) if state.transformer_cache == TC_STATIC else None
),
"transformer_quant": state.transformer_quant,
+ "transformer_quant_backend": _video_transformer_quant_backend(state),
"text_encoder_quant": state.text_encoder_quant,
"has_audio": fam.has_audio,
"supports_cfg": fam.supports_cfg,
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 9f769938bbe..69a1782afc0 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -4512,6 +4512,13 @@ class DiffusionStatusResponse(BaseModel):
description = "Transformer quant engaged on the dense fast path: int8 | fp8 | "
"nvfp4 | mxfp8 | null (null = the GGUF transformer was loaded)",
)
+ transformer_quant_backend: Optional[str] = Field(
+ None,
+ description = "Which NVFP4 kernel path the loaded DiT actually runs: flashinfer | "
+ "torchao | null (null for every scheme but nvfp4). The scheme alone does not say: "
+ "flashinfer is selected per device and falls back to torchao on a preflight failure, so "
+ "this is the only place a render's speed can be attributed to the backend that served it.",
+ )
attention_backend: Optional[str] = Field(
None,
description = "Attention backend engaged via the diffusers dispatcher (e.g. "
@@ -5350,6 +5357,11 @@ class VideoStatusResponse(BaseModel):
"mxfp8 | null (null = the DiT(s) run at their loaded bf16 precision). For a dual-expert "
"MoE family both experts share the reported scheme.",
)
+ transformer_quant_backend: Optional[str] = Field(
+ None,
+ description = "Which NVFP4 kernel path the loaded DiT(s) run: flashinfer | torchao | null "
+ "(null for every scheme but nvfp4).",
+ )
text_encoder_quant: Optional[str] = Field(
None,
description = "Text-encoder quant engaged: fp8 | fp8_dynamic | int8 | nvfp4 | null "
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index b832570eb5d..e7c87b66d4f 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -40083,6 +40083,8 @@ async def diffusion_download_plan(
speed_mode = getattr(request, "speed_mode", None),
# Judged on the card this pick would load on, as the loader does.
gpu_ordinal = gpu_ordinal,
+ repo_id = request.model_path,
+ base_repo = request.base_repo,
)
else:
_assert_native_precision_unset(
@@ -40330,6 +40332,8 @@ async def load_diffusion_model_gated(
cpu_offload = bool(getattr(request, "cpu_offload", False)),
speed_mode = getattr(request, "speed_mode", None),
gpu_ordinal = gpu_ordinal,
+ repo_id = request.model_path,
+ base_repo = request.base_repo,
)
elif fam is not None and pending_name == ENGINE_SD_CPP:
# The native engine accepts both knobs for interface parity and ignores them. It was
@@ -40403,6 +40407,8 @@ async def load_diffusion_model_gated(
cpu_offload = bool(getattr(request, "cpu_offload", False)),
speed_mode = getattr(request, "speed_mode", None),
gpu_ordinal = gpu_ordinal,
+ repo_id = request.model_path,
+ base_repo = request.base_repo,
)
def _start_engine_load():
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index e794196f626..528ac6a9a69 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -1249,6 +1249,7 @@ _NVFP4_ENABLED_TEST_MODULES = frozenset(
"test_diffusion_backend",
"test_diffusion_inference_info",
"test_diffusion_lora",
+ "test_diffusion_more_families",
"test_diffusion_native_quant",
"test_diffusion_pipeline_prequant",
"test_diffusion_precision",
diff --git a/studio/backend/tests/test_diffusion_auto_policy.py b/studio/backend/tests/test_diffusion_auto_policy.py
index cdc1c2f0c36..2b906a59202 100644
--- a/studio/backend/tests/test_diffusion_auto_policy.py
+++ b/studio/backend/tests/test_diffusion_auto_policy.py
@@ -152,6 +152,40 @@ def test_estimate_nvfp4_is_smaller_than_int8():
assert nvfp4.steady_transformer_mib < int8.steady_transformer_mib
+def test_an_nvfp4_policy_base_is_sized_by_the_policy_not_by_whole_model_nvfp4():
+ from core.inference.diffusion_auto_policy import (
+ _MIB_PER_GB,
+ _POLICY_STEADY_FACTOR,
+ _QUANT_STEADY_FACTOR,
+ policy_steady_factor,
+ )
+
+ transformer_gb = ap._FAMILY_BF16_GB["z-image"][0]
+ policy = estimate_dense_quant(_fam("z-image"), "nvfp4", base_repo = "Tongyi-MAI/Z-Image-Turbo")
+ assert policy is not None
+ assert policy.steady_transformer_mib == int(
+ transformer_gb * _POLICY_STEADY_FACTOR["zimg_rg76_v1"] * _MIB_PER_GB
+ )
+ whole_model = int(transformer_gb * _QUANT_STEADY_FACTOR["nvfp4"] * _MIB_PER_GB)
+ assert policy.steady_transformer_mib > whole_model
+ for base in (None, "some-org/Z-Image-Fork"):
+ plain = estimate_dense_quant(_fam("z-image"), "nvfp4", base_repo = base)
+ assert plain is not None and plain.steady_transformer_mib == whole_model, base
+ kontext = estimate_dense_quant(
+ _fam("flux.1-kontext"), "nvfp4", base_repo = "black-forest-labs/FLUX.1-Kontext-dev"
+ )
+ assert kontext is not None
+ assert kontext.steady_transformer_mib == int(
+ ap._FAMILY_BF16_GB["flux.1-kontext"][0] * _QUANT_STEADY_FACTOR["nvfp4"] * _MIB_PER_GB
+ )
+ assert policy_steady_factor("flux.1-kontext", "black-forest-labs/FLUX.1-Kontext-dev") is None
+ fp8 = estimate_dense_quant(_fam("z-image"), "fp8", base_repo = "Tongyi-MAI/Z-Image-Turbo")
+ assert fp8 is not None
+ assert fp8.steady_transformer_mib == int(
+ transformer_gb * _QUANT_STEADY_FACTOR["fp8"] * _MIB_PER_GB
+ )
+
+
def test_estimate_unknown_family_or_scheme_returns_none():
assert estimate_dense_quant(_fam("not-a-family"), "int8") is None
assert estimate_dense_quant(_fam("z-image"), "q4_k") is None
@@ -169,7 +203,9 @@ def _patch_selector(
monkeypatch.setattr(tq, "dense_transformer_supported", lambda target: supported)
monkeypatch.setattr(
- tq, "select_transformer_quant_scheme", lambda target, req, family = None: scheme
+ tq,
+ "select_transformer_quant_scheme",
+ lambda target, req, family = None, **_kw: scheme,
)
import core.inference.diffusion_prequant as pq
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index 4b3f329c6c4..2a02c35e608 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -3599,7 +3599,7 @@ def test_dense_quant_pulls_the_transformer_from_the_mirror(monkeypatch):
return object()
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
monkeypatch.setattr(dmod, "resolve_prequant_source", lambda fam, scheme, **kw: None)
monkeypatch.setattr(dmod, "quantize_transformer", lambda pipe, target, **kw: "fp8")
@@ -4183,7 +4183,7 @@ def _stub_dense_quant(monkeypatch, *, scheme = "fp8"):
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
# Resolve the scheme without the GPU smoke probe, and configure no pre-quant checkpoint so the dense materialise+quantise branch runs.
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: scheme
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: scheme
)
monkeypatch.setattr(dmod, "resolve_prequant_source", lambda fam, scheme, **kw: None)
@@ -4395,7 +4395,7 @@ def test_transformer_quant_prequant_path_engaged(fake_runtime, tmp_path, monkeyp
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
monkeypatch.setattr(dmod, "resolve_prequant_source", lambda fam, scheme, **kw: object())
prequant_obj = object()
@@ -4636,7 +4636,7 @@ def _stub_declining_dense_quant(backend, monkeypatch):
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
monkeypatch.setattr(dmod, "resolve_prequant_source", lambda fam, scheme, **kw: None)
@@ -4981,7 +4981,7 @@ def test_dense_quant_skipped_when_dense_transformer_does_not_fit(
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
# A scheme resolves and there is no prequant, so the dense-fit re-check runs against a will-not-fit dense transformer.
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
monkeypatch.setattr(dmod, "resolve_prequant_source", lambda fam, scheme, **kw: None)
monkeypatch.setattr(
@@ -5026,7 +5026,7 @@ def test_dense_quant_prequant_proceeds_but_forbids_dense_fallback(
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
# usable_ (not resolve_): the re-check only honours a source the loader would accept, so the fake presents a usable one.
monkeypatch.setattr(dmod, "usable_prequant_source", lambda fam, scheme, **kw: "prequant/path")
@@ -5067,6 +5067,118 @@ def test_dense_quant_prequant_proceeds_but_forbids_dense_fallback(
assert attempted == [False] # ...fast path still attempted, dense fallback forbidden
+ "unreachable,expected_mib,expected_fallback",
+ [
+ (("fp8",), 28_561, True),
+ ((), 22_930, False),
+ ],
+)
+def test_dense_quant_replan_sizes_an_unreachable_prequant_as_dense(
+ fake_runtime,
+ tmp_path,
+ monkeypatch,
+ allow_precision_fallback,
+ unreachable,
+ expected_mib,
+ expected_fallback,
+):
+ import dataclasses
+
+ from core.inference import diffusion as dmod
+
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
+ )
+
+ def _candidate(*, force_dense = False, **_kw):
+ if force_dense:
+ return types.SimpleNamespace(
+ transient_transformer_mib = 28_561, companions_mib = 1, prequant = False, scheme = "fp8"
+ )
+ return types.SimpleNamespace(
+ transient_transformer_mib = 22_930, companions_mib = 1, prequant = True, scheme = "fp8"
+ )
+
+ monkeypatch.setattr(dmod, "resolve_dense_quant_candidate", _candidate)
+ sized: list = []
+ orig_plan = DiffusionBackend._plan_memory
+
+ def spy_plan(
+ self,
+ *a,
+ transformer_resident_override_mib = None,
+ **k,
+ ):
+ real = orig_plan(
+ self, *a, transformer_resident_override_mib = transformer_resident_override_mib, **k
+ )
+ if transformer_resident_override_mib is None:
+ return dataclasses.replace(real, offload_policy = "model")
+ sized.append(transformer_resident_override_mib)
+ return dataclasses.replace(real, offload_policy = "none")
+
+ monkeypatch.setattr(DiffusionBackend, "_plan_memory", spy_plan)
+ attempted = []
+
+ def fake_dense_load(self, *a, **k):
+ attempted.append(k.get("allow_dense_fallback"))
+ raise RuntimeError("test: stop after reaching the fast path")
+
+ monkeypatch.setattr(DiffusionBackend, "_load_dense_quant_pipeline", fake_dense_load)
+ (tmp_path / "m.gguf").write_bytes(b"x")
+ _load_m(backend, tmp_path, transformer_quant = "fp8", _prequant_unreachable = unreachable)
+ assert sized == [expected_mib]
+ assert attempted == [expected_fallback]
+
+
+def test_dense_quant_unreachable_prequant_does_not_skip_the_dense_decline(
+ fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
+):
+ from core.inference import diffusion as dmod
+
+ backend = DiffusionBackend()
+ _force_cuda_target(backend, monkeypatch)
+ monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
+ )
+ monkeypatch.setattr(dmod, "usable_prequant_source", lambda fam, scheme, **kw: "prequant/path")
+ monkeypatch.setattr(
+ DiffusionBackend,
+ "_dense_transformer_resident_bytes",
+ staticmethod(lambda base, staged_dir = None: 999 * 1024**3),
+ )
+ orig_plan = DiffusionBackend._plan_memory
+
+ def spy_plan(
+ self,
+ *a,
+ transformer_resident_override_mib = None,
+ **k,
+ ):
+ if transformer_resident_override_mib is not None and self is backend:
+ return types.SimpleNamespace(offload_policy = "model")
+ return orig_plan(self, *a, **k)
+
+ monkeypatch.setattr(DiffusionBackend, "_plan_memory", spy_plan)
+ attempted = []
+
+ def fake_dense_load(self, *a, **k):
+ attempted.append(k.get("allow_dense_fallback"))
+ return None, None
+
+ monkeypatch.setattr(DiffusionBackend, "_load_dense_quant_pipeline", fake_dense_load)
+ (tmp_path / "m.gguf").write_bytes(b"x")
+ status = _load_m(backend, tmp_path, transformer_quant = "fp8", _prequant_unreachable = ("fp8",))
+ assert attempted == []
+ assert status["transformer_quant"] is None
+ assert _FakeTransformer.last["path"] # the GGUF build loaded
+
+
def test_dense_quant_replan_retries_once_on_transient_free_undercount(
fake_runtime, tmp_path, monkeypatch, allow_precision_fallback
):
@@ -5079,7 +5191,7 @@ def test_dense_quant_replan_retries_once_on_transient_free_undercount(
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "int8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "int8"
)
monkeypatch.setattr(
dmod,
@@ -5143,7 +5255,7 @@ def test_dense_quant_replan_no_retry_when_capacity_truly_short(
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "int8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "int8"
)
monkeypatch.setattr(
dmod,
@@ -5192,7 +5304,7 @@ def _decline_dense_quant(backend, monkeypatch, tmp_path):
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "int8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "int8"
)
monkeypatch.setattr(
dmod,
@@ -5286,7 +5398,7 @@ def test_dense_quant_lora_bake_attaches_before_quantize(fake_runtime, monkeypatc
backend = DiffusionBackend()
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "int8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "int8"
)
prequant_consulted = []
monkeypatch.setattr(
@@ -5551,7 +5663,7 @@ def test_dense_quant_unusable_prequant_path_runs_dense_refit(
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
# The real usable_prequant_source refuses a non-allowlisted path (tested elsewhere); None pins that outcome here.
monkeypatch.setattr(dmod, "usable_prequant_source", lambda fam, scheme, **kw: None)
@@ -5602,7 +5714,7 @@ def test_transformer_quant_unsupported_scheme_skips_dense_download(
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: None
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: None
)
monkeypatch.setattr(dmod, "resolve_prequant_source", lambda fam, scheme, **kw: None)
@@ -5771,7 +5883,7 @@ def _stub_hosted_prequant(monkeypatch, *, cached: bool):
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
monkeypatch.setattr(dmod, "usable_prequant_source", lambda fam, scheme, **kw: _HOSTED_PREQUANT)
monkeypatch.setattr(dmod, "prequant_checkpoint_cached", lambda source, **kw: cached)
@@ -5917,7 +6029,7 @@ def test_the_dense_builder_skips_the_prequant_only_for_a_real_bake(
consulted: list = []
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
monkeypatch.setattr(
dmod, "resolve_prequant_source", lambda *a, **k: consulted.append(1) or None
@@ -6420,6 +6532,60 @@ def test_status_reports_the_dense_build_when_it_replaced_the_gguf(
assert backend.status()["transformer_quant"] == "fp8"
+def test_status_names_the_nvfp4_kernel_backend_that_actually_ran():
+ from types import SimpleNamespace
+
+ import core.inference.diffusion as dmod
+
+ class _FlashInferLinear:
+ a_gsf = 1.0
+
+ _FlashInferLinear.__name__ = "NVFP4FlashInferLinear"
+
+ def _state(quant, modules, **kw):
+ denoiser = SimpleNamespace(modules = lambda: iter(modules), **kw)
+ return SimpleNamespace(
+ transformer_quant = quant,
+ pipe = SimpleNamespace(transformer = denoiser),
+ family = SimpleNamespace(denoiser_attr = "transformer"),
+ )
+
+ assert dmod._transformer_quant_backend(_state("nvfp4", [_FlashInferLinear()])) == "flashinfer"
+ assert dmod._transformer_quant_backend(_state("nvfp4", [object()])) == "torchao"
+ assert (
+ dmod._transformer_quant_backend(
+ _state("nvfp4", [object()], _unsloth_nvfp4_backend = "flashinfer")
+ )
+ == "flashinfer"
+ )
+ for scheme in ("fp8", "int8", "mxfp8", None):
+ assert dmod._transformer_quant_backend(_state(scheme, [_FlashInferLinear()])) is None
+
+ def _boom():
+ raise RuntimeError("no")
+
+ hostile = SimpleNamespace(
+ transformer_quant = "nvfp4",
+ pipe = SimpleNamespace(transformer = SimpleNamespace(modules = _boom)),
+ family = SimpleNamespace(denoiser_attr = "transformer"),
+ )
+ assert dmod._transformer_quant_backend(hostile) is None
+
+
+def test_the_unloaded_status_declares_the_quant_backend_key():
+ status = DiffusionBackend().status()
+ assert "transformer_quant_backend" in status
+ assert status["transformer_quant_backend"] is None
+
+
+def test_diffusion_status_response_declares_the_quant_backend():
+ from models.inference import DiffusionStatusResponse
+
+ resp = DiffusionStatusResponse(loaded = True, transformer_quant_backend = "flashinfer")
+ assert resp.model_dump()["transformer_quant_backend"] == "flashinfer"
+ assert DiffusionStatusResponse(loaded = True).model_dump()["transformer_quant_backend"] is None
+
+
def test_status_carries_no_gguf_variant_when_nothing_is_loaded():
# The unloaded payload must declare every key the loaded one does, or the row keeps the
# previous model's quant after an eject.
@@ -7016,7 +7182,7 @@ def test_dense_fit_check_runs_for_a_base_the_live_cache_root_does_not_hold(
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
monkeypatch.setattr(dmod, "usable_prequant_source", lambda fam, scheme, **kw: None)
dense_refit_ran = []
@@ -7059,7 +7225,7 @@ def test_the_dense_builder_reads_transformer_from_the_hub_id_not_the_staged_snap
from core.inference import diffusion as dmod
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
monkeypatch.setattr(dmod, "resolve_prequant_source", lambda *a, **k: None)
_no_cache(monkeypatch)
@@ -8458,7 +8624,7 @@ def test_qwen_edit_q6_auto_stays_gguf_but_explicit_quant_requests_dense_transfor
backend = DiffusionBackend()
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "int8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "int8"
)
monkeypatch.setattr(
dmod,
@@ -9655,7 +9821,7 @@ def test_auto_retries_a_lower_scheme_that_has_a_prequant(monkeypatch):
monkeypatch.setattr(
"core.inference.diffusion_transformer_quant.auto_scheme_candidates",
- lambda target, family = None: ("fp8", "mxfp8", "int8"),
+ lambda target, family = None, **_kw: ("fp8", "mxfp8", "int8"),
)
have = {"int8"}
monkeypatch.setattr(
@@ -9801,7 +9967,7 @@ def test_the_offload_retry_runs_when_the_auto_winner_had_no_candidate_at_all(
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
monkeypatch.setattr(dmod, "_uncached_prequant_repo", lambda *a, **k: None)
monkeypatch.setattr(
@@ -9877,7 +10043,7 @@ def test_the_resident_retry_runs_when_the_dense_shards_were_never_staged(
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
monkeypatch.setattr(dmod, "_uncached_prequant_repo", lambda *a, **k: None)
# The winner has no usable checkpoint, and no shards were staged, so no dense build either.
@@ -9947,7 +10113,7 @@ def test_the_resident_retry_declines_a_rung_that_does_not_plan_resident(
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
monkeypatch.setattr(dmod, "_uncached_prequant_repo", lambda *a, **k: None)
monkeypatch.setattr(dmod, "usable_prequant_source", lambda *a, **k: None)
@@ -11182,7 +11348,7 @@ def test_dense_quant_candidate_replan_prices_the_streamed_encoder_tier(
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "int8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "int8"
)
monkeypatch.setattr(
dmod,
@@ -11452,7 +11618,7 @@ def test_unified_memory_declines_a_prequant_that_outweighs_the_gguf(
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
# A hosted pre-cast checkpoint IS available, which is what skips the dense-size check.
monkeypatch.setattr(dmod, "usable_prequant_source", lambda *a, **kw: "unsloth/Z-Image-FP8")
@@ -11487,7 +11653,7 @@ def test_unified_memory_keeps_a_prequant_that_fits(fake_runtime, monkeypatch, tm
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
monkeypatch.setattr(dmod, "usable_prequant_source", lambda *a, **kw: "unsloth/Z-Image-FP8")
monkeypatch.setattr(
@@ -11706,7 +11872,7 @@ def test_an_unsupported_host_is_not_told_its_shards_are_unstaged(
# A scheme the device rules out (torchao stub, family deny list) is the same case.
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: None
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: None
)
backend2 = DiffusionBackend()
_force_cuda_target(backend2, monkeypatch)
@@ -11721,7 +11887,7 @@ def test_an_unsupported_host_is_not_told_its_shards_are_unstaged(
# ... and a host that CAN run it still gets the accurate unstaged-shards decline.
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: "fp8"
)
_stub_hosted_prequant(monkeypatch, cached = False)
monkeypatch.setattr(dmod, "usable_prequant_source", lambda fam, scheme, **kw: None)
@@ -11773,6 +11939,39 @@ def test_generation_in_flight_never_builds_a_backend(fake_runtime, monkeypatch):
assert diffusion_mod.generation_in_flight() is False
+def test_the_download_plan_resolves_the_same_nvfp4_rung_the_load_does(monkeypatch):
+ from types import SimpleNamespace
+
+ import core.inference.diffusion as dmod
+ from core.inference import diffusion_nvfp4_ops as ops
+ from core.inference import diffusion_transformer_quant as tq
+
+ fam = detect_family("black-forest-labs/FLUX.1-schnell")
+ assert fam is not None and fam.name == "flux.1"
+ base = "black-forest-labs/FLUX.1-schnell"
+
+ monkeypatch.setattr(tq, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(tq, "_capability", lambda: (10, 0))
+ monkeypatch.setattr(tq, "_is_consumer_gpu", lambda device = None: False)
+ monkeypatch.setattr(
+ tq,
+ "_scheme_supported",
+ lambda scheme, device, unproven_ok = False: scheme not in ("int8", "fp8"),
+ )
+ monkeypatch.setattr(dmod, "prequant_checkpoint_cached", lambda source, **kw: False)
+ monkeypatch.setattr(ops, "select_nvfp4_backend", lambda device = None: "flashinfer")
+
+ target = SimpleNamespace(device = "cuda", dtype = None)
+ assert (
+ dmod._planned_quant_scheme(fam, target, "auto", base_repo = base, prequant_path = None)
+ == "nvfp4"
+ )
+ assert (
+ dmod._uncached_prequant_repo(fam, target, "auto", base_repo = base, prequant_path = None)
+ == "unsloth/FLUX.1-schnell-NVFP4"
+ )
+
+
# Pipeline dense quantisation.
@@ -11811,7 +12010,7 @@ def _stub_pipeline_dense_quant(
_force_cuda_target(backend, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **kw: "fp8"
)
real_init = _FakePipe.__init__
@@ -12714,7 +12913,7 @@ def _stub_nvidia_offload_host(
calls = _stub_pipeline_dense_quant(backend, monkeypatch, engages = engages)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: mode
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_: mode
)
monkeypatch.setattr(tq, "native_quant_host", lambda target: False)
monkeypatch.setattr(tq, "native_offload_host", lambda target: True)
@@ -13174,7 +13373,7 @@ def _gguf_candidate_backend(monkeypatch, tmp_path, *, initial_policy, candidate_
backend = _cuda_backend(tmp_path, monkeypatch)
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "int8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_: "int8"
)
monkeypatch.setattr(dmod, "usable_prequant_source", lambda fam, scheme, **kw: "prequant/path")
monkeypatch.setattr(
diff --git a/studio/backend/tests/test_diffusion_convrot.py b/studio/backend/tests/test_diffusion_convrot.py
index fa09bb0f5a5..b8b332ab4ac 100644
--- a/studio/backend/tests/test_diffusion_convrot.py
+++ b/studio/backend/tests/test_diffusion_convrot.py
@@ -336,7 +336,11 @@ def test_format_tag_follows_the_rotation():
assert pq.prequant_format_for({"scheme": "int8"}) == pq.PREQUANT_FORMAT
assert pq.prequant_format_for(_meta(["a"])) == pq.PREQUANT_FORMAT_ROTATED
assert pq.PREQUANT_FORMAT_ROTATED != pq.PREQUANT_FORMAT
- assert set(pq.PREQUANT_FORMATS) == {pq.PREQUANT_FORMAT, pq.PREQUANT_FORMAT_ROTATED}
+ assert set(pq.PREQUANT_FORMATS) == {
+ pq.PREQUANT_FORMAT,
+ pq.PREQUANT_FORMAT_ROTATED,
+ pq.PREQUANT_FORMAT_POLICY,
+ }
@pytest.mark.parametrize(
diff --git a/studio/backend/tests/test_diffusion_cuda_graph.py b/studio/backend/tests/test_diffusion_cuda_graph.py
index b02100b7875..f82c9bbe6f0 100644
--- a/studio/backend/tests/test_diffusion_cuda_graph.py
+++ b/studio/backend/tests/test_diffusion_cuda_graph.py
@@ -828,6 +828,108 @@ def test_real_cuda_capture_replays_bit_identically():
cg.uninstall_all([handle])
+class _FakeNVFP4Linear:
+ """Named exactly as the real class, since ``is_nvfp4_flashinfer_linear`` gates on the NAME."""
+
+ def __init__(
+ self,
+ *,
+ baked = True,
+ in_features = 4,
+ out_features = 8,
+ ):
+ self.a_gsf = 1.0
+ self.in_features = in_features
+ self.out_features = out_features
+ if baked is not None:
+ self.activation_scales_baked = bool(baked)
+
+
+_FakeNVFP4Linear.__name__ = "NVFP4FlashInferLinear"
+
+
+class _NVFP4DiT(_FakeDiT):
+ """A denoiser whose module tree holds the given NVFP4 linears."""
+
+ def __init__(self, layers):
+ super().__init__()
+ self._layers = list(layers)
+
+ def named_modules(self):
+ yield "", self
+ for name, layer in self._layers:
+ yield name, layer
+
+
+def record_prewarm(monkeypatch):
+ from core.inference import diffusion_nvfp4_linear as nl
+
+ calls: list = []
+ monkeypatch.setattr(
+ nl,
+ "nvfp4_prewarm",
+ lambda transformer, shapes, **kwargs: calls.append((transformer, tuple(shapes))) or 0,
+ )
+ return calls
+
+
+def test_capture_prewarms_the_nvfp4_layers_before_the_warmup(stub_torch, record_prewarm):
+ module = _NVFP4DiT([("blocks.0.attention.to_q", _FakeNVFP4Linear())])
+ handle = _armed(module)
+ handle(_t((2, 8, 4)), timestep = _t((1,)), return_dict = False)
+
+ assert len(record_prewarm) == 1
+ tuned_module, shapes = record_prewarm[0]
+ assert tuned_module is module
+ assert 1 in shapes and 16 in shapes
+ assert handle.stats["captures"] == 1
+ assert handle.poisoned is False
+
+
+def test_capture_does_not_prewarm_a_model_without_nvfp4_layers(stub_torch, record_prewarm):
+ handle = _armed()
+ handle(_t(), timestep = _t((1,)), return_dict = False)
+ assert record_prewarm == []
+ assert handle.stats["captures"] == 1
+
+
+def test_unbaked_activation_scales_poison_the_capture(stub_torch, record_prewarm):
+ module = _NVFP4DiT(
+ [
+ ("blocks.0.attention.to_q", _FakeNVFP4Linear()),
+ ("blocks.1.attention.to_q", _FakeNVFP4Linear(baked = False)),
+ ]
+ )
+ handle = _armed(module)
+ out = handle(_t(), timestep = _t((1,)), return_dict = False)
+
+ assert handle.poisoned is True
+ assert handle.stats["captures"] == 0
+ assert "unbaked activation scales" in handle.capture_error["msg"]
+ assert "blocks.1.attention.to_q" in handle.capture_error["msg"]
+ assert record_prewarm == []
+ assert module.calls == 1 # the eager fallback only
+ assert out[0].value == ("out", 1)
+
+
+def test_a_layer_that_cannot_answer_counts_as_unbaked(stub_torch, record_prewarm):
+ """Fail closed: a layer from some other build with no flag is not assumed to be baked."""
+ module = _NVFP4DiT([("blocks.0.attention.to_q", _FakeNVFP4Linear(baked = None))])
+ handle = _armed(module)
+ handle(_t(), timestep = _t((1,)), return_dict = False)
+ assert handle.poisoned is True
+ assert record_prewarm == []
+
+
+def test_prewarm_token_counts_are_bounded_and_sorted(stub_torch):
+ counts = cg._prewarm_token_counts([_t((2, 8, 4)), _t((1,)), _t((4, 4))])
+ assert counts[0] == 1 # the modulation M is always tuned
+ assert counts == tuple(sorted(set(counts)))
+ assert set(counts) >= {1, 4, 16}
+ assert len(cg._prewarm_token_counts([_t((n, 4)) for n in range(2, 40)])) <= 8
+
+
_RESOLVED_ON = {
"cuda_graph": {
"value": "on",
diff --git a/studio/backend/tests/test_diffusion_inference_info.py b/studio/backend/tests/test_diffusion_inference_info.py
index 3bc453a4958..8bf21b3556d 100644
--- a/studio/backend/tests/test_diffusion_inference_info.py
+++ b/studio/backend/tests/test_diffusion_inference_info.py
@@ -53,3 +53,30 @@ def test_nvfp4_is_below_int8():
for info in family_inference_infos():
estimated = info["estimated_resident_gb"]
assert estimated["nvfp4"] < estimated["int8"], info["family"]
+
+
+def test_a_policy_family_reports_its_policy_nvfp4_footprint():
+ from core.inference.diffusion_auto_policy import _POLICY_STEADY_FACTOR, policy_steady_factor
+ infos = {info["family"]: info for info in family_inference_infos()}
+ for family, policy_id in (
+ ("z-image", "zimg_rg76_v1"),
+ ("flux.1", "flux_r420_v1"),
+ ("qwen-image", "qwen_p02_v1"),
+ ("qwen-image-2.1", "qwen21_r020_v1"),
+ ):
+ transformer, text_encoders, vae = _FAMILY_BF16_GB[family]
+ expected = round(transformer * _POLICY_STEADY_FACTOR[policy_id] + text_encoders + vae, 1)
+ assert infos[family]["estimated_resident_gb"]["nvfp4"] == expected, family
+ whole = round(transformer * _QUANT_STEADY_FACTOR["nvfp4"] + text_encoders + vae, 1)
+ assert expected > whole, family
+
+
+def test_a_family_without_a_policy_keeps_the_whole_model_factor():
+ from core.inference.diffusion_auto_policy import policy_steady_factor
+ infos = {info["family"]: info for info in family_inference_infos()}
+ for family in ("flux.1-kontext", "qwen-image-edit", "lumina-2"):
+ transformer, text_encoders, vae = _FAMILY_BF16_GB[family]
+ assert policy_steady_factor(family) is None, family
+ assert infos[family]["estimated_resident_gb"]["nvfp4"] == round(
+ transformer * _QUANT_STEADY_FACTOR["nvfp4"] + text_encoders + vae, 1
+ ), family
diff --git a/studio/backend/tests/test_diffusion_more_families.py b/studio/backend/tests/test_diffusion_more_families.py
index b562563b6f7..c92bf2c9609 100644
--- a/studio/backend/tests/test_diffusion_more_families.py
+++ b/studio/backend/tests/test_diffusion_more_families.py
@@ -87,6 +87,24 @@ def test_flux1_krea_dev_generation_defaults():
assert default_generation_params("krea/Krea-2-Raw") == (52, 3.5)
+def test_flux_dev_and_krea_do_not_inherit_the_schnell_nvfp4_checkpoint():
+ from core.inference.diffusion_families import family_prequant_repo
+
+ fam = detect_family("black-forest-labs/FLUX.1-schnell")
+ assert fam is not None and fam.name == "flux.1"
+ assert (
+ family_prequant_repo(fam, "nvfp4", base_repo = "black-forest-labs/FLUX.1-schnell")
+ == "unsloth/FLUX.1-schnell-NVFP4"
+ )
+ for base, fp8_repo in (
+ ("black-forest-labs/FLUX.1-dev", "unsloth/FLUX.1-dev-FP8"),
+ ("black-forest-labs/FLUX.1-Krea-dev", "unsloth/FLUX.1-Krea-dev-FP8"),
+ ):
+ assert family_prequant_repo(fam, "nvfp4", base_repo = base) is None
+ assert family_prequant_repo(fam, "fp8", base_repo = base) == fp8_repo
+ assert family_prequant_repo(fam, "int8", base_repo = base) == fp8_repo
+
+
def test_flux2_klein_generation_defaults_distinguish_base_from_distilled():
for size in ("4B", "9B"):
assert default_generation_params(f"unsloth/FLUX.2-klein-base-{size}") == (50, 4.0)
diff --git a/studio/backend/tests/test_diffusion_nvfp4_backend.py b/studio/backend/tests/test_diffusion_nvfp4_backend.py
new file mode 100644
index 00000000000..85f05662927
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_nvfp4_backend.py
@@ -0,0 +1,431 @@
+# 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 ast
+import pathlib
+
+import pytest
+
+from core.inference import diffusion_nvfp4_ops as ops
+
+_INFERENCE_DIR = pathlib.Path(ops.__file__).resolve().parent
+
+
[email protected](autouse = True)
+def _clean_backend_state(monkeypatch):
+ monkeypatch.delenv(ops.NVFP4_BACKEND_ENV, raising = False)
+ ops.reset_preflight_cache()
+ yield
+ ops.reset_preflight_cache()
+
+
+def _stub(
+ monkeypatch,
+ *,
+ available = True,
+ capability = (10, 0),
+ preflight_ok = True,
+):
+ monkeypatch.setattr(
+ ops,
+ "_flashinfer_available",
+ lambda: (available, "0.6.6" if available else "ImportError: no flashinfer"),
+ )
+ monkeypatch.setattr(ops, "_device_capability", lambda device = None: capability)
+ monkeypatch.setattr(
+ ops,
+ "nvfp4_preflight",
+ lambda device = None, **kw: {
+ "ok": preflight_ok,
+ "capability": capability,
+ "name": "stub",
+ "reason": "ok" if preflight_ok else "JIT build failed",
+ },
+ )
+
+
+def test_auto_selects_flashinfer_when_import_capability_and_preflight_all_pass(monkeypatch):
+ _stub(monkeypatch)
+ assert ops.select_nvfp4_backend(0) == "flashinfer"
+ assert "preflight ok" in ops.nvfp4_backend_reason(0)
+
+
[email protected]("capability", [(10, 0), (10, 3), (12, 0)])
+def test_every_capability_in_the_flashinfer_set_selects_it(monkeypatch, capability):
+ _stub(monkeypatch, capability = capability)
+ assert ops.select_nvfp4_backend(0) == "flashinfer"
+
+
[email protected]("capability", [(8, 9), (9, 0), (12, 1)])
+def test_a_capability_outside_the_set_falls_to_torchao_and_names_it(monkeypatch, capability):
+ _stub(monkeypatch, capability = capability)
+ assert ops.select_nvfp4_backend(0) == "torchao"
+ assert "sm_%d%d" % capability in ops.nvfp4_backend_reason(0)
+
+
+def test_no_cuda_capability_is_torchao(monkeypatch):
+ _stub(monkeypatch, capability = None)
+ assert ops.select_nvfp4_backend() == "torchao"
+ assert "capability" in ops.nvfp4_backend_reason()
+
+
+def test_import_failure_is_torchao_which_is_how_windows_resolves(monkeypatch):
+ _stub(monkeypatch, available = False)
+ assert ops.select_nvfp4_backend(0) == "torchao"
+ assert "flashinfer unavailable" in ops.nvfp4_backend_reason(0)
+
+
+def test_a_failed_preflight_is_torchao_even_on_a_supported_capability(monkeypatch):
+ _stub(monkeypatch, preflight_ok = False)
+ assert ops.select_nvfp4_backend(0) == "torchao"
+ assert "preflight failed: JIT build failed" in ops.nvfp4_backend_reason(0)
+
+
+def test_explicit_torchao_never_probes(monkeypatch):
+ def _boom(*a, **kw): # pragma: no cover - reached only on a regression
+ raise AssertionError("the probe ran under UNSLOTH_NVFP4_BACKEND=torchao")
+
+ monkeypatch.setattr(ops, "_flashinfer_available", _boom)
+ monkeypatch.setattr(ops, "nvfp4_preflight", _boom)
+ monkeypatch.setenv(ops.NVFP4_BACKEND_ENV, "torchao")
+ assert ops.select_nvfp4_backend(0) == "torchao"
+ assert ops.nvfp4_backend_reason(0).endswith("=torchao")
+
+
+def test_explicit_flashinfer_that_fails_a_check_warns_and_uses_torchao(monkeypatch):
+ _stub(monkeypatch, preflight_ok = False)
+ monkeypatch.setenv(ops.NVFP4_BACKEND_ENV, "flashinfer")
+ with pytest.warns(RuntimeWarning, match = "preflight failed"):
+ assert ops.select_nvfp4_backend(0) == "torchao"
+
+
+def test_explicit_flashinfer_that_passes_warns_about_nothing(monkeypatch):
+ _stub(monkeypatch)
+ monkeypatch.setenv(ops.NVFP4_BACKEND_ENV, "flashinfer")
+ import warnings
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ assert ops.select_nvfp4_backend(0) == "flashinfer"
+
+
[email protected]("value", ["", " ", "cutlass", "TorchAO nope"])
+def test_an_unrecognised_env_value_reads_as_auto(monkeypatch, value):
+ _stub(monkeypatch)
+ monkeypatch.setenv(ops.NVFP4_BACKEND_ENV, value)
+ assert ops.nvfp4_backend_env() == "auto"
+ assert ops.select_nvfp4_backend(0) == "flashinfer"
+
+
[email protected]("value", ["FlashInfer", " flashinfer "])
+def test_the_env_value_is_case_and_space_insensitive(monkeypatch, value):
+ _stub(monkeypatch, preflight_ok = False)
+ monkeypatch.setenv(ops.NVFP4_BACKEND_ENV, value)
+ with pytest.warns(RuntimeWarning):
+ assert ops.select_nvfp4_backend(0) == "torchao"
+
+
+def _dotted(node: ast.AST) -> str:
+ parts: list[str] = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if isinstance(node, ast.Name):
+ parts.append(node.id)
+ return ".".join(reversed(parts))
+
+
+def _is_guard(node: ast.AST) -> bool:
+ """``torch.cuda.device(...)`` or the module's own ``_device_guard(...)`` alias."""
+ if not isinstance(node, ast.Call):
+ return False
+ name = _dotted(node.func)
+ return name.endswith("torch.cuda.device") or name.endswith("_device_guard")
+
+
+def _is_launch(node: ast.Call) -> str:
+ name = _dotted(node.func)
+ if name.startswith("flashinfer.") or name.startswith("_fi."):
+ return name
+ if "torch.ops.unsloth_nvfp4" in name:
+ return name
+ return ""
+
+
+class _LaunchVisitor(ast.NodeVisitor):
+ """Records every launch whose lexical ancestry contains no device guard."""
+
+ def __init__(self) -> None:
+ self.depth = 0
+ self.unguarded: list[tuple[int, str]] = []
+
+ def _visit_with(self, node) -> None:
+ guarded = 0
+ for item in node.items:
+ self.visit(item.context_expr)
+ if _is_guard(item.context_expr):
+ guarded = 1
+ self.depth += guarded
+ for stmt in node.body:
+ self.visit(stmt)
+ self.depth -= guarded
+
+ visit_With = _visit_with
+ visit_AsyncWith = _visit_with
+
+ def visit_Call(self, node: ast.Call) -> None:
+ launch = _is_launch(node)
+ if launch and self.depth == 0:
+ self.unguarded.append((node.lineno, launch))
+ self.generic_visit(node)
+
+
+def _nvfp4_sources() -> list[pathlib.Path]:
+ return sorted(_INFERENCE_DIR.glob("diffusion_nvfp4_*.py"))
+
+
+def test_the_guard_visitor_catches_an_unguarded_launch():
+ tree = ast.parse(
+ "import flashinfer\n"
+ "def f(x):\n"
+ " with torch.cuda.device(x.device):\n"
+ " flashinfer.mm_fp4(x)\n"
+ " flashinfer.nvfp4_quantize(x)\n"
+ " torch.ops.unsloth_nvfp4.mm(x)\n"
+ )
+ visitor = _LaunchVisitor()
+ visitor.visit(tree)
+ assert [name for _, name in visitor.unguarded] == [
+ "flashinfer.nvfp4_quantize",
+ "torch.ops.unsloth_nvfp4.mm",
+ ]
+
+
+def test_every_flashinfer_launch_in_the_nvfp4_modules_sits_inside_a_device_guard():
+ sources = _nvfp4_sources()
+ assert sources, "no diffusion_nvfp4_*.py modules found to guard"
+ offences: list[str] = []
+ for path in sources:
+ visitor = _LaunchVisitor()
+ visitor.visit(ast.parse(path.read_text(encoding = "utf-8")))
+ offences += [
+ f"{path.name}:{line}: {name} outside torch.cuda.device"
+ for line, name in visitor.unguarded
+ ]
+ assert not offences, "\n".join(offences)
+
+
+def test_the_modules_never_set_the_current_stream():
+ for path in _nvfp4_sources():
+ assert "set_stream" not in path.read_text(encoding = "utf-8"), path.name
+
+
+ "m,k,n",
+ [
+ (1, 3072, 18432),
+ (1, 256, 15360),
+ (77, 3072, 3072),
+ (129, 256, 15360),
+ (512, 3072, 12288),
+ (4096, 3072, 3072),
+ (16384, 3072, 18432),
+ ],
+)
+def test_the_fake_impls_reproduce_the_flashinfer_allocation(m, k, n):
+ torch = pytest.importorskip("torch")
+
+ x = torch.empty((m, k), dtype = torch.bfloat16, device = "meta")
+ gsf = torch.empty((1,), dtype = torch.float32, device = "meta")
+ xq, x_sf = ops._quantize_fake(x, gsf)
+ cols = k // 16
+ total = ops._swizzled_sf_numel(m, cols, 128)
+
+ assert tuple(xq.shape) == (m, k // 2) and xq.dtype == torch.uint8
+ assert tuple(x_sf.shape) == (total // cols, cols) and x_sf.dtype == torch.uint8
+ assert x_sf.numel() == total
+ assert x_sf.shape[0] >= m
+
+ w = torch.empty((n, k // 2), dtype = torch.uint8, device = "meta")
+ w_sf = torch.empty(ops.sf_matrix_shape(n, cols), dtype = torch.uint8, device = "meta")
+ alpha = torch.empty((1,), dtype = torch.float32, device = "meta")
+ out = ops._mm_fake(xq, w, x_sf, w_sf, alpha, n, "cutlass")
+ assert tuple(out.shape) == (m, n) and out.dtype == torch.bfloat16
+
+
+def test_swizzled_numel_pads_rows_to_128_and_columns_to_4():
+ assert ops._swizzled_sf_numel(1, 16, 128) == 128 * 16
+ assert ops._swizzled_sf_numel(129, 16, 128) == 256 * 16
+ assert ops._swizzled_sf_numel(128, 17, 128) == 128 * 20
+ assert ops._swizzled_sf_numel(512, 192, 128) == 512 * 192
+
+
+def test_sf_matrix_shape_is_the_flat_buffer_reshaped():
+ assert ops.sf_matrix_shape(3072, 192) == (3072, 192)
+ assert ops.sf_matrix_shape(1, 16) == (128, 16)
+ assert ops.sf_matrix_shape(15360, 16) == (15360, 16)
+
+
+def test_register_ops_is_idempotent():
+ pytest.importorskip("torch")
+ import torch
+
+ ops.register_ops()
+ ops.register_ops()
+ assert hasattr(torch.ops.unsloth_nvfp4, "quantize")
+ assert hasattr(torch.ops.unsloth_nvfp4, "mm")
+
+
+def test_real_preflight_reports_ok_on_a_blackwell_card_with_flashinfer():
+ torch = pytest.importorskip("torch")
+ if not getattr(torch, "cuda", None) or not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ capability = tuple(torch.cuda.get_device_capability(0))
+ if capability not in ops.NVFP4_FLASHINFER_CAPS:
+ pytest.skip("sm_%d%d has no flashinfer NVFP4 kernels" % capability)
+ pytest.importorskip("flashinfer")
+
+ ops.reset_preflight_cache()
+ record = ops.nvfp4_preflight(0)
+ assert record["capability"] == capability
+ assert record["name"]
+ assert record["ok"] is True, record["reason"]
+ assert record["reason"] == "ok"
+ ops.nvfp4_preflight(0)
+ assert ops.nvfp4_preflight(0) == record
+ assert ops.select_nvfp4_backend(0) == "flashinfer"
+
+
+def _fake_blackwell(monkeypatch):
+ """Enough of ``torch.cuda`` for ``nvfp4_preflight`` to reach its probe on a masked-off host."""
+ torch = pytest.importorskip("torch")
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device = None: (10, 0))
+ monkeypatch.setattr(torch.cuda, "get_device_name", lambda device = None: "stub B200")
+ return torch
+
+
+def test_an_allocation_failure_is_answered_but_not_cached(monkeypatch):
+ torch = _fake_blackwell(monkeypatch)
+ calls: list = []
+
+ def _oom(dev):
+ calls.append(dev)
+ raise torch.cuda.OutOfMemoryError("CUDA out of memory. Tried to allocate 64.00 MiB")
+
+ monkeypatch.setattr(ops, "_preflight_probe", _oom)
+ first = ops.nvfp4_preflight(0)
+ assert first["ok"] is False
+ assert "out of memory" in first["reason"].lower()
+
+ monkeypatch.setattr(ops, "_preflight_probe", lambda dev: True)
+ second = ops.nvfp4_preflight(0)
+ assert second["ok"] is True
+ assert len(calls) == 1
+
+
+def test_a_host_property_failure_stays_cached(monkeypatch):
+ _fake_blackwell(monkeypatch)
+ calls: list = []
+
+ def _boom(dev):
+ calls.append(dev)
+ raise RuntimeError("JIT build failed")
+
+ monkeypatch.setattr(ops, "_preflight_probe", _boom)
+ assert ops.nvfp4_preflight(0)["ok"] is False
+
+ monkeypatch.setattr(ops, "_preflight_probe", lambda dev: True)
+ assert ops.nvfp4_preflight(0)["ok"] is False
+ assert len(calls) == 1
+
+
+def test_a_successful_probe_is_cached(monkeypatch):
+ _fake_blackwell(monkeypatch)
+ calls: list = []
+
+ def _ok(dev):
+ calls.append(dev)
+ return True
+
+ monkeypatch.setattr(ops, "_preflight_probe", _ok)
+ assert ops.nvfp4_preflight(0)["ok"] is True
+ assert ops.nvfp4_preflight(0)["ok"] is True
+ assert len(calls) == 1
+
+
+ "exc,transient",
+ [
+ (MemoryError(), True),
+ (RuntimeError("CUDA out of memory. Tried to allocate 64.00 MiB"), True),
+ (RuntimeError("cudaErrorMemoryAllocation"), True),
+ (RuntimeError("JIT build failed"), False),
+ (ImportError("no flashinfer"), False),
+ ],
+)
+def test_only_allocation_failures_read_as_transient(exc, transient):
+ assert ops._transient_preflight_failure(exc) is transient
+
+
+def test_an_unprewarmed_gemm_shape_autotunes_on_its_first_eager_call_only(monkeypatch):
+ import contextlib
+ import sys
+ import types
+
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_nvfp4_linear as nl
+
+ state = {"tuning": False, "capturing": False}
+ calls = []
+
+ @contextlib.contextmanager
+ def _autotune(flag = True):
+ state["tuning"] = flag
+ try:
+ yield
+ finally:
+ state["tuning"] = False
+
+ def _mm_fp4(
+ a,
+ b,
+ a_sf,
+ b_sf,
+ alpha,
+ dtype,
+ out = None,
+ backend = None,
+ ):
+ calls.append((a.shape[0], state["tuning"]))
+ return out
+
+ 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(torch.cuda, "is_current_stream_capturing", lambda: state["capturing"])
+ nl.reset_tuned_shapes()
+ try:
+ wq = torch.zeros(64, 16, dtype = torch.uint8) # N = 64, K = 32
+
+ def _mm(m):
+ xq = torch.zeros(m, 16, dtype = torch.uint8)
+ ops._mm_impl(xq, wq, None, wq, None, 64, "cutlass")
+
+ nl._TUNED_SHAPES.add((1, 32, 64)) # what the loader's M = 1 prewarm leaves behind
+ _mm(1)
+ _mm(4352)
+ _mm(4352)
+ state["capturing"] = True
+ _mm(8192)
+ assert calls == [(1, False), (4352, True), (4352, False), (8192, False)]
+ assert (4352, 32, 64) in nl._TUNED_SHAPES
+ assert (8192, 32, 64) not in nl._TUNED_SHAPES
+ finally:
+ nl.reset_tuned_shapes()
diff --git a/studio/backend/tests/test_diffusion_nvfp4_gate.py b/studio/backend/tests/test_diffusion_nvfp4_gate.py
new file mode 100644
index 00000000000..01cd2fc5ae3
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_nvfp4_gate.py
@@ -0,0 +1,238 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The checked-in NVFP4 gate record, and the verdict the runtime reads out of it."""
+
+from __future__ import annotations
+
+import dataclasses
+import json
+
+import pytest
+
+import core.inference.diffusion_nvfp4_policy as policy_mod
+from core.inference.diffusion_families import canonical_base, detect_family
+from core.inference.diffusion_nvfp4_gate import (
+ GATE_RECORD_PATH,
+ GATE_RECORD_VERSION,
+ RECORD_KEY_FIELDS,
+ load_gate_records,
+ nvfp4_gate_backend,
+ nvfp4_gate_backends,
+ nvfp4_gate_passed,
+ nvfp4_gate_record,
+)
+from core.inference.diffusion_nvfp4_policy import policy_by_id, resolve_policy
+
+ZIMAGE_BASE = "Tongyi-MAI/Z-Image-Turbo"
+
+
+def _record(**overrides):
+ record = {
+ "family": "z-image",
+ "base_repo": ZIMAGE_BASE,
+ "policy_id": "zimg_rg76_v1",
+ "policy_version": 1,
+ "checkpoint_sha256": "a" * 64,
+ "repo_id": "unsloth/Z-Image-Turbo-NVFP4",
+ "filename": "Z-Image-Turbo-NVFP4.pt",
+ "gptq": False,
+ "all_pass": True,
+ "num_pairs": 28,
+ "num_passed": 28,
+ "backend": "flashinfer",
+ }
+ record.update(overrides)
+ return record
+
+
+def _gate_file(
+ tmp_path,
+ *records,
+ version = GATE_RECORD_VERSION,
+):
+ path = tmp_path / "nvfp4_gate_record.json"
+ path.write_text(json.dumps({"version": version, "records": list(records)}), encoding = "utf-8")
+ return path
+
+
+def test_the_shipped_gate_record_parses_and_declares_this_schema():
+ document = json.loads(GATE_RECORD_PATH.read_text(encoding = "utf-8"))
+ assert document["version"] == GATE_RECORD_VERSION
+ assert isinstance(document["records"], list)
+ assert len(load_gate_records()) == len(document["records"])
+
+
+def test_every_shipped_record_names_a_policy_this_commit_resolves():
+ for record in load_gate_records():
+ policy = policy_by_id(record["policy_id"])
+ assert policy is not None, record["policy_id"]
+ assert int(record["policy_version"]) == int(policy.version), record
+ resolved = resolve_policy(record["family"], record["base_repo"])
+ assert resolved is not None and resolved.policy_id == policy.policy_id, record
+ assert set(RECORD_KEY_FIELDS) <= set(record), record
+
+
+def test_every_shipped_record_names_a_checkpoint_the_family_hosts():
+ records = load_gate_records()
+ if not records:
+ pytest.skip("no gate records yet: nvfp4 is out of the auto ladder for every family")
+ for record in records:
+ fam = detect_family(record["base_repo"])
+ assert fam is not None, record
+ hosted = {repo.lower() for _scheme, repo in fam.prequant_repos}
+ hosted.update(repo.lower() for _base, _scheme, repo in fam.prequant_variant_repos)
+ assert str(record["repo_id"]).lower() in hosted, record
+ assert len(str(record["checkpoint_sha256"])) == 64, record
+
+
+def test_the_shipped_record_leaves_every_family_ungated():
+ if load_gate_records():
+ pytest.skip("a gate record has been added; the ladder tests cover its effect")
+ assert nvfp4_gate_passed("z-image", ZIMAGE_BASE) is False
+ assert nvfp4_gate_passed("qwen-image", "Qwen/Qwen-Image") is False
+ assert nvfp4_gate_passed("flux.1", "black-forest-labs/FLUX.1-schnell") is False
+
+
+def test_the_shipped_2512_record_never_gates_the_original_qwen_image():
+ assert nvfp4_gate_passed("qwen-image", "Qwen/Qwen-Image-2512") is True
+ assert nvfp4_gate_passed("qwen-image", "Qwen/Qwen-Image") is False
+ assert nvfp4_gate_passed("qwen-image-edit", "Qwen/Qwen-Image-2512") is False
+
+
+def test_no_record_at_all_reads_false(tmp_path):
+ empty = _gate_file(tmp_path)
+ assert nvfp4_gate_record("z-image", ZIMAGE_BASE, path = empty) is None
+ assert nvfp4_gate_passed("z-image", ZIMAGE_BASE, path = empty) is False
+
+
+def test_a_matching_record_reads_true_and_canonicalises_the_base(tmp_path):
+ path = _gate_file(tmp_path, _record())
+ assert nvfp4_gate_passed("z-image", ZIMAGE_BASE, path = path) is True
+ assert nvfp4_gate_passed("Z-Image", ZIMAGE_BASE.lower(), path = path) is True
+ mirrors = [
+ mirror
+ for mirror in ("unsloth/Z-Image-Turbo",)
+ if canonical_base(mirror).lower() == ZIMAGE_BASE.lower()
+ ]
+ for mirror in mirrors:
+ assert nvfp4_gate_passed("z-image", mirror, path = path) is True
+
+
+def test_the_backend_a_verdict_was_measured_on_is_readable(tmp_path):
+ path = _gate_file(tmp_path, _record())
+ assert nvfp4_gate_backend("z-image", ZIMAGE_BASE, path = path) == "flashinfer"
+ assert nvfp4_gate_backend("Z-Image", ZIMAGE_BASE, path = path) == "flashinfer"
+ for record in (_record(all_pass = False), _record(backend = None), _record(backend = "")):
+ assert (
+ nvfp4_gate_backend("z-image", ZIMAGE_BASE, path = _gate_file(tmp_path, record)) is None
+ ), record
+ assert nvfp4_gate_backend("z-image", ZIMAGE_BASE, path = _gate_file(tmp_path)) is None
+ assert (
+ nvfp4_gate_backend(
+ "z-image", ZIMAGE_BASE, path = _gate_file(tmp_path, _record(backend = "TorchAO "))
+ )
+ == "torchao"
+ )
+
+
+def test_two_artifacts_gated_on_different_backends_both_read_as_covered(tmp_path):
+ path = _gate_file(
+ tmp_path,
+ _record(),
+ _record(checkpoint_sha256 = "b" * 64, gptq = True, backend = "torchao"),
+ )
+ assert nvfp4_gate_backends("z-image", ZIMAGE_BASE, path = path) == ("flashinfer", "torchao")
+ assert nvfp4_gate_backends("Z-Image", ZIMAGE_BASE, path = path) == ("flashinfer", "torchao")
+ assert nvfp4_gate_backends("z-image", ZIMAGE_BASE, path = _gate_file(tmp_path)) == ()
+ assert (
+ nvfp4_gate_backends(
+ "z-image", ZIMAGE_BASE, path = _gate_file(tmp_path, _record(all_pass = False))
+ )
+ == ()
+ )
+
+
+def test_every_shipped_record_names_the_backend_it_was_measured_on():
+ for record in load_gate_records():
+ assert str(record.get("backend") or "").strip(), record
+ assert (
+ nvfp4_gate_backend(record["family"], record["base_repo"])
+ == str(record["backend"]).strip().lower()
+ ), record
+
+
+def test_a_failed_run_reads_false(tmp_path):
+ path = _gate_file(tmp_path, _record(all_pass = False))
+ assert nvfp4_gate_record("z-image", ZIMAGE_BASE, path = path) is not None
+ assert nvfp4_gate_passed("z-image", ZIMAGE_BASE, path = path) is False
+
+
+def test_a_recorded_failure_does_not_mask_a_later_checkpoint_that_passed(tmp_path):
+ path = _gate_file(
+ tmp_path,
+ _record(all_pass = False, checkpoint_sha256 = "b" * 64, backend = "torchao"),
+ _record(),
+ )
+ assert nvfp4_gate_passed("z-image", ZIMAGE_BASE, path = path) is True
+ assert nvfp4_gate_backend("z-image", ZIMAGE_BASE, path = path) == "flashinfer"
+
+
+def test_a_policy_version_bump_invalidates_the_verdict(tmp_path, monkeypatch):
+ path = _gate_file(tmp_path, _record())
+ bumped = dataclasses.replace(policy_mod.ZIMG_RG76, version = 2)
+ monkeypatch.setattr(
+ policy_mod,
+ "NVFP4_POLICIES",
+ (bumped,) + tuple(p for p in policy_mod.NVFP4_POLICIES if p.policy_id != bumped.policy_id),
+ )
+ assert nvfp4_gate_passed("z-image", ZIMAGE_BASE, path = path) is False
+
+
+def test_a_record_at_a_superseded_policy_no_longer_gates_its_base(tmp_path):
+ path = _gate_file(tmp_path, _record(policy_id = "zimg_f8mod_toq34_v1"))
+ assert nvfp4_gate_record("z-image", ZIMAGE_BASE, path = path) is not None
+ assert nvfp4_gate_passed("z-image", ZIMAGE_BASE, path = path) is False
+ flux = _record(
+ family = "flux.1",
+ base_repo = "black-forest-labs/FLUX.1-schnell",
+ policy_id = "flux_mod_single_v1",
+ )
+ # Separate files: the loader caches on (path, mtime_ns, size), and this third document is the first one's size, so
+ # on Windows' ~15.6 ms write clock a rewrite of the same path would read the first document back.
+ (tmp_path / "superseded").mkdir()
+ (tmp_path / "current").mkdir()
+ path = _gate_file(tmp_path / "superseded", flux)
+ assert nvfp4_gate_passed("flux.1", "black-forest-labs/FLUX.1-schnell", path = path) is False
+ path = _gate_file(tmp_path / "current", dict(flux, policy_id = "flux_r420_v1"))
+ assert nvfp4_gate_passed("flux.1", "black-forest-labs/FLUX.1-schnell", path = path) is True
+
+
+def test_a_record_for_another_base_or_family_is_not_inherited(tmp_path):
+ path = _gate_file(tmp_path, _record())
+ assert nvfp4_gate_passed("z-image", "some-org/Z-Image-Fork", path = path) is False
+ assert nvfp4_gate_passed("z-image", None, path = path) is False
+ assert nvfp4_gate_passed("flux.1", ZIMAGE_BASE, path = path) is False
+
+
+def test_a_record_pinned_to_another_policy_id_is_not_returned(tmp_path):
+ path = _gate_file(tmp_path, _record())
+ assert nvfp4_gate_record("z-image", ZIMAGE_BASE, "qwen_p02_v1", path = path) is None
+ assert nvfp4_gate_record("z-image", ZIMAGE_BASE, "zimg_rg76_v1", path = path) is not None
+
+
+def test_an_unreadable_or_absent_file_is_no_evidence_not_an_error(tmp_path):
+ missing = tmp_path / "nope.json"
+ assert load_gate_records(missing) == ()
+ assert nvfp4_gate_passed("z-image", ZIMAGE_BASE, path = missing) is False
+ broken = tmp_path / "broken.json"
+ broken.write_text("{not json", encoding = "utf-8")
+ assert load_gate_records(broken) == ()
+ assert nvfp4_gate_passed("z-image", ZIMAGE_BASE, path = broken) is False
+
+
+def test_a_rewritten_file_is_re_read_rather_than_served_from_the_cache(tmp_path):
+ path = _gate_file(tmp_path)
+ assert nvfp4_gate_passed("z-image", ZIMAGE_BASE, path = path) is False
+ _gate_file(tmp_path, _record())
+ assert nvfp4_gate_passed("z-image", ZIMAGE_BASE, path = path) is True
diff --git a/studio/backend/tests/test_diffusion_nvfp4_linear.py b/studio/backend/tests/test_diffusion_nvfp4_linear.py
new file mode 100644
index 00000000000..49408e467af
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_nvfp4_linear.py
@@ -0,0 +1,514 @@
+# 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 types
+
+import os
+
+import pytest
+
+from core.inference import diffusion_nvfp4_linear as nl
+from core.inference import diffusion_nvfp4_ops as ops
+
+REAL_SHAPES = ((3072, 3072), (12288, 3072), (18432, 3072), (15360, 256))
+
+FORWARD_REL_BOUND = 0.05
+DENSE_GAP_BOUND = 0.002
+
+
+def _cuda_or_skip():
+ torch = pytest.importorskip("torch")
+ if os.environ.get("CUDA_VISIBLE_DEVICES", None) == "":
+ pytest.skip("CUDA devices are masked off for this process")
+ if not getattr(torch, "cuda", None) or not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ capability = tuple(torch.cuda.get_device_capability(0))
+ if capability not in ops.NVFP4_FLASHINFER_CAPS:
+ pytest.skip("sm_%d%d has no flashinfer NVFP4 kernels" % capability)
+ pytest.importorskip("flashinfer")
+ pytest.importorskip("torchao")
+ return torch
+
+
+def _torchao_linear(
+ torch,
+ out_features: int,
+ in_features: int,
+ *,
+ bias: bool = True,
+ seed: int = 0,
+):
+ import torch.nn as nn
+ from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig
+ from torchao.quantization import quantize_
+
+ torch.manual_seed(seed)
+ linear = nn.Linear(in_features, out_features, bias = bias).to("cuda", torch.bfloat16)
+ dense = nn.Linear(in_features, out_features, bias = bias).to("cuda", torch.bfloat16)
+ dense.load_state_dict(linear.state_dict())
+ quantize_(linear, NVFP4DynamicActivationNVFP4WeightConfig(use_triton_kernel = False))
+ return linear, dense
+
+
+def _rel(a, b) -> float:
+ return float((a.float() - b.float()).norm() / b.float().norm())
+
+
[email protected]("out_features,in_features", REAL_SHAPES)
+def test_torchao_and_flashinfer_pack_the_same_payload(out_features, in_features):
+ torch = _cuda_or_skip()
+ import flashinfer
+ from torchao.prototype.mx_formats.nvfp4_tensor import NVFP4Tensor
+
+ torch.manual_seed(0)
+ with torch.cuda.device(0):
+ w = torch.randn(out_features, in_features, device = "cuda", dtype = torch.bfloat16) * 0.02
+ amax = w.float().abs().amax().clamp(min = 1e-8)
+ w_gsf = (6.0 * 448.0 / amax).reshape(1)
+ per_tensor_scale = (amax / (6.0 * 448.0)).reshape(1)
+ tensor = NVFP4Tensor.to_nvfp4(w, per_tensor_scale = per_tensor_scale, is_swizzled_scales = True)
+ fi_q, fi_sf = flashinfer.nvfp4_quantize(w, w_gsf, do_shuffle = False)
+
+ ao_q = tensor.qdata.view(torch.uint8)
+ assert tuple(ao_q.shape) == tuple(fi_q.shape) == (out_features, in_features // 2)
+ assert torch.equal(tensor.scale.reshape(-1).view(torch.uint8), fi_sf.reshape(-1))
+ assert tensor.scale.numel() == ops._swizzled_sf_numel(out_features, in_features // 16, 128)
+
+ codes = lambda t: torch.stack(((t & 0xF).long(), (t >> 4).long()), -1).reshape(t.shape[0], -1)
+ ca, cb = codes(ao_q), codes(fi_q)
+ differing = ca != cb
+ fraction = float(differing.float().mean())
+ assert fraction < 0.005, f"{fraction:.4%} of nibbles differ, which is more than tie noise"
+ if fraction:
+ assert torch.equal((ca >= 8)[differing], (cb >= 8)[differing])
+ assert int(((ca & 7).int() - (cb & 7).int()).abs()[differing].max()) == 1
+
+
[email protected]("m", [1, 512, 4096, 16384])
+def test_converted_layer_matches_the_torchao_module(m):
+ torch = _cuda_or_skip()
+
+ linear, dense = _torchao_linear(torch, 18432, 3072)
+ x = torch.randn(m, 3072, device = "cuda", dtype = torch.bfloat16) * 0.05
+ converted = nl.nvfp4_linear_from_torchao(linear, ops.global_scale(x))
+ with torch.inference_mode():
+ want = linear(x)
+ got = converted(x)
+ reference = dense(x)
+
+ assert bool(torch.isfinite(got).all())
+ assert tuple(got.shape) == (m, 18432)
+ against_torchao = _rel(got, want)
+ assert against_torchao < FORWARD_REL_BOUND, f"M={m} rel={against_torchao:.5f}"
+ assert abs(_rel(got, reference) - _rel(want, reference)) < DENSE_GAP_BOUND
+
+
+def test_converted_layer_keeps_the_leading_dimensions_and_the_bias():
+ torch = _cuda_or_skip()
+
+ linear, _ = _torchao_linear(torch, 3072, 3072)
+ converted = nl.nvfp4_linear_from_torchao(
+ linear, torch.tensor([448.0 * 6.0 / 0.2], device = "cuda")
+ )
+ assert converted.bias is not None
+ x = torch.randn(2, 77, 3072, device = "cuda", dtype = torch.bfloat16) * 0.05
+ with torch.inference_mode():
+ assert tuple(converted(x).shape) == (2, 77, 3072)
+ empty = converted(torch.zeros(0, 3072, device = "cuda", dtype = torch.bfloat16))
+ assert tuple(empty.shape) == (0, 3072)
+
+
[email protected]("out_features,in_features", [(18432, 3072), (15360, 256)])
+def test_m1_gemm_is_finite_on_both_backends(out_features, in_features, capsys):
+ torch = _cuda_or_skip()
+ import time
+
+ linear, _ = _torchao_linear(torch, out_features, in_features)
+ x = torch.randn(1, in_features, device = "cuda", dtype = torch.bfloat16) * 0.05
+ converted = nl.nvfp4_linear_from_torchao(linear, ops.global_scale(x))
+
+ timings = {}
+ for name, module in (("torchao", linear), ("flashinfer", converted)):
+ with torch.inference_mode():
+ for _ in range(3):
+ y = module(x)
+ torch.cuda.synchronize()
+ start = time.perf_counter()
+ for _ in range(20):
+ y = module(x)
+ torch.cuda.synchronize()
+ timings[name] = (time.perf_counter() - start) / 20 * 1e3
+ assert bool(torch.isfinite(y).all()), f"{name} produced a non-finite M=1 result"
+ assert tuple(y.shape) == (1, out_features)
+ with capsys.disabled():
+ print(
+ f"\n M=1 ({in_features} -> {out_features}) per call: "
+ + ", ".join(f"{k} {v:.3f} ms" for k, v in timings.items())
+ )
+
+
+def test_a_two_layer_block_compiles_fullgraph():
+ torch = _cuda_or_skip()
+ pytest.importorskip("triton") # inductor cannot build a GPU kernel without it (TritonMissing)
+ import torch.nn as nn
+
+ class Block(nn.Module):
+ def __init__(self, first, second):
+ super().__init__()
+ self.first, self.second = first, second
+
+ def forward(self, x):
+ return self.second(torch.nn.functional.silu(self.first(x)))
+
+ linear_a, _ = _torchao_linear(torch, 3072, 3072, seed = 1)
+ linear_b, _ = _torchao_linear(torch, 3072, 3072, seed = 2)
+ x = torch.randn(512, 3072, device = "cuda", dtype = torch.bfloat16) * 0.05
+ gsf = ops.global_scale(x)
+ block = Block(
+ nl.nvfp4_linear_from_torchao(linear_a, gsf), nl.nvfp4_linear_from_torchao(linear_b, gsf)
+ ).eval()
+
+ from torch._dynamo.utils import counters
+
+ torch._dynamo.reset()
+ counters.clear()
+ compiled = torch.compile(block, fullgraph = True)
+ with torch.inference_mode():
+ got = compiled(x)
+ want = block(x)
+
+ assert not counters["graph_break"], dict(counters["graph_break"])
+ assert counters["stats"]["unique_graphs"] == 1, dict(counters["stats"])
+ assert bool(torch.isfinite(got).all())
+ assert _rel(got, want) < 0.03
+ torch._dynamo.reset()
+
+
+def test_graphed_forward_captures_and_replays_a_converted_block():
+ torch = _cuda_or_skip()
+ import torch.nn as nn
+
+ from core.inference import diffusion_cuda_graph as cg
+
+ class TinyDiT(nn.Module):
+ def __init__(self, layer):
+ super().__init__()
+ self.layer = layer
+
+ def forward(
+ self,
+ hidden_states,
+ timestep,
+ return_dict = True,
+ ):
+ out = self.layer(hidden_states) + timestep
+ if return_dict:
+ return types.SimpleNamespace(sample = out)
+ return (out,)
+
+ linear, _ = _torchao_linear(torch, 3072, 3072, seed = 3)
+ x = torch.randn(512, 3072, device = "cuda", dtype = torch.bfloat16) * 0.05
+ module = TinyDiT(nl.nvfp4_linear_from_torchao(linear, ops.global_scale(x))).eval()
+ handle = cg.GraphedForward(module).enable()
+ try:
+ timestep = torch.zeros(1, 1, device = "cuda", dtype = torch.bfloat16)
+ with torch.inference_mode():
+ eager = handle.orig(hidden_states = x, timestep = timestep, return_dict = False)[0].clone()
+ first = None
+ for _ in range(20):
+ replayed = module(hidden_states = x, timestep = timestep, return_dict = False)[0]
+ assert _rel(replayed, eager) < FORWARD_REL_BOUND
+ first = replayed.clone() if first is None else first
+ assert torch.equal(replayed, first)
+ assert handle.stats["captures"] == 1
+ assert handle.stats["replays"] == 20
+ assert bool(torch.isfinite(replayed).all())
+ finally:
+ cg.uninstall_all([handle])
+
+
+def test_convert_nvfp4_backend_moves_a_real_quantized_tree_and_prewarms_it():
+ torch = _cuda_or_skip()
+ import torch.nn as nn
+ from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig
+ from torchao.quantization import quantize_
+
+ torch.manual_seed(7)
+ tree = nn.Sequential(nn.Linear(3072, 3072), nn.SiLU(), nn.Linear(3072, 3072))
+ tree = tree.to("cuda", torch.bfloat16).eval()
+ quantize_(tree, NVFP4DynamicActivationNVFP4WeightConfig(use_triton_kernel = False))
+ x = torch.randn(512, 3072, device = "cuda", dtype = torch.bfloat16) * 0.05
+ with torch.inference_mode():
+ hidden = tree[1](tree[0](x))
+ before = tree(x)
+ metadata = {
+ "nvfp4_policy": {"activation_scales_baked": True},
+ "act_global_scales": {
+ "0": float(ops.global_scale(x)),
+ "2": float(ops.global_scale(hidden)),
+ },
+ }
+ assert nl.convert_nvfp4_backend(tree, metadata, "flashinfer") == 2
+ assert nl.is_nvfp4_flashinfer_linear(tree[0]) and nl.is_nvfp4_flashinfer_linear(tree[2])
+ with torch.inference_mode():
+ after = tree(x)
+ assert bool(torch.isfinite(after).all())
+ assert _rel(after, before) < FORWARD_REL_BOUND
+
+ nl.reset_tuned_shapes()
+ assert nl.nvfp4_prewarm(tree, (512,)) == 1
+ assert tree[0]._tuned is True and tree[2]._tuned is True
+ assert nl.nvfp4_prewarm(tree, (512,)) == 0
+ with torch.inference_mode():
+ tuned = tree(x)
+ assert bool(torch.isfinite(tuned).all())
+ nl.reset_tuned_shapes()
+
+
+class _FakeNVFP4Tensor:
+ __name__ = "NVFP4Tensor"
+
+ def __init__(self):
+ self.qdata = object()
+ self.scale = object()
+ self.per_tensor_scale = None
+
+
+_FakeNVFP4Tensor.__name__ = "NVFP4Tensor"
+_FakeNVFP4Tensor.__qualname__ = "NVFP4Tensor"
+
+
+def _quantized_tree():
+ import torch.nn as nn
+
+ class Fake(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.in_features = 64
+ self.out_features = 64
+ self.weight = _FakeNVFP4Tensor()
+
+ class Tree(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.attn = nn.Module()
+ self.attn.to_q = Fake()
+ self.attn.to_k = Fake()
+ self.plain = nn.Linear(8, 8)
+
+ return Tree()
+
+
+def test_the_walk_finds_the_quantized_linears_and_leaves_the_plain_one_alone():
+ pytest.importorskip("torch")
+ tree = _quantized_tree()
+ names = [
+ name
+ for name, mod in nl._iter_linears(tree)
+ if nl.is_nvfp4_tensor(getattr(mod, "weight", None))
+ ]
+ assert names == ["attn.to_q", "attn.to_k"]
+
+
+class _RecordingLogger:
+ def __init__(self):
+ self.lines: list[str] = []
+
+ def __getattr__(self, _level):
+ return self.lines.append
+
+ @property
+ def text(self) -> str:
+ return "\n".join(self.lines)
+
+
+def test_conversion_refuses_without_baked_activation_scales():
+ pytest.importorskip("torch")
+
+ tree = _quantized_tree()
+ logger = _RecordingLogger()
+ assert nl.convert_nvfp4_backend(tree, {"scheme": "nvfp4"}, "flashinfer", logger = logger) == 0
+ assert "bakes no activation scales" in logger.text
+ assert type(tree.attn.to_q).__name__ != "NVFP4FlashInferLinear"
+
+
+def test_conversion_refuses_when_one_layer_has_no_scale():
+ pytest.importorskip("torch")
+
+ tree = _quantized_tree()
+ logger = _RecordingLogger()
+ metadata = {
+ "nvfp4_policy": {"activation_scales_baked": True},
+ "act_global_scales": {"attn.to_q": 1234.0},
+ }
+ assert nl.convert_nvfp4_backend(tree, metadata, "flashinfer", logger = logger) == 0
+ assert "attn.to_k" in logger.text
+ assert "1 of 2" in logger.text
+ assert type(tree.attn.to_q).__name__ != "NVFP4FlashInferLinear"
+
+
+def test_a_layer_that_fails_half_way_leaves_the_whole_tree_on_torchao(monkeypatch):
+ # A raise after the first swap used to leave a mixed tree the loader logged as torchao.
+ torch = pytest.importorskip("torch")
+ import torch.nn as nn
+
+ tree = _quantized_tree()
+ originals = dict(nl._iter_linears(tree))
+ logger = _RecordingLogger()
+ metadata = {"act_global_scales": {"attn.to_q": 1.0, "attn.to_k": 2.0}}
+
+ def _convert(linear, a_gsf, **kwargs):
+ if linear is originals["attn.to_k"]:
+ raise ValueError("this NVFP4 weight carries no per_tensor_scale")
+ return nn.Identity()
+
+ monkeypatch.setattr(nl, "nvfp4_linear_from_torchao", _convert)
+ assert nl.convert_nvfp4_backend(tree, metadata, "flashinfer", logger = logger) == 0
+ assert "attn.to_k could not move" in logger.text
+ assert tree.attn.to_q is originals["attn.to_q"]
+ assert tree.attn.to_k is originals["attn.to_k"]
+ assert torch is not None
+
+
+def test_a_declared_but_empty_scale_block_is_refused_as_loudly_as_a_missing_one():
+ pytest.importorskip("torch")
+
+ logger = _RecordingLogger()
+ metadata = {"nvfp4_policy": {"activation_scales_baked": True}, "act_global_scales": {}}
+ assert nl.convert_nvfp4_backend(_quantized_tree(), metadata, "flashinfer", logger = logger) == 0
+ assert "flag set, scales missing" in logger.text
+
+
+def test_conversion_is_a_no_op_for_the_torchao_backend():
+ pytest.importorskip("torch")
+ tree = _quantized_tree()
+ metadata = {"act_global_scales": {"attn.to_q": 1.0, "attn.to_k": 1.0}}
+ assert nl.convert_nvfp4_backend(tree, metadata, "torchao") == 0
+
+
+def test_conversion_skips_a_model_with_no_nvfp4_weights():
+ torch = pytest.importorskip("torch")
+ import torch.nn as nn
+
+ tree = nn.Sequential(nn.Linear(8, 8), nn.SiLU(), nn.Linear(8, 8))
+ metadata = {"act_global_scales": {"0": 1.0}}
+ assert nl.convert_nvfp4_backend(tree, metadata, "flashinfer") == 0
+ assert isinstance(tree[0], nn.Linear)
+ assert torch is not None
+
+
+def test_state_dict_round_trips_with_and_without_a_bias():
+ torch = pytest.importorskip("torch")
+
+ cls = nl.nvfp4_linear_class()
+ assert cls is nl.nvfp4_linear_class()
+
+ def _build(bias: bool):
+ return cls(
+ 64,
+ 32,
+ wq = torch.arange(32 * 32, dtype = torch.uint8).reshape(32, 32),
+ w_sf = torch.ones(128, 4, dtype = torch.uint8),
+ alpha = torch.tensor([0.25]),
+ a_gsf = torch.tensor([1344.0]),
+ bias = torch.arange(32, dtype = torch.bfloat16) if bias else None,
+ )
+
+ with_bias = _build(True)
+ assert sorted(with_bias.state_dict()) == ["a_gsf", "alpha", "bias", "w_scale", "w_sf", "wq"]
+ assert float(with_bias.w_scale) == 0.25 * 1344.0
+ reloaded = _build(True)
+ reloaded.load_state_dict(with_bias.state_dict(), strict = True)
+ for key, value in with_bias.state_dict().items():
+ assert torch.equal(reloaded.state_dict()[key], value)
+
+ without_bias = _build(False)
+ assert "bias" not in without_bias.state_dict()
+ assert nl.is_nvfp4_flashinfer_linear(without_bias)
+ assert without_bias._tuned is False
+
+
+def test_prewarm_without_flashinfer_is_a_no_op(monkeypatch):
+ pytest.importorskip("torch")
+ import builtins
+
+ real_import = builtins.__import__
+
+ def _no_flashinfer(name, *args, **kwargs):
+ if name == "flashinfer":
+ raise ImportError("no flashinfer here")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _no_flashinfer)
+ assert nl.nvfp4_prewarm(_quantized_tree(), (1, 512)) == 0
+
+
+def test_a_whole_model_artifact_converts_without_a_policy_block():
+ """Video artifacts quantise EVERY admitted linear and declare no policy."""
+ torch = _cuda_or_skip()
+ import torch.nn as nn
+ from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig
+ from torchao.quantization import quantize_
+
+ torch.manual_seed(11)
+ tree = nn.Sequential(nn.Linear(3072, 3072), nn.SiLU(), nn.Linear(3072, 3072))
+ tree = tree.to("cuda", torch.bfloat16).eval()
+ quantize_(tree, NVFP4DynamicActivationNVFP4WeightConfig(use_triton_kernel = False))
+ x = torch.randn(512, 3072, device = "cuda", dtype = torch.bfloat16) * 0.05
+ with torch.inference_mode():
+ hidden = tree[1](tree[0](x))
+ before = tree(x)
+ metadata = {
+ "scheme": "nvfp4",
+ "family": "wan2.2-ti2v-5b",
+ "activation_scales_baked": True,
+ "act_global_scales": {
+ "0": float(ops.global_scale(x)),
+ "2": float(ops.global_scale(hidden)),
+ },
+ }
+ assert nl.convert_nvfp4_backend(tree, metadata, "flashinfer") == 2
+ assert nl.is_nvfp4_flashinfer_linear(tree[0]) and nl.is_nvfp4_flashinfer_linear(tree[2])
+ with torch.inference_mode():
+ after = tree(x)
+ assert bool(torch.isfinite(after).all())
+ assert _rel(after, before) < FORWARD_REL_BOUND
+
+
+def test_a_whole_model_artifact_that_baked_nothing_says_the_flag_is_set():
+ pytest.importorskip("torch")
+
+ logger = _RecordingLogger()
+ metadata = {"scheme": "nvfp4", "activation_scales_baked": True, "act_global_scales": {}}
+ assert nl.convert_nvfp4_backend(_quantized_tree(), metadata, "flashinfer", logger = logger) == 0
+ assert "flag set, scales missing" in logger.text
+
+
+def test_an_fp32_layer_runs_and_answers_in_fp32():
+ """Wan2.2's fp32 time embedder feeds fp32, which ``fp4_quantize`` rejects."""
+ torch = _cuda_or_skip()
+ import torch.nn as nn
+ from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig
+ from torchao.quantization import quantize_
+
+ torch.manual_seed(3)
+ layer = nn.Linear(3072, 3072).to("cuda", torch.float32).eval()
+ reference = nn.Linear(3072, 3072).to("cuda", torch.float32).eval()
+ reference.load_state_dict(layer.state_dict())
+ quantize_(layer, NVFP4DynamicActivationNVFP4WeightConfig(use_triton_kernel = False))
+ quantize_(reference, NVFP4DynamicActivationNVFP4WeightConfig(use_triton_kernel = False))
+ x = torch.randn(512, 3072, device = "cuda", dtype = torch.float32) * 0.05
+ with torch.inference_mode():
+ before = reference(x)
+ converted = nl.nvfp4_linear_from_torchao(layer, float(ops.global_scale(x)))
+ with torch.inference_mode():
+ after = converted(x)
+ assert after.dtype == torch.float32
+ assert bool(torch.isfinite(after).all())
+ assert _rel(after.float(), before.float()) < FORWARD_REL_BOUND
+ with torch.inference_mode():
+ empty = converted(x[:0])
+ assert empty.shape == (0, 3072) and empty.dtype == torch.float32
diff --git a/studio/backend/tests/test_diffusion_nvfp4_policy.py b/studio/backend/tests/test_diffusion_nvfp4_policy.py
new file mode 100644
index 00000000000..72a28bccda6
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_nvfp4_policy.py
@@ -0,0 +1,587 @@
+# 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
+
+torch = pytest.importorskip("torch")
+nn = torch.nn
+
+from core.inference.diffusion_nvfp4_policy import ( # noqa: E402
+ FLUX_R420,
+ NVFP4_POLICY_KEY,
+ NVFP4_POLICIES,
+ NVFP4_POLICY_KIND,
+ QWEN21_R020,
+ QWEN2512_M120_ATTN8,
+ QWEN_P02,
+ ZIMG_RG76,
+ Admit,
+ NVFP4Policy,
+ PolicyMismatch,
+ Rule,
+ assign_precisions,
+ declares_policy,
+ policy_by_id,
+ policy_metadata,
+ policy_metadata_error,
+ quantize_with_policy,
+ resolve_policy,
+)
+
+NVFP4 = "nvfp4"
+FP8 = "fp8"
+BF16 = "bf16"
+
+
+def _zimage_rows() -> list:
+ """Z-Image-Turbo's 276 linears: 30 transformer layers, 2 noise refiners, 2 context refiners."""
+ rows = [
+ ("all_x_embedder.2-1", 64, 3840),
+ ("all_final_layer.2-1.linear", 3840, 64),
+ ("all_final_layer.2-1.adaLN_modulation.1", 256, 3840),
+ ("cap_embedder.1", 2560, 3840),
+ ("t_embedder.mlp.0", 256, 1024),
+ ("t_embedder.mlp.2", 1024, 256),
+ ]
+
+ def block(
+ prefix: str,
+ index: int,
+ modulation: bool = True,
+ ) -> list:
+ out = []
+ if modulation:
+ out.append((f"{prefix}.{index}.adaLN_modulation.0", 256, 15360))
+ for leaf in ("to_q", "to_k", "to_v"):
+ out.append((f"{prefix}.{index}.attention.{leaf}", 3840, 3840))
+ out.append((f"{prefix}.{index}.attention.to_out.0", 3840, 3840))
+ out.append((f"{prefix}.{index}.feed_forward.w1", 3840, 10240))
+ out.append((f"{prefix}.{index}.feed_forward.w2", 10240, 3840))
+ out.append((f"{prefix}.{index}.feed_forward.w3", 3840, 10240))
+ return out
+
+ for index in range(30):
+ rows += block("layers", index)
+ for index in range(2):
+ rows += block("noise_refiner", index)
+ for index in range(2):
+ rows += block("context_refiner", index, modulation = False)
+ return rows
+
+
+def _flux_rows() -> list:
+ """FLUX.1-schnell's 502 linears: 19 double blocks and 38 single blocks."""
+ rows = [
+ ("x_embedder", 64, 3072),
+ ("context_embedder", 4096, 3072),
+ ("proj_out", 3072, 64),
+ ("norm_out.linear", 3072, 6144),
+ ("time_text_embed.text_embedder.linear_1", 768, 3072),
+ ("time_text_embed.text_embedder.linear_2", 3072, 3072),
+ ("time_text_embed.timestep_embedder.linear_1", 256, 3072),
+ ("time_text_embed.timestep_embedder.linear_2", 3072, 3072),
+ ]
+ for index in range(19):
+ prefix = f"transformer_blocks.{index}"
+ for leaf in (
+ "to_q",
+ "to_k",
+ "to_v",
+ "add_q_proj",
+ "add_k_proj",
+ "add_v_proj",
+ "to_add_out",
+ ):
+ rows.append((f"{prefix}.attn.{leaf}", 3072, 3072))
+ rows.append((f"{prefix}.attn.to_out.0", 3072, 3072))
+ rows.append((f"{prefix}.ff.net.0.proj", 3072, 12288))
+ rows.append((f"{prefix}.ff.net.2", 12288, 3072))
+ rows.append((f"{prefix}.ff_context.net.0.proj", 3072, 12288))
+ rows.append((f"{prefix}.ff_context.net.2", 12288, 3072))
+ rows.append((f"{prefix}.norm1.linear", 3072, 18432))
+ rows.append((f"{prefix}.norm1_context.linear", 3072, 18432))
+ for index in range(38):
+ prefix = f"single_transformer_blocks.{index}"
+ for leaf in ("to_q", "to_k", "to_v"):
+ rows.append((f"{prefix}.attn.{leaf}", 3072, 3072))
+ rows.append((f"{prefix}.norm.linear", 3072, 9216))
+ rows.append((f"{prefix}.proj_mlp", 3072, 12288))
+ rows.append((f"{prefix}.proj_out", 15360, 3072))
+ return rows
+
+
+def _qwen_rows() -> list:
+ """Qwen-Image's 846 linears: 60 joint blocks, each with an img and a txt modulation."""
+ rows = [
+ ("img_in", 64, 3072),
+ ("txt_in", 3584, 3072),
+ ("proj_out", 3072, 64),
+ ("norm_out.linear", 3072, 6144),
+ ("time_text_embed.timestep_embedder.linear_1", 256, 3072),
+ ("time_text_embed.timestep_embedder.linear_2", 3072, 3072),
+ ]
+ for index in range(60):
+ prefix = f"transformer_blocks.{index}"
+ for leaf in (
+ "to_q",
+ "to_k",
+ "to_v",
+ "add_q_proj",
+ "add_k_proj",
+ "add_v_proj",
+ "to_add_out",
+ ):
+ rows.append((f"{prefix}.attn.{leaf}", 3072, 3072))
+ rows.append((f"{prefix}.attn.to_out.0", 3072, 3072))
+ rows.append((f"{prefix}.img_mlp.net.0.proj", 3072, 12288))
+ rows.append((f"{prefix}.img_mlp.net.2", 12288, 3072))
+ rows.append((f"{prefix}.txt_mlp.net.0.proj", 3072, 12288))
+ rows.append((f"{prefix}.txt_mlp.net.2", 12288, 3072))
+ rows.append((f"{prefix}.img_mod.1", 3072, 18432))
+ rows.append((f"{prefix}.txt_mod.1", 3072, 18432))
+ return rows
+
+
+def _qwen21_rows() -> list:
+ """Qwen-Image-2.1's 232 linears: 32 single-stream blocks and one global modulation."""
+ rows = [
+ ("img_in", 64, 4096),
+ ("txt_in.in_layer", 4096, 4096),
+ ("txt_in.out_layer", 4096, 4096),
+ ("modulation.1", 4096, 16384),
+ ("norm_out.linear", 4096, 4096),
+ ("proj_out", 4096, 64),
+ ("time_text_embed.timestep_embedder.linear_1", 256, 4096),
+ ("time_text_embed.timestep_embedder.linear_2", 4096, 4096),
+ ]
+ for index in range(32):
+ prefix = f"transformer_blocks.{index}"
+ for leaf in ("to_q", "to_k", "to_v"):
+ rows.append((f"{prefix}.attn.{leaf}", 4096, 4096))
+ rows.append((f"{prefix}.attn.to_out.0", 4096, 4096))
+ rows.append((f"{prefix}.img_mlp.proj", 4096, 12288))
+ rows.append((f"{prefix}.img_mlp.gate_layer", 4096, 12288))
+ rows.append((f"{prefix}.img_mlp.out", 12288, 4096))
+ return rows
+
+
+class _Tree:
+ def __init__(self, rows) -> None:
+ self.linears = {
+ fqn: nn.Linear(in_features, out_features, device = "meta", dtype = torch.bfloat16)
+ for fqn, in_features, out_features in rows
+ }
+
+ def named_modules(self):
+ yield "", self
+ yield from self.linears.items()
+
+
+def _zimage() -> _Tree:
+ return _Tree(_zimage_rows())
+
+
+def _flux() -> _Tree:
+ return _Tree(_flux_rows())
+
+
+def _qwen() -> _Tree:
+ return _Tree(_qwen_rows())
+
+
+def _qwen21() -> _Tree:
+ return _Tree(_qwen21_rows())
+
+
+def test_the_synthetic_trees_reproduce_the_census_they_came_from():
+ from core.inference.diffusion_transformer_quant import make_filter_fn
+ admitted = make_filter_fn(512, ("lora_",), require_bf16 = True, require_divisible = 16)
+ for tree, total, admits in (
+ (_zimage(), 276, 239),
+ (_flux(), 502, 499),
+ (_qwen(), 846, 843),
+ (_qwen21(), 232, 229),
+ ):
+ assert len(tree.linears) == total
+ assert sum(1 for fqn, m in tree.linears.items() if admitted(m, fqn)) == admits
+
+
+def test_a_policy_resolves_for_the_bases_it_was_solved_on_and_no_others():
+ assert resolve_policy("z-image", "Tongyi-MAI/Z-Image-Turbo") is ZIMG_RG76
+ assert resolve_policy("flux.1", "black-forest-labs/FLUX.1-schnell") is FLUX_R420
+ assert resolve_policy("qwen-image", "Qwen/Qwen-Image") is QWEN_P02
+ assert resolve_policy("qwen-image", "Qwen/Qwen-Image-2512") is QWEN2512_M120_ATTN8
+ assert resolve_policy("qwen-image", "unsloth/Qwen-Image-2512") is QWEN2512_M120_ATTN8
+ assert resolve_policy("qwen-image-2.1", "Qwen/Qwen-Image-2.1") is QWEN21_R020
+ assert resolve_policy("qwen-image-2.1", "unsloth/Qwen-Image-2.1") is QWEN21_R020
+ assert resolve_policy("qwen-image", "Qwen/Qwen-Image-2.1") is None
+ assert resolve_policy("qwen-image-2.1", "Qwen/Qwen-Image-2512") is None
+ assert resolve_policy("z-image", "unsloth/Z-Image-Turbo") is ZIMG_RG76
+ assert resolve_policy("flux.1", " UNSLOTH/FLUX.1-schnell ") is FLUX_R420
+ assert resolve_policy("flux.1", "black-forest-labs/FLUX.1-dev") is None
+ assert resolve_policy("qwen-image", "Qwen/Qwen-Image-Edit-2511") is None
+ assert resolve_policy("z-image", None) is None
+ assert resolve_policy("z-image", "") is None
+ assert resolve_policy("wan2.2-ti2v-5b", "Wan-AI/Wan2.2-TI2V-5B-Diffusers") is None
+ assert resolve_policy(None, "Tongyi-MAI/Z-Image-Turbo") is None
+ assert policy_by_id("qwen_p02_v1") is QWEN_P02
+ assert policy_by_id("qwen_p02_v2") is None
+
+
+ ("policy", "tree_fn", "expected"),
+ [
+ (ZIMG_RG76, _zimage, {NVFP4: 76, FP8: 195, BF16: 5}),
+ (FLUX_R420, _flux, {NVFP4: 187, FP8: 312, BF16: 3}),
+ (QWEN21_R020, _qwen21, {NVFP4: 48, FP8: 181, BF16: 3}),
+ (QWEN2512_M120_ATTN8, _qwen, {NVFP4: 600, FP8: 243, BF16: 3}),
+ (QWEN_P02, _qwen, {NVFP4: 120, FP8: 723, BF16: 3}),
+ ],
+)
+def test_each_policy_assigns_the_layer_counts_it_was_gated_at(policy, tree_fn, expected):
+ from collections import Counter
+
+ assignment = assign_precisions(tree_fn(), policy)
+ assert dict(Counter(assignment.values())) == expected
+ assert dict(policy.expected_counts) == expected
+
+
+def test_the_superseded_picks_are_gone_rather_than_left_resolvable():
+ assert policy_by_id("zimg_f8mod_toq34_v1") is None
+ assert policy_by_id("flux_mod_single_v1") is None
+ bases = {}
+ for policy in NVFP4_POLICIES:
+ for base in policy.base_repos:
+ assert (policy.family, base) not in bases, (
+ policy.policy_id,
+ bases.get((policy.family, base)),
+ )
+ bases[(policy.family, base)] = policy.policy_id
+
+
+def test_zimage_takes_both_query_and_key_the_early_ffn_gate_and_admits_the_modulation():
+ tree = _zimage()
+ assignment = assign_precisions(tree, ZIMG_RG76)
+ nvfp4 = sorted(fqn for fqn, precision in assignment.items() if precision == NVFP4)
+ assert len(nvfp4) == 76
+ assert sum(1 for fqn in nvfp4 if fqn.endswith(".attention.to_q")) == 34
+ assert sum(1 for fqn in nvfp4 if fqn.endswith(".attention.to_k")) == 34
+ assert "context_refiner.0.attention.to_k" in nvfp4
+ w1 = sorted(fqn for fqn in nvfp4 if fqn.endswith(".feed_forward.w1"))
+ assert w1 == [f"layers.{i}.feed_forward.w1" for i in range(6)] + [
+ "noise_refiner.0.feed_forward.w1",
+ "noise_refiner.1.feed_forward.w1",
+ ]
+ assert assignment["layers.6.feed_forward.w1"] == FP8
+ assert assignment["context_refiner.0.feed_forward.w1"] == FP8
+ assert assignment["layers.0.attention.to_v"] == FP8
+ admits = [fqn for fqn in assignment if fqn.endswith(".adaLN_modulation.0")]
+ assert len(admits) == 32
+ assert {assignment[fqn] for fqn in admits} == {FP8}
+ assert assignment["all_final_layer.2-1.adaLN_modulation.1"] == BF16
+
+
+def test_qwen_takes_both_modulation_streams_and_nothing_else():
+ assignment = assign_precisions(_qwen(), QWEN_P02)
+ nvfp4 = sorted(fqn for fqn, precision in assignment.items() if precision == NVFP4)
+ assert len(nvfp4) == 120
+ assert sum(1 for fqn in nvfp4 if fqn.endswith(".img_mod.1")) == 60
+ assert sum(1 for fqn in nvfp4 if fqn.endswith(".txt_mod.1")) == 60
+ assert assignment["transformer_blocks.0.img_mlp.net.0.proj"] == FP8
+
+
+def test_a_renamed_layer_raises_rather_than_shipping_a_different_model():
+ rows = [
+ (fqn.replace("attention.to_q", "attention.q_proj"), i, o) for fqn, i, o in _zimage_rows()
+ ]
+ with pytest.raises(PolicyMismatch, match = "attention.to_q"):
+ assign_precisions(_Tree(rows), ZIMG_RG76)
+ extra = _zimage_rows() + [("layers.30.attention.to_q", 3840, 3840)]
+ with pytest.raises(PolicyMismatch, match = "expects 34 layers, found 35"):
+ assign_precisions(_Tree(extra), ZIMG_RG76)
+
+
+def test_an_admitted_layer_of_another_width_is_refused_not_quantised():
+ rows = [
+ (fqn, i, 7680 if fqn.endswith(".adaLN_modulation.0") else o) for fqn, i, o in _zimage_rows()
+ ]
+ with pytest.raises(PolicyMismatch, match = r"\(256, 15360\)"):
+ assign_precisions(_Tree(rows), ZIMG_RG76)
+ fewer = [row for row in _zimage_rows() if not row[0].startswith("noise_refiner.0.adaLN")]
+ with pytest.raises(PolicyMismatch, match = "expecting 32 layers, found 31"):
+ assign_precisions(_Tree(fewer), ZIMG_RG76)
+
+
+def test_a_layer_that_changed_width_moves_the_totals_and_raises():
+ rows = [
+ (fqn, 256 if fqn == "transformer_blocks.0.attn.to_k" else i, o)
+ for fqn, i, o in _qwen_rows()
+ ]
+ with pytest.raises(PolicyMismatch, match = "expected"):
+ assign_precisions(_Tree(rows), QWEN_P02)
+
+
+def test_a_policy_whose_totals_do_not_add_up_cannot_be_applied_at_all():
+ bogus = NVFP4Policy(
+ policy_id = "bogus_v1",
+ version = 1,
+ family = "z-image",
+ base_repos = ("tongyi-mai/z-image-turbo",),
+ rules = (Rule(suffix = "attention.to_q", precision = NVFP4, expect = 34),),
+ admit = (Admit(suffix = "adaLN_modulation.0", shape = (256, 15360), expect = 32),),
+ expected_counts = {NVFP4: 34, FP8: 236, BF16: 6},
+ )
+ with pytest.raises(PolicyMismatch, match = "assigned"):
+ assign_precisions(_zimage(), bogus)
+
+
+def test_a_table_that_spells_out_a_zero_total_still_applies():
+ spelled = NVFP4Policy(
+ policy_id = "spelled_v1",
+ version = 1,
+ family = "flux.1",
+ base_repos = ("black-forest-labs/flux.1-schnell",),
+ rules = (
+ Rule(
+ suffix = "norm.linear",
+ precision = NVFP4,
+ expect = 38,
+ prefix = "single_transformer_blocks.",
+ ),
+ ),
+ expected_counts = {NVFP4: 38, FP8: 461, BF16: 3, "int8": 0},
+ )
+ assert assign_precisions(_flux(), spelled)
+
+
+def test_a_per_block_rule_takes_exactly_the_blocks_it_lists():
+ flux = assign_precisions(_flux(), FLUX_R420)
+ single = [i for i in range(38) if flux[f"single_transformer_blocks.{i}.norm.linear"] == NVFP4]
+ assert single == list(range(11, 38))
+ assert flux["single_transformer_blocks.14.attn.to_k"] == FP8
+ assert flux["single_transformer_blocks.15.attn.to_k"] == NVFP4
+ assert flux["single_transformer_blocks.20.attn.to_v"] == FP8
+ assert flux["single_transformer_blocks.21.attn.to_v"] == NVFP4
+ assert flux["transformer_blocks.5.norm1.linear"] == NVFP4
+ assert flux["transformer_blocks.3.norm1.linear"] == FP8
+ assert flux["transformer_blocks.17.ff_context.net.2"] == FP8
+ assert flux["norm_out.linear"] == NVFP4
+ assert all(flux[f"transformer_blocks.{i}.attn.to_out.0"] == FP8 for i in range(19))
+ qwen21 = assign_precisions(_qwen21(), QWEN21_R020)
+ assert qwen21["transformer_blocks.5.attn.to_k"] == NVFP4
+ assert qwen21["transformer_blocks.3.attn.to_k"] == FP8
+ assert qwen21["transformer_blocks.29.attn.to_q"] == NVFP4
+ assert qwen21["transformer_blocks.28.attn.to_q"] == FP8
+ assert all(qwen21[f"transformer_blocks.{i}.img_mlp.out"] == FP8 for i in range(32))
+ assert not any(
+ qwen21[f"transformer_blocks.{i}.{leaf}"] == NVFP4
+ for i in (30, 31)
+ for leaf in ("attn.to_q", "attn.to_k", "img_mlp.proj", "img_mlp.gate_layer", "img_mlp.out")
+ )
+ assert qwen21["modulation.1"] == FP8 and qwen21["txt_in.in_layer"] == FP8
+
+
+def test_the_2512_policy_takes_modulation_and_all_eight_attention_projections():
+ assignment = assign_precisions(_qwen(), QWEN2512_M120_ATTN8)
+ nvfp4 = {fqn for fqn, precision in assignment.items() if precision == NVFP4}
+ leaves = {fqn.split(".", 2)[2] for fqn in nvfp4}
+ assert leaves == {
+ "img_mod.1",
+ "txt_mod.1",
+ "attn.to_q",
+ "attn.to_k",
+ "attn.to_v",
+ "attn.to_out.0",
+ "attn.add_q_proj",
+ "attn.add_k_proj",
+ "attn.add_v_proj",
+ "attn.to_add_out",
+ }
+ assert assignment["transformer_blocks.0.img_mlp.net.0.proj"] == FP8
+ assert assignment["norm_out.linear"] == FP8
+
+
+def test_a_suffix_never_matches_a_longer_leaf_name():
+ rule = Rule(suffix = "attention.to_q", precision = NVFP4, expect = 1)
+ assert rule.matches("layers.0.attention.to_q")
+ assert rule.matches("attention.to_q")
+ assert not rule.matches("layers.0.attention.to_q_extra")
+ assert not rule.matches("layers.0.self_attention.to_q")
+ assert not rule.matches("layers.0.attention.to_qkv")
+ prefixed = Rule(
+ suffix = "norm.linear",
+ precision = NVFP4,
+ expect = 1,
+ prefix = "single_transformer_blocks.",
+ )
+ assert prefixed.matches("single_transformer_blocks.7.norm.linear")
+ assert not prefixed.matches("transformer_blocks.7.norm.linear")
+ assert not prefixed.matches("single_transformer_blocks.7.norm1.linear")
+
+
+def test_the_timestep_embedder_mlp_stays_dense_under_every_image_policy():
+ assignment = assign_precisions(_zimage(), ZIMG_RG76)
+ assert assignment["t_embedder.mlp.0"] == BF16
+ assert assignment["t_embedder.mlp.2"] == BF16
+ flux = assign_precisions(_flux(), FLUX_R420)
+ assert flux["time_text_embed.timestep_embedder.linear_1"] == BF16
+ assert flux["x_embedder"] == BF16 and flux["proj_out"] == BF16
+ for policy, tree in (
+ (QWEN_P02, _qwen()),
+ (QWEN2512_M120_ATTN8, _qwen()),
+ (QWEN21_R020, _qwen21()),
+ ):
+ qwen = assign_precisions(tree, policy)
+ assert qwen["time_text_embed.timestep_embedder.linear_1"] == BF16, policy.policy_id
+ assert qwen["img_in"] == BF16 and qwen["proj_out"] == BF16, policy.policy_id
+
+
+class _FakeQuantized:
+ def __init__(self, name: str) -> None:
+ self.__class__ = type(name, (_FakeQuantized,), {})
+
+
+def _stub_quantize(
+ monkeypatch,
+ *,
+ skip = (),
+ produced = None,
+):
+ calls: list = []
+ classes = produced or {"cfg:nvfp4": "NVFP4Tensor", "cfg:fp8": "Float8Tensor"}
+
+ def _quantize_(
+ module,
+ config,
+ filter_fn = None,
+ ):
+ selected = [
+ fqn
+ for fqn, sub in module.named_modules()
+ if isinstance(sub, nn.Linear) and (filter_fn is None or filter_fn(sub, fqn))
+ ]
+ calls.append({"config": config, "selected": selected, "filter_fn": filter_fn})
+ modules = dict(module.named_modules())
+ for fqn in selected:
+ if fqn in skip:
+ continue
+ modules[fqn]._parameters["weight"] = _FakeQuantized(classes[config])
+
+ quantization = types.ModuleType("torchao.quantization")
+ quantization.quantize_ = _quantize_
+ monkeypatch.setitem(sys.modules, "torchao", types.ModuleType("torchao"))
+ monkeypatch.setitem(sys.modules, "torchao.quantization", quantization)
+ dtq = sys.modules["core.inference.diffusion_transformer_quant"]
+ monkeypatch.setattr(dtq, "_make_quant_config", lambda scheme, fast_accum = None: f"cfg:{scheme}")
+ return calls
+
+
+def test_the_two_passes_are_disjoint_and_nvfp4_runs_first(monkeypatch):
+ import core.inference.diffusion_transformer_quant # noqa: F401 - the stub patches the module
+
+ calls = _stub_quantize(monkeypatch)
+ tree = _flux()
+ assignment = quantize_with_policy(tree, FLUX_R420)
+ assert [call["config"] for call in calls] == ["cfg:nvfp4", "cfg:fp8"]
+ nvfp4, fp8 = set(calls[0]["selected"]), set(calls[1]["selected"])
+ assert len(nvfp4) == 187 and len(fp8) == 312
+ assert not (nvfp4 & fp8)
+ assert nvfp4 == {fqn for fqn, p in assignment.items() if p == NVFP4}
+ assert fp8 == {fqn for fqn, p in assignment.items() if p == FP8}
+ fp8_filter = calls[1]["filter_fn"]
+ already = tree.linears["single_transformer_blocks.11.norm.linear"]
+ assert not fp8_filter(already, "single_transformer_blocks.11.norm.linear")
+ victim = "single_transformer_blocks.0.attn.to_q"
+ tree.linears[victim]._parameters["weight"] = _FakeQuantized("NVFP4Tensor")
+ assert not fp8_filter(tree.linears[victim], victim)
+
+
+def test_a_layer_the_quantiser_silently_declined_fails_the_build(monkeypatch):
+ import core.inference.diffusion_transformer_quant # noqa: F401 - the stub patches the module
+ _stub_quantize(monkeypatch, skip = ("transformer_blocks.3.attn.to_v",))
+ with pytest.raises(PolicyMismatch, match = "transformer_blocks.3.attn.to_v"):
+ quantize_with_policy(_qwen(), QWEN_P02)
+
+
+def test_a_pass_that_produced_the_wrong_tensor_class_fails_the_build(monkeypatch):
+ import core.inference.diffusion_transformer_quant # noqa: F401 - the stub patches the module
+ _stub_quantize(monkeypatch, produced = {"cfg:nvfp4": "Float8Tensor", "cfg:fp8": "Float8Tensor"})
+ with pytest.raises(PolicyMismatch, match = "wanted NVFP4Tensor"):
+ quantize_with_policy(_zimage(), ZIMG_RG76)
+
+
+def test_the_metadata_block_records_the_set_that_was_built():
+ assignment = assign_precisions(_zimage(), ZIMG_RG76)
+ fragment = policy_metadata(ZIMG_RG76, assignment)
+ block = fragment[NVFP4_POLICY_KEY]
+ assert block["kind"] == NVFP4_POLICY_KIND
+ assert block["policy_id"] == "zimg_rg76_v1" and block["policy_version"] == 1
+ assert block["counts"] == {BF16: 5, FP8: 195, NVFP4: 76}
+ assert len(block["nvfp4_fqns"]) == 76
+ assert block["nvfp4_fqns"] == sorted(block["nvfp4_fqns"])
+ assert block["activation_scales_baked"] is False and block["gptq"] is False
+ assert declares_policy({"scheme": "nvfp4", **fragment})
+ assert policy_metadata_error({"scheme": "nvfp4", **fragment}) is None
+ assert policy_metadata(ZIMG_RG76, assign_precisions(_zimage(), ZIMG_RG76)) == fragment
+
+
+def test_an_unreadable_policy_block_reads_as_declared_so_it_can_be_refused():
+ assert not declares_policy({"scheme": "nvfp4"})
+ assert not declares_policy(None)
+ assert not declares_policy({NVFP4_POLICY_KEY: None})
+ assert declares_policy({NVFP4_POLICY_KEY: {}})
+ assert policy_metadata_error({"scheme": "nvfp4"}) is None
+
+
+ ("block", "expected"),
+ [
+ ({}, "unsupported nvfp4 policy"),
+ ("zimg_rg76_v1", "not a dict"),
+ ({"kind": "unsloth_nvfp4_layer_policy_v2"}, "unsupported nvfp4 policy"),
+ ({"kind": NVFP4_POLICY_KIND}, "no policy_id"),
+ ({"kind": NVFP4_POLICY_KIND, "policy_id": "p"}, "policy_version"),
+ (
+ {"kind": NVFP4_POLICY_KIND, "policy_id": "p", "policy_version": 1},
+ "no counts",
+ ),
+ (
+ {
+ "kind": NVFP4_POLICY_KIND,
+ "policy_id": "p",
+ "policy_version": 1,
+ "counts": {NVFP4: 2},
+ },
+ "no nvfp4_fqns",
+ ),
+ (
+ {
+ "kind": NVFP4_POLICY_KIND,
+ "policy_id": "p",
+ "policy_version": 1,
+ "counts": {NVFP4: 2},
+ "nvfp4_fqns": ["a", "a"],
+ },
+ "duplicates",
+ ),
+ (
+ {
+ "kind": NVFP4_POLICY_KIND,
+ "policy_id": "p",
+ "policy_version": 1,
+ "counts": {NVFP4: 3},
+ "nvfp4_fqns": ["a", "b"],
+ },
+ "lists 2",
+ ),
+ ],
+)
+def test_every_malformed_policy_block_says_why(block, expected):
+ problem = policy_metadata_error({NVFP4_POLICY_KEY: block})
+ assert problem is not None and expected in problem
diff --git a/studio/backend/tests/test_diffusion_nvfp4_protect.py b/studio/backend/tests/test_diffusion_nvfp4_protect.py
new file mode 100644
index 00000000000..3a0895f729b
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_nvfp4_protect.py
@@ -0,0 +1,631 @@
+# 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 os
+import types
+
+import pytest
+
+from core.inference import diffusion_nvfp4_linear as nl
+from core.inference import diffusion_nvfp4_ops as ops
+from core.inference import diffusion_nvfp4_protect as pr
+
+REAL_SHAPES = ((3072, 3072), (18432, 3072), (15360, 256), (5120, 3072))
+
+
+class _CapableLayer:
+ """A stand-in for a converted flashinfer Linear: weak-referenceable is all the registry asks."""
+
+
+def _capable(ctl):
+ """Keep the result alive: the registry is weak."""
+ layer = _CapableLayer()
+ ctl.register_layer(layer)
+ return layer
+
+
+def _cuda_or_skip():
+ torch = pytest.importorskip("torch")
+ if os.environ.get("CUDA_VISIBLE_DEVICES", None) == "":
+ pytest.skip("CUDA devices are masked off for this process")
+ if not getattr(torch, "cuda", None) or not torch.cuda.is_available():
+ pytest.skip("needs CUDA")
+ capability = tuple(torch.cuda.get_device_capability(0))
+ if capability not in ops.NVFP4_FLASHINFER_CAPS:
+ pytest.skip("sm_%d%d has no flashinfer NVFP4 kernels" % capability)
+ pytest.importorskip("flashinfer")
+ pytest.importorskip("torchao")
+ return torch
+
+
+ "spec,total,want",
+ [
+ ("0,1,2,3,-1", 50, (0, 1, 2, 3, 49)),
+ ("0,-1", 50, (0, 49)),
+ ("0,1,2,3,4,5,6,7,-1", 50, (0, 1, 2, 3, 4, 5, 6, 7, 49)),
+ ("auto", 50, (0, 1, 2, 3, 49)),
+ ("auto", 8, (0, 7)),
+ ("auto", 100, tuple(range(8)) + (99,)),
+ ("auto", 1, (0,)),
+ (" 0 , 0 , -1 , 49 ", 50, (0, 49)),
+ ("", 50, ()),
+ ("off", 50, ()),
+ ("none", 50, ()),
+ (None, 50, ()),
+ ("0,1,2,3,-1", 4, (0, 1, 2, 3)),
+ ("0,1,2,3,-1", 2, (0, 1)),
+ ("60", 50, ()),
+ ("0", 0, ()),
+ ],
+)
+def test_the_schedule_parses(spec, total, want):
+ assert pr.parse_protect_steps(spec, total) == want
+
+
+def test_a_typo_in_the_schedule_raises_rather_than_protecting_nothing():
+ with pytest.raises(ValueError) as excinfo:
+ pr.parse_protect_steps("0,fisrt,-1", 50)
+ assert "not a step index" in str(excinfo.value)
+ assert pr.PROTECT_STEPS_ENV in str(excinfo.value)
+
+
+def test_the_env_reader_treats_blank_and_off_as_off(monkeypatch):
+ monkeypatch.delenv(pr.PROTECT_STEPS_ENV, raising = False)
+ assert pr.protect_steps_env() == ""
+ monkeypatch.setenv(pr.PROTECT_STEPS_ENV, " ")
+ assert pr.protect_steps_env() == ""
+ monkeypatch.setenv(pr.PROTECT_STEPS_ENV, "OFF")
+ assert pr.protect_steps_env() == ""
+ monkeypatch.setenv(pr.PROTECT_STEPS_ENV, " 0,1,2,3,-1 ")
+ assert pr.protect_steps_env() == "0,1,2,3,-1"
+ monkeypatch.setenv(pr.PROTECT_STEPS_ENV, "AUTO")
+ assert pr.protect_steps_env() == "auto"
+
+
+def test_an_unarmed_controller_never_protects():
+ ctl = pr.NVFP4StepController("")
+ assert ctl.armed is False
+ assert ctl.begin(50) == ()
+ for _ in range(50):
+ assert ctl.protected is False
+ ctl.advance()
+ assert ctl.protected_steps_seen == 0
+
+
+def test_the_controller_protects_exactly_the_named_steps():
+ ctl = pr.NVFP4StepController("0,1,2,3,-1")
+ assert ctl.armed is True
+ assert ctl.begin(50) == (0, 1, 2, 3, 49)
+ fired = []
+ for step in range(50):
+ assert ctl.index == step
+ if ctl.protected:
+ fired.append(step)
+ ctl.advance()
+ assert fired == [0, 1, 2, 3, 49]
+ assert ctl.protected_steps_seen == 5
+ assert ctl.protected is False
+
+
+def test_reset_leaves_a_controller_protecting_nothing():
+ ctl = pr.NVFP4StepController("auto")
+ ctl.begin(50)
+ assert ctl.protected is True
+ ctl.reset()
+ assert (ctl.protected, ctl.index, ctl.steps, ctl.total) == (False, 0, (), 0)
+ assert ctl.armed is True
+
+
+def test_begin_clears_the_previous_generation():
+ ctl = pr.NVFP4StepController("-1")
+ ctl.begin(4)
+ for _ in range(3):
+ ctl.advance()
+ assert (ctl.index, ctl.protected) == (3, True)
+ assert ctl.begin(50) == (49,)
+ assert (ctl.index, ctl.protected, ctl.generations) == (0, False, 2)
+
+
+def test_a_bad_schedule_is_logged_and_costs_no_render():
+ class _Logger:
+ def __init__(self):
+ self.text = ""
+
+ def warning(self, message, *args):
+ self.text += (message % args if args else message) + "\n"
+
+ def info(self, message, *args):
+ self.text += (message % args if args else message) + "\n"
+
+ logger = _Logger()
+ ctl = pr.NVFP4StepController("0,oops")
+ assert ctl.begin(50, logger = logger) == ()
+ assert "protect schedule ignored" in logger.text
+ assert ctl.protected is False
+
+
+def test_configure_rearms_and_disarms():
+ ctl = pr.NVFP4StepController("")
+ assert ctl.armed is False
+ ctl.configure("0,-1")
+ assert (ctl.armed, ctl.spec) == (True, "0,-1")
+ ctl.configure("off")
+ assert (ctl.armed, ctl.spec) == (False, "")
+
+
+class _FakeScheduler:
+ def __init__(self) -> None:
+ self.calls = 0
+
+ def step(self, *args, **kwargs):
+ self.calls += 1
+ return "stepped"
+
+
+class _FakePipe:
+ def __init__(self) -> None:
+ self.scheduler = _FakeScheduler()
+
+ def run(self, steps: int, observe) -> None:
+ for _ in range(steps):
+ observe()
+ self.scheduler.step()
+
+
+def test_the_scheduler_wrapper_gives_the_forward_the_right_step_index():
+ ctl = pr.NVFP4StepController("0,1,2,3,-1")
+ layer = _capable(ctl)
+ pipe = _FakePipe()
+ seen: list = []
+ with pr.protect_generation(pipe, 50, controller = ctl):
+ pipe.run(50, lambda: seen.append((ctl.index, ctl.protected)))
+ assert [index for index, _ in seen] == list(range(50))
+ assert [index for index, protected in seen if protected] == [0, 1, 2, 3, 49]
+ assert pipe.scheduler.calls == 50
+
+
+def test_the_wrapper_is_removed_and_the_controller_reset_afterwards():
+ ctl = pr.NVFP4StepController("0")
+ layer = _capable(ctl)
+ pipe = _FakePipe()
+ assert "step" not in pipe.scheduler.__dict__
+ with pr.protect_generation(pipe, 8, controller = ctl):
+ assert "step" in pipe.scheduler.__dict__
+ assert ctl.protected is True
+ assert "step" not in pipe.scheduler.__dict__
+ assert (ctl.protected, ctl.steps, ctl.index) == (False, (), 0)
+
+
+def test_the_wrapper_is_removed_when_the_denoise_loop_raises():
+ ctl = pr.NVFP4StepController("0,-1")
+ layer = _capable(ctl)
+ pipe = _FakePipe()
+ with pytest.raises(RuntimeError):
+ with pr.protect_generation(pipe, 8, controller = ctl):
+ pipe.scheduler.step()
+ raise RuntimeError("cancelled")
+ assert "step" not in pipe.scheduler.__dict__
+ assert ctl.protected is False
+
+
+def test_an_unarmed_controller_wraps_nothing_at_all():
+ ctl = pr.NVFP4StepController("")
+ pipe = _FakePipe()
+ with pr.protect_generation(pipe, 50, controller = ctl):
+ assert "step" not in pipe.scheduler.__dict__
+ pipe.run(50, lambda: None)
+ assert ctl.protected is False
+
+
+def test_a_pipeline_with_no_scheduler_protects_nothing():
+ class _NoScheduler:
+ scheduler = None
+
+ class _Logger:
+ text = ""
+
+ def warning(self, message, *args):
+ type(self).text += message % args if args else message
+
+ ctl = pr.NVFP4StepController("0,-1")
+ layer = _capable(ctl)
+ logger = _Logger()
+ with pr.protect_generation(_NoScheduler(), 50, controller = ctl, logger = logger):
+ assert ctl.protected is False
+ assert "no scheduler.step" in _Logger.text
+
+
+def test_a_second_wrapper_over_the_first_still_counts_once():
+ ctl = pr.NVFP4StepController("0,-1")
+ layer = _capable(ctl)
+ pipe = _FakePipe()
+ with pr.protect_generation(pipe, 10, controller = ctl):
+ inner = pipe.scheduler.step
+ ticks: list = []
+ progress = pipe.scheduler.step
+
+ def outer(*a, **kw):
+ ticks.append(1)
+ return progress(*a, **kw)
+
+ pipe.scheduler.step = outer
+ seen: list = []
+ pipe.run(10, lambda: seen.append(ctl.index))
+ pipe.scheduler.step = inner
+ assert seen == list(range(10))
+ assert len(ticks) == 10
+ assert "step" not in pipe.scheduler.__dict__
+
+
+def test_the_graph_key_is_empty_when_the_lever_is_off(monkeypatch):
+ monkeypatch.delenv(pr.PROTECT_STEPS_ENV, raising = False)
+ pr.reset_protect_controller()
+ assert pr.protect_graph_key() == ()
+ assert pr.protect_graph_key(True) == ()
+
+
+def test_the_graph_key_separates_the_two_branches(monkeypatch):
+ monkeypatch.setenv(pr.PROTECT_STEPS_ENV, "0,-1")
+ ctl = pr.reset_protect_controller()
+ try:
+ ctl.begin(50)
+ assert pr.protect_graph_key() == (("nvfp4_protect", True),)
+ ctl.advance()
+ assert pr.protect_graph_key() == (("nvfp4_protect", False),)
+ assert pr.protect_graph_key(True) != pr.protect_graph_key(False)
+ finally:
+ monkeypatch.delenv(pr.PROTECT_STEPS_ENV, raising = False)
+ pr.reset_protect_controller()
+
+
+def test_the_wrapper_does_not_key_a_model_with_no_nvfp4_layers(monkeypatch):
+ """An fp8 load in a process that names protect steps must not double its graph count."""
+ torch = pytest.importorskip("torch")
+ import torch.nn as nn
+ from core.inference import diffusion_cuda_graph as cg
+
+ monkeypatch.setenv(pr.PROTECT_STEPS_ENV, "0,-1")
+ pr.reset_protect_controller()
+ try:
+ assert cg._protect_keyed(nn.Sequential(nn.Linear(8, 8))) is False
+ finally:
+ monkeypatch.delenv(pr.PROTECT_STEPS_ENV, raising = False)
+ pr.reset_protect_controller()
+ assert torch is not None
+
+
+def _cpu_layer(
+ torch,
+ *,
+ in_features = 64,
+ out_features = 32,
+):
+ return nl.nvfp4_linear_class()(
+ in_features,
+ out_features,
+ wq = torch.zeros(out_features, in_features // 2, dtype = torch.uint8),
+ w_sf = torch.ones(128, 4, dtype = torch.uint8),
+ alpha = torch.tensor([0.25]),
+ a_gsf = torch.tensor([1344.0]),
+ bias = None,
+ )
+
+
+def test_a_layer_takes_the_process_controller_and_derives_its_weight_scale():
+ torch = pytest.importorskip("torch")
+ layer = _cpu_layer(torch)
+ assert layer.protect is pr.protect_controller()
+ assert float(layer.w_scale) == pytest.approx(0.25 * 1344.0)
+ assert "protect=" not in layer.extra_repr()
+
+
+def test_the_layer_repr_names_the_schedule_when_armed(monkeypatch):
+ torch = pytest.importorskip("torch")
+ monkeypatch.setenv(pr.PROTECT_STEPS_ENV, "0,1,2,3,-1")
+ pr.reset_protect_controller()
+ try:
+ assert "protect=0,1,2,3,-1" in _cpu_layer(torch).extra_repr()
+ finally:
+ monkeypatch.delenv(pr.PROTECT_STEPS_ENV, raising = False)
+ pr.reset_protect_controller()
+
+
+def test_attach_controller_reaches_every_nvfp4_layer():
+ torch = pytest.importorskip("torch")
+ import torch.nn as nn
+
+ tree = nn.Sequential(_cpu_layer(torch), nn.SiLU(), _cpu_layer(torch), nn.Linear(4, 4))
+ ctl = pr.NVFP4StepController("0")
+ assert pr.attach_controller(tree, ctl) == 2
+ assert tree[0].protect is ctl and tree[2].protect is ctl
+ assert [name for name, _ in pr.protect_layers(tree)] == ["0", "2"]
+
+
+def test_an_image_and_a_video_render_in_flight_keep_their_own_schedules(monkeypatch):
+ torch = pytest.importorskip("torch")
+ import torch.nn as nn
+
+ monkeypatch.setenv(pr.PROTECT_STEPS_ENV, "0")
+ pr.reset_protect_controller()
+ try:
+ image, video = _FakePipe(), _FakePipe()
+ image.transformer = nn.Sequential(_cpu_layer(torch))
+ video.transformer = nn.Sequential(_cpu_layer(torch))
+ a = pr.attach_own_controller(image.transformer)
+ b = pr.attach_own_controller(video.transformer)
+ assert a is not b and a.armed and b.armed
+ assert pr.pipeline_controllers(image) == [a]
+ assert pr.module_controller(video.transformer) is b
+ assert pr.protect_controller().capable_layers() == 0
+ with pr.protect_generation(video, 10):
+ assert b.protected
+ with pr.protect_generation(image, 10):
+ image.run(3, lambda: None)
+ assert a.index == 3 and not a.protected
+ assert b.index == 0 and b.protected and b.total == 10
+ finally:
+ monkeypatch.delenv(pr.PROTECT_STEPS_ENV, raising = False)
+ pr.reset_protect_controller()
+
+
[email protected]("out_features,in_features", REAL_SHAPES)
+def test_the_dequantiser_matches_torchao_bit_for_bit(out_features, in_features):
+ torch = _cuda_or_skip()
+ from torchao.prototype.mx_formats.nvfp4_tensor import NVFP4Tensor
+
+ torch.manual_seed(7)
+ with torch.cuda.device(0):
+ w = torch.randn(out_features, in_features, device = "cuda", dtype = torch.bfloat16) * 0.02
+ amax = w.float().abs().amax().clamp(min = 1e-8)
+ per_tensor_scale = (amax / (6.0 * 448.0)).reshape(1)
+ tensor = NVFP4Tensor.to_nvfp4(w, per_tensor_scale = per_tensor_scale, is_swizzled_scales = True)
+ wq = tensor.qdata.view(torch.uint8).contiguous()
+ cols = in_features // 16
+ w_sf = (
+ tensor.scale.reshape(-1)
+ .view(torch.uint8)
+ .reshape(ops.sf_matrix_shape(out_features, cols))
+ .contiguous()
+ )
+
+ want = tensor.dequantize(torch.bfloat16)
+ got = ops.dequantize_nvfp4_weight(wq, w_sf, per_tensor_scale, dtype = torch.bfloat16)
+
+ assert tuple(got.shape) == (out_features, in_features)
+ assert got.dtype == torch.bfloat16
+ assert torch.equal(got, want), (
+ f"{int((got != want).sum())} of {got.numel()} elements differ from "
+ f"NVFP4Tensor.dequantize"
+ )
+ with torch.cuda.device(0):
+ assert torch.equal(
+ ops.dequantize_nvfp4_weight(wq, w_sf, per_tensor_scale, dtype = torch.float32),
+ tensor.dequantize(torch.float32),
+ )
+
+
+def test_the_dequantiser_matches_flashinfers_own_packing():
+ torch = _cuda_or_skip()
+ import flashinfer
+
+ out_features, in_features = 3072, 3072
+ torch.manual_seed(11)
+ with torch.cuda.device(0):
+ w = torch.randn(out_features, in_features, device = "cuda", dtype = torch.bfloat16) * 0.02
+ amax = w.float().abs().amax().clamp(min = 1e-8)
+ w_gsf = (6.0 * 448.0 / amax).reshape(1)
+ wq, w_sf = flashinfer.nvfp4_quantize(w, w_gsf, do_shuffle = False)
+ cols = in_features // 16
+ deq = ops.dequantize_nvfp4_weight(
+ wq.view(torch.uint8),
+ w_sf.reshape(-1).view(torch.uint8).reshape(ops.sf_matrix_shape(out_features, cols)),
+ (1.0 / w_gsf),
+ dtype = torch.float32,
+ )
+ rel = float((deq - w.float()).norm() / w.float().norm())
+ assert rel < 0.12, rel
+ assert bool(torch.isfinite(deq).all())
+
+
+def _torchao_linear(
+ torch,
+ out_features,
+ in_features,
+ *,
+ bias = True,
+ seed = 0,
+):
+ import torch.nn as nn
+ from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig
+ from torchao.quantization import quantize_
+
+ torch.manual_seed(seed)
+ linear = nn.Linear(in_features, out_features, bias = bias).to("cuda", torch.bfloat16)
+ quantize_(linear, NVFP4DynamicActivationNVFP4WeightConfig(use_triton_kernel = False))
+ return linear
+
+
[email protected]("m", [1, 512, 4096])
+def test_a_protected_forward_is_the_dense_bf16_gemm(m):
+ torch = _cuda_or_skip()
+ import torch.nn.functional as F
+
+ with torch.cuda.device(0):
+ linear = _torchao_linear(torch, 3072, 3072)
+ x = torch.randn(m, 3072, device = "cuda", dtype = torch.bfloat16) * 0.05
+ converted = nl.nvfp4_linear_from_torchao(linear, ops.global_scale(x))
+ ctl = pr.NVFP4StepController("0")
+ converted.protect = ctl
+ ctl.begin(2)
+
+ with torch.inference_mode():
+ got = converted(x)
+ weight = ops.dequantize_nvfp4_weight(
+ converted.wq, converted.w_sf, converted.w_scale, dtype = torch.bfloat16
+ )
+ want = F.linear(x, weight)
+ want = want.to(x.dtype)
+ want.add_(converted.bias)
+ ctl.advance()
+ assert ctl.protected is False
+ w4a4 = converted(x)
+
+ assert torch.equal(got, want)
+ assert bool(torch.isfinite(w4a4).all())
+ rel = float((got.float() - w4a4.float()).norm() / w4a4.float().norm())
+ assert 0.0 < rel < 0.2, rel
+
+
+def test_the_protected_branch_leaves_no_resident_weight_behind():
+ torch = _cuda_or_skip()
+
+ with torch.cuda.device(0):
+ linear = _torchao_linear(torch, 18432, 3072, seed = 3)
+ x = torch.randn(1024, 3072, device = "cuda", dtype = torch.bfloat16) * 0.05
+ converted = nl.nvfp4_linear_from_torchao(linear, ops.global_scale(x))
+ ctl = pr.NVFP4StepController("1")
+ converted.protect = ctl
+ ctl.begin(4)
+
+ resident = lambda: sum(b.numel() * b.element_size() for b in converted.buffers())
+ before_bytes = resident()
+ with torch.inference_mode():
+ converted(x)
+ torch.cuda.synchronize()
+ baseline = torch.cuda.memory_allocated()
+ ctl.advance()
+ assert ctl.protected is True
+ with torch.inference_mode():
+ out = converted(x)
+ del out
+ torch.cuda.synchronize()
+ after = torch.cuda.memory_allocated()
+
+ assert resident() == before_bytes
+ assert after == baseline, f"{(after - baseline) / 2 ** 20:.1f} MiB left resident"
+
+
+def test_the_switch_costs_two_compiled_variants_over_a_fifty_step_render():
+ torch = _cuda_or_skip()
+ import torch._dynamo as dynamo
+
+ with torch.cuda.device(0):
+ linear = _torchao_linear(torch, 3072, 3072, seed = 5)
+ x = torch.randn(512, 3072, device = "cuda", dtype = torch.bfloat16) * 0.05
+ converted = nl.nvfp4_linear_from_torchao(linear, ops.global_scale(x))
+ ctl = pr.NVFP4StepController("0,1,2,3,-1")
+ converted.protect = ctl
+
+ dynamo.reset()
+ dynamo.utils.counters.clear()
+ compiled = torch.compile(converted, fullgraph = True, dynamic = False)
+ ctl.begin(50)
+ with torch.inference_mode():
+ for _ in range(50):
+ compiled(x)
+ ctl.advance()
+ frames = dynamo.utils.counters["stats"]["unique_graphs"]
+
+ assert frames == 2, f"{frames} compiled variants for one bool; expected 2"
+ assert ctl.protected_steps_seen == 5
+
+
+def test_a_captured_block_gets_one_graph_per_branch(monkeypatch):
+ torch = _cuda_or_skip()
+ import torch.nn as nn
+ from core.inference import diffusion_cuda_graph as cg
+
+ monkeypatch.setenv(pr.PROTECT_STEPS_ENV, "0")
+ ctl = pr.reset_protect_controller()
+ try:
+ with torch.cuda.device(0):
+ linear = _torchao_linear(torch, 3072, 3072, seed = 9)
+ x = torch.randn(512, 3072, device = "cuda", dtype = torch.bfloat16) * 0.05
+ converted = nl.nvfp4_linear_from_torchao(linear, ops.global_scale(x))
+
+ class Block(nn.Module):
+ def __init__(self, inner):
+ super().__init__()
+ self.inner = inner
+
+ def forward(
+ self,
+ hidden_states,
+ return_dict = True,
+ ):
+ out = self.inner(hidden_states)
+ return types.SimpleNamespace(sample = out) if return_dict else (out,)
+
+ block = Block(converted).eval()
+ handle = cg.GraphedForward(block).install().enable()
+ ctl.begin(4)
+ call = lambda: block(hidden_states = x, return_dict = False)[0].clone()
+ with torch.inference_mode():
+ protected = call()
+ ctl.advance()
+ assert ctl.protected is False
+ plain = call()
+ ctl.advance()
+ again = call()
+ captures = handle.stats["captures"]
+ replays = handle.stats["replays"]
+ cg.uninstall_all([handle])
+ finally:
+ monkeypatch.delenv(pr.PROTECT_STEPS_ENV, raising = False)
+ pr.reset_protect_controller()
+
+ assert captures == 2, handle.stats
+ assert replays == 3, handle.stats
+ assert torch.equal(plain, again)
+ assert not torch.equal(protected, plain)
+
+
+def test_an_armed_controller_with_no_protect_capable_layer_refuses_and_says_so():
+ """A torchao load runs W4A4 at every step, so arming there would count steps nothing ran."""
+
+ class _Logger:
+ def __init__(self):
+ self.text = ""
+
+ def warning(self, message, *args):
+ self.text += (message % args if args else message) + "\n"
+
+ def info(self, message, *args):
+ self.text += (message % args if args else message) + "\n"
+
+ ctl = pr.NVFP4StepController("0,-1")
+ assert ctl.capable_layers() == 0
+ pipe = _FakePipe()
+ logger = _Logger()
+ with pr.protect_generation(pipe, 10, controller = ctl, logger = logger):
+ assert "step" not in pipe.scheduler.__dict__
+ pipe.run(10, lambda: None)
+ assert "no protect-capable NVFP4 layer" in logger.text
+ assert (ctl.steps, ctl.protected, ctl.protected_steps_seen) == ((), False, 0)
+
+
+def test_a_registered_layer_lets_the_same_controller_arm():
+ ctl = pr.NVFP4StepController("0,-1")
+ layer = _capable(ctl)
+ assert ctl.capable_layers() == 1
+ pipe = _FakePipe()
+ seen: list = []
+ with pr.protect_generation(pipe, 10, controller = ctl):
+ pipe.run(10, lambda: seen.append(ctl.protected))
+ assert [i for i, protected in enumerate(seen) if protected] == [0, 9]
+ assert layer is not None
+
+
+def test_the_layer_registry_is_weak_so_an_unloaded_model_stops_counting():
+ import gc
+
+ ctl = pr.NVFP4StepController("0,-1")
+ layer = _capable(ctl)
+ assert ctl.capable_layers() == 1
+ del layer
+ gc.collect()
+ assert ctl.capable_layers() == 0
diff --git a/studio/backend/tests/test_diffusion_nvfp4_protect_image.py b/studio/backend/tests/test_diffusion_nvfp4_protect_image.py
new file mode 100644
index 00000000000..64ae6e48b71
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_nvfp4_protect_image.py
@@ -0,0 +1,460 @@
+# 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 ast
+import os
+import pathlib
+import sys
+import types
+
+import pytest
+
+from core.inference import diffusion_nvfp4_protect as pr
+
+_INFERENCE_DIR = pathlib.Path(__file__).resolve().parents[1] / "core" / "inference"
+_DIFFUSION = _INFERENCE_DIR / "diffusion.py"
+
+
+def _generate_body() -> ast.FunctionDef:
+ tree = ast.parse(_DIFFUSION.read_text(encoding = "utf-8"))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.FunctionDef) and node.name == "generate":
+ return node
+ raise AssertionError("diffusion.py has no generate()")
+
+
+def _calls(node: ast.AST, name: str) -> list:
+ found = []
+ for sub in ast.walk(node):
+ if isinstance(sub, ast.Call):
+ func = sub.func
+ target = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None)
+ if target == name:
+ found.append(sub)
+ return found
+
+
+def test_generate_arms_the_lever_with_the_effective_step_count():
+ """Not ``steps``: an img2img at strength < 1 denoises a fraction of them."""
+ generate = _generate_body()
+ calls = _calls(generate, "protect_generation")
+ assert len(calls) == 1, "generate() should arm the lever exactly once, per chunk"
+ call = calls[0]
+ assert len(call.args) >= 2
+ assert isinstance(call.args[1], ast.Name) and call.args[1].id == "denoise_steps"
+
+
+def test_the_effective_step_count_is_computed_outside_the_auto_cache_branch():
+ generate = _generate_body()
+ assignments = [
+ node
+ for node in ast.walk(generate)
+ if isinstance(node, ast.Assign)
+ and any(isinstance(t, ast.Name) and t.id == "denoise_steps" for t in node.targets)
+ ]
+ assert len(assignments) == 1
+ assert _calls(assignments[0], "effective_denoise_steps")
+ for node in ast.walk(generate):
+ if isinstance(node, ast.If):
+ for sub in ast.walk(node):
+ assert sub is not assignments[0], "denoise_steps is computed conditionally again"
+
+
+def test_the_lever_wraps_the_chunk_render_itself():
+ generate = _generate_body()
+ wrapped = []
+ for node in ast.walk(generate):
+ if not isinstance(node, ast.With):
+ continue
+ names = set()
+ for item in node.items:
+ expr = item.context_expr
+ if isinstance(expr, ast.Name):
+ names.add(expr.id)
+ elif isinstance(expr, ast.Call):
+ func = expr.func
+ names.add(func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", ""))
+ if "protect_ctx" in names:
+ wrapped.append(names)
+ assert wrapped, "the protect context is never entered"
+ assert any("inference_mode" in names for names in wrapped)
+
+
+def test_the_image_module_imports_the_lever_at_module_scope():
+ source = _DIFFUSION.read_text(encoding = "utf-8")
+ assert "from .diffusion_nvfp4_protect import protect_generation" in source
+
+
+class _CachedScheduler:
+ def __init__(self) -> None:
+ self.calls = 0
+
+ def step(self, *args, **kwargs):
+ self.calls += 1
+ return "stepped"
+
+
+class _CapableLayer:
+ """A stand-in for a converted flashinfer Linear: weak-referenceable is all the registry asks."""
+
+
+def _capable(ctl):
+ """Keep the result alive: the registry is weak."""
+ layer = _CapableLayer()
+ ctl.register_layer(layer)
+ return layer
+
+
+class _CachingPipe:
+ def __init__(self, skip_steps) -> None:
+ self.scheduler = _CachedScheduler()
+ self.skip = set(skip_steps)
+
+ def run(self, steps: int, forward) -> None:
+ for i in range(steps):
+ if i not in self.skip:
+ forward()
+ self.scheduler.step()
+
+
+def test_a_cached_step_is_simply_not_protected():
+ """The index still counts scheduler steps, so the lever protects the steps that are COMPUTED."""
+ ctl = pr.NVFP4StepController("0,4,-1")
+ layer = _capable(ctl)
+ pipe = _CachingPipe(skip_steps = {4})
+ seen: list = []
+ with pr.protect_generation(pipe, 9, controller = ctl):
+ pipe.run(9, lambda: seen.append((ctl.index, ctl.protected)))
+ assert pipe.scheduler.calls == 9
+ assert [index for index, _ in seen] == [0, 1, 2, 3, 5, 6, 7, 8]
+ assert [index for index, protected in seen if protected] == [0, 8]
+ assert ctl.protected_steps_seen == 3
+
+
+def test_the_cache_marker_and_the_lever_do_not_fight():
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_cuda_graph as cg
+
+ module = types.SimpleNamespace(_unsloth_step_cache = "[email protected]")
+ handle = object.__new__(cg.GraphedForward)
+ handle.module = module
+ handle.enabled = True
+ handle.bypassed = False
+ handle.poisoned = False
+ handle.orig = lambda *a, **kw: "eager"
+ handle.stats = {"eager_calls": 0}
+ assert handle(torch.zeros(1), return_dict = False) == "eager"
+ assert handle.stats["eager_calls"] == 1
+
+
+def test_each_chunk_restarts_the_schedule_at_step_zero():
+ ctl = pr.NVFP4StepController("0,-1")
+ layer = _capable(ctl)
+ first: list = []
+ second: list = []
+ for sink in (first, second):
+ pipe = _CachingPipe(skip_steps = ())
+ with pr.protect_generation(pipe, 9, controller = ctl):
+ pipe.run(9, lambda: sink.append((ctl.index, ctl.protected)))
+ assert [i for i, p in first if p] == [0, 8]
+ assert [i for i, p in second if p] == [0, 8]
+ assert ctl.generations == 2
+ assert ctl.protected is False
+
+
+ "spec,steps,want",
+ [
+ ("auto", 9, (0, 8)),
+ ("auto", 4, (0, 3)),
+ ("0", 9, (0,)),
+ ("0", 4, (0,)),
+ ("all", 9, tuple(range(9))),
+ ("all", 4, (0, 1, 2, 3)),
+ ],
+)
+def test_the_image_schedules(spec, steps, want):
+ assert pr.parse_protect_steps(spec, steps) == want
+
+
+def test_suspend_protect_disarms_every_controller_it_reaches_and_restores_it():
+ a, b = pr.NVFP4StepController("0"), pr.NVFP4StepController("auto")
+ shared = pr.NVFP4StepController("all")
+ modules = [
+ types.SimpleNamespace(protect = a),
+ types.SimpleNamespace(protect = b),
+ types.SimpleNamespace(protect = shared),
+ types.SimpleNamespace(protect = shared),
+ types.SimpleNamespace(protect = None),
+ types.SimpleNamespace(),
+ ]
+ with pr.suspend_protect(modules):
+ assert not any(c.armed for c in (a, b, shared))
+ assert all(c.armed for c in (a, b, shared))
+
+
+def test_suspend_protect_restores_after_a_raise():
+ ctl = pr.NVFP4StepController("0")
+ with pytest.raises(RuntimeError):
+ with pr.suspend_protect([types.SimpleNamespace(protect = ctl)]):
+ raise RuntimeError("tuning blew up")
+ assert ctl.armed is True
+
+
+def test_prewarm_tunes_the_fp4_kernel_even_on_a_protected_step(monkeypatch):
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_nvfp4_linear as nl
+
+ monkeypatch.setitem(sys.modules, "flashinfer", types.ModuleType("flashinfer"))
+ layer = nl.nvfp4_linear_class()(
+ 64,
+ 32,
+ wq = torch.zeros(32, 32, dtype = torch.uint8),
+ w_sf = torch.ones(128, 4, dtype = torch.uint8),
+ alpha = torch.tensor([0.25]),
+ a_gsf = torch.tensor([1344.0]),
+ bias = None,
+ )
+ ctl = pr.NVFP4StepController("0")
+ layer.protect = ctl
+ ctl.begin(2)
+ assert ctl.protected is True
+
+ branches: list = []
+ original = nl._prewarm_shapes
+
+ def _record(modules, shapes, *, logger, tuned_box):
+ branches.append([m.protect.armed for m in modules])
+
+ nl._prewarm_shapes = _record
+ try:
+ import torch.nn as nn
+ tree = nn.Sequential(layer)
+ nl.nvfp4_prewarm(tree, (1,))
+ finally:
+ nl._prewarm_shapes = original
+ assert branches and branches[0] == [False]
+ assert ctl.armed is True and ctl.protected is True
+
+
+class _BlockHolding:
+ def __new__(cls, inner):
+ import torch.nn as nn
+ class _Impl(nn.Module):
+ def __init__(self, held):
+ super().__init__()
+ self.held = held
+
+ def forward(
+ self,
+ hidden_states,
+ return_dict = True,
+ ):
+ out = hidden_states * 2
+ return (out,) if not return_dict else out
+
+ return _Impl(inner)
+
+
+def _cpu_nvfp4_tree(torch):
+ import torch.nn as nn
+ from core.inference import diffusion_nvfp4_linear as nl
+
+ layer = nl.nvfp4_linear_class()(
+ 64,
+ 32,
+ wq = torch.zeros(32, 32, dtype = torch.uint8),
+ w_sf = torch.ones(128, 4, dtype = torch.uint8),
+ alpha = torch.tensor([0.25]),
+ a_gsf = torch.tensor([1344.0]),
+ bias = None,
+ )
+ return nn.Sequential(layer), layer
+
+
+def test_arming_the_lever_doubles_the_graph_cap_once(monkeypatch):
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_cuda_graph as cg
+
+ monkeypatch.setenv(pr.PROTECT_STEPS_ENV, "0,-1")
+ pr.reset_protect_controller()
+ try:
+ tree, _layer = _cpu_nvfp4_tree(torch)
+
+ block = _BlockHolding(tree).eval()
+ handle = cg.GraphedForward(block, max_graphs = 4).install().enable()
+ before = handle.max_graphs
+ block(hidden_states = torch.zeros(2, 64), return_dict = False)
+ assert handle.protect_keyed is True
+ assert handle.max_graphs == before * 2
+ block(hidden_states = torch.zeros(2, 64), return_dict = False)
+ assert handle.max_graphs == before * 2, "the cap must be raised once, not per call"
+ cg.uninstall_all([handle])
+ finally:
+ monkeypatch.delenv(pr.PROTECT_STEPS_ENV, raising = False)
+ pr.reset_protect_controller()
+
+
+def test_an_unarmed_load_keeps_its_graph_cap(monkeypatch):
+ torch = pytest.importorskip("torch")
+ from core.inference import diffusion_cuda_graph as cg
+
+ monkeypatch.delenv(pr.PROTECT_STEPS_ENV, raising = False)
+ pr.reset_protect_controller()
+ tree, _layer = _cpu_nvfp4_tree(torch)
+ block = _BlockHolding(tree).eval()
+ handle = cg.GraphedForward(block, max_graphs = 4).install().enable()
+ block(hidden_states = torch.zeros(2, 64), return_dict = False)
+ assert handle.protect_keyed is False
+ assert handle.max_graphs == 4
+ cg.uninstall_all([handle])
+
+
+def _cuda_or_skip():
+ from core.inference import diffusion_nvfp4_ops as ops
+
+ torch = pytest.importorskip("torch")
+ if os.environ.get("CUDA_VISIBLE_DEVICES", None) == "":
+ pytest.skip("CUDA devices are masked off for this process")
+ 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("no flashinfer NVFP4 kernels on this card")
+ pytest.importorskip("flashinfer")
+ pytest.importorskip("torchao")
+ return torch
+
+
+def test_a_graphed_dit_captures_one_tuned_graph_per_branch_and_replays_both(monkeypatch):
+ """Two tuned captures, each replay bit-identical to its branch's un-graphed forward."""
+ torch = _cuda_or_skip()
+ import torch.nn as nn
+ from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig
+ from torchao.quantization import quantize_
+
+ from core.inference import diffusion_cuda_graph as cg
+ from core.inference import diffusion_nvfp4_linear as nl
+ from core.inference import diffusion_nvfp4_ops as ops
+
+ monkeypatch.setenv(pr.PROTECT_STEPS_ENV, "0,-1")
+ ctl = pr.reset_protect_controller()
+ nl.reset_tuned_shapes()
+ prewarms: list = []
+ real_prewarm = nl.nvfp4_prewarm
+
+ def _counting_prewarm(module, shapes, **kw):
+ tuned = real_prewarm(module, shapes, **kw)
+ prewarms.append(tuned)
+ return tuned
+
+ monkeypatch.setattr(nl, "nvfp4_prewarm", _counting_prewarm)
+ monkeypatch.setattr(cg, "_nvfp4_flashinfer_linears", cg._nvfp4_flashinfer_linears)
+
+ try:
+ with torch.cuda.device(0):
+ torch.manual_seed(17)
+ dit = (
+ nn.Sequential(nn.Linear(3072, 3072), nn.SiLU(), nn.Linear(3072, 3072))
+ .to("cuda", torch.bfloat16)
+ .eval()
+ )
+ x = torch.randn(1024, 3072, device = "cuda", dtype = torch.bfloat16) * 0.05
+ with torch.inference_mode():
+ hidden = dit[1](dit[0](x))
+ quantize_(dit, NVFP4DynamicActivationNVFP4WeightConfig(use_triton_kernel = False))
+ metadata = {
+ "scheme": "nvfp4",
+ "activation_scales_baked": True,
+ "act_global_scales": {
+ "0": float(ops.global_scale(x)),
+ "2": float(ops.global_scale(hidden)),
+ },
+ }
+ assert nl.convert_nvfp4_backend(dit, metadata, "flashinfer") == 2
+ ctl = pr.module_controller(dit)
+ assert ctl is not pr.protect_controller() and ctl.armed
+
+ class DiT(nn.Module):
+ def __init__(self, inner):
+ super().__init__()
+ self.inner = inner
+
+ def forward(
+ self,
+ hidden_states,
+ return_dict = True,
+ ):
+ out = self.inner(hidden_states)
+ return types.SimpleNamespace(sample = out) if return_dict else (out,)
+
+ module = DiT(dit).eval()
+ eager = {}
+ ctl.begin(9)
+ with torch.inference_mode():
+ eager[True] = module(hidden_states = x, return_dict = False)[0].clone()
+ for _ in range(8):
+ ctl.advance()
+ if not ctl.protected:
+ break
+ assert ctl.protected is False
+ eager[False] = module(hidden_states = x, return_dict = False)[0].clone()
+
+ handle = cg.GraphedForward(module, max_graphs = 4).install().enable()
+
+ def settled() -> tuple:
+ torch.cuda.synchronize()
+ torch.cuda.empty_cache()
+ return torch.cuda.memory_reserved(), torch.cuda.memory_allocated()
+
+ base_reserved, base_alloc = settled()
+ torch.cuda.reset_peak_memory_stats()
+
+ ctl.begin(9)
+ with torch.inference_mode():
+ first = module(hidden_states = x, return_dict = False)[0].clone()
+ after_one, _ = settled()
+ one_graph_peak = torch.cuda.max_memory_allocated()
+
+ for _ in range(8):
+ ctl.advance()
+ if not ctl.protected:
+ break
+ with torch.inference_mode():
+ second = module(hidden_states = x, return_dict = False)[0].clone()
+ after_two, _ = settled()
+ two_graph_peak = torch.cuda.max_memory_allocated()
+
+ ctl.begin(9)
+ with torch.inference_mode():
+ first_again = module(hidden_states = x, return_dict = False)[0].clone()
+ stats = dict(handle.stats)
+ cap = handle.max_graphs
+ cg.uninstall_all([handle])
+ finally:
+ monkeypatch.delenv(pr.PROTECT_STEPS_ENV, raising = False)
+ pr.reset_protect_controller()
+
+ assert stats["captures"] == 2, stats
+ assert stats["replays"] == 3, stats
+ assert stats["fallbacks"] == 0 and stats["cap_skips"] == 0, stats
+ assert cap == 8, "arming the lever should have doubled the cap"
+ assert prewarms and prewarms[0] > 0, prewarms
+ assert torch.equal(first, eager[True])
+ assert torch.equal(second, eager[False])
+ assert torch.equal(first_again, first)
+ assert not torch.equal(first, second)
+ first_graph = after_one - base_reserved
+ second_graph = after_two - after_one
+ print(
+ f"\n[graph memory] model={base_alloc / 2 ** 20:.1f} MiB "
+ f"base_reserved={base_reserved / 2 ** 20:.1f} MiB "
+ f"graph1=+{first_graph / 2 ** 20:.1f} MiB graph2=+{second_graph / 2 ** 20:.1f} MiB "
+ f"peak_after_1={one_graph_peak / 2 ** 20:.1f} MiB "
+ f"peak_after_2={two_graph_peak / 2 ** 20:.1f} MiB"
+ )
+ assert first_graph > 0, "the first capture reserved nothing; the measurement is not reading it"
+ assert second_graph <= 1.5 * first_graph, (first_graph, second_graph)
+ assert two_graph_peak < base_alloc + 2 * first_graph + (64 << 20)
diff --git a/studio/backend/tests/test_diffusion_pipeline_prequant.py b/studio/backend/tests/test_diffusion_pipeline_prequant.py
index cb12d2ef759..aba787026a1 100644
--- a/studio/backend/tests/test_diffusion_pipeline_prequant.py
+++ b/studio/backend/tests/test_diffusion_pipeline_prequant.py
@@ -297,7 +297,7 @@ def _settle_backend(
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda _t: True)
monkeypatch.setattr(dmod, "_pipeline_quant_uncompilable_reason", lambda *_a, **_k: None)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: scheme
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_k: scheme
)
monkeypatch.setattr(
pqmod, "restricted_prequant_load_supported", lambda _scheme, filename = None: True
@@ -382,7 +382,7 @@ def _settle_backend_walking(monkeypatch, *, artifacts: tuple, candidates: tuple)
from core.inference import diffusion_transformer_quant as tq
backend = _settle_backend(monkeypatch, scheme = candidates[0])
- monkeypatch.setattr(tq, "auto_scheme_candidates", lambda target, family = None: candidates)
+ monkeypatch.setattr(tq, "auto_scheme_candidates", lambda target, family = None, **_k: candidates)
monkeypatch.setattr(
dmod,
"denoiser_prequant_source",
@@ -430,6 +430,57 @@ def test_a_walk_with_no_resident_rung_declines(monkeypatch):
assert _settle(backend) == PIPELINE_SEED_DECLINED
+def test_auto_planning_passes_the_base_and_prequant_probe(monkeypatch):
+ """Without the base and a checkpoint probe AUTO drops nvfp4, so the plan must ask like the load."""
+ from core.inference import diffusion_transformer_quant as tq
+
+ backend = _settle_backend(monkeypatch)
+ seen: dict = {}
+
+ def _select(
+ target,
+ mode,
+ family = None,
+ *,
+ base_repo = None,
+ has_prequant = None,
+ **_k,
+ ):
+ seen["select"] = base_repo
+ if base_repo == Z_IMAGE_REPO and has_prequant is not None and has_prequant("nvfp4"):
+ return "nvfp4"
+ return "mxfp8"
+
+ def _candidates(
+ target,
+ family = None,
+ *,
+ base_repo = None,
+ has_prequant = None,
+ **_k,
+ ):
+ seen["candidates"] = base_repo
+ head = ("nvfp4",) if has_prequant is not None and has_prequant("nvfp4") else ()
+ return head + ("mxfp8",)
+
+ monkeypatch.setattr(dmod, "select_transformer_quant_scheme", _select)
+ monkeypatch.setattr(tq, "auto_scheme_candidates", _candidates)
+ monkeypatch.setattr(
+ dmod,
+ "usable_prequant_source",
+ lambda fam, scheme, **_k: object() if scheme == "nvfp4" else None,
+ )
+ monkeypatch.setattr(
+ dmod,
+ "denoiser_prequant_source",
+ lambda fam, scheme, **_k: ("unsloth/Z-Image-Turbo-NVFP4", "z.safetensors")
+ if scheme == "nvfp4"
+ else None,
+ )
+ assert _settle(backend) == "nvfp4"
+ assert seen == {"select": Z_IMAGE_REPO, "candidates": Z_IMAGE_REPO}
+
+
def test_an_explicit_scheme_is_never_swapped_for_a_lower_rung(monkeypatch):
"""An explicit int8 that offloads declines; auto's walk is not offered to an explicit request."""
backend = _settle_backend_walking(
@@ -440,7 +491,7 @@ def test_an_explicit_scheme_is_never_swapped_for_a_lower_rung(monkeypatch):
def test_a_family_with_no_hosted_artifact_falls_through(monkeypatch):
"""A scheme with no hosted artifact falls through to the in-memory quantise."""
- assert _settle(_settle_backend(monkeypatch, scheme = "nvfp4")) is None
+ assert _settle(_settle_backend(monkeypatch, scheme = "mxfp8")) is None
def test_a_base_with_no_hosted_artifact_falls_through(monkeypatch):
@@ -698,7 +749,7 @@ def _load_backend(
monkeypatch.setattr(dmod, "dense_transformer_supported", lambda _t: True)
monkeypatch.setattr(tqmod, "dense_transformer_supported", lambda _t: True)
monkeypatch.setattr(
- dmod, "select_transformer_quant_scheme", lambda target, mode, family = None: "fp8"
+ dmod, "select_transformer_quant_scheme", lambda target, mode, family = None, **_k: "fp8"
)
monkeypatch.setattr(dmod, "dense_quant_blocker", lambda _pipe: None)
monkeypatch.setattr(dmod, "_pipeline_quant_uncompilable_reason", lambda *_a, **_k: None)
diff --git a/studio/backend/tests/test_diffusion_prequant.py b/studio/backend/tests/test_diffusion_prequant.py
index 14ef77d1650..b5153c3fc45 100644
--- a/studio/backend/tests/test_diffusion_prequant.py
+++ b/studio/backend/tests/test_diffusion_prequant.py
@@ -346,11 +346,25 @@ class _Bytes:
class Float8Tensor:
- """A quantized weight as far as the fingerprint is concerned: the class NAME is the key."""
+ """The class NAME is what the fingerprint and the activation-floor check key on."""
- def __init__(self, qdata):
+ def __init__(
+ self,
+ qdata = b"",
+ hp_value_lb = 1e-12,
+ ):
+ self.qdata = _Bytes(qdata)
+ self.scale = _Bytes(b"scale")
+ self.act_quant_kwargs = types.SimpleNamespace(hp_value_lb = hp_value_lb)
+
+
+class NVFP4Tensor:
+ """The 4-bit half of a per-layer policy checkpoint."""
+
+ def __init__(self, qdata = b""):
self.qdata = _Bytes(qdata)
self.scale = _Bytes(b"scale")
+ self.act_quant_kwargs = types.SimpleNamespace(scale_dtype = "float8_e4m3fn")
class _Recorder:
@@ -818,6 +832,35 @@ def test_load_require_bf16_nvfp4_false_ok(monkeypatch, tmp_path):
assert _load(monkeypatch, tmp_path, ckpt, scheme = "nvfp4") is not None
+def test_an_nvfp4_checkpoint_is_prewarmed_by_the_shared_loader(monkeypatch, tmp_path):
+ from core.inference import diffusion_nvfp4_linear as nl
+
+ seen: list = []
+ monkeypatch.setattr(
+ nl, "nvfp4_prewarm", lambda module, shapes, **_k: seen.append(tuple(shapes)) or 0
+ )
+ ckpt = _good_ckpt(scheme = "nvfp4")
+ ckpt["metadata"]["require_bf16"] = False
+ assert _load(monkeypatch, tmp_path, ckpt, scheme = "nvfp4") is not None
+ assert seen == [(1,)]
+
+ seen.clear()
+ assert _load(monkeypatch, tmp_path, _good_ckpt(scheme = "fp8"), scheme = "fp8") is not None
+ assert seen == []
+
+
+def test_a_failed_prewarm_keeps_the_loaded_checkpoint(monkeypatch, tmp_path):
+ from core.inference import diffusion_nvfp4_linear as nl
+
+ def _boom(*_a, **_k):
+ raise RuntimeError("autotune failed")
+
+ monkeypatch.setattr(nl, "nvfp4_prewarm", _boom)
+ ckpt = _good_ckpt(scheme = "nvfp4")
+ ckpt["metadata"]["require_bf16"] = False
+ assert _load(monkeypatch, tmp_path, ckpt, scheme = "nvfp4") is not None
+
+
def test_load_require_bf16_nvfp4_true_is_none(monkeypatch, tmp_path):
# An nvfp4 checkpoint claiming the bf16 gate quantised a different layer set, so it is rejected.
ckpt = _good_ckpt(scheme = "nvfp4")
@@ -2127,25 +2170,18 @@ def test_load_is_dropped_when_the_padding_cannot_be_proven(monkeypatch, tmp_path
# ── fp8 activation scale floor ──────────────────────────────────────────────────
-class _FakeFp8Tensor:
- """Stands in for a torchao Float8Tensor: only act_quant_kwargs.hp_value_lb is read."""
-
- def __init__(self, hp_value_lb):
- self.act_quant_kwargs = types.SimpleNamespace(hp_value_lb = hp_value_lb)
-
-
def test_an_fp8_checkpoint_without_the_activation_floor_is_rejected():
# A checkpoint built before activation_value_lb bakes hp_value_lb=None into every quantised
# tensor, and stays broken however it is loaded: torchao's per-row activation quantiser divides
# by the row amax, so qwen's all-zero text rows give scale 0 and NaN. The metadata checks around
# this one all accept an absent field for back-compat, which is exactly wrong here, so the floor
# is read off the TENSORS instead. Measured: 412 of 512 rows non-finite without it, 0 with it.
- floored = {"blocks.0.attn.to_q.weight": _FakeFp8Tensor(1e-12)}
- unfloored = {"blocks.0.attn.to_q.weight": _FakeFp8Tensor(None)}
+ floored = {"blocks.0.attn.to_q.weight": Float8Tensor(hp_value_lb = 1e-12)}
+ unfloored = {"blocks.0.attn.to_q.weight": Float8Tensor(hp_value_lb = None)}
assert pq._fp8_activation_floor_present(floored, None) is True
assert pq._fp8_activation_floor_present(unfloored, None) is False
# Zero is not a floor either: it is what an unclamped amax divide produces.
- assert pq._fp8_activation_floor_present({"w": _FakeFp8Tensor(0.0)}, None) is False
+ assert pq._fp8_activation_floor_present({"w": Float8Tensor(hp_value_lb = 0.0)}, None) is False
def test_the_floor_check_ignores_dense_and_unreadable_state_dicts():
@@ -2157,6 +2193,140 @@ def test_the_floor_check_ignores_dense_and_unreadable_state_dicts():
assert pq._fp8_activation_floor_present({}, None) is True
+def _policy_meta(
+ policy = None,
+ *,
+ base = "Tongyi-MAI/Z-Image-Turbo",
+ family = "z-image",
+ **overrides,
+):
+ from core.inference.diffusion_nvfp4_policy import (
+ NVFP4_POLICY_KEY,
+ ZIMG_RG76,
+ policy_metadata,
+ )
+
+ policy = policy or ZIMG_RG76
+ assignment = {f"layers.{i}.attention.to_q": "nvfp4" for i in range(76)}
+ assignment.update({f"layers.{i}.feed_forward.w1": "fp8" for i in range(195)})
+ assignment.update({f"t_embedder.mlp.{i}": "bf16" for i in range(5)})
+ block = dict(policy_metadata(policy, assignment)[NVFP4_POLICY_KEY])
+ block.update(overrides)
+ return {
+ "scheme": "nvfp4",
+ "base_model_id": base,
+ "family": family,
+ "fp8_granularity": "per_row",
+ NVFP4_POLICY_KEY: block,
+ }
+
+
+def test_the_format_tag_follows_the_policy_and_refuses_to_carry_two_claims():
+ from core.inference.diffusion_convrot import rotation_metadata
+
+ assert pq.prequant_format_for({"scheme": "nvfp4"}) == pq.PREQUANT_FORMAT
+ assert pq.prequant_format_for(_policy_meta()) == pq.PREQUANT_FORMAT_POLICY
+ assert pq.PREQUANT_FORMAT_POLICY not in (pq.PREQUANT_FORMAT, pq.PREQUANT_FORMAT_ROTATED)
+ both = {**_policy_meta(), **rotation_metadata(128, ["layers.0.attention.to_q"])}
+ with pytest.raises(ValueError, match = "both"):
+ pq.prequant_format_for(both)
+
+
+ ("fmt", "declared", "ok"),
+ [
+ (pq.PREQUANT_FORMAT_POLICY, True, True),
+ (pq.PREQUANT_FORMAT, False, True),
+ (pq.PREQUANT_FORMAT, True, False),
+ (pq.PREQUANT_FORMAT_ROTATED, True, False),
+ (pq.PREQUANT_FORMAT_POLICY, False, False),
+ ],
+)
+def test_the_validator_enforces_the_format_policy_biconditional(fmt, declared, ok):
+ meta = _policy_meta() if declared else {"scheme": "nvfp4"}
+ assert pq._validate_policy(fmt, meta, "nvfp4", None) is ok
+
+
+def test_a_policy_declaration_this_build_cannot_reproduce_is_refused():
+ from core.inference.diffusion_nvfp4_policy import NVFP4_POLICY_KEY
+
+ fmt = pq.PREQUANT_FORMAT_POLICY
+ assert pq._validate_policy(fmt, _policy_meta(), "nvfp4", None) is True
+ assert pq._validate_policy(fmt, _policy_meta(kind = "v2"), "nvfp4", None) is False
+ assert pq._validate_policy(fmt, _policy_meta(nvfp4_fqns = []), "nvfp4", None) is False
+ assert pq._validate_policy(fmt, _policy_meta(), "fp8", None) is False
+ assert pq._validate_policy(fmt, _policy_meta(base = "some/other-dit"), "nvfp4", None) is False
+ assert pq._validate_policy(fmt, _policy_meta(family = "flux.1"), "nvfp4", None) is False
+ assert pq._validate_policy(fmt, _policy_meta(policy_version = 2), "nvfp4", None) is False
+ assert pq._validate_policy(fmt, _policy_meta(policy_id = "qwen_p02_v1"), "nvfp4", None) is False
+ drifted = _policy_meta()
+ drifted[NVFP4_POLICY_KEY]["counts"] = {"nvfp4": 34, "fp8": 236, "bf16": 6}
+ assert pq._validate_policy(fmt, drifted, "nvfp4", None) is False
+
+
+def test_a_policy_checkpoint_is_validated_end_to_end():
+ logger = _Recorder()
+ ckpt = {
+ "format": pq.PREQUANT_FORMAT_POLICY,
+ "metadata": _policy_meta(),
+ "state_dict": {"weight": object()},
+ }
+ assert pq._validate_checkpoint(ckpt, "nvfp4", "Tongyi-MAI/Z-Image-Turbo", logger) is True
+ ckpt["format"] = pq.PREQUANT_FORMAT
+ assert pq._validate_checkpoint(ckpt, "nvfp4", "Tongyi-MAI/Z-Image-Turbo", logger) is False
+ assert "v3" in logger.text
+
+
+def test_the_fp8_invariants_cover_the_fp8_half_of_a_policy_checkpoint():
+ # A policy artifact is declared nvfp4 but mostly Float8Tensor; gating on scheme == fp8 skipped it.
+ logger = _Recorder()
+ ckpt = {
+ "format": pq.PREQUANT_FORMAT_POLICY,
+ "metadata": _policy_meta(),
+ "state_dict": {
+ "layers.0.attention.to_q.weight": NVFP4Tensor(b"q4"),
+ "layers.0.feed_forward.w1.weight": Float8Tensor(hp_value_lb = 1e-12),
+ },
+ }
+ base = "Tongyi-MAI/Z-Image-Turbo"
+ assert pq._validate_checkpoint(ckpt, "nvfp4", base, logger) is True
+ unfloored = dict(ckpt)
+ unfloored["state_dict"] = dict(ckpt["state_dict"])
+ unfloored["state_dict"]["layers.0.feed_forward.w1.weight"] = Float8Tensor(hp_value_lb = None)
+ assert pq._validate_checkpoint(unfloored, "nvfp4", base, logger) is False
+ per_tensor = dict(ckpt)
+ per_tensor["metadata"] = _policy_meta()
+ per_tensor["metadata"]["fp8_granularity"] = "per_tensor"
+ assert pq._validate_checkpoint(per_tensor, "nvfp4", base, logger) is False
+
+
+def test_the_floor_check_skips_the_4_bit_weights_beside_the_fp8_ones():
+ mixed = {
+ "layers.0.attention.to_q.weight": NVFP4Tensor(b"q4"),
+ "layers.0.feed_forward.w1.weight": Float8Tensor(hp_value_lb = 1e-12),
+ }
+ assert pq._fp8_activation_floor_present(mixed, None) is True
+ mixed["layers.0.feed_forward.w1.weight"] = Float8Tensor(hp_value_lb = None)
+ assert pq._fp8_activation_floor_present(mixed, None) is False
+ assert pq._fp8_activation_floor_present({"w": NVFP4Tensor()}, None) is True
+
+
+def test_pinning_the_fp8_kernel_leaves_the_4_bit_weights_alone(monkeypatch):
+ _stub_kernel_preference(monkeypatch)
+ sd = {
+ "layers.0.attention.to_q.weight": NVFP4Tensor(b"q4"),
+ "layers.0.feed_forward.w1.weight": _FakeFp8Weight(_FakeKernelPreference.AUTO),
+ }
+ assert pq._pin_kernel_preference(sd, logger = None) == 1
+ assert not hasattr(sd["layers.0.attention.to_q.weight"], "kernel_preference")
+
+
+def test_an_nvfp4_install_must_be_able_to_open_the_fp8_weights_too():
+ required = pq._SCHEME_REQUIRED_GLOBALS["nvfp4"]
+ assert pq._SCHEME_REQUIRED_GLOBALS["fp8"] <= required
+ assert "torchao.prototype.mx_formats.nvfp4_tensor.NVFP4Tensor" in required
+
+
def test_the_checkpoint_is_released_before_the_device_copy(monkeypatch, tmp_path):
"""assign=True shares the checkpoint's tensors: unreference them before ``.to(device)``."""
import weakref
@@ -2414,3 +2584,223 @@ def test_a_cached_name_this_install_cannot_open_is_not_a_cache_hit(monkeypatch,
monkeypatch.setattr(pq, "restricted_prequant_load_supported", _boom)
assert pq.cached_checkpoint_path(source) == str(tmp_path / "st")
+
+
+def _refused(cls, status):
+ message = f"{status} Client Error: unsloth/Z-Image-Turbo-NVFP4"
+ try:
+ return cls(message, response = None)
+ except (TypeError, AttributeError): # huggingface_hub >= 1.0 reads an httpx response
+ import httpx
+ request = httpx.Request(
+ "GET", "https://huggingface.co/api/models/unsloth/Z-Image-Turbo-NVFP4"
+ )
+ return cls(message, response = httpx.Response(status, request = request))
+
+
+def _nvfp4_repo_source():
+ return PrequantSource(
+ kind = "repo",
+ location = "unsloth/Z-Image-Turbo-NVFP4",
+ filename = "Z-Image-Turbo-NVFP4.pt",
+ )
+
+
+ "error_name,status",
+ [("RepositoryNotFoundError", 401), ("RepositoryNotFoundError", 404), ("GatedRepoError", 403)],
+)
+def test_a_refused_prequant_repo_is_no_checkpoint_not_a_plan_failure(
+ monkeypatch, error_name, status
+):
+ import huggingface_hub
+ from huggingface_hub import errors as hub_errors
+
+ from core.inference.diffusion import DiffusionBackend
+
+ def _refuse(self, *a, **k):
+ raise _refused(getattr(hub_errors, error_name), status)
+
+ monkeypatch.setattr(huggingface_hub.HfApi, "model_info", _refuse)
+ failures: list = []
+ entry = DiffusionBackend._prequant_source_hub_entry(
+ _nvfp4_repo_source(), None, failures, scheme = "nvfp4"
+ )
+ assert entry is None
+ assert failures == [], "a repo this user cannot see must not mark the download plan failed"
+
+
+def test_a_transient_hub_error_still_fails_the_plan(monkeypatch):
+ """Only the repo-level refusal is "no checkpoint". A network error says nothing about the repo,
+ so it still propagates and the planner records it."""
+ import huggingface_hub
+
+ from core.inference.diffusion import DiffusionBackend
+
+ def _boom(self, *a, **k):
+ raise ConnectionError("no route to host")
+
+ monkeypatch.setattr(huggingface_hub.HfApi, "model_info", _boom)
+ with pytest.raises(ConnectionError):
+ DiffusionBackend._prequant_source_hub_entry(_nvfp4_repo_source(), None, [], scheme = "nvfp4")
+
+
+def _prefetch_backend(monkeypatch, *, cached, model_info):
+ """A backend whose dense-quant candidate is the hosted NVFP4 prequant, with the Hub answering
+ ``model_info``. Explicit nvfp4, so the auto-only cache gates do not decide it first."""
+ import types
+
+ import huggingface_hub
+
+ from core.inference import diffusion as dmod
+ from core.inference import diffusion_memory as dmem
+ from core.inference.diffusion import DiffusionBackend
+
+ tokens: list = []
+
+ class _Api:
+ def __init__(
+ self,
+ token = None,
+ **k,
+ ):
+ tokens.append(token)
+
+ def model_info(self, repo_id, **k):
+ return model_info(repo_id)
+
+ monkeypatch.setattr(huggingface_hub, "HfApi", _Api)
+ monkeypatch.setattr(
+ dmod,
+ "resolve_dense_quant_candidate",
+ lambda **kw: types.SimpleNamespace(prequant = True, scheme = "nvfp4", steady_total_mib = 1),
+ )
+ monkeypatch.setattr(
+ dmod, "usable_prequant_source", lambda fam, scheme, **kw: _nvfp4_repo_source()
+ )
+ monkeypatch.setattr(dmod, "prequant_checkpoint_cached", lambda source, **kw: cached)
+ monkeypatch.setattr(
+ dmem,
+ "snapshot_device_memory",
+ lambda target: types.SimpleNamespace(total_mib = None, memory_kind = "discrete_vram"),
+ )
+ monkeypatch.setattr(
+ pq, "restricted_prequant_load_supported", lambda scheme = None, filename = None: True
+ )
+ backend = DiffusionBackend()
+ monkeypatch.setattr(backend, "_target_for_ordinal", lambda fam, ordinal: object())
+ return backend, tokens
+
+
+_NVFP4_PREFETCH_KWARGS = {"transformer_quant": "nvfp4", "hf_token": "hf_user_token"}
+
+
+def test_an_unreachable_prequant_does_not_suppress_the_dense_shards(monkeypatch):
+ """The candidate is PREQUANT because the family table names a checkpoint, whether or not this user
+ can read it. Private, the load falls back to the dense build, so the plan must stage the dense
+ shards rather than let the load pull ~25 GB inline after the phase switched to finalizing."""
+ from huggingface_hub import errors as hub_errors
+
+ def _refuse(repo_id):
+ raise _refused(hub_errors.RepositoryNotFoundError, 401)
+
+ backend, tokens = _prefetch_backend(monkeypatch, cached = False, model_info = _refuse)
+ fam = _fam()
+ assert backend._dense_quant_prefetch_needed(fam, dict(_NVFP4_PREFETCH_KWARGS)) is True
+ assert tokens == [
+ "hf_user_token"
+ ], "the probe must ask as the user, else a granted token reads as refused"
+
+
+def test_an_unreachable_prequant_is_carried_into_the_load(monkeypatch):
+ """begin_load hands these kwargs to load_pipeline, so the load sizes the scheme as the dense build
+ it will fall back to rather than as a checkpoint that will never arrive."""
+ from huggingface_hub import errors as hub_errors
+
+ def _refuse(repo_id):
+ raise _refused(hub_errors.RepositoryNotFoundError, 401)
+
+ backend, _tokens = _prefetch_backend(monkeypatch, cached = False, model_info = _refuse)
+ kwargs = dict(_NVFP4_PREFETCH_KWARGS)
+ assert backend._dense_quant_prefetch_needed(_fam(), kwargs) is True
+ assert kwargs["_prequant_unreachable"] == ("nvfp4",)
+ backend._dense_quant_prefetch_needed(_fam(), kwargs)
+ assert kwargs["_prequant_unreachable"] == ("nvfp4",)
+
+
+def test_a_readable_prequant_is_not_marked_unreachable(monkeypatch):
+ import types
+
+ def _listing(repo_id):
+ return types.SimpleNamespace(
+ siblings = [types.SimpleNamespace(rfilename = "Z-Image-Turbo-NVFP4.pt", size = 4096)]
+ )
+
+ backend, _tokens = _prefetch_backend(monkeypatch, cached = False, model_info = _listing)
+ kwargs = dict(_NVFP4_PREFETCH_KWARGS)
+ assert backend._dense_quant_prefetch_needed(_fam(), kwargs) is False
+ assert "_prequant_unreachable" not in kwargs
+
+
+def test_local_only_treats_an_uncached_prequant_as_unreachable(monkeypatch):
+ """local_files_only forbids the loader from fetching the checkpoint, so a Hub listing that
+ names it must not keep the load sizing a packed artifact that will never arrive."""
+ import types
+
+ def _listing(repo_id):
+ return types.SimpleNamespace(
+ siblings = [types.SimpleNamespace(rfilename = "Z-Image-Turbo-NVFP4.pt", size = 4096)]
+ )
+
+ backend, tokens = _prefetch_backend(monkeypatch, cached = False, model_info = _listing)
+ kwargs = {**_NVFP4_PREFETCH_KWARGS, "local_files_only": True}
+ assert backend._dense_quant_prefetch_needed(_fam(), kwargs) is True
+ assert kwargs["_prequant_unreachable"] == ("nvfp4",)
+ assert tokens == [], "local-only mode must not ask the Hub"
+ backend, _tokens = _prefetch_backend(monkeypatch, cached = True, model_info = _listing)
+ kwargs = {**_NVFP4_PREFETCH_KWARGS, "local_files_only": True}
+ assert backend._dense_quant_prefetch_needed(_fam(), kwargs) is False
+ assert "_prequant_unreachable" not in kwargs
+
+
+def test_a_readable_prequant_still_drops_the_dense_shards(monkeypatch):
+ """Positive control: a repo that lists the checkpoint keeps the small download."""
+ import types
+
+ def _listing(repo_id):
+ return types.SimpleNamespace(
+ siblings = [types.SimpleNamespace(rfilename = "Z-Image-Turbo-NVFP4.pt", size = 4096)]
+ )
+
+ backend, _tokens = _prefetch_backend(monkeypatch, cached = False, model_info = _listing)
+ assert backend._dense_quant_prefetch_needed(_fam(), dict(_NVFP4_PREFETCH_KWARGS)) is False
+
+
+def test_a_cached_prequant_drops_the_dense_shards_without_asking_the_hub(monkeypatch):
+ def _no_hub(repo_id):
+ raise AssertionError("a cached checkpoint must not cost a Hub round trip")
+
+ backend, tokens = _prefetch_backend(monkeypatch, cached = True, model_info = _no_hub)
+ assert backend._dense_quant_prefetch_needed(_fam(), dict(_NVFP4_PREFETCH_KWARGS)) is False
+ assert tokens == []
+
+
+def test_an_unanswerable_reachability_probe_keeps_the_prequant_verdict(monkeypatch):
+ """Offline or a Hub hiccup says nothing about access, so it must not widen a multi-GB pull."""
+
+ def _offline(repo_id):
+ raise ConnectionError("offline")
+
+ backend, _tokens = _prefetch_backend(monkeypatch, cached = False, model_info = _offline)
+ assert backend._dense_quant_prefetch_needed(_fam(), dict(_NVFP4_PREFETCH_KWARGS)) is False
+
+
+def test_the_download_plan_probes_with_the_user_token():
+ """download_plan builds its own kwargs for the prefetch decision; without the token threaded in,
+ a user granted access to a private prequant reads as refused and stages the dense shards."""
+ import inspect
+
+ from core.inference.diffusion import DiffusionBackend
+
+ src = inspect.getsource(DiffusionBackend.download_plan)
+ assert '{**load_kwargs, "base_repo": base, "hf_token": hf_token}' in src
diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.py
index bbb7afce0c9..46174572f08 100644
--- a/studio/backend/tests/test_diffusion_routes.py
+++ b/studio/backend/tests/test_diffusion_routes.py
@@ -2748,6 +2748,104 @@ def test_generate_schema_bounds_for_unified_editing(client):
assert bad_mode.status_code == 422
+def test_the_precision_gate_judges_an_explicit_scheme_on_the_pipeline_base(monkeypatch):
+ """A per-base NVFP4 gate record (Qwen-Image-2512) lifts the family deny only for that base, so the
+ route gate must ask about the base the load keys on, or it 409s a load the loader accepts."""
+ from core.inference.diffusion import DiffusionBackend
+
+ monkeypatch.setenv("UNSLOTH_NVFP4_DIFFUSION", "1")
+ backend = DiffusionBackend.__new__(DiffusionBackend)
+ monkeypatch.setattr(
+ DiffusionBackend, "_resolve_device_target", lambda self, fam: _cuda_target()
+ )
+ monkeypatch.setattr(diffusion_module, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(
+ diffusion_module, "_pipeline_quant_uncompilable_reason", lambda *a, **k: None
+ )
+ seen = []
+
+ def _select(target, requested, **kwargs):
+ seen.append(kwargs.get("base_repo"))
+ return requested
+
+ monkeypatch.setattr(diffusion_module, "select_transformer_quant_scheme", _select)
+ backend.assert_precision_available(
+ types.SimpleNamespace(name = "qwen-image"),
+ model_kind = "pipeline",
+ transformer_quant = "nvfp4",
+ repo_id = "Qwen/Qwen-Image-2512",
+ )
+ assert seen == ["Qwen/Qwen-Image-2512"]
+
+
+def test_a_gpu_refusal_on_a_gated_base_is_not_blamed_on_the_family_deny(monkeypatch):
+ """Qwen-Image-2512's gate record lifts the qwen-image NVFP4 deny for that base only. When the GPU then declines
+ the scheme, the refusal must say so, not claim no accuracy record covers the base."""
+ from core.inference.diffusion import DiffusionBackend
+
+ monkeypatch.setenv("UNSLOTH_NVFP4_DIFFUSION", "1")
+ backend = DiffusionBackend.__new__(DiffusionBackend)
+ monkeypatch.setattr(
+ DiffusionBackend, "_resolve_device_target", lambda self, fam: _cuda_target()
+ )
+ monkeypatch.setattr(diffusion_module, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(
+ diffusion_module, "_pipeline_quant_uncompilable_reason", lambda *a, **k: None
+ )
+ monkeypatch.setattr(diffusion_module, "select_transformer_quant_scheme", lambda *a, **k: None)
+ import core.inference.diffusion_transformer_quant as tq
+
+ monkeypatch.setattr(tq, "torchao_unavailable_reason", lambda: None)
+ base = "Qwen/Qwen-Image-2512"
+ assert not tq.family_denies_scheme("qwen-image", "nvfp4", base)
+ with pytest.raises(RuntimeError) as err:
+ backend.assert_precision_available(
+ types.SimpleNamespace(name = "qwen-image"),
+ model_kind = "pipeline",
+ transformer_quant = "nvfp4",
+ repo_id = base,
+ )
+ message = str(err.value)
+ assert "on this GPU" in message
+ assert "accuracy-gate record" not in message
+
+
+def test_a_gguf_pick_whose_base_comes_from_its_card_is_judged_on_the_gated_base(monkeypatch):
+ """A GGUF load that names no base_repo resolves it from the repo card at load time. The network-free gate must not
+ refuse explicit NVFP4 under the generic family deny that the Qwen-Image-2512 gate record lifts."""
+ from core.inference.diffusion import DiffusionBackend
+
+ monkeypatch.setenv("UNSLOTH_NVFP4_DIFFUSION", "1")
+ backend = DiffusionBackend.__new__(DiffusionBackend)
+ monkeypatch.setattr(
+ DiffusionBackend, "_resolve_device_target", lambda self, fam: _cuda_target()
+ )
+ monkeypatch.setattr(diffusion_module, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(
+ diffusion_module, "_pipeline_quant_uncompilable_reason", lambda *a, **k: None
+ )
+ import core.inference.diffusion_transformer_quant as tq
+
+ seen = []
+
+ def _select(target, requested, **kwargs):
+ seen.append(kwargs.get("base_repo"))
+ return (
+ None
+ if tq.family_denies_scheme(kwargs.get("family"), requested, kwargs.get("base_repo"))
+ else requested
+ )
+
+ monkeypatch.setattr(diffusion_module, "select_transformer_quant_scheme", _select)
+ backend.assert_precision_available(
+ types.SimpleNamespace(name = "qwen-image"),
+ model_kind = "gguf",
+ transformer_quant = "nvfp4",
+ repo_id = "unsloth/Qwen-Image-2512-GGUF",
+ )
+ assert seen == ["Qwen/Qwen-Image-2512"]
+
+
def test_a_managed_account_cannot_send_allow_oversized(client, monkeypatch):
from hub.services.models import account_access
diff --git a/studio/backend/tests/test_diffusion_speed.py b/studio/backend/tests/test_diffusion_speed.py
index e19f4ed17ef..a1462105a4a 100644
--- a/studio/backend/tests/test_diffusion_speed.py
+++ b/studio/backend/tests/test_diffusion_speed.py
@@ -1322,6 +1322,133 @@ def test_cuda_graph_install_failure_leaves_the_load_usable(monkeypatch):
assert applied["compiled"] is True # the rest of the tier still engaged
+class _StreamBlock:
+ """A repeated block whose ``forward`` source is what the detector reads."""
+
+ def forward(self, hidden_states, encoder_hidden_states, temb): # pragma: no cover - never run
+ return hidden_states, encoder_hidden_states
+
+
+class FluxSingleTransformerBlock(_StreamBlock):
+ """Named on ``_STREAM_MERGING_BLOCKS``, so it is recognised without reading source."""
+
+
+class _MergingByArgOrderA(_StreamBlock):
+ def forward(self, hidden_states, encoder_hidden_states, temb): # pragma: no cover
+ import torch # source fixture: only the text is read
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim = 1)
+ return hidden_states, encoder_hidden_states
+
+
+class _MergingByArgOrderB(_StreamBlock):
+ def forward(self, hidden_states, encoder_hidden_states, temb): # pragma: no cover
+ import torch # source fixture: only the text is read
+ hidden_states = torch.cat([hidden_states, encoder_hidden_states], dim = 1)
+ return hidden_states, encoder_hidden_states
+
+
+class _DualStreamBlock(_StreamBlock):
+ """Takes BOTH streams but keeps them separate (Qwen-Image / SD3 shape), so it stays dynamic."""
+
+ def forward(self, hidden_states, encoder_hidden_states, temb): # pragma: no cover
+ return hidden_states + 1, encoder_hidden_states + 1
+
+
+def _dit(*block_classes):
+ blocks = [cls() for cls in block_classes]
+ dit = types.SimpleNamespace(
+ _repeated_blocks = [cls.__name__ for cls in block_classes],
+ named_modules = lambda: [("", None)] + [(f"blocks.{i}", b) for i, b in enumerate(blocks)],
+ )
+ return dit
+
+
+def test_class_merges_streams_is_crash_confirmed_names_only_by_default():
+ assert ds_mod._class_merges_streams(FluxSingleTransformerBlock) is True
+ assert ds_mod._class_merges_streams(_MergingByArgOrderA) is False
+ assert ds_mod._class_merges_streams(_MergingByArgOrderB) is False
+ assert ds_mod._class_merges_streams(_DualStreamBlock) is False
+
+
+def test_class_merges_streams_broad_sweep_is_opt_in():
+ assert ds_mod._class_merges_streams(_MergingByArgOrderA, True) is True
+ assert ds_mod._class_merges_streams(_MergingByArgOrderB, True) is True
+ assert ds_mod._class_merges_streams(_DualStreamBlock, True) is False
+
+
+def test_class_merges_streams_without_source_falls_back_to_the_name_list(monkeypatch):
+ import inspect
+
+ monkeypatch.setattr(
+ inspect, "getsource", lambda _obj: (_ for _ in ()).throw(OSError("no source"))
+ )
+ ds_mod._class_merges_streams.cache_clear()
+ assert ds_mod._class_merges_streams(_MergingByArgOrderA, True) is False
+ assert ds_mod._class_merges_streams(FluxSingleTransformerBlock, True) is True
+ ds_mod._class_merges_streams.cache_clear()
+
+
+def test_dits_merge_streams_honours_the_opt_in_env(monkeypatch):
+ monkeypatch.delenv(ds_mod._STREAM_MERGE_DETECT_ENV, raising = False)
+ assert ds_mod._dits_merge_streams([_dit(_MergingByArgOrderA)]) is False
+ monkeypatch.setenv(ds_mod._STREAM_MERGE_DETECT_ENV, "1")
+ assert ds_mod._dits_merge_streams([_dit(_MergingByArgOrderA)]) is True
+ monkeypatch.delenv(ds_mod._STREAM_MERGE_DETECT_ENV, raising = False)
+ assert ds_mod._dits_merge_streams([_dit(FluxSingleTransformerBlock)]) is True
+
+
+def test_dits_merge_streams_scans_every_denoiser():
+ assert ds_mod._dits_merge_streams([]) is False
+ assert ds_mod._dits_merge_streams([types.SimpleNamespace()]) is False
+ assert ds_mod._dits_merge_streams([_dit(_DualStreamBlock)]) is False
+ assert ds_mod._dits_merge_streams([_dit(_MergingByArgOrderA)]) is False
+ assert ds_mod._dits_merge_streams([_dit(_DualStreamBlock, FluxSingleTransformerBlock)]) is True
+ assert (
+ ds_mod._dits_merge_streams([_dit(_DualStreamBlock), _dit(FluxSingleTransformerBlock)])
+ is True
+ )
+
+
+def test_speed_default_compiles_stream_merging_dit_with_static_shapes(monkeypatch):
+ """FLUX.1 regression: dynamic=True cannot be codegen'd for a stream-merging block."""
+ _stub_torch(monkeypatch)
+ _stub_gguf_accel(monkeypatch)
+ pipe = _Pipe(with_compile = True)
+ pipe.transformer._repeated_blocks = ["FluxSingleTransformerBlock"]
+ block = FluxSingleTransformerBlock()
+ pipe.transformer.named_modules = lambda: [("blocks.0", block)]
+ applied = apply_speed_optims(
+ pipe, _target(), is_gguf = False, family = _family(), speed_mode = SPEED_DEFAULT
+ )
+ assert applied["compiled"] is True
+ assert pipe.compile_kwargs == {"fullgraph": True, "dynamic": False}
+ assert pipe.compile_kwargs["dynamic"] is not None
+
+
+def test_compiled_shapes_are_static_reports_the_stream_merging_downgrade(monkeypatch):
+ _stub_torch(monkeypatch)
+ merging = types.SimpleNamespace(transformer = _dit(FluxSingleTransformerBlock))
+ plain = types.SimpleNamespace(transformer = _dit(_DualStreamBlock))
+ assert ds_mod.compiled_shapes_are_static(merging, SPEED_DEFAULT) is True
+ assert ds_mod.compiled_shapes_are_static(plain, SPEED_DEFAULT) is False
+ assert ds_mod.compiled_shapes_are_static(plain, SPEED_MAX) is True
+ assert ds_mod.compiled_shapes_are_static(merging, SPEED_OFF) is False
+ assert ds_mod.compiled_shapes_are_static(merging, SPEED_EAGER) is False
+
+
+def test_speed_max_keeps_automatic_dynamic_for_a_stream_merging_dit(monkeypatch):
+ """The static exception is the default tier's alone: max compiles every DiT with automatic dynamic."""
+ _stub_torch(monkeypatch)
+ _stub_gguf_accel(monkeypatch)
+ pipe = _Pipe(with_compile = True)
+ pipe.transformer._repeated_blocks = ["FluxSingleTransformerBlock"]
+ block = FluxSingleTransformerBlock()
+ pipe.transformer.named_modules = lambda: [("blocks.0", block)]
+ apply_speed_optims(pipe, _target(), is_gguf = False, family = _family(), speed_mode = SPEED_MAX)
+ assert pipe.compile_kwargs["dynamic"] is None
+ assert ds_mod.auto_dynamic_active(pipe) is True
+
+
# ── runtime compile failure falls back to eager ──────────────────────────────
# compile_repeated_blocks is lazy: inductor runs on the first forward, inside generate(). A lowering bug there
# (Qwen-Image-2.1 int8 / fp8: inductor CantSplit) used to fail every render; the guard drops that DiT to eager.
@@ -1586,6 +1713,22 @@ def test_auto_dynamic_active_follows_the_torchao_marker():
assert isinstance(ds_mod.dynamo_graph_count(), int)
+def test_speed_max_compiles_a_quantised_stream_merging_dit_static(monkeypatch):
+ """A torchao FLUX block under automatic dynamic hits CantSplit on the first new resolution and drops to eager;
+ max compiles it static instead, and reports its artifacts as per-shape."""
+ _stub_torch(monkeypatch)
+ _stub_gguf_accel(monkeypatch)
+ monkeypatch.setattr(ds_mod, "_carries_torchao_weights", lambda module: True)
+ pipe = _Pipe(with_compile = True)
+ pipe.transformer._repeated_blocks = ["FluxSingleTransformerBlock"]
+ block = FluxSingleTransformerBlock()
+ pipe.transformer.named_modules = lambda: [("blocks.0", block)]
+ apply_speed_optims(pipe, _target(), is_gguf = False, family = _family(), speed_mode = SPEED_MAX)
+ assert pipe.compile_kwargs["dynamic"] is False
+ assert ds_mod.auto_dynamic_active(pipe) is False
+ assert ds_mod.compiled_shapes_are_static(pipe, SPEED_MAX) is True
+
+
def test_real_rope_installed_before_the_qwen_image_21_block_compile_only(monkeypatch):
from core.inference import diffusion_qwenimage21_rope as rope
diff --git a/studio/backend/tests/test_diffusion_transformer_quant.py b/studio/backend/tests/test_diffusion_transformer_quant.py
index d24ebc71148..409e5e9f9fa 100644
--- a/studio/backend/tests/test_diffusion_transformer_quant.py
+++ b/studio/backend/tests/test_diffusion_transformer_quant.py
@@ -946,7 +946,7 @@ def test_make_filter_fn_int8_excludes_modulation_and_embedders(monkeypatch):
monkeypatch.setitem(sys.modules, "torch", torch)
keep = make_filter_fn(512, exclude_name_tokens = _INT8_EXCLUDE_NAME_TOKENS)
- big = lambda: _Lin(3072, 18432) # noqa: E731 — large enough to pass min_features
+ big = lambda: _Lin(3072, 18432) # noqa: E731 - large enough to pass min_features
# Excluded (M=1 modulation / conditioning embedders), despite large features:
for fqn in (
"transformer_blocks.0.norm1.linear",
@@ -1068,7 +1068,7 @@ def test_fp8_config_pins_torch_kernel_preference():
def test_quantize_transformer_applies_and_marks(monkeypatch):
monkeypatch.setattr(
- tq, "select_transformer_quant_scheme", lambda target, mode, family = None: TQ_FP8
+ tq, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: TQ_FP8
)
seen: dict = {}
@@ -1095,7 +1095,7 @@ def test_quantize_transformer_applies_and_marks(monkeypatch):
def test_quantize_transformer_none_when_unsupported(monkeypatch):
monkeypatch.setattr(
- tq, "select_transformer_quant_scheme", lambda target, mode, family = None: None
+ tq, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: None
)
pipe = types.SimpleNamespace(transformer = types.SimpleNamespace())
assert quantize_transformer(pipe, _target(), mode = "auto") is None
@@ -1103,7 +1103,7 @@ def test_quantize_transformer_none_when_unsupported(monkeypatch):
def test_quantize_transformer_tolerates_failure(monkeypatch):
monkeypatch.setattr(
- tq, "select_transformer_quant_scheme", lambda target, mode, family = None: TQ_INT8
+ tq, "select_transformer_quant_scheme", lambda target, mode, family = None, **_kw: TQ_INT8
)
monkeypatch.setattr(tq, "_make_quant_config", lambda scheme: "cfg")
tqz = types.ModuleType("torchao.quantization")
@@ -1181,6 +1181,30 @@ def test_quantize_transformer_threads_family(monkeypatch):
assert called == {}
+def test_quantize_transformer_threads_base_repo(monkeypatch):
+ import core.inference.diffusion_transformer_quant as dtq
+
+ seen = {}
+
+ def _select(
+ target,
+ mode,
+ family = None,
+ **kwargs,
+ ):
+ seen.update(kwargs, family = family)
+ return None
+
+ monkeypatch.setattr(dtq, "select_transformer_quant_scheme", _select)
+ pipe = types.SimpleNamespace(transformer = types.SimpleNamespace())
+ base = "Qwen/Qwen-Image-2512"
+ assert (
+ quantize_transformer(pipe, _target(), mode = "nvfp4", family = "qwen-image", base_repo = base)
+ is None
+ )
+ assert seen == {"family": "qwen-image", "base_repo": base}
+
+
def test_the_attention_trim_families_exclude_their_small_m_text_streams():
"""The trim in this PR is what makes these excludes necessary, so they ship together.
@@ -1551,12 +1575,18 @@ def _nvfp4_head(**kw):
return tq._AutoPrefer(floor = (10, 0), schemes = (TQ_NVFP4,), **kw)
+_HAS_PREQUANT = {"has_prequant": lambda scheme: True}
+
+
def test_a_prefer_row_leads_the_tier_on_datacenter_blackwell(monkeypatch):
_stub_torch(monkeypatch, cc = (10, 0))
_allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
_prefer(monkeypatch, _nvfp4_head())
- assert select_transformer_quant_scheme(_target(), "auto", family = "fake-video") == TQ_NVFP4
- assert tq.auto_scheme_candidates(_target(), "fake-video") == (
+ assert (
+ select_transformer_quant_scheme(_target(), "auto", family = "fake-video", **_HAS_PREQUANT)
+ == TQ_NVFP4
+ )
+ assert tq.auto_scheme_candidates(_target(), "fake-video", **_HAS_PREQUANT) == (
TQ_NVFP4,
TQ_INT8,
TQ_FP8,
@@ -1594,10 +1624,16 @@ def test_a_prefer_row_needs_consumer_ok_to_apply_to_a_consumer_gpu(monkeypatch):
_stub_torch(monkeypatch, cc = (12, 0), device_name = "NVIDIA GeForce RTX 5090")
_allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
_prefer(monkeypatch, _nvfp4_head())
- assert select_transformer_quant_scheme(_target(), "auto", family = "fake-video") == TQ_INT8
+ assert (
+ select_transformer_quant_scheme(_target(), "auto", family = "fake-video", **_HAS_PREQUANT)
+ == TQ_INT8
+ )
_prefer(monkeypatch, _nvfp4_head(consumer_ok = True))
- assert select_transformer_quant_scheme(_target(), "auto", family = "fake-video") == TQ_NVFP4
- assert tq.auto_scheme_candidates(_target(), "fake-video") == (
+ assert (
+ select_transformer_quant_scheme(_target(), "auto", family = "fake-video", **_HAS_PREQUANT)
+ == TQ_NVFP4
+ )
+ assert tq.auto_scheme_candidates(_target(), "fake-video", **_HAS_PREQUANT) == (
TQ_NVFP4,
TQ_INT8,
TQ_FP8,
@@ -1632,21 +1668,220 @@ def test_a_capability_below_every_tier_has_no_order_even_with_a_head(monkeypatch
set(),
],
)
[email protected]("row_backend", [None, "flashinfer", "torchao"])
[email protected]("probe_backend", ["flashinfer", "torchao", "raises"])
def test_the_candidate_head_stays_the_selector_winner_with_a_prefer_row(
- monkeypatch, family, allowed
+ monkeypatch, family, allowed, row_backend, probe_backend
):
_stub_torch(monkeypatch, cc = (10, 0))
_allow(monkeypatch, allowed)
- _prefer(monkeypatch, _nvfp4_head())
- candidates = tq.auto_scheme_candidates(_target(), family)
- chosen = select_transformer_quant_scheme(_target(), "auto", family = family)
+ _stub_nvfp4_backend(monkeypatch, probe_backend)
+ _prefer(monkeypatch, _nvfp4_head(backend = row_backend))
+ candidates = tq.auto_scheme_candidates(_target(), family, **_HAS_PREQUANT)
+ chosen = select_transformer_quant_scheme(_target(), "auto", family = family, **_HAS_PREQUANT)
assert (candidates[0] if candidates else None) == chosen, (family, allowed)
def test_the_shipped_prefer_table_keeps_the_ladder_as_it_was(monkeypatch):
_stub_torch(monkeypatch, cc = (10, 0))
_allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
- assert tq._FAMILY_AUTO_PREFER == {}
+ assert set(tq._FAMILY_AUTO_PREFER) == {
+ "z-image",
+ "flux.1",
+ "qwen-image",
+ "qwen-image-2.1",
+ "wan2.2-t2v-a14b",
+ }
+ ungated = {name for name, row in tq._FAMILY_AUTO_PREFER.items() if not row.gated}
+ assert ungated == {"wan2.2-t2v-a14b"}
+ for name in ungated:
+ assert tq._FAMILY_AUTO_PREFER[name].backend
+ families = (
+ None,
+ "hunyuanvideo-1.5",
+ "hunyuanvideo-1.5-720p",
+ "wan2.2-ti2v-5b",
+ "z-image",
+ "flux.1",
+ )
+ for family in families:
+ assert (
+ select_transformer_quant_scheme(
+ _target(),
+ "auto",
+ family = family,
+ base_repo = "Tongyi-MAI/Z-Image-Turbo",
+ **_HAS_PREQUANT,
+ )
+ == TQ_INT8
+ )
+ assert select_transformer_quant_scheme(_target(), "auto", family = family) == TQ_INT8
+ assert tq.auto_scheme_candidates(
+ _target(), "qwen-image", base_repo = "Qwen/Qwen-Image", **_HAS_PREQUANT
+ ) == (TQ_INT8, TQ_FP8)
+
+
+def _stub_nvfp4_backend(monkeypatch, answer):
+ """Make ``select_nvfp4_backend`` answer ``answer``, or raise when it is "raises"."""
+ from core.inference import diffusion_nvfp4_ops as ops
+
+ def _answer(device = None):
+ if answer == "raises":
+ raise RuntimeError("probe blew up")
+ return answer
+
+ monkeypatch.setattr(ops, "select_nvfp4_backend", _answer)
+
+
+def test_a_backend_conditional_head_applies_on_the_backend_it_was_measured_on(monkeypatch):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ _stub_nvfp4_backend(monkeypatch, "flashinfer")
+ _prefer(monkeypatch, _nvfp4_head(backend = "flashinfer"))
+ assert (
+ select_transformer_quant_scheme(_target(), "auto", family = "fake-video", **_HAS_PREQUANT)
+ == TQ_NVFP4
+ )
+ assert tq.auto_scheme_candidates(_target(), "fake-video", **_HAS_PREQUANT) == (
+ TQ_NVFP4,
+ TQ_INT8,
+ TQ_FP8,
+ TQ_MXFP8,
+ )
+
+
+def test_a_backend_conditional_head_is_dropped_on_the_other_backend(monkeypatch):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ _stub_nvfp4_backend(monkeypatch, "torchao")
+ _prefer(monkeypatch, _nvfp4_head(backend = "flashinfer"))
+ assert (
+ select_transformer_quant_scheme(_target(), "auto", family = "fake-video", **_HAS_PREQUANT)
+ == TQ_INT8
+ )
+ assert tq.auto_scheme_candidates(_target(), "fake-video", **_HAS_PREQUANT) == (
+ TQ_INT8,
+ TQ_FP8,
+ TQ_MXFP8,
+ )
+
+
+def test_a_backend_probe_that_raises_drops_the_head_rather_than_the_load(monkeypatch):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ _stub_nvfp4_backend(monkeypatch, "raises")
+ _prefer(monkeypatch, _nvfp4_head(backend = "flashinfer"))
+ assert tq._nvfp4_backend_is("cuda", "flashinfer") is False
+ assert (
+ select_transformer_quant_scheme(_target(), "auto", family = "fake-video", **_HAS_PREQUANT)
+ == TQ_INT8
+ )
+ assert tq.auto_scheme_candidates(_target(), "fake-video", **_HAS_PREQUANT) == (
+ TQ_INT8,
+ TQ_FP8,
+ TQ_MXFP8,
+ )
+
+
+def test_the_backend_helper_answers_false_without_torch(monkeypatch):
+ monkeypatch.setitem(sys.modules, "torch", None)
+ assert tq._nvfp4_backend_is("cuda", "flashinfer") is False
+
+
+def test_a_row_with_no_backend_requirement_is_unconditional(monkeypatch):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ _stub_nvfp4_backend(monkeypatch, "torchao")
+ _prefer(monkeypatch, _nvfp4_head())
+ assert (
+ select_transformer_quant_scheme(_target(), "auto", family = "fake-video", **_HAS_PREQUANT)
+ == TQ_NVFP4
+ )
+
+
+def test_the_floor_and_the_consumer_rule_still_outrank_the_backend(monkeypatch):
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ _stub_nvfp4_backend(monkeypatch, "flashinfer")
+ _prefer(monkeypatch, _nvfp4_head(backend = "flashinfer"))
+ _stub_torch(monkeypatch, cc = (8, 9), device_name = "NVIDIA L40S")
+ assert (
+ select_transformer_quant_scheme(_target(), "auto", family = "fake-video", **_HAS_PREQUANT)
+ == TQ_INT8
+ )
+ _stub_torch(monkeypatch, cc = (12, 0), device_name = "NVIDIA GeForce RTX 5090")
+ assert (
+ select_transformer_quant_scheme(_target(), "auto", family = "fake-video", **_HAS_PREQUANT)
+ == TQ_INT8
+ )
+
+
+def test_the_a14b_row_leads_with_nvfp4_only_where_flashinfer_serves_it(monkeypatch):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ base = "Wan-AI/Wan2.2-T2V-A14B-Diffusers"
+
+ _stub_nvfp4_backend(monkeypatch, "flashinfer")
+ assert (
+ select_transformer_quant_scheme(
+ _target(), "auto", family = "wan2.2-t2v-a14b", base_repo = base, **_HAS_PREQUANT
+ )
+ == TQ_NVFP4
+ )
+ assert tq.auto_scheme_candidates(
+ _target(), "wan2.2-t2v-a14b", base_repo = base, **_HAS_PREQUANT
+ ) == (TQ_NVFP4, TQ_INT8, TQ_FP8, TQ_MXFP8)
+
+ assert (
+ select_transformer_quant_scheme(
+ _target(),
+ "auto",
+ family = "wan2.2-t2v-a14b",
+ base_repo = base,
+ has_prequant = lambda scheme: False,
+ )
+ == TQ_INT8
+ )
+
+ _stub_nvfp4_backend(monkeypatch, "torchao")
+ assert (
+ select_transformer_quant_scheme(
+ _target(), "auto", family = "wan2.2-t2v-a14b", base_repo = base, **_HAS_PREQUANT
+ )
+ == TQ_INT8
+ )
+
+
+def test_the_a14b_promotion_does_not_touch_the_explicit_request_path(monkeypatch):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ base = "Wan-AI/Wan2.2-T2V-A14B-Diffusers"
+ for backend in ("flashinfer", "torchao", "raises"):
+ _stub_nvfp4_backend(monkeypatch, backend)
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ for scheme in (TQ_NVFP4, TQ_FP8, TQ_INT8):
+ assert (
+ select_transformer_quant_scheme(
+ _target(),
+ scheme,
+ family = "wan2.2-t2v-a14b",
+ base_repo = base,
+ has_prequant = lambda candidate: False,
+ )
+ == scheme
+ ), (backend, scheme)
+ _allow(monkeypatch, {TQ_FP8})
+ assert (
+ select_transformer_quant_scheme(
+ _target(), TQ_NVFP4, family = "wan2.2-t2v-a14b", base_repo = base
+ )
+ is None
+ )
+
+
+def test_the_other_three_measured_video_families_were_not_promoted(monkeypatch):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ for family in ("wan2.2-ti2v-5b", "hunyuanvideo-1.5", "hunyuanvideo-1.5-720p"):
+ assert family not in tq._FAMILY_AUTO_PREFER
for family in (None, "hunyuanvideo-1.5", "hunyuanvideo-1.5-720p", "wan2.2-ti2v-5b"):
assert select_transformer_quant_scheme(_target(), "auto", family = family) == TQ_INT8
@@ -1848,6 +2083,419 @@ def test_real_torchao_configs_carry_set_inductor_config_false():
assert getattr(ic, "coordinate_descent_tuning", None) == before
+def _policy_stub(monkeypatch, *, policy, applied, resolved):
+ from core.inference import diffusion_nvfp4_policy as np
+
+ def _resolve(family, base_repo = None):
+ resolved.append((family, base_repo))
+ return policy
+
+ def _apply(
+ transformer,
+ policy_arg,
+ *,
+ min_features = None,
+ fast_accum = None,
+ logger = None,
+ ):
+ applied.append((transformer, policy_arg, min_features, fast_accum))
+ return {"blocks.0.attention.to_q": "nvfp4"}
+
+ monkeypatch.setattr(np, "resolve_policy", _resolve)
+ monkeypatch.setattr(np, "quantize_with_policy", _apply)
+
+
+def _nvfp4_runtime(monkeypatch, order):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4})
+ tqz = types.ModuleType("torchao.quantization")
+ tqz.quantize_ = lambda module, config, filter_fn = None: order.append("quantize_")
+ monkeypatch.setitem(sys.modules, "torchao.quantization", tqz)
+ monkeypatch.setattr(tq, "_make_quant_config", lambda scheme, fast_accum = None: "cfg")
+ monkeypatch.setattr(
+ tq,
+ "apply_small_m_padding",
+ lambda transformer, scheme, family = None, logger = None: (order.append("pad") or ()),
+ )
+ monkeypatch.setattr(
+ tq,
+ "apply_zero_row_guard",
+ lambda transformer, scheme, family = None, logger = None: (order.append("guard") or ()),
+ )
+
+
+def test_quantize_transformer_applies_the_policy_when_one_resolves(monkeypatch):
+ """An explicit nvfp4 on a gated base quantises the policy's layers, never the whole model."""
+ order: list = []
+ _nvfp4_runtime(monkeypatch, order)
+ policy = types.SimpleNamespace(policy_id = "zimg_rg76_v1", version = 1)
+ applied: list = []
+ resolved: list = []
+ _policy_stub(monkeypatch, policy = policy, applied = applied, resolved = resolved)
+
+ transformer = types.SimpleNamespace()
+ pipe = types.SimpleNamespace(transformer = transformer)
+ engaged = quantize_transformer(
+ pipe,
+ _target(),
+ mode = "nvfp4",
+ family = "z-image",
+ base_repo = "Tongyi-MAI/Z-Image-Turbo",
+ min_features = 512,
+ )
+
+ assert engaged == TQ_NVFP4
+ assert resolved == [("z-image", "Tongyi-MAI/Z-Image-Turbo")]
+ assert len(applied) == 1 and applied[0][0] is transformer and applied[0][1] is policy
+ assert applied[0][2] == 512
+ assert order == ["pad", "guard"]
+ assert transformer._unsloth_runtime_quant == TQ_NVFP4
+ assert transformer._unsloth_nvfp4_policy == "zimg_rg76_v1"
+
+
+def test_quantize_transformer_quantises_the_whole_model_without_a_policy(monkeypatch):
+ order: list = []
+ _nvfp4_runtime(monkeypatch, order)
+ applied: list = []
+ resolved: list = []
+ _policy_stub(monkeypatch, policy = None, applied = applied, resolved = resolved)
+
+ pipe = types.SimpleNamespace(transformer = types.SimpleNamespace())
+ assert quantize_transformer(pipe, _target(), mode = "nvfp4", family = "z-image") == TQ_NVFP4
+ assert resolved == [("z-image", None)]
+ assert applied == []
+ assert order == ["quantize_", "pad", "guard"]
+ assert not hasattr(pipe.transformer, "_unsloth_nvfp4_policy")
+
+
+def test_quantize_transformer_only_asks_about_a_policy_for_nvfp4(monkeypatch):
+ """fp8 on a base that HAS an nvfp4 policy is still whole-model fp8."""
+ order: list = []
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_FP8})
+ tqz = types.ModuleType("torchao.quantization")
+ tqz.quantize_ = lambda module, config, filter_fn = None: order.append("quantize_")
+ monkeypatch.setitem(sys.modules, "torchao.quantization", tqz)
+ monkeypatch.setattr(tq, "_make_quant_config", lambda scheme, fast_accum = None: "cfg")
+ resolved: list = []
+ _policy_stub(
+ monkeypatch,
+ policy = types.SimpleNamespace(policy_id = "zimg_rg76_v1", version = 1),
+ applied = [],
+ resolved = resolved,
+ )
+
+ pipe = types.SimpleNamespace(transformer = types.SimpleNamespace())
+ engaged = quantize_transformer(
+ pipe,
+ _target(),
+ mode = "fp8",
+ family = "z-image",
+ base_repo = "Tongyi-MAI/Z-Image-Turbo",
+ )
+ assert engaged == TQ_FP8
+ assert resolved == []
+ assert order == ["quantize_"]
+
+
+def test_a_policy_mismatch_fails_the_whole_quantise(monkeypatch):
+ order: list = []
+ _nvfp4_runtime(monkeypatch, order)
+ from core.inference import diffusion_nvfp4_policy as np
+
+ monkeypatch.setattr(
+ np,
+ "resolve_policy",
+ lambda family, base_repo = None: types.SimpleNamespace(policy_id = "zimg_rg76_v1", version = 1),
+ )
+
+ def _boom(transformer, policy, **kwargs):
+ raise np.PolicyMismatch("rule 'attention.to_q' expects 34 layers, found 30")
+
+ monkeypatch.setattr(np, "quantize_with_policy", _boom)
+ pipe = types.SimpleNamespace(transformer = types.SimpleNamespace())
+ assert (
+ quantize_transformer(
+ pipe,
+ _target(),
+ mode = "nvfp4",
+ family = "z-image",
+ base_repo = "Tongyi-MAI/Z-Image-Turbo",
+ )
+ is None
+ )
+ assert order == []
+ assert not hasattr(pipe.transformer, "_unsloth_runtime_quant")
+ assert not hasattr(pipe.transformer, "_unsloth_nvfp4_policy")
+
+
+_ZIMAGE_BASE = "Tongyi-MAI/Z-Image-Turbo"
+_QWEN_BASE = "Qwen/Qwen-Image"
+
+
+def _gate_row(family, base_repo, policy_id, **overrides):
+ row = {
+ "family": family,
+ "base_repo": base_repo,
+ "policy_id": policy_id,
+ "policy_version": 1,
+ "checkpoint_sha256": "b" * 64,
+ "all_pass": True,
+ "backend": "flashinfer",
+ }
+ row.update(overrides)
+ return row
+
+
+def _gate(monkeypatch, tmp_path, *rows):
+ """Point the gate module at a record file holding ``rows`` (none = the shipped, empty state)."""
+ import json
+
+ import core.inference.diffusion_nvfp4_gate as gate
+
+ path = tmp_path / "nvfp4_gate_record.json"
+ path.write_text(json.dumps({"version": 1, "records": list(rows)}), encoding = "utf-8")
+ monkeypatch.setattr(gate, "GATE_RECORD_PATH", path)
+ return path
+
+
+def _zimage_candidates(
+ monkeypatch,
+ *,
+ has_prequant = True,
+ base_repo = _ZIMAGE_BASE,
+):
+ return tq.auto_scheme_candidates(
+ _target(),
+ "z-image",
+ base_repo = base_repo,
+ has_prequant = (lambda scheme: True) if has_prequant else (lambda scheme: False),
+ )
+
+
+def test_a_gated_row_is_inert_without_a_record_and_leads_with_one(monkeypatch, tmp_path):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ _stub_nvfp4_backend(monkeypatch, "flashinfer")
+ _gate(monkeypatch, tmp_path)
+ assert _zimage_candidates(monkeypatch) == (TQ_INT8, TQ_FP8, TQ_MXFP8)
+ _gate(monkeypatch, tmp_path, _gate_row("z-image", _ZIMAGE_BASE, "zimg_rg76_v1"))
+ assert _zimage_candidates(monkeypatch) == (TQ_INT8, TQ_FP8, TQ_NVFP4, TQ_MXFP8)
+ assert (
+ select_transformer_quant_scheme(
+ _target(),
+ "auto",
+ family = "z-image",
+ base_repo = _ZIMAGE_BASE,
+ has_prequant = lambda scheme: True,
+ )
+ == TQ_INT8
+ )
+ _allow(monkeypatch, {TQ_NVFP4, TQ_MXFP8})
+ assert (
+ select_transformer_quant_scheme(
+ _target(),
+ "auto",
+ family = "z-image",
+ base_repo = _ZIMAGE_BASE,
+ has_prequant = lambda scheme: True,
+ )
+ == TQ_NVFP4
+ )
+
+
+def test_the_gated_head_stands_on_any_backend_a_passing_record_names(monkeypatch, tmp_path):
+ """One policy can hold records on both backends; neither device may lose nvfp4 to row order."""
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ _gate(
+ monkeypatch,
+ tmp_path,
+ _gate_row("z-image", _ZIMAGE_BASE, "zimg_rg76_v1"),
+ _gate_row(
+ "z-image",
+ _ZIMAGE_BASE,
+ "zimg_rg76_v1",
+ checkpoint_sha256 = "c" * 64,
+ gptq = True,
+ backend = "torchao",
+ ),
+ )
+ for backend in ("flashinfer", "torchao"):
+ _stub_nvfp4_backend(monkeypatch, backend)
+ assert _zimage_candidates(monkeypatch) == (TQ_INT8, TQ_FP8, TQ_NVFP4, TQ_MXFP8), backend
+ _stub_nvfp4_backend(monkeypatch, "something-else")
+ assert _zimage_candidates(monkeypatch) == (TQ_INT8, TQ_FP8, TQ_MXFP8)
+
+
+ "row",
+ [
+ None,
+ _gate_row("z-image", _ZIMAGE_BASE, "zimg_rg76_v1", all_pass = False),
+ _gate_row("z-image", _ZIMAGE_BASE, "zimg_rg76_v1", policy_version = 2),
+ _gate_row("z-image", "some-org/Z-Image-Fork", "zimg_rg76_v1"),
+ _gate_row("flux.1", "black-forest-labs/FLUX.1-schnell", "flux_r420_v1"),
+ ],
+ ids = ["absent", "failed", "version-bump", "another-base", "another-family"],
+)
+def test_nvfp4_stays_out_of_auto_unless_the_record_matches_exactly(monkeypatch, tmp_path, row):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ _gate(monkeypatch, tmp_path, *([] if row is None else [row]))
+ assert _zimage_candidates(monkeypatch) == (TQ_INT8, TQ_FP8, TQ_MXFP8)
+
+
+def test_auto_will_not_offer_nvfp4_without_a_checkpoint_to_run(monkeypatch, tmp_path):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ _gate(monkeypatch, tmp_path, _gate_row("z-image", _ZIMAGE_BASE, "zimg_rg76_v1"))
+ assert _zimage_candidates(monkeypatch, has_prequant = False) == (TQ_INT8, TQ_FP8, TQ_MXFP8)
+ assert tq.auto_scheme_candidates(_target(), "z-image", base_repo = _ZIMAGE_BASE) == (
+ TQ_INT8,
+ TQ_FP8,
+ TQ_MXFP8,
+ )
+
+ def _boom(scheme):
+ raise RuntimeError("hub unreachable")
+
+ assert tq.auto_scheme_candidates(
+ _target(), "z-image", base_repo = _ZIMAGE_BASE, has_prequant = _boom
+ ) == (TQ_INT8, TQ_FP8, TQ_MXFP8)
+ assert (
+ select_transformer_quant_scheme(
+ _target(), TQ_NVFP4, family = "z-image", base_repo = _ZIMAGE_BASE
+ )
+ == TQ_NVFP4
+ )
+
+
+def test_a_record_lifts_the_qwen_nvfp4_deny_for_the_gated_base_only(monkeypatch, tmp_path):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ _stub_nvfp4_backend(monkeypatch, "flashinfer")
+ _gate(monkeypatch, tmp_path)
+ assert tq._family_denied("qwen-image", TQ_NVFP4, _QWEN_BASE) is True
+ assert (
+ select_transformer_quant_scheme(
+ _target(), TQ_NVFP4, family = "qwen-image", base_repo = _QWEN_BASE
+ )
+ is None
+ )
+
+ _gate(monkeypatch, tmp_path, _gate_row("qwen-image", _QWEN_BASE, "qwen_p02_v1"))
+ assert tq._family_denied("qwen-image", TQ_NVFP4, _QWEN_BASE) is False
+ assert (
+ select_transformer_quant_scheme(
+ _target(), TQ_NVFP4, family = "qwen-image", base_repo = _QWEN_BASE
+ )
+ == TQ_NVFP4
+ )
+ for family, base in (
+ ("qwen-image", "Qwen/Qwen-Image-2509"),
+ ("qwen-image-edit", "Qwen/Qwen-Image-Edit"),
+ ("qwen-image", None),
+ ):
+ assert tq._family_denied(family, TQ_NVFP4, base) is True, (family, base)
+ assert tq._family_denied("qwen-image", TQ_MXFP8, _QWEN_BASE) is True
+ assert tq.auto_scheme_candidates(
+ _target(), "qwen-image", base_repo = _QWEN_BASE, has_prequant = lambda scheme: True
+ ) == (TQ_INT8, TQ_FP8, TQ_NVFP4)
+
+
+def test_the_refusal_message_names_the_missing_gate_record(monkeypatch, tmp_path):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _gate(monkeypatch, tmp_path)
+ message = tq.explain_unusable_scheme("qwen-image", TQ_NVFP4, _QWEN_BASE)
+ assert "nvfp4_gate_record.json" in message and _QWEN_BASE in message
+ assert "measured accuracy gate" in tq.explain_unusable_scheme("qwen-image", TQ_MXFP8)
+
+
+def test_training_is_denied_nvfp4_for_every_family_gated_or_not(monkeypatch, tmp_path):
+ from core.inference.diffusion_families import supported_family_names
+
+ _gate(monkeypatch, tmp_path, _gate_row("z-image", _ZIMAGE_BASE, "zimg_rg76_v1"))
+ assert tq._family_denied("z-image", TQ_NVFP4, _ZIMAGE_BASE) is False
+ for family in (*supported_family_names(), "wan2.2-ti2v-5b", "minimax-h3", None, ""):
+ assert tq._family_train_denied(family, TQ_NVFP4) is True, family
+ assert tq._family_train_denied(family, TQ_NVFP4, _ZIMAGE_BASE) is True, family
+ assert tq._family_train_denied("z-image", TQ_INT8) is False
+ assert tq._family_train_denied("z-image", TQ_FP8) is False
+
+
[email protected]("has_prequant", [True, False])
[email protected]("gated", [True, False])
+ "allowed",
+ [
+ {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8},
+ {TQ_NVFP4, TQ_MXFP8, TQ_INT8},
+ {TQ_NVFP4},
+ {TQ_INT8},
+ set(),
+ ],
+)
+def test_the_candidate_head_stays_the_selector_winner_under_the_gate(
+ monkeypatch, tmp_path, allowed, gated, has_prequant
+):
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, allowed)
+ _stub_nvfp4_backend(monkeypatch, "flashinfer")
+ rows = [_gate_row("z-image", _ZIMAGE_BASE, "zimg_rg76_v1")] if gated else []
+ _gate(monkeypatch, tmp_path, *rows)
+ kwargs = {"base_repo": _ZIMAGE_BASE, "has_prequant": lambda scheme: has_prequant}
+ candidates = tq.auto_scheme_candidates(_target(), "z-image", **kwargs)
+ chosen = select_transformer_quant_scheme(_target(), "auto", family = "z-image", **kwargs)
+ assert (candidates[0] if candidates else None) == chosen, (allowed, gated, has_prequant)
+ assert (TQ_NVFP4 in candidates) == (gated and has_prequant and TQ_NVFP4 in allowed)
+
+
+ ("probe", "recorded", "offered"),
+ [
+ ("flashinfer", "flashinfer", True),
+ ("torchao", "flashinfer", False),
+ ("flashinfer", "torchao", False),
+ ("torchao", "torchao", True),
+ ("raises", "flashinfer", False),
+ ("flashinfer", None, False),
+ ],
+ ids = [
+ "measured",
+ "unmeasured-torchao",
+ "unmeasured-flashinfer",
+ "torchao-record",
+ "unprobed",
+ "no-backend",
+ ],
+)
+def test_a_gated_row_stands_only_on_the_backend_its_record_was_measured_on(
+ monkeypatch, tmp_path, probe, recorded, offered
+):
+ """The two NVFP4 backends quantise activations differently, so one verdict cannot enable both."""
+ _stub_torch(monkeypatch, cc = (10, 0))
+ _allow(monkeypatch, {TQ_NVFP4, TQ_FP8, TQ_MXFP8, TQ_INT8})
+ _stub_nvfp4_backend(monkeypatch, probe)
+ _gate(
+ monkeypatch,
+ tmp_path,
+ _gate_row("z-image", _ZIMAGE_BASE, "zimg_rg76_v1", backend = recorded),
+ )
+ candidates = _zimage_candidates(monkeypatch)
+ assert (TQ_NVFP4 in candidates) is offered
+ assert candidates[0] == TQ_INT8
+ _allow(monkeypatch, {TQ_NVFP4, TQ_MXFP8})
+ chosen = select_transformer_quant_scheme(
+ _target(),
+ "auto",
+ family = "z-image",
+ base_repo = _ZIMAGE_BASE,
+ has_prequant = lambda scheme: True,
+ )
+ assert chosen == (TQ_NVFP4 if offered else TQ_MXFP8)
+
+
# Load-kind eligibility.
@@ -2189,3 +2837,24 @@ def test_a_later_shard_still_reveals_a_narrow_source(tmp_path):
str(sub / "diffusion_pytorch_model-00002-of-00002.safetensors"),
)
assert tq.stored_denoiser_precision(str(tmp_path)) == "fp8"
+
+
+def test_a_missing_nvfp4_prequant_is_named_instead_of_the_gpu(monkeypatch):
+ monkeypatch.setattr(tq, "_TORCHAO_UNAVAILABLE", (None,))
+ monkeypatch.setattr(tq, "family_denies_scheme", lambda *a, **k: False)
+ message = tq.explain_unusable_scheme("z-image", TQ_NVFP4, prequant_missing = True)
+ assert "needs a pre-quantized checkpoint" in message and "on this GPU" not in message
+ monkeypatch.setattr(tq, "family_denies_scheme", lambda *a, **k: True)
+ assert "accuracy-gate record" in tq.explain_unusable_scheme(
+ "qwen-image", TQ_NVFP4, prequant_missing = True
+ )
+
+
+def test_the_loader_decline_asks_explain_unusable_scheme():
+ import inspect
+
+ from core.inference import diffusion
+
+ src = inspect.getsource(diffusion.DiffusionBackend)
+ assert 'is not usable for family "\n' not in src
+ assert "transformer_quant_decline = explain_unusable_scheme(" in src
diff --git a/studio/backend/tests/test_nvfp4_diffusion_flag.py b/studio/backend/tests/test_nvfp4_diffusion_flag.py
index 62bc8e34f70..a059a5e9922 100644
--- a/studio/backend/tests/test_nvfp4_diffusion_flag.py
+++ b/studio/backend/tests/test_nvfp4_diffusion_flag.py
@@ -470,6 +470,88 @@ def test_enabled_the_routes_let_nvfp4_through_the_switch(monkeypatch):
)
+def _record_nvfp4_probes(monkeypatch):
+ """Record every gate-record read and flashinfer backend probe instead of running them."""
+ from core.inference import diffusion_nvfp4_gate as gate
+ from core.inference import diffusion_nvfp4_ops as ops
+
+ calls: list[str] = []
+ monkeypatch.setattr(gate, "nvfp4_gate_passed", lambda *a, **k: calls.append("gate") or True)
+ monkeypatch.setattr(
+ gate, "nvfp4_gate_backends", lambda *a, **k: calls.append("gate") or ("flashinfer",)
+ )
+ monkeypatch.setattr(
+ ops, "select_nvfp4_backend", lambda *a, **k: calls.append("backend") or "flashinfer"
+ )
+ return calls
+
+
[email protected]("family", ["wan2.2-t2v-a14b", "z-image", "flux.1", "qwen-image"])
+def test_the_nvfp4_auto_rows_are_dropped_before_any_gate_or_flashinfer_probe(monkeypatch, family):
+ calls = _record_nvfp4_probes(monkeypatch)
+ order = tq._auto_scheme_order(family, "cuda", (10, 0), "some/base")
+ assert tq.TQ_NVFP4 not in order
+ assert order == (tq.TQ_INT8, tq.TQ_FP8, tq.TQ_MXFP8)
+ assert calls == []
+
+
+def test_enabled_the_flashinfer_auto_row_leads_again(monkeypatch):
+ _enable(monkeypatch)
+ calls = _record_nvfp4_probes(monkeypatch)
+ monkeypatch.setattr(
+ tq, "_is_consumer_gpu", lambda device = None: False
+ ) # not the runner's own card
+ order = tq._auto_scheme_order("wan2.2-t2v-a14b", "cuda", (10, 0), "Wan-AI/Wan2.2-T2V-A14B")
+ assert order[0] == tq.TQ_NVFP4
+ assert "backend" in calls
+
+
+def test_no_flashinfer_import_or_preflight_is_triggered(monkeypatch):
+ from core.inference import diffusion_nvfp4_linear as linear
+ from core.inference import diffusion_nvfp4_ops as ops
+
+ touched = []
+ monkeypatch.setattr(
+ ops, "_flashinfer_available", lambda: touched.append("import") or (True, "x")
+ )
+ monkeypatch.setattr(ops, "_preflight_probe", lambda dev: touched.append("preflight") or True)
+ backend, reason = ops._resolve_backend(0)
+ assert backend == ops.BACKEND_TORCHAO and DISABLED in reason
+ assert ops.select_nvfp4_backend(0) == ops.BACKEND_TORCHAO
+ assert ops.nvfp4_preflight(0)["ok"] is False
+ assert linear.nvfp4_prewarm(object(), (16,)) == 0
+ assert touched == []
+ assert tq._nvfp4_gate_passed("z-image", "Tongyi-MAI/Z-Image-Turbo") is False
+ assert tq._nvfp4_backend_is("cuda", "flashinfer") is False
+
+
+def test_the_hosted_image_nvfp4_rows_resolve_to_nothing(monkeypatch):
+ from core.inference.diffusion_families import detect_family, family_prequant_repo
+ from core.inference.diffusion_prequant import usable_prequant_source
+
+ schnell = "black-forest-labs/FLUX.1-schnell"
+ zimage = "Tongyi-MAI/Z-Image-Turbo"
+ for base in (schnell, zimage):
+ fam = detect_family(base)
+ assert family_prequant_repo(fam, "nvfp4", base_repo = base) is None
+ assert usable_prequant_source(fam, "nvfp4", base_repo = base) is None
+ _enable(monkeypatch)
+ assert family_prequant_repo(detect_family(schnell), "nvfp4", base_repo = schnell) == (
+ "unsloth/FLUX.1-schnell-NVFP4"
+ )
+ assert family_prequant_repo(detect_family(zimage), "nvfp4", base_repo = zimage) == (
+ "unsloth/Z-Image-Turbo-NVFP4"
+ )
+
+
+def test_the_per_layer_policy_factor_is_not_applied(monkeypatch):
+ from core.inference.diffusion_auto_policy import policy_steady_factor
+
+ assert policy_steady_factor("z-image", "Tongyi-MAI/Z-Image-Turbo") is None
+ _enable(monkeypatch)
+ assert policy_steady_factor("z-image", "Tongyi-MAI/Z-Image-Turbo") is not None
+
+
def _prequant_dir(root, name, scheme):
"""A directory holding one tiny safetensors pre-quant artifact that records ``scheme``."""
import json
@@ -541,6 +623,15 @@ def test_every_family_registered_nvfp4_repo_is_recognised_by_the_table():
assert registered and registered <= hosted_nvfp4_repo_ids()
+def test_the_image_family_nvfp4_repos_are_recognised_by_the_table():
+ from core.inference.diffusion_prequant import hosted_nvfp4_repo_ids
+
+ ids = hosted_nvfp4_repo_ids()
+ assert "unsloth/z-image-turbo-nvfp4" in ids
+ assert "unsloth/flux.1-schnell-nvfp4" in ids
+ assert not any("fp8" in repo and "nvfp4" not in repo for repo in ids)
+
+
def test_a_cached_repo_is_judged_by_its_metadata_not_its_name(tmp_path, monkeypatch):
from core.inference import diffusion_prequant as dpq
diff --git a/studio/backend/tests/test_saved_image_metadata_precision_contract.py b/studio/backend/tests/test_saved_image_metadata_precision_contract.py
index 3db44ec6b14..9ddc2cd1f13 100644
--- a/studio/backend/tests/test_saved_image_metadata_precision_contract.py
+++ b/studio/backend/tests/test_saved_image_metadata_precision_contract.py
@@ -307,7 +307,7 @@ def test_generate_reports_the_engaged_scheme_when_it_differs_from_the_request(
monkeypatch.setattr(
diffusion_module,
"select_transformer_quant_scheme",
- lambda target, mode, family = None: engaged,
+ lambda target, mode, family = None, **_kw: engaged,
)
monkeypatch.setattr(diffusion_module, "resolve_prequant_source", lambda fam, scheme, **kw: None)
monkeypatch.setattr(
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 5c0df4690df..fa79279187a 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -8177,7 +8177,9 @@ def test_dense_quant_replan_uses_the_scaled_text_encoder(fake_runtime, monkeypat
scale, text_encoder_gb, transformer_gb, vae_gb = _shared_setup_9(monkeypatch)
monkeypatch.setattr(video_mod, "dense_transformer_supported", lambda target: True)
monkeypatch.setattr(
- video_mod, "select_transformer_quant_scheme", lambda target, mode, family = None: "int8"
+ video_mod,
+ "select_transformer_quant_scheme",
+ lambda target, mode, family = None, **_kw: "int8",
)
monkeypatch.setattr(video_mod, "quantize_transformer", lambda *a, **k: None)
# Force the first plan to offload so the re-plan branch runs.
@@ -8597,7 +8599,7 @@ def test_unified_memory_refuses_on_the_dense_peak_even_when_a_quant_is_requested
monkeypatch.setattr(video_mod, "resolve_diffusion_device_target", lambda: target)
monkeypatch.setattr(video_mod, "dense_transformer_supported", lambda t: True)
monkeypatch.setattr(
- video_mod, "select_transformer_quant_scheme", lambda t, q, family = None: "fp8"
+ video_mod, "select_transformer_quant_scheme", lambda t, q, family = None, **_kw: "fp8"
)
# An integrated CUDA device: 48 GiB shared, so LTX-2's ~65 GB of dense weights cannot fit even
# though the fp8 steady size would.
@@ -9389,6 +9391,7 @@ def _plans_for(monkeypatch, video_mod):
def test_the_memory_plan_prices_a_seeded_denoiser_at_the_measured_row(fake_runtime, monkeypatch):
+ """The memory plan prices a seeded denoiser at the measured row, not the dense term."""
import core.inference.video as video_mod
monkeypatch.setattr(video_mod, "dense_transformer_supported", lambda target: True)
@@ -9445,6 +9448,7 @@ def test_a_failed_seed_replans_at_bf16_and_refuses_again(fake_runtime, monkeypat
def test_the_planned_scheme_is_what_the_load_seeds(fake_runtime, monkeypatch):
+ """The scheme the plan committed to is the one the load seeds."""
import core.inference.video as video_mod
monkeypatch.setattr(video_mod, "dense_transformer_supported", lambda target: True)
@@ -9499,6 +9503,7 @@ _A14B_SIBLINGS = [
def test_base_download_files_drops_both_experts_and_keeps_both_configs():
+ """A seeded MoE drops both experts' dense shards and keeps both configs."""
info = types.SimpleNamespace(siblings = _A14B_SIBLINGS)
dense = dict(VideoBackend._base_download_files(info, "pipeline"))
@@ -9529,6 +9534,7 @@ def test_base_download_files_keeps_the_h3_partition_default():
def test_the_download_plan_stages_both_experts_artifacts(monkeypatch):
+ """The download plan stages both experts' artifacts."""
import core.inference.video as video_mod
import core.inference.video_denoiser_prequant as dq
@@ -9644,6 +9650,19 @@ def test_an_explicit_scheme_under_speed_off_stages_the_hosted_experts(monkeypatc
assert {"Wan2.2-T2V-A14B-NVFP4.pt", "Wan2.2-T2V-A14B-transformer_2-NVFP4.pt"} <= staged
+def test_the_video_status_response_carries_the_nvfp4_backend_label():
+ """'NVFP4' alone does not say which backend ran."""
+ from models.inference import VideoStatusResponse
+
+ resp = VideoStatusResponse(
+ loaded = True,
+ transformer_quant = "nvfp4",
+ transformer_quant_backend = "flashinfer",
+ )
+ assert resp.model_dump()["transformer_quant_backend"] == "flashinfer"
+ assert VideoStatusResponse(loaded = True).model_dump()["transformer_quant_backend"] is None
+
+
def _cuda_plan_target(monkeypatch, video_mod, *, free_gib):
"""Point the planning path at a cuda card of ``free_gib``, off the test host's own hardware."""
import torch
diff --git a/studio/backend/tests/test_video_prequant.py b/studio/backend/tests/test_video_prequant.py
index d1d2405272d..c37b527b617 100644
--- a/studio/backend/tests/test_video_prequant.py
+++ b/studio/backend/tests/test_video_prequant.py
@@ -1338,9 +1338,23 @@ def _video_auto(
"""``_video_auto_denoiser_scheme`` with the device selector stubbed to ``scheme``."""
from core.inference import video as vid
- monkeypatch.setattr(
- vid, "select_transformer_quant_scheme", lambda target, requested, family = None: scheme
- )
+ def _select(
+ target,
+ requested,
+ family = None,
+ base_repo = None,
+ **kw,
+ ):
+ _video_auto.calls.append(
+ dict(requested = requested, family = family, base_repo = base_repo, **kw)
+ )
+ probe = kw.get("has_prequant")
+ if scheme is not None and requested == "auto" and probe is not None and not probe(scheme):
+ return None
+ return scheme
+
+ _video_auto.calls = []
+ monkeypatch.setattr(vid, "select_transformer_quant_scheme", _select)
kw = dict(
target = None,
requested = "auto",
@@ -1363,6 +1377,16 @@ def test_the_conventional_auto_scheme_needs_an_artifact_for_every_expert(monkeyp
assert _video_auto(monkeypatch, scheme = None) is None
+def test_auto_is_handed_the_probe_that_lets_it_reach_a_prequant_only_scheme(monkeypatch):
+ assert _video_auto(monkeypatch, scheme = "nvfp4") == "nvfp4"
+ probe = _video_auto.calls[-1]["has_prequant"]
+ assert probe("nvfp4") is True
+ assert probe("int8") is False
+ half = _fam(is_moe = True, prequant_repos = (("nvfp4", "org/x"),))
+ assert _video_auto(monkeypatch, scheme = "nvfp4", fam = half) is None
+ assert _video_auto.calls[-1]["has_prequant"]("nvfp4") is False
+
+
def test_speed_off_and_the_modular_workflow_are_never_seeded_here(monkeypatch):
assert _video_auto(monkeypatch, scheme = "nvfp4", speed_mode = "off") is None
assert _video_auto(monkeypatch, scheme = "nvfp4", speed_mode = " OFF ") is None
@@ -1399,6 +1423,84 @@ def test_the_conventional_coverage_probe_reads_every_component():
assert not VideoBackend._denoiser_prequant_covered(half, "nvfp4", "org/test-video")
+def _a14b_auto(
+ monkeypatch,
+ *,
+ backend,
+ fam = None,
+ allowed = None,
+):
+ """Real selector, preference table and coverage resolver for the shipped A14B family."""
+ import types
+
+ import core.inference.diffusion_nvfp4_ops as ops
+ import core.inference.diffusion_prequant as pq
+ import core.inference.diffusion_transformer_quant as tq
+ from core.inference import video as vid
+ from core.inference.video_denoiser_prequant import denoiser_prequant_sources
+ from core.inference.video_families import detect_video_family
+
+ allowed = allowed or {"nvfp4", "fp8", "mxfp8", "int8"}
+ monkeypatch.setattr(tq, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(tq, "_capability", lambda: (10, 0))
+ monkeypatch.setattr(tq, "_is_consumer_gpu", lambda device: False)
+ monkeypatch.setattr(tq, "_scheme_supported", lambda scheme, device, **kw: scheme in allowed)
+ monkeypatch.setattr(ops, "select_nvfp4_backend", lambda device = None: backend)
+ monkeypatch.setattr(pq, "restricted_prequant_load_supported", lambda scheme = None: True)
+ fam = fam if fam is not None else detect_video_family("Wan-AI/Wan2.2-T2V-A14B-Diffusers")
+ base = fam.base_repo
+ return (
+ vid._video_auto_denoiser_scheme(
+ fam,
+ target = types.SimpleNamespace(device = "cuda:0", dtype = "bfloat16"),
+ requested = "auto",
+ base_repo = base,
+ speed_mode = None,
+ ),
+ tq.select_transformer_quant_scheme(
+ types.SimpleNamespace(device = "cuda:0", dtype = "bfloat16"),
+ "auto",
+ family = fam.name,
+ base_repo = base,
+ has_prequant = lambda scheme: (denoiser_prequant_sources(fam, scheme, base) is not None),
+ ),
+ )
+
+
+def test_the_a14b_auto_plan_seeds_nvfp4_where_flashinfer_serves_the_device(monkeypatch):
+ seeded, chosen = _a14b_auto(monkeypatch, backend = "flashinfer")
+ assert seeded == "nvfp4"
+ assert chosen == "nvfp4"
+
+
+def test_the_a14b_auto_plan_stays_on_the_ladder_on_the_torchao_backend(monkeypatch):
+ seeded, chosen = _a14b_auto(monkeypatch, backend = "torchao")
+ assert chosen == "int8"
+ assert seeded is None
+
+
+def test_the_a14b_auto_plan_stays_on_the_ladder_with_only_one_expert_hosted(monkeypatch):
+ """One expert hosted is uncovered, not partly covered."""
+ import dataclasses
+
+ from core.inference.video_families import detect_video_family
+
+ full = detect_video_family("Wan-AI/Wan2.2-T2V-A14B-Diffusers")
+ half = dataclasses.replace(
+ full,
+ prequant_filenames = tuple(row for row in full.prequant_filenames if len(row) == 2),
+ )
+ seeded, chosen = _a14b_auto(monkeypatch, backend = "flashinfer", fam = half)
+ assert seeded is None
+ assert chosen == "int8"
+
+
+def test_the_a14b_auto_plan_falls_through_when_the_fp4_kernel_is_missing(monkeypatch):
+ seeded, chosen = _a14b_auto(monkeypatch, backend = "flashinfer", allowed = {"fp8", "mxfp8", "int8"})
+ assert seeded is None
+ assert chosen == "int8"
+
+
def _planned_denoiser_request(monkeypatch, fam, **load_kwargs):
"""The scheme the planner hands ``_denoiser_prequant_verified`` (stubbed, as is the build)."""
from core.inference import video as vid
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index aeb9288b717..d8bb22b4c4d 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -42,6 +42,7 @@ export interface DiffusionStatus {
// actually ran instead of echoing the load request back. Transformer quant engaged on the dense fast path
// ("int8" / "fp8" / ...), null = the GGUF ran as-is.
transformer_quant?: string | null;
+ transformer_quant_backend?: string | null;
// Text-encoder quant engaged ("fp8" | "fp8_dynamic" | "int8" | "nvfp4"), null = dense bf16.
text_encoder_quant?: string | null;
// Memory mode the load ran under: "auto" | "fast" | "balanced" | "low_vram".
diff --git a/studio/frontend/src/features/loaded-models/loaded-models-sources.ts b/studio/frontend/src/features/loaded-models/loaded-models-sources.ts
index acaee621db4..31924f231d7 100644
--- a/studio/frontend/src/features/loaded-models/loaded-models-sources.ts
+++ b/studio/frontend/src/features/loaded-models/loaded-models-sources.ts
@@ -198,6 +198,18 @@ export function precisionLabel(value: string | null | undefined): string | null
return known[value] ?? value.toUpperCase();
}
+/** NVFP4 kernel path label; unrecognised values pass through as sent. */
+export function quantBackendLabel(
+ value: string | null | undefined,
+): string | null {
+ if (!value) return null;
+ const known: Record<string, string> = {
+ flashinfer: "FlashInfer",
+ torchao: "torchao",
+ };
+ return known[value.toLowerCase()] ?? value;
+}
+
export function describeDiffusionStatus(
status: DiffusionStatus | null,
): LoadedModelEntry[] {
@@ -225,6 +237,7 @@ export function describeDiffusionStatus(
precisionLabel(status.transformer_quant) ??
precisionLabel(status.gguf_variant) ??
precisionLabel(status.dtype),
+ quantBackendLabel(status.transformer_quant_backend),
status.device,
),
},
@@ -249,6 +262,7 @@ export function describeVideoStatus(
precisionLabel(status.gguf_variant) ??
precisionLabel(status.transformer_quant) ??
precisionLabel(status.dtype),
+ quantBackendLabel(status.transformer_quant_backend),
status.device,
),
},
diff --git a/studio/frontend/src/features/video/api.ts b/studio/frontend/src/features/video/api.ts
index 233da57e887..4a5d7f7bba0 100644
--- a/studio/frontend/src/features/video/api.ts
+++ b/studio/frontend/src/features/video/api.ts
@@ -77,6 +77,7 @@ export interface VideoStatus {
} | null;
// Dense DiT precision actually engaged ("int8" | "fp8" | ...) or null for bf16.
transformer_quant?: string | null;
+ transformer_quant_backend?: string | null;
// Text-encoder quant actually engaged ("fp8" | "fp8_dynamic" | "int8" | "nvfp4") or null for dense bf16.
text_encoder_quant?: string | null;
// Whether the loaded family produces a synchronized audio track.
diff --git a/studio/frontend/tests/loaded-models-sources.test.ts b/studio/frontend/tests/loaded-models-sources.test.ts
index eae093340a1..8e6c8182575 100644
--- a/studio/frontend/tests/loaded-models-sources.test.ts
+++ b/studio/frontend/tests/loaded-models-sources.test.ts
@@ -531,3 +531,88 @@ test("the announced row yields once that same model is resident", () => {
assert.equal(rows.length, 1);
assert.notEqual(rows[0].loading, true);
});
+
+test("an nvfp4 image row names the kernel backend that served it", () => {
+ const [flashinfer] = describeDiffusionStatus({
+ loaded: true,
+ repo_id: "unsloth/Z-Image-Turbo-NVFP4",
+ family: "z-image",
+ transformer_quant: "nvfp4",
+ transformer_quant_backend: "flashinfer",
+ dtype: "bfloat16",
+ device: "cuda",
+ } as never);
+ assert.equal(flashinfer.detail, "z-image · NVFP4 · FlashInfer · cuda");
+
+ const [torchao] = describeDiffusionStatus({
+ loaded: true,
+ repo_id: "unsloth/Z-Image-Turbo-NVFP4",
+ family: "z-image",
+ transformer_quant: "nvfp4",
+ transformer_quant_backend: "torchao",
+ dtype: "bfloat16",
+ device: "cuda",
+ } as never);
+ assert.equal(torchao.detail, "z-image · NVFP4 · torchao · cuda");
+});
+
+test("a row without a quant backend is unchanged, on old and new backends alike", () => {
+ const [fp8] = describeDiffusionStatus({
+ loaded: true,
+ repo_id: "unsloth/Z-Image-Turbo",
+ family: "z-image",
+ transformer_quant: "fp8",
+ transformer_quant_backend: null,
+ dtype: "bfloat16",
+ device: "cuda",
+ } as never);
+ assert.equal(fp8.detail, "z-image · FP8 · cuda");
+ const [old] = describeDiffusionStatus({
+ loaded: true,
+ repo_id: "unsloth/Z-Image-Turbo",
+ family: "z-image",
+ transformer_quant: "fp8",
+ dtype: "bfloat16",
+ device: "cuda",
+ } as never);
+ assert.equal(old.detail, "z-image · FP8 · cuda");
+});
+
+test("an nvfp4 video row names the kernel backend that served it", () => {
+ const [flashinfer] = describeVideoStatus({
+ loaded: true,
+ repo_id: "unsloth/Wan2.2-T2V-A14B-NVFP4",
+ family: "wan2.2-t2v-a14b",
+ transformer_quant: "nvfp4",
+ transformer_quant_backend: "flashinfer",
+ dtype: "bfloat16",
+ device: "cuda",
+ } as never);
+ assert.equal(
+ flashinfer.detail,
+ "wan2.2-t2v-a14b · NVFP4 · FlashInfer · cuda",
+ );
+
+ const [torchao] = describeVideoStatus({
+ loaded: true,
+ repo_id: "unsloth/Wan2.2-T2V-A14B-NVFP4",
+ family: "wan2.2-t2v-a14b",
+ transformer_quant: "nvfp4",
+ transformer_quant_backend: "torchao",
+ dtype: "bfloat16",
+ device: "cuda",
+ } as never);
+ assert.equal(torchao.detail, "wan2.2-t2v-a14b · NVFP4 · torchao · cuda");
+});
+
+test("a video row without a quant backend is unchanged", () => {
+ const [row] = describeVideoStatus({
+ loaded: true,
+ repo_id: "unsloth/Wan2.2-T2V-A14B",
+ family: "wan2.2-t2v-a14b",
+ transformer_quant: "fp8",
+ dtype: "bfloat16",
+ device: "cuda",
+ } as never);
+ assert.equal(row.detail, "wan2.2-t2v-a14b · FP8 · cuda");
+});