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: load ComfyUI nvfp4 and mxfp8 DiT single files (#12877)

Daniel Han2402838d790f
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index e7057e13736..88d379525ed 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -282,6 +282,12 @@ from .diffusion_denoiser_prequant import (
pipeline_seed_supported,
prequant_artifact_label,
)
+from .diffusion_comfy_block import (
+ comfy_block_backend,
+ comfy_block_backends,
+ comfy_block_runtime_layers,
+ comfy_nvfp4_runtime_possible,
+)
from .diffusion_comfy_quant import (
comfy_fp8_backend,
comfy_int8_backend,
@@ -5831,8 +5837,14 @@ class DiffusionBackend:
_ensure_attention_backend_installed(preinstall_backend, logger)
except Exception: # noqa: BLE001 - the locked path re-resolves and validates
pass
- # Install FlashInfer only when a pre-quantised checkpoint will load: the on-the-fly build is torchao.
+ # Install FlashInfer only when a pre-quantised checkpoint (incl. a ComfyUI nvfp4 file) will load: on-the-fly is torchao.
if (
+ kind == "single_file"
+ and nvfp4_diffusion_enabled()
+ and comfy_nvfp4_runtime_possible(getattr(fam, "name", None))
+ and not _has_active_lora(loras)
+ and self._comfy_single_file_holds_nvfp4(repo_id, gguf_filename)
+ ) or (
dense_quant_supported_kind(kind)
and nvfp4_diffusion_enabled()
and TQ_NVFP4
@@ -5931,6 +5943,7 @@ class DiffusionBackend:
memory_mode,
cpu_offload,
kind = kind,
+ lora = _has_active_lora(loras),
repo_id = repo_id,
# The base may be resolved off the OTHER cache root, which the plan's live-root scans read as zero
# companions.
@@ -7015,6 +7028,7 @@ class DiffusionBackend:
memory_mode,
cpu_offload,
kind = kind,
+ lora = _has_active_lora(loras),
repo_id = repo_id,
base_local_dir = _base_local_dir,
fetch_base = fetch_base,
@@ -7140,6 +7154,14 @@ class DiffusionBackend:
base,
offload = _comfy_offload,
),
+ **comfy_block_backends(
+ comfy_scan,
+ target,
+ fam.name,
+ dtype = dtype,
+ logger = logger,
+ lora = _has_active_lora(loras),
+ ),
family = fam.name,
target = target,
fast_accum = transformer_quant_fast_accum,
@@ -8187,13 +8209,49 @@ class DiffusionBackend:
except Exception: # noqa: BLE001 - status only
return None
+ @staticmethod
+ def _comfy_single_file_holds_nvfp4(repo_id: Optional[str], filename: Optional[str]) -> bool:
+ """Whether an already-on-disk single file holds ComfyUI nvfp4 layers; never downloads, never raises."""
+ try:
+ if not repo_id or not filename:
+ return False
+ local_root = Path(str(repo_id)).expanduser()
+ if local_root.exists():
+ path = str(resolve_local_gguf_child(local_root, filename))
+ else:
+ from huggingface_hub import try_to_load_from_cache
+ path = try_to_load_from_cache(repo_id, filename, cache_dir = hub_cache_dir())
+ if not isinstance(path, str):
+ # the resolver falls back to Hugging Face's default cache too
+ path = try_to_load_from_cache(repo_id, filename, cache_dir = None)
+ if not isinstance(path, str):
+ return False
+ from .diffusion_comfy_quant import scan_comfy_quant
+
+ scan = scan_comfy_quant(path)
+ return bool(scan is not None and not scan.problems and scan.counts().get("nvfp4"))
+ except Exception: # noqa: BLE001 - an install hint only: the load decides on its own
+ return False
+
@staticmethod
def _comfy_single_file_resident_mib(
- single_file_path: Optional[str], fam: Any, target: Any, base: Optional[str]
+ single_file_path: Optional[str],
+ fam: Any,
+ target: Any,
+ base: Optional[str],
+ *,
+ lora: bool = False,
) -> Optional[int]:
"""``comfy_resident_mib`` for a ComfyUI-quantized single file under a resident plan, else None."""
try:
from .diffusion_comfy_quant import comfy_resident_mib, scan_comfy_quant
+ from .diffusion_transformer_quant import (
+ DEFAULT_MIN_LINEAR_FEATURES,
+ TQ_FP8,
+ TQ_MXFP8,
+ TQ_NVFP4,
+ divisible_for_scheme,
+ )
scan = scan_comfy_quant(single_file_path)
if scan is None or scan.problems:
@@ -8204,6 +8262,26 @@ class DiffusionBackend:
scan,
keep_int8 = comfy_int8_backend(target, name, base) is not None,
keep_fp8 = comfy_fp8_backend(target, name, base) is not None,
+ # the loader's runtime filter: layers it skips are priced dequantized
+ min_features = DEFAULT_MIN_LINEAR_FEATURES,
+ fp8_divisible = divisible_for_scheme(TQ_FP8),
+ block_divisible = {
+ "nvfp4": divisible_for_scheme(TQ_NVFP4),
+ "mxfp8": divisible_for_scheme(TQ_MXFP8),
+ },
+ **{
+ # a LoRA dequantizes the block layers (comfy_block_backends)
+ f"keep_{fmt}": backend is not None and not lora
+ for fmt, backend in (
+ ("nvfp4", comfy_block_backend("nvfp4", target, name)[0]),
+ (
+ "mxfp8",
+ comfy_block_backend(
+ "mxfp8", target, name, dtype = getattr(target, "dtype", None)
+ )[0],
+ ),
+ )
+ },
)
except Exception: # noqa: BLE001 - a planning aid: the file-size estimate stands
return None
@@ -9143,6 +9221,7 @@ class DiffusionBackend:
fetch_base: Optional[str] = None,
device_memory_override: Optional[DeviceMemory] = None,
text_encoder_quant: Optional[str] = None,
+ lora: bool = False,
):
"""Build the memory plan for this load: snapshot free device memory and estimate the model's
resident footprint, then let the planner pick an offload policy + VAE memory savers. Kept on
@@ -9304,7 +9383,7 @@ class DiffusionBackend:
if not getattr(fam, "single_file_is_pipeline", False):
# Priced from the header: layers a resident runtime keeps at stored size, dequantized ones at 2x.
_comfy_mib = self._comfy_single_file_resident_mib(
- single_file_path, fam, target, base
+ single_file_path, fam, target, base, lora = lora
)
if _comfy_mib is not None:
transformer_resident = _comfy_mib
@@ -9694,6 +9773,12 @@ class DiffusionBackend:
"stored the transformer as int8 weights (small-host route), which cannot carry adapters. Load the "
"model with the LoRA selected (Studio then keeps the dense transformer), or use a host with more RAM."
)
+ if comfy_block_runtime_layers(getattr(pipe, "transformer", None)):
+ raise ValueError(
+ "LoRA is not available on this load: the ComfyUI file's nvfp4 / mxfp8 layers run on their own "
+ "quantized Linears, which cannot carry adapters. Load the file with the LoRA selected (Studio then "
+ "dequantizes those layers), or set UNSLOTH_DIFFUSION_COMFY_NVFP4=0 / UNSLOTH_DIFFUSION_COMFY_MXFP8=0."
+ )
if not diffusion_lora.supports_lora(
engine = "diffusers",
family = getattr(state.family, "name", None),
@@ -11212,7 +11297,8 @@ class DiffusionBackend:
transformer_quant = state.transformer_quant,
compiled = "compiled" in (getattr(state, "speed_optims", ()) or ()),
)
- and not _small_host_int8(state.pipe),
+ and not _small_host_int8(state.pipe)
+ and not comfy_block_runtime_layers(getattr(state.pipe, "transformer", None)),
"small_host": small_host_engaged_on(state.pipe),
"supports_controlnet": diffusion_controlnet.supports_controlnet(
engine = "diffusers",
diff --git a/studio/backend/core/inference/diffusion_comfy_block.py b/studio/backend/core/inference/diffusion_comfy_block.py
new file mode 100644
index 00000000000..40189e338f4
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_comfy_block.py
@@ -0,0 +1,488 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""ComfyUI ``nvfp4`` / ``mxfp8`` layers: decode, dequantize, and the runtimes that keep them.
+
+Layout measured on Comfy-Org's files: nvfp4 ``.weight`` uint8 ``[N, K/2]`` with the EVEN column in the HIGH nibble,
+e4m3 block scales (per 16 columns) in the cuBLAS 128x4 tiled layout, ``.weight_scale_2`` per-tensor,
+``.input_scale`` = activation ``amax / (448 * 6)``, optional ``.pre_quant_scale`` input smoothing. mxfp8 ``.weight``
+e4m3 ``[N, K]`` with e8m0 exponents (per 32 columns) in the same tiled layout. Decoded layers are row-major so the
+row-tag mapping in ``diffusion_comfy_quant`` splits and concatenates them as for int8 / fp8.
+"""
+
+from __future__ import annotations
+
+import os
+import threading
+from typing import Any, Optional
+
+NVFP4 = "nvfp4"
+MXFP8 = "mxfp8"
+BLOCK_SIZES = {NVFP4: 16, MXFP8: 32}
+COMFY_NVFP4_ENV = "UNSLOTH_DIFFUSION_COMFY_NVFP4"
+COMFY_MXFP8_ENV = "UNSLOTH_DIFFUSION_COMFY_MXFP8"
+NVFP4_RUNTIME = "flashinfer"
+MXFP8_RUNTIME = "scaled_mm"
+
+_OFF = ("0", "off", "false", "no")
+_E2M1 = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0)
+_FP8_MAX = 448.0
+_E8M0_BIAS = 127
+
+
+def _roundup(x: int, m: int) -> int:
+ return (int(x) + m - 1) // m * m
+
+
+def tiled_scale_numel(rows: int, blocks: int) -> int:
+ """Elements of a cuBLAS 128x4-tiled scale buffer for ``rows`` x ``blocks`` scales (padding included)."""
+ return _roundup(rows, 128) * _roundup(blocks, 4)
+
+
+def untile_scales(tiled: Any, rows: int, blocks: int) -> Any:
+ """The plain ``[rows, blocks]`` scale matrix from a 128x4-tiled buffer (any shape, same dtype)."""
+ rp, bp = _roundup(rows, 128), _roundup(blocks, 4)
+ flat = tiled.reshape(-1)
+ if flat.numel() != rp * bp:
+ raise ValueError(
+ f"tiled scales hold {flat.numel()} values, {rp * bp} expected for {rows}x{blocks}"
+ )
+ # tile (row // 128, block // 4) is 512 values: inner (row % 32, (row % 128) // 32, block % 4)
+ v = flat.reshape(rp // 128, bp // 4, 32, 4, 4).permute(0, 3, 2, 1, 4).reshape(rp, bp)
+ return v[:rows, :blocks].contiguous()
+
+
+def tile_scales(plain: Any) -> Any:
+ """``untile_scales`` inverted: a flat 128x4-tiled buffer, zero padded."""
+ import torch
+
+ rows, blocks = plain.shape
+ rp, bp = _roundup(rows, 128), _roundup(blocks, 4)
+ raw = plain.view(torch.uint8) if plain.element_size() == 1 else plain
+ full = torch.zeros(rp, bp, dtype = raw.dtype, device = raw.device)
+ full[:rows, :blocks] = raw
+ out = full.reshape(rp // 128, 4, 32, bp // 4, 4).permute(0, 3, 2, 1, 4).reshape(-1).contiguous()
+ return out.view(plain.dtype) if plain.element_size() == 1 else out
+
+
+def swap_nibbles(packed: Any) -> Any:
+ """High-first fp4 packing <-> low-first (``0xAB`` -> ``0xBA``)."""
+ import torch
+
+ u = packed.view(torch.uint8) if packed.dtype != torch.uint8 else packed
+ return ((u << 4) | (u >> 4)).to(torch.uint8)
+
+
+def decode_layer(fmt: str, weight: Any, weight_scale: Any) -> tuple[Any, Any]:
+ """Row-major ``(codes, plain scales)``; nvfp4 codes come out low-nibble-first (FlashInfer's packing)."""
+ import torch
+
+ rows = int(weight.shape[0])
+ if fmt == NVFP4:
+ cols = int(weight.shape[1]) * 2
+ codes = swap_nibbles(weight)
+ scale = untile_scales(weight_scale.view(torch.uint8), rows, cols // 16).view(
+ torch.float8_e4m3fn
+ )
+ return codes, scale
+ if fmt == MXFP8:
+ codes = weight if weight.dtype == torch.float8_e4m3fn else weight.view(torch.float8_e4m3fn)
+ scale = untile_scales(weight_scale.view(torch.uint8), rows, int(weight.shape[1]) // 32)
+ return codes, scale
+ raise ValueError(f"not a block-scaled ComfyUI format: {fmt!r}")
+
+
+def logical_cols(fmt: str, codes: Any) -> int:
+ return int(codes.shape[1]) * (2 if fmt == NVFP4 else 1)
+
+
+def dequant_block(
+ fmt: str,
+ codes: Any,
+ scale: Any,
+ *,
+ tensor_scale: Any = None,
+ pre_quant_scale: Any = None,
+ dtype: Any = None,
+) -> Any:
+ """Dense ``[N, K]`` weight; ``pre_quant_scale`` folds into the columns: ``(x * s) @ W.T == x @ (W * s).T``."""
+ import torch
+
+ dtype = dtype or torch.bfloat16
+ rows = int(codes.shape[0])
+ if fmt == NVFP4:
+ lut = torch.tensor(
+ _E2M1 + tuple(-v for v in _E2M1), dtype = torch.float32, device = codes.device
+ )
+ c = codes.to(torch.int32)
+ values = torch.stack((lut[c & 0x0F], lut[c >> 4]), dim = -1).reshape(rows, -1, 16)
+ step = scale.to(torch.float32)
+ if tensor_scale is not None:
+ step = step * torch.as_tensor(
+ tensor_scale, dtype = torch.float32, device = codes.device
+ ).reshape(-1, 1)
+ weight = (values * step.unsqueeze(-1)).reshape(rows, -1)
+ elif fmt == MXFP8:
+ exp = scale.view(torch.uint8).to(torch.float32) - _E8M0_BIAS
+ weight = (
+ codes.to(torch.float32).reshape(rows, -1, 32) * torch.exp2(exp).unsqueeze(-1)
+ ).reshape(rows, -1)
+ else:
+ raise ValueError(f"not a block-scaled ComfyUI format: {fmt!r}")
+ if pre_quant_scale is not None:
+ weight = weight * pre_quant_scale.to(torch.float32).reshape(1, -1)
+ return weight.to(dtype)
+
+
+def mx_quantize_activation(x: Any) -> tuple[Any, Any]:
+ """``[M, K]`` -> (e4m3 codes, tiled e8m0 scales), exponent ``ceil(log2(amax / 448))`` per 32 columns (ComfyUI's rule)."""
+ import torch
+
+ m, k = x.shape
+ blocks = x.float().reshape(m, k // 32, 32)
+ amax = blocks.abs().amax(dim = -1)
+ exp = torch.ceil(torch.log2(torch.clamp(amax / _FP8_MAX, min = 2.0**-127)))
+ exp = torch.clamp(exp, -_E8M0_BIAS, _E8M0_BIAS)
+ q = torch.clamp(blocks * torch.exp2(-exp).unsqueeze(-1), -_FP8_MAX, _FP8_MAX)
+ codes = q.to(torch.float8_e4m3fn).reshape(m, k)
+ biased = (exp + _E8M0_BIAS).to(torch.uint8)
+ rows_p, blocks_p = _roundup(m, 128), _roundup(k // 32, 4)
+ full = torch.full((rows_p, blocks_p), _E8M0_BIAS, dtype = torch.uint8, device = x.device)
+ full[:m, : k // 32] = biased
+ tiled = full.reshape(rows_p // 128, 4, 32, blocks_p // 4, 4).permute(0, 3, 2, 1, 4).reshape(-1)
+ return codes, tiled.view(torch.float8_e8m0fnu)
+
+
+def mxfp8_linear_class():
+ import torch
+ from torch import nn
+
+ global _MX_CLASS
+ if _MX_CLASS is not None:
+ return _MX_CLASS
+
+ class ComfyMXFP8Linear(nn.Module):
+ """Plain buffers so offload hooks can move it; forward stays capture-safe (no host sync)."""
+
+ def __init__(
+ self,
+ in_features: int,
+ out_features: int,
+ *,
+ codes,
+ tiled_scale,
+ bias = None,
+ ):
+ super().__init__()
+ self.in_features = int(in_features)
+ self.out_features = int(out_features)
+ self.register_buffer("weight_q", codes)
+ self.register_buffer("weight_sf", tiled_scale.view(torch.uint8))
+ self.register_buffer("bias", bias)
+
+ def forward(self, x):
+ shape = x.shape
+ out_dtype = x.dtype if x.dtype in (torch.bfloat16, torch.float16) else torch.bfloat16
+ flat = x.reshape(-1, self.in_features)
+ if flat.shape[0] == 0:
+ return flat.new_zeros((0, self.out_features), dtype = out_dtype).reshape(
+ *shape[:-1], self.out_features
+ )
+ xq, x_sf = mx_quantize_activation(flat)
+ out = torch._scaled_mm(
+ xq,
+ self.weight_q.t(),
+ scale_a = x_sf,
+ scale_b = self.weight_sf.view(torch.float8_e8m0fnu),
+ out_dtype = torch.bfloat16,
+ )
+ if self.bias is not None:
+ out = out + self.bias.to(out.dtype)
+ return out.to(out_dtype).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}, mxfp8=scaled_mm"
+ )
+
+ _MX_CLASS = ComfyMXFP8Linear
+ return _MX_CLASS
+
+
+_MX_CLASS = None
+_NVFP4_DYNAMIC_CLASS = None
+
+
+def nvfp4_dynamic_linear_class():
+ """FlashInfer NVFP4 Linear scaling activations from each call's amax, for layers without ``input_scale``."""
+ global _NVFP4_DYNAMIC_CLASS
+ if _NVFP4_DYNAMIC_CLASS is not None:
+ return _NVFP4_DYNAMIC_CLASS
+ import torch
+ from torch.nn import functional as F
+
+ from .diffusion_nvfp4_bias import fused_bias_add_
+ from .diffusion_nvfp4_linear import nvfp4_linear_class
+ from .diffusion_nvfp4_ops import _device_guard, dequantize_nvfp4_weight, global_scale
+
+ base = nvfp4_linear_class()
+
+ class ComfyNVFP4DynamicLinear(base):
+ def forward(self, x):
+ shape = x.shape
+ flat = x.reshape(-1, self.in_features)
+ 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:
+ out = F.linear(
+ flat,
+ dequantize_nvfp4_weight(self.wq, self.w_sf, self.w_scale, dtype = torch.bfloat16),
+ )
+ else:
+ with _device_guard(flat):
+ a_gsf = global_scale(flat)
+ xq, x_sf = torch.ops.unsloth_nvfp4.quantize(flat, a_gsf)
+ out = torch.ops.unsloth_nvfp4.mm(
+ xq,
+ self.wq,
+ x_sf,
+ self.w_sf,
+ self.w_scale / a_gsf,
+ self.out_features,
+ self.backend,
+ )
+ out = out.to(out_dtype)
+ if self.bias is not None:
+ fused_bias_add_(out, self.bias)
+ return out.reshape(*shape[:-1], self.out_features)
+
+ _NVFP4_DYNAMIC_CLASS = ComfyNVFP4DynamicLinear
+ return _NVFP4_DYNAMIC_CLASS
+
+
+_PROBE_LOCK = threading.Lock()
+_MX_PROBE: dict = {}
+
+
+def _device_of(target: Any) -> Any:
+ import torch
+
+ device = getattr(target, "torch_device", None) or getattr(target, "device", None)
+ if device is None:
+ return None
+ try:
+ return torch.device(device)
+ except Exception: # noqa: BLE001 -- not a device we can name
+ return None
+
+
+def mxfp8_runtime_reason(target: Any) -> Optional[str]:
+ """None when ``torch._scaled_mm`` runs e8m0 block-scaled fp8 on ``target``'s device (cached probe), else why not."""
+ try:
+ import torch
+ except Exception: # noqa: BLE001
+ return "torch unavailable"
+ device = _device_of(target)
+ if device is None or device.type != "cuda" or not torch.cuda.is_available():
+ return f"device {device} is not CUDA"
+ if not hasattr(torch, "float8_e8m0fnu"):
+ return f"torch {torch.__version__} has no float8_e8m0fnu"
+ index = device.index if device.index is not None else torch.cuda.current_device()
+ capability = tuple(torch.cuda.get_device_capability(index))
+ if capability < (10, 0):
+ return "sm_%d%d has no MXFP8 tensor cores (Blackwell sm_100+ needed)" % capability
+ with _PROBE_LOCK:
+ if index not in _MX_PROBE:
+ try:
+ with torch.cuda.device(index):
+ x = torch.randn(128, 64, device = "cuda", dtype = torch.bfloat16)
+ w = torch.randn(32, 64, device = "cuda", dtype = torch.bfloat16)
+ wq, wsf = mx_quantize_activation(w)
+ linear = mxfp8_linear_class()(64, 32, codes = wq, tiled_scale = wsf)
+ y = linear(x).float()
+ ref = x.float() @ w.float().T
+ err = float((y - ref).norm() / ref.norm())
+ _MX_PROBE[index] = None if err < 0.1 else f"probe error {err:.3f}"
+ except Exception as exc: # noqa: BLE001 -- any failure means dequantize
+ # not cached: a transient failure (an OOM on a busy GPU) must not pin this process to dequant
+ return f"{type(exc).__name__}: {str(exc)[:160]}"
+ return _MX_PROBE[index]
+
+
+def reset_probe_cache() -> None:
+ with _PROBE_LOCK:
+ _MX_PROBE.clear()
+
+
+def _env_off(name: str) -> bool:
+ return (os.environ.get(name) or "").strip().lower() in _OFF
+
+
+def comfy_block_runtime_layers(model: Any) -> int:
+ """How many nvfp4 / mxfp8 layers of a ComfyUI load kept their codes (they cannot carry LoRA adapters)."""
+ info = getattr(model, "_unsloth_comfy_quant", None) or {}
+ try:
+ return int(info.get(NVFP4) or 0) + int(info.get(MXFP8) or 0)
+ except (TypeError, ValueError):
+ return 0
+
+
+def comfy_nvfp4_runtime_possible(family: Optional[str]) -> bool:
+ """Whether the switch and the family let a ComfyUI nvfp4 file keep its codes (the device is the load's call)."""
+ try:
+ from .diffusion_transformer_quant import TQ_NVFP4, _family_denied
+ return not _env_off(COMFY_NVFP4_ENV) and not _family_denied(family, TQ_NVFP4)
+ except Exception: # noqa: BLE001 -- no answer, no install
+ return False
+
+
+def comfy_block_backend(
+ fmt: str,
+ target: Any,
+ family: Optional[str],
+ *,
+ dtype: Any = None,
+) -> tuple[Optional[str], str]:
+ """``(runtime or None, reason)`` for ``fmt`` layers on ``target``; None = dequantize (always correct).
+ nvfp4 follows Studio's own NVFP4 gating (flag, FlashInfer backend choice, family); mxfp8 needs the probe + bf16."""
+ try:
+ from .diffusion_transformer_quant import TQ_MXFP8, TQ_NVFP4, _family_denied
+ if fmt == NVFP4:
+ if _env_off(COMFY_NVFP4_ENV):
+ return None, f"{COMFY_NVFP4_ENV}=0"
+ from .diffusion_nvfp4_flag import NVFP4_DIFFUSION_ENV, nvfp4_diffusion_enabled
+
+ if not nvfp4_diffusion_enabled():
+ return None, f"Studio's NVFP4 runtime is off ({NVFP4_DIFFUSION_ENV}=1 enables it)"
+ if _family_denied(family, TQ_NVFP4):
+ return None, f"nvfp4 is denied for {family}"
+ device = _device_of(target)
+ if device is None or device.type != "cuda":
+ return None, f"device {device} is not CUDA"
+ from .diffusion_nvfp4_ops import BACKEND_FLASHINFER, _resolve_backend
+
+ backend, reason = _resolve_backend(device)
+ if backend != BACKEND_FLASHINFER:
+ return None, reason
+ return NVFP4_RUNTIME, reason
+ if fmt == MXFP8:
+ if _env_off(COMFY_MXFP8_ENV):
+ return None, f"{COMFY_MXFP8_ENV}=0"
+ import torch
+
+ if dtype is not None and dtype is not torch.bfloat16:
+ return (
+ None,
+ f"the pipeline runs {str(dtype).replace('torch.', '')}, the mxfp8 GEMM needs bfloat16",
+ )
+ if _family_denied(family, TQ_MXFP8):
+ return None, f"mxfp8 is denied for {family}"
+ reason = mxfp8_runtime_reason(target)
+ if reason:
+ return None, reason
+ return MXFP8_RUNTIME, "torch._scaled_mm e8m0 block scales"
+ except Exception as exc: # noqa: BLE001 -- an unanswerable probe takes the exact dense path
+ return None, f"{type(exc).__name__}: {str(exc)[:160]}"
+ return None, f"unknown format {fmt!r}"
+
+
+def build_runtime_linear(
+ fmt: str,
+ linear: Any,
+ codes: Any,
+ scale: Any,
+ *,
+ tensor_scale: Any = None,
+ input_scale: Any = None,
+ bias: Any = None,
+) -> Any:
+ import torch
+
+ rows = int(codes.shape[0])
+ if fmt == NVFP4:
+ from .diffusion_nvfp4_linear import nvfp4_linear_class
+ from .diffusion_nvfp4_ops import register_ops, sf_matrix_shape
+
+ register_ops()
+ cols = logical_cols(fmt, codes)
+ w_sf = (
+ tile_scales(scale)
+ .view(torch.uint8)
+ .reshape(sf_matrix_shape(rows, cols // 16))
+ .contiguous()
+ )
+ w_scale = torch.as_tensor(tensor_scale, dtype = torch.float32).reshape(1).clone()
+ if input_scale is None:
+ # no calibrated scale: per-call amax, as ComfyUI does
+ a_gsf = torch.ones(1, dtype = torch.float32)
+ cls = nvfp4_dynamic_linear_class()
+ else:
+ in_scale = torch.as_tensor(input_scale, dtype = torch.float32).reshape(1)
+ # FlashInfer's activation global scale is the reciprocal of ComfyUI's decode-side input_scale.
+ a_gsf = (1.0 / in_scale).clone()
+ cls = nvfp4_linear_class()
+ return cls(
+ cols,
+ rows,
+ wq = codes.contiguous(),
+ w_sf = w_sf,
+ alpha = (w_scale / a_gsf).clone(),
+ a_gsf = a_gsf,
+ bias = bias,
+ w_scale = w_scale,
+ activation_scales_baked = True,
+ )
+ if fmt == MXFP8:
+ return mxfp8_linear_class()(
+ int(codes.shape[1]),
+ rows,
+ codes = codes.contiguous(),
+ tiled_scale = tile_scales(scale),
+ bias = bias,
+ )
+ raise ValueError(f"not a block-scaled ComfyUI format: {fmt!r}")
+
+
+def comfy_block_backends(
+ scan: Any,
+ target: Any,
+ family: Optional[str],
+ *,
+ dtype: Any = None,
+ logger: Any = None,
+ lora: bool = False,
+) -> dict:
+ """``load_comfy_quant_transformer`` backend kwargs, logging per format which runtime keeps it or why not."""
+ out = {"nvfp4_backend": None, "mxfp8_backend": None}
+ counts = scan.counts() if scan is not None else {}
+ for fmt in (NVFP4, MXFP8):
+ if not counts.get(fmt):
+ continue
+ backend, reason = comfy_block_backend(fmt, target, family, dtype = dtype)
+ if lora and backend:
+ backend, reason = None, "a LoRA is selected: adapters need dense Linears"
+ out[f"{fmt}_backend"] = backend
+ if logger is not None:
+ if backend:
+ logger.info(
+ "diffusion.comfy_quant: %d %s layer(s) stay %s on the %s runtime (%s)",
+ counts[fmt],
+ fmt,
+ fmt,
+ backend,
+ reason,
+ )
+ else:
+ logger.info(
+ "diffusion.comfy_quant: %d %s layer(s) are dequantized to the compute dtype on load: correct, but no memory "
+ "saving over the bf16 checkpoint (%s)",
+ counts[fmt],
+ fmt,
+ reason,
+ )
+ return out
diff --git a/studio/backend/core/inference/diffusion_comfy_quant.py b/studio/backend/core/inference/diffusion_comfy_quant.py
index bd0c7383499..c0d407446b7 100644
--- a/studio/backend/core/inference/diffusion_comfy_quant.py
+++ b/studio/backend/core/inference/diffusion_comfy_quant.py
@@ -10,8 +10,9 @@ Stock ``from_single_file`` casts the codes as weights and drops the scales: the
From the header alone: int8_tensorwise (optionally ConvRot) maps into Studio's int8 runtime with codes and
per-row scales unchanged; float8_e4m3fn into Studio's per-row fp8 runtime (scalar scale repeated per row);
-where neither runs, or for layers Studio keeps in bf16 and float8_e5m2, layers dequantize. Any other
-format is refused by name, never mis-loaded.
+nvfp4 into Studio's FlashInfer NVFP4 Linear and mxfp8 into a ``torch._scaled_mm`` block-scaled Linear
+(``diffusion_comfy_block``); where none runs, or for layers Studio keeps in bf16 and float8_e5m2, layers
+dequantize. Any other format is refused by name, never mis-loaded.
Row mapping: the family's converter runs once on float64 row tags ``(source key, row)``; the tags that
come out say which source rows each diffusers weight holds. A converter that splices columns, changes
@@ -27,6 +28,8 @@ import struct
from dataclasses import dataclass, field
from typing import Any, Optional
+from .diffusion_comfy_block import BLOCK_SIZES, MXFP8, NVFP4, tiled_scale_numel
+
COMFY_QUANT_SUFFIX = ".comfy_quant"
QUANT_METADATA_KEY = "_quantization_metadata"
LEGACY_SCALED_FP8_KEY = "scaled_fp8"
@@ -56,6 +59,8 @@ _CONSUMED = {
INT8_TENSORWISE: (".weight_scale",),
"float8_e4m3fn": (".weight_scale", ".input_scale"),
"float8_e5m2": (".weight_scale", ".input_scale"),
+ NVFP4: (".weight_scale", ".weight_scale_2", ".input_scale", ".pre_quant_scale"),
+ MXFP8: (".weight_scale", ".input_scale"),
}
_LEGACY_RENAME = {".scale_weight": ".weight_scale", ".scale_input": ".input_scale"}
@@ -203,6 +208,10 @@ def scan_comfy_quant(path: Optional[str]) -> Optional[ComfyQuantScan]:
why = f"{fmt} declared but there is no {name}.weight"
elif len(weight.get("shape") or ()) != 2:
why = f"{fmt} weight of shape {weight.get('shape')} (only 2-D linears are supported)"
+ elif fmt in BLOCK_SIZES:
+ why = (
+ f"ConvRot on {fmt}" if convrot else _block_layer_problem(name, fmt, weight, header)
+ )
elif fmt == INT8_TENSORWISE and weight.get("dtype") != "I8":
why = f"int8_tensorwise weight stored as {weight.get('dtype')}"
elif fmt in FP8_FORMATS and weight.get("dtype") not in ("U8", FP8_FORMATS[fmt]):
@@ -249,6 +258,7 @@ _DTYPE_BYTES = {
"BF16": 2,
"F8_E4M3": 1,
"F8_E5M2": 1,
+ "F8_E8M0": 1,
"I8": 1,
"U8": 1,
"I16": 2,
@@ -264,11 +274,14 @@ def comfy_resident_mib(
*,
keep_int8: bool,
keep_fp8: bool,
+ keep_nvfp4: bool = False,
+ keep_mxfp8: bool = False,
compute_bytes: int = 2,
keep_key: Any = None,
exclude_tokens: Any = (),
min_features: int = 0,
fp8_divisible: int = 0,
+ block_divisible: Optional[dict] = None,
key_map: Any = None,
) -> Optional[int]:
"""What the loader leaves resident for a ComfyUI-quantized file, priced from its header: a quantized
@@ -306,6 +319,11 @@ def comfy_resident_mib(
pass
return any(t in n for n in names for t in exclude_tokens)
+ def _logical(fmt: str, shape: Any) -> Any:
+ if fmt == NVFP4 and len(shape or ()) == 2:
+ return (int(shape[0]), int(shape[1]) * 2)
+ return shape
+
kept = {}
for name, layer in scan.layers.items():
shape = (header.get(name + ".weight") or {}).get("shape")
@@ -314,7 +332,18 @@ def comfy_resident_mib(
and keep_int8
and not _excluded(name + ".weight", shape)
and _fits(shape, 0)
- ) or (layer.format == FP8_E4M3 and keep_fp8 and _fits(shape, fp8_divisible))
+ ) or (
+ (layer.format == FP8_E4M3 and keep_fp8 and _fits(shape, fp8_divisible))
+ or (
+ {NVFP4: keep_nvfp4, MXFP8: keep_mxfp8}.get(layer.format, False)
+ # input smoothing has no runtime Linear: the loader dequantizes such a layer
+ and name + ".pre_quant_scale" not in header
+ and _fits(
+ _logical(layer.format, shape), (block_divisible or {}).get(layer.format, 0)
+ )
+ )
+ )
+ packed = {name + ".weight" for name, layer in scan.layers.items() if layer.format == NVFP4}
total = 0
for key, entry in header.items():
if keep_key is not None and not keep_key(key):
@@ -326,7 +355,7 @@ def comfy_resident_mib(
dtype = str(entry.get("dtype", ""))
stored = numel * _DTYPE_BYTES.get(dtype, 2)
if key in kept:
- total += stored if kept[key] else numel * compute_bytes
+ total += stored if kept[key] else numel * compute_bytes * (2 if key in packed else 1)
elif key.endswith(COMFY_QUANT_SUFFIX) or any(key.endswith(s) for s in _SCALE_SUFFIXES):
total += stored
elif dtype.startswith(("F", "BF")):
@@ -336,6 +365,55 @@ def comfy_resident_mib(
return -(-total // (1024 * 1024)) if total > 0 else None
+def _numel(entry: Optional[dict]) -> int:
+ n = 1
+ for d in (entry or {}).get("shape") or ():
+ n *= int(d)
+ return n
+
+
+def _block_layer_problem(name: str, fmt: str, weight: dict, header: dict) -> Optional[str]:
+ """Why an ``nvfp4`` / ``mxfp8`` layer cannot be decoded, from its header entries, or None."""
+ rows, stored = (int(d) for d in weight["shape"])
+ if fmt == NVFP4:
+ if weight.get("dtype") != "U8":
+ return f"nvfp4 weight stored as {weight.get('dtype')}"
+ cols = stored * 2
+ else:
+ if weight.get("dtype") not in ("F8_E4M3", "U8"):
+ return f"mxfp8 weight stored as {weight.get('dtype')}"
+ cols = stored
+ block = BLOCK_SIZES[fmt]
+ if cols % block:
+ return f"{fmt} weight with {cols} columns (not a multiple of {block})"
+ scale = header.get(name + ".weight_scale")
+ want = ("F8_E4M3", "U8") if fmt == NVFP4 else ("F8_E8M0", "U8")
+ if scale is None:
+ return f"{fmt} declared but {name}.weight_scale is missing"
+ if scale.get("dtype") not in want:
+ return f"{fmt} block scales stored as {scale.get('dtype')}"
+ if _numel(scale) != tiled_scale_numel(rows, cols // block):
+ return f"{fmt} block scales of shape {scale.get('shape')} for a {rows}x{cols} weight (not the 128x4 tiled layout)"
+ if fmt == NVFP4:
+ second = header.get(name + ".weight_scale_2")
+ if second is None or _numel(second) != 1:
+ return f"nvfp4 needs a scalar {name}.weight_scale_2"
+ smooth = header.get(name + ".pre_quant_scale")
+ if smooth is not None and _numel(smooth) != cols:
+ return f"pre_quant_scale of shape {smooth.get('shape')} for {cols} input features"
+ entry = header.get(name + ".input_scale")
+ if entry is not None and _numel(entry) != 1:
+ return f"input_scale of shape {entry.get('shape')} (only a per-tensor scale is supported)"
+ leftover = [
+ s
+ for s in _SCALE_SUFFIXES
+ if name + s in header and _LEGACY_RENAME.get(s, s) not in _CONSUMED[fmt]
+ ]
+ if leftover:
+ return f"{fmt} layer carries {', '.join(leftover)}, which this format does not use"
+ return None
+
+
def _is_power_of_four(size: Any) -> bool:
from .diffusion_convrot import is_power_of_four
return is_power_of_four(size)
@@ -350,8 +428,8 @@ def comfy_quant_error(scan: Optional[ComfyQuantScan], filename: str = "") -> Opt
return (
f"{filename or 'This checkpoint'} is a ComfyUI-quantized checkpoint Studio cannot run "
f"faithfully: {shown}{more}. Supported ComfyUI formats are int8_tensorwise (with or "
- "without ConvRot), float8_e4m3fn and float8_e5m2; use the bf16 file, a GGUF, or Studio's "
- "own int8 / fp8 transformer quantization instead."
+ "without ConvRot), float8_e4m3fn, float8_e5m2, nvfp4 and mxfp8; use the bf16 file, a GGUF, "
+ "or Studio's own int8 / fp8 transformer quantization instead."
)
@@ -380,6 +458,56 @@ def _dequant(codes: Any, scale: Any, group: int, dtype: Any) -> Any:
return weight.to(dtype)
+@dataclass
+class _BlockWeight:
+ """Row segments ``(codes, plain scales, extras)`` from one or more layers."""
+
+ fmt: str
+ parts: list
+
+
+def _dequant_parts(fmt: str, parts: list, dtype: Any) -> Any:
+ import torch
+
+ from .diffusion_comfy_block import dequant_block
+
+ dense = [
+ dequant_block(
+ fmt,
+ codes,
+ scale,
+ tensor_scale = extra.get("tensor_scale"),
+ pre_quant_scale = extra.get("pre_quant_scale"),
+ dtype = dtype,
+ )
+ for codes, scale, extra in parts
+ ]
+ return dense[0] if len(dense) == 1 else torch.cat(dense)
+
+
+def _block_runtime_args(value: "_BlockWeight") -> Optional[tuple]:
+ """``(codes, scales, tensor_scale, input_scale)`` when one runtime Linear holds ``value`` exactly, else None.
+ Segments share an input: the largest static input_scale (none clips); any missing one = dynamic (None)."""
+ import torch
+
+ extras = [extra for _c, _s, extra in value.parts]
+ codes = (
+ torch.cat([c for c, _s, _e in value.parts]) if len(value.parts) > 1 else value.parts[0][0]
+ )
+ scale = (
+ torch.cat([s for _c, s, _e in value.parts]) if len(value.parts) > 1 else value.parts[0][1]
+ )
+ if value.fmt == MXFP8:
+ return codes, scale, None, None
+ tensor_scales = {e.get("tensor_scale") for e in extras}
+ input_scales = [e.get("input_scale") for e in extras]
+ if len(tensor_scales) != 1 or None in tensor_scales:
+ return None
+ if any(e.get("pre_quant_scale") is not None for e in extras):
+ return None
+ return codes, scale, tensor_scales.pop(), None if None in input_scales else max(input_scales)
+
+
def _int8_tensor(name: str, codes: Any, scale: Any, dtype: Any) -> Optional[Any]:
"""The torchao int8 weight a hosted INT8 checkpoint rebuilds into, built by the same decoder."""
import torch
@@ -551,7 +679,7 @@ def _apply_key_map(state: dict, kept: list, key_map: Any) -> dict:
sources = {
layer.name + ".weight": (codes, scale, layer.group, layer.format)
- for layer, codes, scale in kept
+ for layer, codes, scale, *_extra in kept
}
def take(value: Any, rows: Any) -> Any:
@@ -767,6 +895,8 @@ def load_comfy_quant_transformer(
*,
int8_backend: Optional[str],
fp8_backend: Optional[str] = None,
+ nvfp4_backend: Optional[str] = None,
+ mxfp8_backend: Optional[str] = None,
family: Optional[str] = None,
target: Any = None,
fast_accum: Optional[bool] = None,
@@ -787,8 +917,10 @@ def load_comfy_quant_transformer(
their codes and scales, as torchao ``Int8Tensor`` weights under ConvRot-rotating Linears
(``"torchao"``) or as native int8 twins (``"native"``); with an ``fp8_backend``
(``comfy_fp8_backend``) the ``float8_e4m3fn`` layers Studio's own fp8 filter selects do the same,
- as per-row ``Float8Tensor`` weights or native fp8 twins. Everything else is dequantized to the
- compute dtype. ``finalize`` applies the small-M padding here (the single-file path); the hosted
+ as per-row ``Float8Tensor`` weights or native fp8 twins; with an ``nvfp4_backend`` / ``mxfp8_backend``
+ (``diffusion_comfy_block.comfy_block_backend``) the nvfp4 / mxfp8 layers the matching Studio filter selects
+ keep their codes on Studio's FlashInfer NVFP4 Linear / the ``torch._scaled_mm`` MXFP8 Linear. Everything
+ else is dequantized to the compute dtype. ``finalize`` applies the small-M padding here (the single-file path); the hosted
prequant loader passes False and pads after placement, as for its own checkpoints.
``keep_key(key)`` limits the read to the DiT's keys of a file that bundles other components;
@@ -801,10 +933,18 @@ def load_comfy_quant_transformer(
import torch
from safetensors.torch import load_file
+ from .diffusion_comfy_block import (
+ build_runtime_linear,
+ decode_layer,
+ dequant_block,
+ logical_cols,
+ )
from .diffusion_transformer_quant import (
DEFAULT_MIN_LINEAR_FEATURES,
TQ_FP8,
TQ_INT8,
+ TQ_MXFP8,
+ TQ_NVFP4,
divisible_for_scheme,
exclude_tokens_for_scheme,
make_filter_fn,
@@ -825,6 +965,7 @@ def load_comfy_quant_transformer(
if dtype is not torch.bfloat16:
# Studio's fp8 runtime asserts bf16 weights; an fp16 / fp32 pipeline dequantizes them instead.
fp8_backend = None
+ mxfp8_backend = None
if keep_key is None:
state = load_file(str(path))
else:
@@ -856,19 +997,45 @@ def load_comfy_quant_transformer(
def _dtype_for(key: str) -> Any:
return torch.float32 if fp16_keep and any(m in key.split(".") for m in keep_fp32) else dtype
- backends = {INT8_TENSORWISE: int8_backend, FP8_E4M3: fp8_backend}
- sources: list = [] # (layer, codes, scale) kept for a runtime
+ backends = {
+ INT8_TENSORWISE: int8_backend,
+ FP8_E4M3: fp8_backend,
+ NVFP4: nvfp4_backend,
+ MXFP8: mxfp8_backend,
+ }
+ sources: list = [] # (layer, codes, scale, block extras or None) kept for a runtime
dequantized = 0
for layer in scan.layers.values():
codes = state.pop(layer.name + ".weight")
scale = state.pop(layer.name + ".weight_scale")
- # Activations are quantized per row at runtime, as for Studio's own fp8; input_scale is unused.
- state.pop(layer.name + ".input_scale", None)
- if layer.format in FP8_FORMATS and codes.dtype == torch.uint8:
+ # int8 / fp8 / mxfp8 activations are quantized per call; only nvfp4 uses its static input_scale.
+ input_scale = state.pop(layer.name + ".input_scale", None)
+ extra = None
+ if layer.format in BLOCK_SIZES:
+ tensor_scale = state.pop(layer.name + ".weight_scale_2", None)
+ extra = {
+ "tensor_scale": None
+ if tensor_scale is None
+ else float(tensor_scale.float().reshape(-1)[0]),
+ "input_scale": None
+ if input_scale is None
+ else float(input_scale.float().reshape(-1)[0]),
+ "pre_quant_scale": state.pop(layer.name + ".pre_quant_scale", None),
+ }
+ codes, scale = decode_layer(layer.format, codes, scale)
+ elif layer.format in FP8_FORMATS and codes.dtype == torch.uint8:
codes = codes.view(getattr(torch, layer.format))
- if backends.get(layer.format) or fp16_keep:
- sources.append((layer, codes, scale))
+ # A key-mapped (original-layout) family moves rows whole, which the tiled block scales do not survive.
+ if (backends.get(layer.format) or fp16_keep) and not (
+ extra is not None and key_map is not None
+ ):
+ sources.append((layer, codes, scale, extra))
state[layer.name + ".weight"] = None # placeholder, tagged below
+ elif extra is not None:
+ state[layer.name + ".weight"] = _dequant_parts(
+ layer.format, [(codes, scale, extra)], dtype
+ )
+ dequantized += 1
else:
state[layer.name + ".weight"] = _dequant(codes, scale, layer.group, dtype)
dequantized += 1
@@ -910,7 +1077,7 @@ def load_comfy_quant_transformer(
def _convert_tagged(width: Optional[int]) -> dict:
# float64 row tags, ``width`` columns wide (None: real width); converted tags name each output's source rows.
- for index, (layer, codes, _scale) in enumerate(sources):
+ for index, (layer, codes, *_rest) in enumerate(sources):
rows = torch.arange(codes.shape[0], dtype = torch.float64) + index * _TAG
cols = codes.shape[1] if width is None else width
state[layer.name + ".weight"] = rows.view(-1, 1).expand(codes.shape[0], cols)
@@ -929,6 +1096,18 @@ def load_comfy_quant_transformer(
if len(kinds) != 1:
raise ValueError(f"{name}: rows from layers of different formats or ConvRot groups")
fmt, group = kinds.pop()
+ if fmt in BLOCK_SIZES:
+ blocks = [
+ (sources[i][1][r : r + n], sources[i][2][r : r + n], sources[i][3])
+ for i, r, n in segments
+ ]
+ logical = (sum(n for _i, _r, n in segments), logical_cols(fmt, blocks[0][0]))
+ if name in wanted and tuple(wanted[name].shape) != logical:
+ raise ValueError(
+ f"{name}: rebuilt as {logical}, the model expects {tuple(wanted[name].shape)}"
+ )
+ out[name] = _BlockWeight(fmt, blocks)
+ continue
parts = [sources[i][1][r : r + n] for i, r, n in segments]
# one segment (a split or renamed layer) is a row slice of a contiguous tensor: no copy
codes = parts[0] if len(parts) == 1 else torch.cat(parts)
@@ -967,7 +1146,7 @@ def load_comfy_quant_transformer(
converted[key] = value.to(_dtype_for(key))
min_features = DEFAULT_MIN_LINEAR_FEATURES if min_features is None else int(min_features)
- schemes = {INT8_TENSORWISE: TQ_INT8, FP8_E4M3: TQ_FP8}
+ schemes = {INT8_TENSORWISE: TQ_INT8, FP8_E4M3: TQ_FP8, NVFP4: TQ_NVFP4, MXFP8: TQ_MXFP8}
filters = {
fmt: make_filter_fn(
min_features,
@@ -979,8 +1158,33 @@ def load_comfy_quant_transformer(
modules = dict(model.named_modules())
rotations: dict = {}
native: dict = {}
- built = {TQ_INT8: 0, TQ_FP8: 0}
+ block_native: dict = {} # fqn -> (fmt, codes, scale, tensor_scale, input_scale, bias)
+ built = {TQ_INT8: 0, TQ_FP8: 0, TQ_NVFP4: 0, TQ_MXFP8: 0}
for name, value in list(converted.items()):
+ if isinstance(value, _BlockWeight):
+ fmt = value.fmt
+ fqn = name[: -len(".weight")] if name.endswith(".weight") else name
+ module = modules.get(fqn)
+ runtime = _block_runtime_args(value)
+ if (
+ backends.get(fmt) is not None
+ and runtime is not None
+ and isinstance(module, torch.nn.Linear)
+ and name.endswith(".weight")
+ and filters[fmt](module, fqn)
+ and not any(m in fqn.split(".") for m in keep_fp32)
+ ):
+ codes, scale, tensor_scale, input_scale = runtime
+ bias = converted.get(fqn + ".bias")
+ if torch.is_tensor(bias):
+ bias = bias.to(dtype)
+ block_native[fqn] = (fmt, codes, scale, tensor_scale, input_scale, bias)
+ del converted[name]
+ built[schemes[fmt]] += 1
+ else:
+ converted[name] = _dequant_parts(fmt, value.parts, _dtype_for(name))
+ dequantized += 1
+ continue
if not isinstance(value, tuple):
continue
codes, scale, group, fmt = value
@@ -1039,6 +1243,21 @@ def load_comfy_quant_transformer(
setattr(parent, leaf, layer)
converted[fqn + ".weight_q"] = layer.weight_q
converted[fqn + ".weight_scale"] = layer.weight_scale
+ for fqn, (fmt, codes, scale, tensor_scale, input_scale, bias) in block_native.items():
+ parent_name, _, leaf = fqn.rpartition(".")
+ parent = model.get_submodule(parent_name) if parent_name else model
+ layer = build_runtime_linear(
+ fmt,
+ getattr(parent, leaf),
+ codes,
+ scale,
+ tensor_scale = tensor_scale,
+ input_scale = input_scale,
+ bias = bias,
+ )
+ setattr(parent, leaf, layer)
+ for buffer_name, buffer in layer.named_buffers(recurse = False):
+ converted[f"{fqn}.{buffer_name}"] = buffer
_install_native(model)
missing, unexpected = model.load_state_dict(converted, strict = False, assign = True)
@@ -1064,6 +1283,8 @@ def load_comfy_quant_transformer(
del converted
# __init__ buffers (Wan's float64 rope) follow the compute dtype; checkpoint buffers keep theirs (H3 curve table)
for module_name, module in model.named_modules():
+ if module_name in block_native:
+ continue # fp32 scales / alpha the block kernels need; codes are not floating
for buffer_name, buffer in list(module._buffers.items()):
if (f"{module_name}.{buffer_name}" if module_name else buffer_name) in loaded:
continue
@@ -1092,7 +1313,9 @@ def load_comfy_quant_transformer(
warm_rotation_cache(model, device, dtype)
except Exception: # noqa: BLE001 -- only saves one recompile
pass
- native_schemes = {v[3] for v in native.values()}
+ native_schemes = {v[3] for v in native.values()} | {
+ schemes[v[0]] for v in block_native.values()
+ }
on_torchao = {s for s, count in built.items() if count and s not in native_schemes}
if finalize:
from .diffusion_transformer_quant import apply_small_m_padding, apply_zero_row_guard
@@ -1105,12 +1328,21 @@ def load_comfy_quant_transformer(
model._unsloth_runtime_quant = max(built, key = lambda s: built[s])
except Exception: # noqa: BLE001 -- marker is best-effort
pass
+ if built[TQ_NVFP4]:
+ try:
+ model._unsloth_nvfp4_backend = nvfp4_backend
+ except Exception: # noqa: BLE001 -- marker is best-effort
+ pass
+ # per-model step-protect controller, as for Studio's own NVFP4 checkpoints
+ from .diffusion_nvfp4_protect import attach_own_controller
+ attach_own_controller(model)
model.eval()
convrot = len(rotated) + sum(1 for v in native.values() if v[2])
if logger is not None:
logger.info(
"diffusion.comfy_quant: %s loaded from a ComfyUI checkpoint (%s): %d int8 layers kept as "
- "int8 (%s, %d ConvRot), %d fp8 layers kept as fp8 (%s), %d layers dequantized to %s",
+ "int8 (%s, %d ConvRot), %d fp8 layers kept as fp8 (%s), %d nvfp4 layers kept as nvfp4 (%s), "
+ "%d mxfp8 layers kept as mxfp8 (%s), %d layers dequantized to %s",
transformer_cls.__name__,
", ".join(f"{k} x{v}" for k, v in sorted(scan.counts().items())),
built[TQ_INT8],
@@ -1118,11 +1350,15 @@ def load_comfy_quant_transformer(
convrot,
built[TQ_FP8],
f"{fp8_backend} runtime" if built[TQ_FP8] else "no fp8 runtime",
+ built[TQ_NVFP4],
+ f"{nvfp4_backend} runtime" if built[TQ_NVFP4] else "no nvfp4 runtime",
+ built[TQ_MXFP8],
+ f"{mxfp8_backend} runtime" if built[TQ_MXFP8] else "no mxfp8 runtime",
dequantized,
str(dtype).replace("torch.", ""),
)
try:
- model._unsloth_comfy_quant = {
+ info = {
"backend": int8_backend if built[TQ_INT8] else None,
"int8": built[TQ_INT8],
"convrot": convrot,
@@ -1130,6 +1366,11 @@ def load_comfy_quant_transformer(
"fp8": built[TQ_FP8],
"dequantized": dequantized,
}
+ for fmt, backend in ((NVFP4, nvfp4_backend), (MXFP8, mxfp8_backend)):
+ if scan.counts().get(fmt):
+ info[f"{fmt}_backend"] = backend if built[schemes[fmt]] else None
+ info[fmt] = built[schemes[fmt]]
+ model._unsloth_comfy_quant = info
except Exception: # noqa: BLE001 -- diagnostic marker only
pass
return model
diff --git a/studio/backend/core/inference/diffusion_nvfp4_linear.py b/studio/backend/core/inference/diffusion_nvfp4_linear.py
index 1ab353b2735..a93ad64b104 100644
--- a/studio/backend/core/inference/diffusion_nvfp4_linear.py
+++ b/studio/backend/core/inference/diffusion_nvfp4_linear.py
@@ -128,7 +128,12 @@ def nvfp4_linear_class():
def is_nvfp4_flashinfer_linear(module: Any) -> bool:
- return type(module).__name__ == "NVFP4FlashInferLinear" and hasattr(module, "a_gsf")
+ """The FlashInfer NVFP4 Linear or a subclass of it (the ComfyUI per-call activation-scale variant)."""
+ if not hasattr(module, "a_gsf"):
+ return False
+ return type(module).__name__ == "NVFP4FlashInferLinear" or isinstance(
+ module, nvfp4_linear_class()
+ )
def is_nvfp4_tensor(t: Any) -> bool:
diff --git a/studio/backend/tests/test_diffusion_comfy_block.py b/studio/backend/tests/test_diffusion_comfy_block.py
new file mode 100644
index 00000000000..b20402430e4
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_comfy_block.py
@@ -0,0 +1,629 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for ComfyUI ``nvfp4`` / ``mxfp8`` single files (``diffusion_comfy_block.py`` + the loader).
+
+Synthetic files are written in ComfyUI's on-disk layout by an encoder here that shares no code with the
+module under test: nvfp4 codes packed EVEN column in the HIGH nibble, block scales placed by the cuBLAS
+128x4 tile formula (offset computed per element, not by a reshape). The reference dequant reads every
+value back through that same formula, so a layout mistake in either direction fails bit-exactly.
+"""
+
+from __future__ import annotations
+
+import json
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+safetensors_torch = pytest.importorskip("safetensors.torch")
+nn = torch.nn
+
+import core.inference.diffusion_comfy_block as cb # noqa: E402
+import core.inference.diffusion_comfy_quant as cq # noqa: E402
+
+DIM = 512
+E2M1 = torch.tensor(
+ [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0]
+)
+
+
+def _conf(**conf) -> torch.Tensor:
+ return torch.tensor(list(json.dumps(conf).encode("utf-8")), dtype = torch.uint8)
+
+
+def _save(
+ path,
+ tensors,
+ metadata = None,
+) -> str:
+ safetensors_torch.save_file(
+ {k: v.contiguous().clone() for k, v in tensors.items()}, str(path), metadata = metadata
+ )
+ return str(path)
+
+
+def _ceil(x: int, m: int) -> int:
+ return -(-x // m) * m
+
+
+def _tile_offsets(rows: int, blocks: int) -> torch.Tensor:
+ """Flat offset of scale (r, b) in the cuBLAS 1D block-scaling-factor layout, element by element."""
+ r = torch.arange(rows).view(-1, 1)
+ b = torch.arange(blocks).view(1, -1)
+ tiles_per_row = _ceil(blocks, 4) // 4
+ return (
+ (r // 128) * tiles_per_row * 512
+ + (b // 4) * 512
+ + (r % 32) * 16
+ + ((r % 128) // 32) * 4
+ + (b % 4)
+ )
+
+
+def _tile(plain_u8: torch.Tensor) -> torch.Tensor:
+ rows, blocks = plain_u8.shape
+ flat = torch.zeros(_ceil(rows, 128) * _ceil(blocks, 4), dtype = torch.uint8)
+ flat[_tile_offsets(rows, blocks).reshape(-1)] = plain_u8.reshape(-1)
+ return flat.reshape(_ceil(rows, 128), _ceil(blocks, 4))
+
+
+def _untile(tiled: torch.Tensor, rows: int, blocks: int) -> torch.Tensor:
+ return tiled.reshape(-1)[_tile_offsets(rows, blocks)]
+
+
+def nvfp4_encode(w: torch.Tensor) -> dict:
+ """ComfyUI nvfp4 layout of ``w`` (round-to-nearest e2m1; exactness of the encoder is not under test)."""
+ rows, cols = w.shape
+ w = w.float()
+ tensor_scale = w.abs().amax() / (448.0 * 6.0)
+ blocks = w.reshape(rows, cols // 16, 16)
+ block_scale = (blocks.abs().amax(-1) / 6.0 / tensor_scale).to(torch.float8_e4m3fn)
+ step = block_scale.float() * tensor_scale
+ x = blocks / torch.where(step == 0, torch.ones_like(step), step).unsqueeze(-1)
+ nibble = (x.unsqueeze(-1) - E2M1[:8].abs().mul(x.sign().unsqueeze(-1))).abs().argmin(-1)
+ nibble = torch.where(x < 0, nibble + 8, nibble).reshape(rows, cols).to(torch.uint8)
+ packed = (nibble[:, 0::2] << 4) | nibble[:, 1::2] # even column -> high nibble
+ return {
+ "weight": packed,
+ "weight_scale": _tile(block_scale.view(torch.uint8)).view(torch.float8_e4m3fn),
+ "weight_scale_2": tensor_scale.reshape(()),
+ "input_scale": torch.tensor(0.01),
+ }
+
+
+def nvfp4_reference(t: dict) -> torch.Tensor:
+ q = t["weight"]
+ rows, cols = q.shape[0], q.shape[1] * 2
+ j = torch.arange(cols)
+ byte = q[:, j // 2].to(torch.int64)
+ nibble = torch.where(j % 2 == 0, byte >> 4, byte & 15)
+ scales = (
+ _untile(t["weight_scale"].view(torch.uint8), rows, cols // 16)
+ .view(torch.float8_e4m3fn)
+ .float()
+ )
+ step = scales * t["weight_scale_2"].float()
+ return E2M1[nibble] * step[:, j // 16]
+
+
+def mxfp8_encode(w: torch.Tensor) -> dict:
+ rows, cols = w.shape
+ blocks = w.float().reshape(rows, cols // 32, 32)
+ exp = torch.ceil(torch.log2((blocks.abs().amax(-1) / 448.0).clamp(min = 2.0**-127)))
+ codes = (
+ (blocks / torch.exp2(exp).unsqueeze(-1))
+ .clamp(-448, 448)
+ .to(torch.float8_e4m3fn)
+ .reshape(rows, cols)
+ )
+ return {
+ "weight": codes,
+ "weight_scale": _tile((exp + 127).to(torch.uint8)).view(torch.float8_e8m0fnu),
+ }
+
+
+def mxfp8_reference(t: dict) -> torch.Tensor:
+ q = t["weight"]
+ rows, cols = q.shape
+ exp = _untile(t["weight_scale"].view(torch.uint8), rows, cols // 32).float() - 127
+ return q.float() * torch.exp2(exp)[:, torch.arange(cols) // 32]
+
+
+ENCODERS = {"nvfp4": (nvfp4_encode, nvfp4_reference), "mxfp8": (mxfp8_encode, mxfp8_reference)}
+
+
[email protected]("rows,blocks", [(128, 4), (200, 6), (3, 1), (384, 120)])
+def test_tiling_matches_the_cublas_formula_and_round_trips(rows, blocks):
+ plain = torch.randint(0, 255, (rows, blocks), dtype = torch.uint8)
+ tiled = cb.tile_scales(plain)
+ assert torch.equal(tiled, _tile(plain).reshape(-1))
+ assert torch.equal(cb.untile_scales(tiled, rows, blocks), plain)
+ assert cb.tiled_scale_numel(rows, blocks) == tiled.numel()
+
+
[email protected]("fmt", ["nvfp4", "mxfp8"])
[email protected]("rows", [256, 200])
+def test_dequant_is_bit_exact_against_the_reference(fmt, rows):
+ torch.manual_seed(0)
+ encode, reference = ENCODERS[fmt]
+ t = encode(torch.randn(rows, 96) * 0.05)
+ codes, scale = cb.decode_layer(fmt, t["weight"], t["weight_scale"])
+ got = cb.dequant_block(
+ fmt, codes, scale, tensor_scale = t.get("weight_scale_2"), dtype = torch.float32
+ )
+ assert torch.equal(got, reference(t))
+
+
+def test_nvfp4_codes_are_repacked_low_nibble_first():
+ t = nvfp4_encode(torch.randn(128, 64))
+ codes, _scale = cb.decode_layer("nvfp4", t["weight"], t["weight_scale"])
+ assert torch.equal(codes & 0x0F, t["weight"] >> 4)
+ assert torch.equal(codes >> 4, t["weight"] & 0x0F)
+
+
+def test_pre_quant_scale_is_folded_into_the_columns():
+ t = nvfp4_encode(torch.randn(128, 64))
+ codes, scale = cb.decode_layer("nvfp4", t["weight"], t["weight_scale"])
+ smooth = torch.rand(64) + 0.5
+ got = cb.dequant_block(
+ "nvfp4",
+ codes,
+ scale,
+ tensor_scale = t["weight_scale_2"],
+ pre_quant_scale = smooth,
+ dtype = torch.float32,
+ )
+ assert torch.equal(got, nvfp4_reference(t) * smooth)
+
+
+def _layer_file(
+ tmp_path,
+ fmt,
+ rows = 128,
+ cols = 64,
+ drop = (),
+ extra = None,
+ conf = None,
+ name = "m",
+):
+ encode, _ref = ENCODERS[fmt]
+ t = encode(torch.randn(rows, cols))
+ tensors = {f"a.{k}": v for k, v in t.items() if k not in drop}
+ tensors.update(extra or {})
+ tensors["a.comfy_quant"] = _conf(**(conf or {"format": fmt}))
+ return _save(tmp_path / f"{name}.safetensors", tensors)
+
+
[email protected]("fmt", ["nvfp4", "mxfp8"])
+def test_block_formats_are_detected(tmp_path, fmt):
+ scan = cq.refuse_comfy_quant(_layer_file(tmp_path, fmt))
+ assert scan.counts() == {fmt: 1}
+ assert not scan.problems
+
+
+def test_block_formats_in_the_header_table_are_detected(tmp_path):
+ t = nvfp4_encode(torch.randn(128, 64))
+ meta = {
+ "_quantization_metadata": json.dumps(
+ {"format_version": "1.0", "layers": {"a": {"format": "nvfp4"}}}
+ )
+ }
+ path = _save(tmp_path / "h.safetensors", {f"a.{k}": v for k, v in t.items()}, metadata = meta)
+ assert cq.refuse_comfy_quant(path).counts() == {"nvfp4": 1}
+
+
+ "fmt,kwargs,why",
+ [
+ ("nvfp4", {"drop": ("weight_scale_2",)}, "weight_scale_2"),
+ ("nvfp4", {"drop": ("weight_scale",)}, "weight_scale is missing"),
+ ("nvfp4", {"extra": {"a.weight_codebook": torch.zeros(4)}}, "weight_codebook"),
+ ("nvfp4", {"extra": {"a.pre_quant_scale": torch.ones(3)}}, "pre_quant_scale"),
+ ("nvfp4", {"conf": {"format": "nvfp4", "convrot": True}}, "ConvRot on nvfp4"),
+ ("mxfp8", {"extra": {"a.weight_scale_2": torch.ones(())}}, "weight_scale_2"),
+ ],
+)
+def test_malformed_block_layers_are_refused(tmp_path, fmt, kwargs, why):
+ with pytest.raises(ValueError, match = why):
+ cq.refuse_comfy_quant(_layer_file(tmp_path, fmt, **kwargs))
+
+
+def test_untiled_block_scales_are_refused(tmp_path):
+ t = nvfp4_encode(torch.randn(256, 64))
+ t["weight_scale"] = t["weight_scale"][:200] # a plain [N, K/16] matrix is not ComfyUI's layout
+ path = _save(
+ tmp_path / "u.safetensors",
+ {**{f"a.{k}": v for k, v in t.items()}, "a.comfy_quant": _conf(format = "nvfp4")},
+ )
+ with pytest.raises(ValueError, match = "tiled layout"):
+ cq.refuse_comfy_quant(path)
+
+
[email protected]("fmt", ["convrot_w4a4", "asym_w4a8_int8", "w6a8_int8", "brand_new"])
+def test_remaining_formats_keep_the_refusal(tmp_path, fmt):
+ path = _save(
+ tmp_path / "r.safetensors",
+ {
+ "a.weight": torch.zeros(8, 8, dtype = torch.uint8),
+ "a.weight_scale": torch.ones(8, 1),
+ "a.comfy_quant": _conf(format = fmt),
+ },
+ )
+ with pytest.raises(ValueError, match = rf"1 layer\(s\) in ComfyUI format '{fmt}'"):
+ cq.refuse_comfy_quant(path)
+
+
+def test_resident_size_prices_kept_and_dequantized_nvfp4(tmp_path):
+ path = _layer_file(tmp_path, "nvfp4", rows = 2048, cols = 2048)
+ kept = cq.comfy_resident_mib(path, keep_int8 = False, keep_fp8 = False, keep_nvfp4 = True)
+ dense = cq.comfy_resident_mib(path, keep_int8 = False, keep_fp8 = False)
+ assert dense == 8 + 1 # 2048 x 2048 bf16, plus the scales rounded up
+ assert kept == 3 # 2 MiB of codes + 256 KiB of block scales
+ kw = dict(keep_int8 = False, keep_fp8 = False, keep_nvfp4 = True, block_divisible = {"nvfp4": 16})
+ assert cq.comfy_resident_mib(path, min_features = 2048, **kw) == 3
+ assert cq.comfy_resident_mib(path, min_features = 2049, **kw) == dense
+ smoothed = _layer_file(
+ tmp_path,
+ "nvfp4",
+ rows = 2048,
+ cols = 2048,
+ name = "s",
+ extra = {"a.pre_quant_scale": torch.ones(2048)},
+ )
+ assert cq.comfy_resident_mib(smoothed, **kw) > kept
+
+
+def test_lora_and_block_runtime_layers(monkeypatch, tmp_path):
+ scan = cq.scan_comfy_quant(_layer_file(tmp_path, "mxfp8"))
+ monkeypatch.setattr(cb, "mxfp8_runtime_reason", lambda target: None)
+ assert (
+ cb.comfy_block_backends(scan, _target("cuda:0"), "krea-2")["mxfp8_backend"] == "scaled_mm"
+ )
+ assert (
+ cb.comfy_block_backends(scan, _target("cuda:0"), "krea-2", lora = True)["mxfp8_backend"]
+ is None
+ )
+ model = types.SimpleNamespace(_unsloth_comfy_quant = {"mxfp8": 3, "nvfp4": 0})
+ assert cb.comfy_block_runtime_layers(model) == 3
+ assert (
+ cb.comfy_block_runtime_layers(types.SimpleNamespace(_unsloth_comfy_quant = {"mxfp8": 0})) == 0
+ )
+ assert cb.comfy_block_runtime_layers(None) == 0
+
+
+def test_install_hint_reads_the_default_hub_cache_too(monkeypatch, tmp_path):
+ import huggingface_hub
+
+ from core.inference.diffusion import DiffusionBackend
+
+ path = str(_layer_file(tmp_path, "nvfp4"))
+ seen = []
+
+ def fake(
+ repo_id,
+ filename,
+ cache_dir = None,
+ ):
+ seen.append(cache_dir)
+ return path if cache_dir is None else None
+
+ monkeypatch.setattr(huggingface_hub, "try_to_load_from_cache", fake)
+ assert DiffusionBackend._comfy_single_file_holds_nvfp4("Comfy-Org/x", "m.safetensors")
+ assert seen[-1] is None and len(seen) == 2
+
+
+class _Block(nn.Module):
+ def __init__(self, dim: int) -> None:
+ super().__init__()
+ self.to_q = nn.Linear(dim, dim)
+ self.to_k = nn.Linear(dim, dim)
+ self.to_v = nn.Linear(dim, dim)
+ self.to_out = nn.Linear(dim, dim)
+
+
+class _Tiny(nn.Module):
+ _keep_in_fp32_modules = None
+ _keys_to_ignore_on_load_unexpected = None
+
+ def __init__(
+ self,
+ dim: int = DIM,
+ blocks: int = 2,
+ ) -> None:
+ super().__init__()
+ self.blocks = nn.ModuleList(_Block(dim) for _ in range(blocks))
+ self.norm = nn.LayerNorm(dim)
+
+ @classmethod
+ def load_config(cls, repo, **_kwargs):
+ return {"dim": DIM, "blocks": 2}
+
+ @staticmethod
+ def _get_signature_keys(_cls):
+ return {"dim", "blocks"}, set()
+
+ @classmethod
+ def from_config(cls, config):
+ return cls(**config)
+
+
+def _convert(checkpoint = None, **_kwargs):
+ """What the diffusers converters do to a ComfyUI DiT: split the fused qkv by rows, rename the rest."""
+ out = {}
+ for key, value in checkpoint.items():
+ if ".qkv." in key:
+ stem, leaf = key.rsplit(".qkv.", 1)
+ for part, chunk in zip(("to_q", "to_k", "to_v"), value.chunk(3, dim = 0)):
+ out[f"{stem}.{part}.{leaf}"] = chunk
+ else:
+ out[key.replace(".out.", ".to_out.")] = value
+ return out
+
+
+def block_file(tmp_path, monkeypatch):
+ def make(fmt, drop_input_scale = False):
+ monkeypatch.setattr(
+ cq,
+ "_mapping",
+ lambda cls: (
+ _convert,
+ types.SimpleNamespace(
+ _should_convert_state_dict_to_diffusers = lambda a, b: set(a) != set(b),
+ _get_mapping_function_kwargs = lambda fn, **kw: {},
+ ),
+ ),
+ )
+ torch.manual_seed(0)
+ dense = _Tiny()
+ encode, reference = ENCODERS[fmt]
+ tensors, expected = {}, {}
+ for b, block in enumerate(dense.blocks):
+ layers = {
+ f"blocks.{b}.qkv": torch.cat(
+ [block.to_q.weight, block.to_k.weight, block.to_v.weight]
+ ),
+ f"blocks.{b}.out": block.to_out.weight,
+ }
+ for name, weight in layers.items():
+ t = encode(weight.detach())
+ if drop_input_scale:
+ t.pop("input_scale", None)
+ tensors.update({f"{name}.{k}": v for k, v in t.items()})
+ tensors[f"{name}.comfy_quant"] = _conf(format = fmt)
+ ref = reference(t)
+ if name.endswith(".qkv"):
+ for part, chunk in zip(("to_q", "to_k", "to_v"), ref.chunk(3)):
+ expected[f"blocks.{b}.{part}.weight"] = chunk
+ else:
+ expected[f"blocks.{b}.to_out.weight"] = ref
+ bias = getattr(block, "to_out" if name.endswith("out") else "to_q").bias
+ tensors[f"{name}.bias"] = (
+ torch.cat([block.to_q.bias, block.to_k.bias, block.to_v.bias])
+ if name.endswith(".qkv")
+ else bias
+ ).detach()
+ tensors["norm.weight"] = dense.norm.weight.detach()
+ tensors["norm.bias"] = dense.norm.bias.detach()
+ return _save(tmp_path / f"tiny_{fmt}.safetensors", tensors), tensors, expected
+
+ return make
+
+
+def _load(
+ path,
+ dtype = torch.float32,
+ **kwargs,
+):
+ return cq.load_comfy_quant_transformer(
+ _Tiny,
+ path,
+ cq.refuse_comfy_quant(path),
+ {"torch_dtype": dtype, "config": "base/repo", "subfolder": "transformer"},
+ int8_backend = None,
+ family = "z-image",
+ **kwargs,
+ )
+
+
[email protected]("fmt", ["nvfp4", "mxfp8"])
+def test_dequant_load_is_bit_exact_through_the_row_split(block_file, fmt):
+ path, tensors, expected = block_file(fmt)
+ model = _load(path)
+ info = model._unsloth_comfy_quant
+ assert info["dequantized"] == 4 and info[fmt] == 0
+ state = model.state_dict()
+ for key, want in expected.items():
+ assert torch.equal(state[key], want), key
+ assert torch.equal(state["blocks.0.to_k.bias"], tensors["blocks.0.qkv.bias"][DIM : 2 * DIM])
+
+
[email protected]("fmt", ["nvfp4", "mxfp8"])
+def test_runtime_linears_keep_codes_and_tiled_scales_unchanged(block_file, fmt):
+ if fmt == "nvfp4":
+ pytest.importorskip("flashinfer")
+ path, tensors, _expected = block_file(fmt)
+ model = _load(path, dtype = torch.bfloat16, **{f"{fmt}_backend": "kept"})
+ assert model._unsloth_comfy_quant[fmt] == 8 and model._unsloth_comfy_quant["dequantized"] == 0
+ out = model.blocks[1].to_out
+ file_codes = tensors["blocks.1.out.weight"]
+ file_scale = tensors["blocks.1.out.weight_scale"].view(torch.uint8).reshape(-1)
+ if fmt == "nvfp4":
+ assert type(out).__name__ == "NVFP4FlashInferLinear"
+ assert torch.equal(out.wq, cb.swap_nibbles(file_codes))
+ assert torch.equal(out.w_sf.reshape(-1), file_scale)
+ assert out.w_scale.item() == tensors["blocks.1.out.weight_scale_2"].item()
+ assert out.a_gsf.item() == pytest.approx(1.0 / tensors["blocks.1.out.input_scale"].item())
+ q = model.blocks[
+ 0
+ ].to_q # a row split of the fused qkv: scales re-tiled from the plain matrix
+ plain = cb.untile_scales(
+ tensors["blocks.0.qkv.weight_scale"].view(torch.uint8), 3 * DIM, DIM // 16
+ )
+ assert torch.equal(cb.untile_scales(q.w_sf, DIM, DIM // 16), plain[:DIM])
+ else:
+ assert type(out).__name__ == "ComfyMXFP8Linear"
+ assert torch.equal(out.weight_q.view(torch.uint8), file_codes.view(torch.uint8))
+ assert torch.equal(out.weight_sf, file_scale)
+ assert torch.equal(out.bias.float(), tensors["blocks.1.out.bias"].bfloat16().float())
+
+
+def _blackwell() -> bool:
+ return torch.cuda.is_available() and torch.cuda.get_device_capability() >= (10, 0)
+
+
+def test_nvfp4_without_an_input_scale_scales_activations_per_call(block_file):
+ pytest.importorskip("flashinfer")
+ path, _tensors, _expected = block_file("nvfp4", drop_input_scale = True)
+ model = _load(path, dtype = torch.bfloat16, nvfp4_backend = "kept")
+ assert model._unsloth_comfy_quant["nvfp4"] == 8
+ assert {type(m).__name__ for m in model.modules() if hasattr(m, "wq")} == {
+ "ComfyNVFP4DynamicLinear"
+ }
+ from core.inference.diffusion_nvfp4_linear import is_nvfp4_flashinfer_linear
+ from core.inference.diffusion_nvfp4_protect import protect_controller, protect_layers
+
+ layers = [m for _n, m in protect_layers(model)]
+ assert len(layers) == 8 and all(is_nvfp4_flashinfer_linear(m) for m in layers)
+ # its own step controller, not the process-wide one
+ assert (
+ all(m.protect is layers[0].protect for m in layers)
+ and layers[0].protect is not protect_controller()
+ )
+
+
[email protected](not _blackwell(), reason = "needs a Blackwell GPU")
[email protected]("fmt,dynamic", [("nvfp4", False), ("nvfp4", True), ("mxfp8", False)])
+def test_runtime_forward_matches_the_dequantized_product(block_file, fmt, dynamic, monkeypatch):
+ if fmt == "nvfp4":
+ pytest.importorskip("flashinfer")
+ monkeypatch.setenv("UNSLOTH_NVFP4_DIFFUSION", "1")
+ path, _tensors, expected = block_file(fmt, drop_input_scale = dynamic)
+ model = _load(path, dtype = torch.bfloat16, **{f"{fmt}_backend": "kept"}).cuda()
+ x = torch.randn(64, DIM, device = "cuda", dtype = torch.bfloat16)
+ ref = (
+ x.float() @ expected["blocks.1.to_out.weight"].cuda().T
+ + model.blocks[1].to_out.bias.float()
+ )
+ got = model.blocks[1].to_out(x).float()
+ rel = ((got - ref).norm() / ref.norm()).item()
+ assert rel < (0.15 if fmt == "nvfp4" else 0.05), rel # activation quantization error only
+
+
+def _target(device):
+ return types.SimpleNamespace(torch_device = device, dtype = torch.bfloat16)
+
+
+def test_nvfp4_on_cpu_or_mps_dequantizes(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_NVFP4_DIFFUSION", "1")
+ for device in ("cpu", "mps"):
+ backend, reason = cb.comfy_block_backend("nvfp4", _target(device), "z-image")
+ assert backend is None and "not CUDA" in reason
+
+
+def test_nvfp4_follows_studios_nvfp4_switch(monkeypatch):
+ import core.inference.diffusion_nvfp4_ops as ops
+
+ monkeypatch.setattr(ops, "_resolve_backend", lambda device = None: ("flashinfer", "preflight ok"))
+ monkeypatch.setenv("UNSLOTH_NVFP4_DIFFUSION", "0")
+ backend, reason = cb.comfy_block_backend("nvfp4", _target("cuda:0"), "z-image")
+ assert backend is None and "UNSLOTH_NVFP4_DIFFUSION=1" in reason
+ monkeypatch.setenv("UNSLOTH_NVFP4_DIFFUSION", "1")
+ assert cb.comfy_block_backend("nvfp4", _target("cuda:0"), "z-image")[0] == "flashinfer"
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_COMFY_NVFP4", "0")
+ assert cb.comfy_block_backend("nvfp4", _target("cuda:0"), "z-image")[0] is None
+
+
+def test_nvfp4_without_flashinfer_or_on_a_denied_family_dequantizes(monkeypatch):
+ import core.inference.diffusion_nvfp4_ops as ops
+
+ monkeypatch.setenv("UNSLOTH_NVFP4_DIFFUSION", "1")
+ monkeypatch.setattr(
+ ops,
+ "_resolve_backend",
+ lambda device = None: ("torchao", "sm_90 is not in the flashinfer NVFP4 set"),
+ )
+ backend, reason = cb.comfy_block_backend("nvfp4", _target("cuda:0"), "z-image")
+ assert backend is None and "sm_90" in reason
+ monkeypatch.setattr(ops, "_resolve_backend", lambda device = None: ("flashinfer", "ok"))
+ assert cb.comfy_block_backend("nvfp4", _target("cuda:0"), "qwen-image")[0] is None
+
+
+def test_flashinfer_install_is_only_wanted_when_the_codes_can_stay_nvfp4(monkeypatch):
+ assert cb.comfy_nvfp4_runtime_possible("z-image")
+ assert not cb.comfy_nvfp4_runtime_possible("qwen-image")
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_COMFY_NVFP4", "0")
+ assert not cb.comfy_nvfp4_runtime_possible("z-image")
+
+
+def test_mxfp8_needs_blackwell_bf16_and_an_allowed_family(monkeypatch):
+ monkeypatch.setattr(cb, "mxfp8_runtime_reason", lambda target: None)
+ assert (
+ cb.comfy_block_backend("mxfp8", _target("cuda:0"), "krea-2", dtype = torch.bfloat16)[0]
+ == "scaled_mm"
+ )
+ assert (
+ cb.comfy_block_backend("mxfp8", _target("cuda:0"), "krea-2", dtype = torch.float16)[0] is None
+ )
+ assert cb.comfy_block_backend("mxfp8", _target("cuda:0"), "qwen-image")[0] is None
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_COMFY_MXFP8", "0")
+ assert cb.comfy_block_backend("mxfp8", _target("cuda:0"), "krea-2")[0] is None
+
+
+def test_mxfp8_probe_refuses_pre_blackwell_and_non_cuda(monkeypatch):
+ assert "not CUDA" in cb.mxfp8_runtime_reason(_target("cpu"))
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a: (9, 0))
+ assert "sm_90" in cb.mxfp8_runtime_reason(_target("cuda:0"))
+
+
+def test_backends_are_logged_per_format_present(caplog):
+ import logging
+
+ scan = types.SimpleNamespace(counts = lambda: {"nvfp4": 3})
+ logger = logging.getLogger("comfy_block_test")
+ with caplog.at_level(logging.INFO, logger = "comfy_block_test"):
+ out = cb.comfy_block_backends(scan, _target("cpu"), "z-image", logger = logger)
+ assert out == {"nvfp4_backend": None, "mxfp8_backend": None}
+ assert "3 nvfp4 layer(s) are dequantized" in caplog.text and "mxfp8" not in caplog.text
+
+
+def test_a_failed_mxfp8_probe_is_not_cached(monkeypatch):
+ import contextlib
+
+ cb.reset_probe_cache()
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda index = None: (10, 0))
+ monkeypatch.setattr(torch.cuda, "device", lambda index: contextlib.nullcontext())
+
+ def boom(*_a, **_k):
+ raise torch.OutOfMemoryError("CUDA out of memory")
+
+ # the probe's first allocation fails, as it would on a full GPU (and before CPU-only torch can object)
+ monkeypatch.setattr(torch, "randn", boom)
+ assert "OutOfMemoryError" in cb.mxfp8_runtime_reason(_target("cuda:0"))
+ assert cb._MX_PROBE == {}
+
+
+def test_a_lora_load_prices_block_layers_dequantized(monkeypatch, tmp_path):
+ import core.inference.diffusion as d
+
+ path = str(_layer_file(tmp_path, "mxfp8", rows = 2048, cols = 2048))
+ monkeypatch.setattr(d, "comfy_block_backend", lambda fmt, *a, **k: ("scaled_mm", "ok"))
+ monkeypatch.setattr(d, "comfy_int8_backend", lambda *a, **k: None)
+ monkeypatch.setattr(d, "comfy_fp8_backend", lambda *a, **k: None)
+ fam = types.SimpleNamespace(name = "krea-2")
+ kept = d.DiffusionBackend._comfy_single_file_resident_mib(path, fam, _target("cuda:0"), None)
+ lora = d.DiffusionBackend._comfy_single_file_resident_mib(
+ path, fam, _target("cuda:0"), None, lora = True
+ )
+ assert kept is not None and lora > kept
+
+
+def test_mxfp8_e8m0_scales_are_priced_one_byte(tmp_path):
+ path = _layer_file(tmp_path, "mxfp8", rows = 4096, cols = 8192)
+ # 32 MiB of fp8 codes + 1 MiB of e8m0 block scales + the comfy_quant bytes, rounded up (35 at 2 bytes)
+ assert cq.comfy_resident_mib(path, keep_int8 = False, keep_fp8 = False, keep_mxfp8 = True) == 34
diff --git a/studio/backend/tests/test_diffusion_comfy_quant.py b/studio/backend/tests/test_diffusion_comfy_quant.py
index e4e26333b5d..eaaa4fceb97 100644
--- a/studio/backend/tests/test_diffusion_comfy_quant.py
+++ b/studio/backend/tests/test_diffusion_comfy_quant.py
@@ -83,9 +83,7 @@ def test_per_layer_int8_convrot_is_detected(tmp_path):
assert cq.comfy_quant_error(scan) is None
- "fmt", ["nvfp4", "mxfp8", "convrot_w4a4", "asym_w4a8_int8", "w6a8_int8", "brand_new"]
-)
[email protected]("fmt", ["convrot_w4a4", "asym_w4a8_int8", "w6a8_int8", "brand_new"])
def test_unsupported_formats_are_refused_by_name(tmp_path, fmt):
path = _save(
tmp_path / "m.safetensors",
@@ -100,8 +98,8 @@ def test_unsupported_formats_are_refused_by_name(tmp_path, fmt):
def test_header_quantization_metadata_is_read_and_refused(tmp_path):
- """The Comfy-Org nvfp4 files declare formats only in the header, with no per-layer tensors."""
- meta = {cq.QUANT_METADATA_KEY: json.dumps({"layers": {"a": {"format": "nvfp4"}}})}
+ """Comfy-Org files declare formats only in the header, with no per-layer tensors."""
+ meta = {cq.QUANT_METADATA_KEY: json.dumps({"layers": {"a": {"format": "convrot_w4a4"}}})}
path = _save(
tmp_path / "m.safetensors",
{
@@ -114,7 +112,7 @@ def test_header_quantization_metadata_is_read_and_refused(tmp_path):
)
scan = cq.scan_comfy_quant(path)
assert scan is not None and not scan.layers
- with pytest.raises(ValueError, match = "'nvfp4'"):
+ with pytest.raises(ValueError, match = "'convrot_w4a4'"):
cq.refuse_comfy_quant(path)
diff --git a/studio/backend/tests/test_diffusion_nvfp4_install.py b/studio/backend/tests/test_diffusion_nvfp4_install.py
index 9de6f816538..b30994f2103 100644
--- a/studio/backend/tests/test_diffusion_nvfp4_install.py
+++ b/studio/backend/tests/test_diffusion_nvfp4_install.py
@@ -924,7 +924,16 @@ def test_install_gates_skip_kinds_the_dense_quant_path_cannot_reach():
img = inspect.getsource(diffusion.DiffusionBackend)
gate = img[: img.index("ensure_flashinfer_for_nvfp4(")].rsplit("if ", 1)[-1]
- assert gate.lstrip("( \n").startswith("dense_quant_supported_kind(kind)")
+ # One exception, by kind: a ComfyUI nvfp4 single file (it never reaches the dense quant path, but its own codes
+ # run on the FlashInfer Linear). Every other kind still has to pass the dense-quant clause.
+ comfy, dense = gate.split(") or (", 1)
+ assert comfy.lstrip("( \n").startswith('kind == "single_file"')
+ assert "_comfy_single_file_holds_nvfp4(" in comfy
+ assert comfy.index("comfy_nvfp4_runtime_possible(") < comfy.index(
+ "_comfy_single_file_holds_nvfp4("
+ )
+ assert comfy.index("_has_active_lora(loras)") < comfy.index("_comfy_single_file_holds_nvfp4(")
+ assert dense.lstrip("( \n").startswith("dense_quant_supported_kind(kind)")
vid = inspect.getsource(video.VideoBackend)
gate = vid[vid.index("_nvfp4_install_wanted = (") + len("_nvfp4_install_wanted = (") :]
assert gate.lstrip("( \n").startswith('kind == "pipeline"')