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.

NVFP4 QAT: keep the fake-quantized linear out of compiled graphs (#14812)

Daniel Hanfda27b8e68b9
diff --git a/tests/test_qat_microscaling_schemes.py b/tests/test_qat_microscaling_schemes.py
index 17ab0943bd1..e2cbb950565 100644
--- a/tests/test_qat_microscaling_schemes.py
+++ b/tests/test_qat_microscaling_schemes.py
@@ -360,6 +360,184 @@ def test_nvfp4_accepts_rank4_inputs(monkeypatch):
assert out.shape == (*shape[:-1], 128)
+def test_nvfp4_qat_forward_compiles_fullgraph(monkeypatch):
+ # fullgraph = True: the patched forward must not be a compiler boundary.
+ linear_cls = _nvfp4_linear()
+ monkeypatch.setattr(linear_cls, "forward", lambda self, x: x @ self.weight.t())
+ _probe_ok(monkeypatch)
+
+ class Block(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.proj = torch.nn.Linear(64, 128, bias = False)
+
+ def forward(self, x):
+ return self.proj(x * 2) + 1
+
+ model = _prepare_model_for_qat(Block().to(torch.bfloat16), "nvfp4")
+ assert isinstance(model.proj, linear_cls)
+ torch._dynamo.reset()
+ explain = torch._dynamo.explain(model)(torch.randn(4, 64, dtype = torch.bfloat16))
+ assert explain.graph_break_count == 0 and explain.graph_count == 1
+ x = torch.randn(2, 3, 64, dtype = torch.bfloat16)
+ torch.testing.assert_close(torch.compile(model, fullgraph = True, backend = "eager")(x), model(x))
+
+
+_needs_fp4_gpu = pytest.mark.skipif(
+ not torch.cuda.is_available() or torch.cuda.get_device_capability() < (10, 0),
+ reason = "needs an FP4 tensor core GPU",
+)
+
+
+def exact_inductor(monkeypatch):
+ # Inductor otherwise keeps silu(gate) * up in fp32 before the bf16 round, shifting fp4 codes (~2% grads).
+ import torch._inductor.config as inductor_config
+
+ monkeypatch.setattr(inductor_config, "emulate_precision_casts", True)
+ torch._dynamo.reset()
+ yield
+ torch._dynamo.reset()
+
+
+def _nvfp4_mlp(weight_dtype = torch.bfloat16):
+ import torch.nn.functional as F
+
+ class MLP(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.gate_proj = torch.nn.Linear(256, 512, bias = False)
+ self.up_proj = torch.nn.Linear(256, 512, bias = False)
+ self.down_proj = torch.nn.Linear(512, 256, bias = False)
+
+ def forward(self, x):
+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
+
+ torch.manual_seed(0)
+ model = MLP().to("cuda", weight_dtype)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ model = _prepare_model_for_qat(model, "nvfp4")
+ assert isinstance(model.gate_proj, _nvfp4_linear())
+ return model
+
+
+def _torchao_reference(model):
+ """torchao's own eager NVFP4 QAT forward (its autograd Function), not the custom op."""
+ import types
+ from torchao.prototype.qat import NVFP4FakeQuantizedLinear
+
+ ref = __import__("copy").deepcopy(model)
+ for module in ref.modules():
+ if isinstance(module, NVFP4FakeQuantizedLinear):
+ module.forward = types.MethodType(NVFP4FakeQuantizedLinear.forward, module)
+ return ref
+
+
+def _grads(model, forward, x):
+ model.zero_grad(set_to_none = True)
+ x = x.detach().requires_grad_(True)
+ out = forward(x)
+ out.float().square().mean().backward()
+ grads = {n: p.grad.float().clone() for n, p in model.named_parameters()}
+ grads["x"] = x.grad.float().clone()
+ return out.detach().float(), grads
+
+
+def _assert_same(
+ got,
+ want,
+ tol = 0.0,
+):
+ (out, grads), (ref_out, ref_grads) = got, want
+ assert float((out - ref_out).norm() / ref_out.norm()) <= tol
+ for name, ref in ref_grads.items():
+ rel = float((grads[name] - ref).norm() / ref.norm())
+ assert rel <= tol, (name, rel)
+
+
+@_needs_fp4_gpu
+def test_nvfp4_qat_custom_op_matches_torchao_eager():
+ model = _nvfp4_mlp()
+ x = torch.randn(2, 64, 256, device = "cuda", dtype = torch.bfloat16)
+ ref = _torchao_reference(model)
+ _assert_same(_grads(model, model, x), _grads(ref, ref, x))
+ op = qat_utils._nvfp4_qat_linear_op()
+ w = model.gate_proj.weight
+ torch.library.opcheck(
+ op,
+ (x.view(-1, 256).detach().requires_grad_(True), w, None, True, True, True, False, None),
+ # test_aot_dispatch_dynamic sums every output, which float8 scales do not support.
+ test_utils = ("test_schema", "test_autograd_registration", "test_faketensor"),
+ )
+
+
+@_needs_fp4_gpu
[email protected]("fullgraph", [False, True])
+def test_nvfp4_qat_weight_grads_match_eager_under_compile(exact_inductor, fullgraph):
+ # Inductor used to shrink the gate / up weight grads (~100% relative error against eager).
+ model = _nvfp4_mlp()
+ x = torch.randn(2, 64, 256, device = "cuda", dtype = torch.bfloat16)
+ eager = _grads(model, model, x)
+ compiled = torch.compile(model, fullgraph = fullgraph)
+ _assert_same(_grads(model, compiled, x), eager)
+ _assert_same(_grads(model, compiled, x), eager) # warm call
+
+
+@_needs_fp4_gpu
+def test_nvfp4_qat_weight_grads_close_to_eager_with_default_inductor():
+ model = _nvfp4_mlp()
+ x = torch.randn(2, 64, 256, device = "cuda", dtype = torch.bfloat16)
+ eager = _grads(model, model, x)
+ torch._dynamo.reset()
+ _assert_same(_grads(model, torch.compile(model, fullgraph = True), x), eager, 0.05)
+
+
+@_needs_fp4_gpu
+def test_nvfp4_qat_dynamic_batch_fullgraph_one_graph(exact_inductor):
+ from torch._dynamo.testing import CompileCounterWithBackend
+
+ model = _nvfp4_mlp()
+ counter = CompileCounterWithBackend("inductor")
+ compiled = torch.compile(model, fullgraph = True, dynamic = True, backend = counter)
+ for batch in (2, 3, 4, 7):
+ x = torch.randn(batch, 32, 256, device = "cuda", dtype = torch.bfloat16)
+ torch._dynamo.mark_dynamic(x, 0)
+ _assert_same(_grads(model, compiled, x), _grads(model, model, x))
+ assert counter.frame_count == 1, counter.frame_count
+
+
+@_needs_fp4_gpu
+def test_nvfp4_qat_one_token_decode_fullgraph(exact_inductor):
+ model = _nvfp4_mlp()
+ model.requires_grad_(False)
+ x = torch.randn(1, 1, 256, device = "cuda", dtype = torch.bfloat16)
+ with torch.no_grad():
+ want = model(x)
+ got = torch.compile(model, fullgraph = True)(x)
+ torch.testing.assert_close(got, want, rtol = 0, atol = 0)
+
+
+@_needs_fp4_gpu
[email protected]("weight_dtype", [torch.bfloat16, torch.float32])
+def test_nvfp4_qat_autocast_grads_match_torchao(exact_inductor, weight_dtype):
+ model = _nvfp4_mlp(weight_dtype)
+ ref = _torchao_reference(model)
+ x = torch.randn(2, 16, 256, device = "cuda", dtype = torch.bfloat16)
+
+ def under_autocast(module):
+ def run(t):
+ with torch.autocast("cuda", dtype = torch.bfloat16):
+ return module(t)
+
+ return run
+
+ want = _grads(ref, under_autocast(ref), x)
+ _assert_same(_grads(model, under_autocast(model), x), want)
+ compiled = torch.compile(under_autocast(model), fullgraph = True)
+ _assert_same(_grads(model, compiled, x), want)
+
+
def _torchao_nvfp4_contract_forward(self, x):
# What torchao's NVFP4 QAT forward accepts: nvfp4_quantize asserts these, then the output follows x.
assert x.dim() == 2, x.shape
diff --git a/unsloth/models/_utils.py b/unsloth/models/_utils.py
index 6ae1a4d5a4d..513577dfdd0 100644
--- a/unsloth/models/_utils.py
+++ b/unsloth/models/_utils.py
@@ -9087,11 +9087,196 @@ def _mx_autocast_forward(self, x):
return MXFakeQuantizedLinear.forward(self, x)
+_NVFP4_QAT_LINEAR = []
+
+
+def _nvfp4_qat_linear_op():
+ """torchao's NVFP4 QAT linear (_NVFP4QuantizedForwardFakeQuantizedBackward) as two opaque custom ops.
+
+ Inductor miscompiles the traced fake quantization (torch 2.13 / 2.14, torchao 0.18): the backward's
+ dequantized activation comes out scaled by 2**-126 for every normal fp4 code, so compiled weight grads
+ are ~100% off while eager and aot_eager match. As custom ops with fake impls and an autograd formula,
+ torch.compile keeps them whole (fullgraph = True, no graph break) and runs torchao's eager numerics."""
+ if _NVFP4_QAT_LINEAR:
+ return _NVFP4_QAT_LINEAR[0]
+ from torchao.prototype.mx_formats.nvfp4_tensor import (
+ NVFP4Tensor,
+ _addmm_nvfp4_dispatch,
+ per_tensor_amax_to_scale,
+ )
+ from torchao.prototype.mx_formats.utils import hp_data_dims_to_swizzled_scale_dims_nvfp4
+
+ def quantize(t, per_tensor, swizzled):
+ scale = per_tensor_amax_to_scale(torch.max(torch.abs(t))) if per_tensor else None
+ return NVFP4Tensor.to_nvfp4(t, per_tensor_scale = scale, is_swizzled_scales = swizzled)
+
+ def quantize_weight(weight, per_tensor, swizzled, triton):
+ weight = quantize(weight, per_tensor, swizzled)
+ weight.use_triton_kernel = triton
+ return weight
+
+ name = "unsloth::nvfp4_qat_linear"
+ forward_schema = (
+ "(Tensor x, Tensor weight, Tensor? bias, bool act_per_tensor, bool w_per_tensor, "
+ "bool w_swizzled, bool w_triton, ScalarType? mm_dtype) "
+ "-> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)"
+ )
+ backward_schema = (
+ "(Tensor grad, Tensor x_qdata, Tensor x_scale, Tensor x_per_tensor_scale, Tensor w_qdata, "
+ "Tensor w_scale, Tensor w_per_tensor_scale, ScalarType x_dtype, ScalarType w_dtype, "
+ "bool act_per_tensor, bool w_per_tensor, bool w_swizzled, ScalarType? mm_dtype) -> (Tensor, Tensor)"
+ )
+
+ def per_tensor(t, like):
+ scale = t.per_tensor_scale
+ return like.new_ones((), dtype = torch.float32) if scale is None else scale.float()
+
+ @torch.library.custom_op(name, mutates_args = (), schema = forward_schema)
+ def forward(x, weight, bias, act_per_tensor, w_per_tensor, w_swizzled, w_triton, mm_dtype):
+ # Activations: torchao's QAT config always uses unswizzled scales and the plain quantizer.
+ x_q = quantize(x, act_per_tensor, False)
+ w_q = quantize_weight(weight, w_per_tensor, w_swizzled, w_triton)
+ out = _addmm_nvfp4_dispatch(x_q, w_q.t(), None, bias)
+ if (
+ out.dtype != x.dtype
+ ): # older torchao adds a float32 bias without casting; the fake impl says x.dtype
+ out = out.to(x.dtype)
+ return (
+ out,
+ x_q.qdata,
+ x_q.scale,
+ per_tensor(x_q, x),
+ w_q.qdata,
+ w_q.scale,
+ per_tensor(w_q, x),
+ )
+
+ @forward.register_fake
+ def _(x, weight, bias, act_per_tensor, w_per_tensor, w_swizzled, w_triton, mm_dtype):
+ M, K = x.shape
+ N = weight.shape[0]
+ w_scale = hp_data_dims_to_swizzled_scale_dims_nvfp4(N, K) if w_swizzled else (N, K // 16)
+ return (
+ x.new_empty((M, N)),
+ x.new_empty((M, K // 2), dtype = torch.uint8),
+ x.new_empty((M, K // 16), dtype = torch.float8_e4m3fn),
+ x.new_empty((), dtype = torch.float32),
+ x.new_empty((N, K // 2), dtype = torch.uint8),
+ x.new_empty(w_scale, dtype = torch.float8_e4m3fn),
+ x.new_empty((), dtype = torch.float32),
+ )
+
+ @torch.library.custom_op(name + "_backward", mutates_args = (), schema = backward_schema)
+ def backward_op(
+ grad,
+ x_qdata,
+ x_scale,
+ x_per_tensor_scale,
+ w_qdata,
+ w_scale,
+ w_per_tensor_scale,
+ x_dtype,
+ w_dtype,
+ act_per_tensor,
+ w_per_tensor,
+ w_swizzled,
+ mm_dtype,
+ ):
+ x_q = NVFP4Tensor(
+ x_qdata,
+ x_scale,
+ 16,
+ x_dtype,
+ per_tensor_scale = x_per_tensor_scale if act_per_tensor else None,
+ )
+ x_dq = x_q.dequantize(x_dtype)
+ # Positional: the swizzle flag is `_is_swizzled_scales` in torchao 0.15, `is_swizzled_scales` later.
+ w_q = NVFP4Tensor(
+ w_qdata,
+ w_scale,
+ 16,
+ w_dtype,
+ w_per_tensor_scale if w_per_tensor else None,
+ None,
+ w_swizzled,
+ )
+ w_dq = w_q.dequantize(w_dtype)
+ if (
+ mm_dtype is not None
+ ): # torchao's backward runs under the forward's autocast (custom_bwd)
+ grad, x_dq, w_dq = grad.to(mm_dtype), x_dq.to(mm_dtype), w_dq.to(mm_dtype)
+ return torch.mm(grad, w_dq), torch.mm(grad.t(), x_dq)
+
+ @backward_op.register_fake
+ def _(
+ grad,
+ x_qdata,
+ x_scale,
+ x_per_tensor_scale,
+ w_qdata,
+ w_scale,
+ w_per_tensor_scale,
+ x_dtype,
+ w_dtype,
+ act_per_tensor,
+ w_per_tensor,
+ w_swizzled,
+ mm_dtype,
+ ):
+ dtype = grad.dtype if mm_dtype is None else mm_dtype
+ N, K = w_qdata.shape[0], w_qdata.shape[1] * 2
+ return (
+ grad.new_empty((grad.shape[0], K), dtype = dtype),
+ grad.new_empty((N, K), dtype = dtype),
+ )
+
+ def setup_context(ctx, inputs, output):
+ x, weight, bias, act_per_tensor, w_per_tensor, w_swizzled, _, mm_dtype = inputs
+ saved = output[1:]
+ ctx.save_for_backward(*saved)
+ ctx.mark_non_differentiable(*saved)
+ ctx.args = (x.dtype, weight.dtype, act_per_tensor, w_per_tensor, w_swizzled, mm_dtype)
+
+ def backward(ctx, grad, *_):
+ grad_x, grad_w = backward_op(grad, *ctx.saved_tensors, *ctx.args)
+ grad_bias = grad.sum(0) if ctx.needs_input_grad[2] else None
+ return grad_x, grad_w, grad_bias, None, None, None, None, None
+
+ forward.register_autograd(backward, setup_context = setup_context)
+ _NVFP4_QAT_LINEAR.append(forward)
+ return forward
+
+
+def _nvfp4_qat_linear(self, x):
+ from torchao.prototype.qat import NVFP4FakeQuantizedLinear
+
+ act, weight = self.activation_config, self.weight_config
+ op = None
+ # The custom op covers torchao's CUDA kernel path with its QAT config (unswizzled, plain activation
+ # quantizer); anything else, or a torchao without these internals, keeps torchao's own forward.
+ if x.is_cuda and not act.use_swizzled_scales and not act.use_triton_kernel:
+ try:
+ op = _nvfp4_qat_linear_op()
+ except Exception:
+ op = None
+ if op is None:
+ return NVFP4FakeQuantizedLinear.forward(self, x)
+ mm_dtype = torch.get_autocast_dtype("cuda") if torch.is_autocast_enabled("cuda") else None
+ return op(
+ x,
+ self.weight,
+ self.bias,
+ act.use_per_tensor_scale,
+ weight.use_per_tensor_scale,
+ weight.use_swizzled_scales,
+ weight.use_triton_kernel,
+ mm_dtype,
+ )[0]
+
+
def _nvfp4_any_rank_forward(self, x):
# torchao's NVFP4FakeQuantizedLinear flattens only rank-3 inputs (vision layers see rank 4+), and
# its quantizer asserts contiguous bfloat16 / float32 activations (nvfp4_quantize).
- from torchao.prototype.qat import NVFP4FakeQuantizedLinear
-
out_dtype = None
# float16 autocast hands over float16 activations (an earlier Linear / SDPA); prepare only
# admits bfloat16 / float32 weights, so quantize from the weight dtype and return what an
@@ -9102,7 +9287,7 @@ def _nvfp4_any_rank_forward(self, x):
x2 = x if x.dim() == 2 else x.reshape(-1, x.shape[-1])
if not x2.is_contiguous():
x2 = x2.contiguous()
- out = NVFP4FakeQuantizedLinear.forward(self, x2)
+ out = _nvfp4_qat_linear(self, x2)
if x.dim() != 2:
out = out.view(*x.shape[:-1], out.shape[-1])
return out if out_dtype is None or out.dtype == out_dtype else out.to(out_dtype)
@@ -9123,10 +9308,16 @@ def _patch_microscaling_qat_forwards(model) -> None:
)
]
forwards = [(cls, forward) for cls, forward in forwards if isinstance(cls, type)]
+ nvfp4 = forwards[0][0] if forwards and forwards[0][1] is _nvfp4_any_rank_forward else None
for module in model.modules():
for cls, forward in forwards:
if isinstance(module, cls):
module.forward = types.MethodType(forward, module)
+ if cls is nvfp4:
+ try:
+ _nvfp4_qat_linear_op() # register the ops now, not inside a compile trace
+ except Exception:
+ pass
def _is_lora_adapter_name(fqn: str) -> bool: