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 fused GEMM: honor autocast dtype and check K alignment for dX (#14625)

Daniel Hand302a58b7fb4
diff --git a/tests/test_nvfp4_fused_gate_shape.py b/tests/test_nvfp4_fused_gate_shape.py
index 627ea710d49..dcf0f7cc3f9 100644
--- a/tests/test_nvfp4_fused_gate_shape.py
+++ b/tests/test_nvfp4_fused_gate_shape.py
@@ -146,3 +146,13 @@ def test_split_k_per_capability(N, monkeypatch, cap, sms, dx, M, n_out, k_red, s
monkeypatch.setattr(N, "_device_capability", lambda index: cap)
monkeypatch.setattr(N, "_sm_count", lambda index: sms)
assert N._fused_config(M, n_out, k_red, torch.device("cuda", 0), dx)[-1] == split
+
+
[email protected]("cap", [(8, 0), (8, 9), (12, 0)])
[email protected]("dx", [False, True])
+def test_unaligned_k_stays_dense_in_both_directions(N, monkeypatch, cap, dx):
+ # dX reduces over N, so K must be checked apart from inner.
+ assert _decide(N, monkeypatch, cap, 16, 4096, 4096, dx)
+ assert not _decide(N, monkeypatch, cap, 16, 4096, 4112, dx)
+ assert not _decide(N, monkeypatch, cap, 16, 4112, 4096, dx)
+ assert _decide(N, monkeypatch, cap, 16, 4096, 4112, dx, mode = "1")
diff --git a/tests/test_nvfp4_fused_gemm.py b/tests/test_nvfp4_fused_gemm.py
index 1dd262c3fc2..610232df84e 100644
--- a/tests/test_nvfp4_fused_gemm.py
+++ b/tests/test_nvfp4_fused_gemm.py
@@ -500,3 +500,82 @@ def test_fullgraph_compile_runs_the_fused_kernels(N, fused):
compiled(X).backward()
assert _calls(N)["fwd"] >= before["fwd"] + 3 and _calls(N)["bwd"] >= before["bwd"] + 3
torch.testing.assert_close(X.grad, eager)
+
+
+_AMP_CASES = [(torch.float16, torch.bfloat16), (torch.bfloat16, torch.float16)]
+_needs_bf16 = pytest.mark.skipif(
+ not has_real_cuda() or torch.cuda.get_device_capability() < (8, 0), reason = "needs bf16"
+)
+
+
+def _amp_step(N, X, packed, scale, gs, amp, monkeypatch, mode):
+ monkeypatch.setenv("UNSLOTH_NVFP4_FUSED", mode)
+ X = X.detach().clone().requires_grad_(True)
+ before = _calls(N)
+ with torch.autocast("cuda", dtype = amp):
+ Y = N.nvfp4_linear(X, packed, scale, gs)
+ loss = Y.float().square().mean()
+ loss.backward()
+ engaged = _calls(N)["fwd"] - before["fwd"], _calls(N)["bwd"] - before["bwd"]
+ return Y, X.grad, engaged
+
+
+@_needs_bf16
[email protected]("dtype, amp", _AMP_CASES)
+def test_autocast_dtype_matches_dense(N, monkeypatch, dtype, amp):
+ # fp16 1000s against all ones weights: 128000 is finite in bf16, inf in fp16.
+ packed = torch.full((128, 64), 0x22, device = "cuda", dtype = torch.uint8)
+ scale = torch.ones(128, 8, device = "cuda")
+ gs = torch.ones(1, device = "cuda")
+ X = torch.full((4, 128), 1000.0, device = "cuda", dtype = dtype)
+ Yf, gf, ef = _amp_step(N, X, packed, scale, gs, amp, monkeypatch, "1")
+ Yd, gd, ed = _amp_step(N, X, packed, scale, gs, amp, monkeypatch, "0")
+ assert ef == (1, 1) and ed == (0, 0)
+ assert Yf.dtype == amp and gf.dtype == dtype
+ _same(Yf, Yd)
+ _same(gf, gd)
+ assert Yf.isfinite().all() == (amp == torch.bfloat16)
+
+
+@_needs_bf16
[email protected]("dtype, amp", _AMP_CASES + [(torch.float32, torch.bfloat16)])
+def test_autocast_random_weights_match_dense_and_oracle(N, monkeypatch, dtype, amp):
+ packed, scale, gs = _random_nvfp4(256, 512, seed = 7)
+ X = torch.randn(16, 512, device = "cuda", dtype = dtype)
+ Yf, gf, ef = _amp_step(N, X, packed, scale, gs, amp, monkeypatch, "1")
+ Yd, gd, _ = _amp_step(N, X, packed, scale, gs, amp, monkeypatch, "0")
+ assert ef == (1, 1) and Yf.dtype == Yd.dtype == amp and gf.dtype == gd.dtype == dtype
+ W = N.nvfp4_dequantize(packed, scale, gs, torch.float64)
+ Xe = X.to(amp).double()
+ _check(Yf, Yd, Xe @ W.t())
+ dY = (2 / Yd.numel()) * Yd.double()
+ _check(gf, gd, dY @ W)
+
+
+@_needs_bf16
+def test_autocast_fullgraph_compile_has_no_graph_break(N, fused):
+ import torch._dynamo
+
+ packed, scale, gs = _random_nvfp4(384, 256)
+
+ def step(X):
+ with torch.autocast("cuda", dtype = torch.bfloat16):
+ Y = N.nvfp4_linear(X, packed, scale, gs)
+ return Y, Y.float().square().mean()
+
+ X = torch.randn(32, 256, device = "cuda", dtype = torch.float16, requires_grad = True)
+ eager, loss = step(X)
+ loss.backward()
+ eager_grad = X.grad.clone()
+ X.grad = None
+ torch._dynamo.reset()
+ assert torch._dynamo.explain(step)(X).graph_break_count == 0
+ torch._dynamo.reset()
+ compiled = torch.compile(step, fullgraph = True)
+ before = _calls(N)
+ Y, loss = compiled(X)
+ loss.backward()
+ assert _calls(N)["fwd"] >= before["fwd"] + 1 and _calls(N)["bwd"] >= before["bwd"] + 1
+ assert Y.dtype == eager.dtype == torch.bfloat16 and X.grad.dtype == torch.float16
+ torch.testing.assert_close(Y, eager)
+ torch.testing.assert_close(X.grad, eager_grad)
diff --git a/unsloth/kernels/nvfp4.py b/unsloth/kernels/nvfp4.py
index 0e1e39f273e..19422088c0e 100644
--- a/unsloth/kernels/nvfp4.py
+++ b/unsloth/kernels/nvfp4.py
@@ -488,7 +488,8 @@ def _fused_ok(
and packed.dtype == torch.uint8
and packed.dim() == 2
and packed.shape[0] > 0
- and (mode in _FUSED_FORCE or (inner % 64 == 0 and packed.shape[0] % 64 == 0))
+ # N and K both 64 aligned (inner is N for dX); unaligned dX is up to 2.8x slower.
+ and (mode in _FUSED_FORCE or (packed.shape[0] % 64 == 0 and packed.shape[1] % 32 == 0))
and not _is_transposed_view(packed)
and scale.dtype in (torch.float8_e4m3fn, torch.float32, torch.float16, torch.bfloat16)
and scale.dim() == 2
@@ -687,6 +688,18 @@ def _nvfp4_matmul_bwd(
return torch.matmul(grad, nvfp4_dequantize(packed, scale, global_scale, grad.dtype))
+_AUTOCAST_CASTS = (torch.float16, torch.bfloat16, torch.float32)
+
+
+def _autocast_operand(X):
+ # Cast outside the opaque op so fused, dense and fake impl all return the autocast dtype.
+ if X.is_cuda and X.dtype in _AUTOCAST_CASTS and torch.is_autocast_enabled("cuda"):
+ dtype = torch.get_autocast_dtype("cuda")
+ if dtype != X.dtype:
+ return X.to(dtype)
+ return X
+
+
class NVFP4Linear_matmul(torch.autograd.Function):
@staticmethod
def forward(
@@ -697,7 +710,7 @@ class NVFP4Linear_matmul(torch.autograd.Function):
global_scale,
bias = None,
):
- output = _nvfp4_matmul_fwd(X, packed, scale, global_scale)
+ output = _nvfp4_matmul_fwd(_autocast_operand(X), packed, scale, global_scale)
if bias is not None:
output = output + bias
# A float32 bias promotes; cast back only then (a no-op .to() aliases, zeroing dX under torch 2.11 compile).