Skip to content

NVFP4 fused GEMM: honor autocast dtype and check K alignment for dX - #14625

Merged
danielhanchen merged 3 commits into
mainfrom
nvfp4-fused-autocast
Oct 22, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
nvfp4-fused-autocast

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

Two issues in the NVFP4 fused decode GEMM added in #13840 (gate refined in #14122 and #14536).

  1. Fused forward ignores autocast. The dense path it replaced is torch.matmul(X, W.t()), which autocast runs in the autocast dtype. The fused Triton GEMM allocates its output in X.dtype and never looks at autocast. With fp16 activations under bf16 autocast, the result comes back as fp16 and overflows where the dense path returned finite bf16. bf16 activations under fp16 autocast flip the other way.

    Repro: fp16 X of shape [4, 128] filled with 1000, packed weights 0x22 (every decoded weight is 1), unit scales, torch.autocast("cuda", dtype=torch.bfloat16):

    before NVFP4: decode weight tiles inside the GEMM for small-batch forward and dX #13840 (dense) main (fused) this PR (fused)
    output dtype bf16 fp16 bf16
    output value 128000 inf 128000
    loss 1.6384e10 inf 1.6384e10
    grad X finite yes no yes

    The same happens through a PEFT LoRA wrapper (LoRA B grad non finite on main, finite before NVFP4: decode weight tiles inside the GEMM for small-batch forward and dX #13840 and with this PR). The bf16 input / fp16 autocast case now also matches the dense result exactly (fp16 output, as dense gives).

  2. Fused dX skips the K alignment check. _fused_ok checks inner % 64 and N % 64. In the forward pass inner is K, but in dX it is N, so K was never checked. A weight with N=4096, K=4112 was refused fused forward but accepted for fused dX on sm80, sm89 and sm120, the shape class NVFP4: decode weight tiles inside the GEMM for small-batch forward and dX #13840 measured as up to 2.8x slower than dense in dX.

Change

  • NVFP4Linear_matmul.forward casts X to the active CUDA autocast dtype before calling the matmul op, outside the opaque torch.library op. The fused path, the dense path and the fake impl then all return the autocast dtype, and grad_X is still returned in X.dtype as before. Without autocast nothing changes. Autocast state is already a dynamo guard, so no new graph breaks or recompiles.
  • _fused_ok checks N and K alignment directly (packed.shape[0] % 64 and packed.shape[1] % 32) in both directions. UNSLOTH_NVFP4_FUSED=1 still forces the fused path past the check.

Validation

B200 (fused path forced with UNSLOTH_NVFP4_FUSED=1, as the existing tests do; dispatch for sm80 / sm89 / sm120 checked by monkeypatching the capability).

  • New tests, failing on main and passing here:
    • test_autocast_dtype_matches_dense (fp16 under bf16 and bf16 under fp16): fused output and grad equal the dense path bit for bit, dtype included. 2 of 2 fail on main.
    • test_autocast_random_weights_match_dense_and_oracle (fp16 / bf16 / fp32 inputs): fused vs dense vs fp64 oracle, forward and dX. 3 of 3 fail on main (the fp32 case because main never runs fused for fp32 inputs; under autocast they now take the bf16 fused kernel, like the dense path computes in bf16).
    • test_autocast_fullgraph_compile_has_no_graph_break: 0 graph breaks, compiled output bf16 and equal to eager. Fails on main (compiled output fp16).
    • test_unaligned_k_stays_dense_in_both_directions (sm80, sm89, sm120, forward and dX): the 3 dX cases fail on main.
  • NVFP4 test files (tests/test_nvfp4*.py, GPU tests included):
    • torch 2.14.1 / Triton 3.8.0: 166 passed, 5 skipped, 1 failed. The failure, test_nvfp4_loader.py::test_peft_merge_dequantizes_the_routed_base[nvfp4-True], fails the same way on main (pre-existing, not touched here).
    • torch 2.10.0 / Triton 3.6.0: 111 passed, 4 skipped.
  • torch.compile (forward + backward, rows 16 / 32 / 48 / 64 / 64, dynamic): 0 graph breaks, 2 graphs, 0 recompiles on main and here, with and without bf16 autocast, on both torch versions. Under autocast the compiled output is fp16 on main and bf16 here.
  • Existing fp64 oracle tests for the non autocast path pass unchanged.
  • Speed, no autocast (bf16, 4096 x 4096 weight, forced fused, eager, 7 interleaved repeats of 500 calls, median per call): M=1 117.6 us vs 118.2 us on main, M=16 107.6 us vs 107.8 us. Same within noise.

Not covered

_fused_ok checked inner % 64 and N % 64. In the forward pass inner is K,
but in dX it is N, so an unaligned K (for example N=4096, K=4112) passed
the auto gate and took the fused dX kernel, which #13840 measured as up
to 2.8x slower than dense on unaligned shapes. Check N and K directly in
both directions. UNSLOTH_NVFP4_FUSED=1 still forces fused.
…ul does

The dense path is torch.matmul, which autocast runs in the autocast
dtype. The fused Triton GEMM (#13840) allocates its output in X.dtype
and ignores autocast, so fp16 activations under bf16 autocast came back
as fp16 and overflowed where the dense path returned finite bf16 (fp16
1000s against unit weights: 128000 before, inf after), also through a
PEFT LoRA wrapper; bf16 activations under fp16 autocast flipped the
other way.

Cast X to the autocast dtype in NVFP4Linear_matmul.forward, outside the
opaque op, so the fused path, the dense path and the fake impl all
return that dtype and grad_X keeps X's dtype as before. Autocast state
is a dynamo guard: fullgraph compile under autocast stays at 0 graph
breaks. Without autocast nothing changes.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-22T09:17:40.102264Z 1aac00f Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 1aac00f486

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit d302a58 into main Oct 22, 2026
@danielhanchen
danielhanchen deleted the nvfp4-fused-autocast branch October 22, 2026 09:19
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 22, 2026
unslothai#14750)

## Problem

Since unslothai#14625, `nvfp4_linear` returns the CUDA autocast dtype, matching
the dense matmul it replaces. That is right for the autograd path, but
two inference callers work in the activation dtype and use in-place or
`out=` ops, which PyTorch does not autocast. With fp16 activations under
bf16 autocast (or bf16 under fp16), on the fused path:

- `fast_linear_forward` with LoRA (decode, batch 1 and 2) updates the
NVFP4 output in place with LoRA operands cached in `X.dtype`:
- `addmv input tensors must have the same dtype, but got BFloat16, Half,
and Half` (batch 1)
- `self and mat2 must have the same dtype, but got BFloat16 and Half`
(batch 2)
- Llama decode attention (`LlamaAttention_fast_forward_inference`, batch
1) allocates its KV and score buffers in the hidden-state dtype and runs
`_gqa_decode_scores` with `out=`:
  - `expected scalar type BFloat16 but found Half` (llama.py:607)

Before unslothai#14625 the fused kernel returned `X.dtype`, so both callers
worked.

A second, older issue: with a bias, `NVFP4Linear_matmul.forward` cast
the result back to `X.dtype` after the bias add. A direct
`nvfp4_linear(X_fp16, ..., bias)` under bf16 autocast still returned
fp16 and overflowed to `inf` where `F.linear` returns finite bf16.

## Change

- `fast_linear_forward`: cast the NVFP4 result back to `X.dtype` when it
differs. This is the decode contract (buffers, LoRA scratch and cached
LoRA weights are all `X.dtype`), and the cast only runs under mixed
autocast. Without autocast nothing changes.
- `NVFP4Linear_matmul.forward` with a bias: keep the compute dtype (the
autocast dtype under autocast, else `X.dtype`). A float32 bias still
promotes and is cast back to the compute dtype, and the cast is still
skipped when the dtype already matches. Without autocast the output
dtype is unchanged. The compressed-tensors forward adds its bias outside
the op and already follows `out.dtype`.
- The training path from unslothai#14625 is unchanged: `nvfp4_linear` without a
bias still returns the autocast dtype, `grad_X` is still `X.dtype`.

Other callers checked: `matmul_lora` and the fused LoRA MLP/QKV/O
kernels dequantize NVFP4 weights and never call `nvfp4_linear`; all
Llama decode projections go through `fast_linear_forward`; the Studio
diffusion NVFP4 module is a separate implementation.

## Validation

B200, fused path forced with `UNSLOTH_NVFP4_FUSED=1` as the existing
tests do. New `tests/test_nvfp4_autocast_callers.py`, base = current
main:

| Test | main | this PR |
|---|---|---|
| `fast_linear_forward` LoRA decode, fp16 / bf16 autocast, batch 1 and 2
| 2 fail | 2 pass |
| `fast_linear_forward` LoRA decode, bf16 / fp16 autocast, batch 1 and 2
| 2 fail | 2 pass |
| Llama decode attention, batch 1, both mixed cases | 2 fail | 2 pass |
| Llama decode attention, batch 2 (SDPA), both mixed cases | 2 pass | 2
pass |
| `nvfp4_linear` with fp16 / fp32 bias, fp16 `X` under bf16 autocast, vs
`F.linear` | 2 fail | 2 pass |
| No autocast with a bias keeps `X.dtype` | pass | pass |

Each caller test checks that the fused kernel ran for every projection,
the output dtype and the result against an fp64 reference.

NVFP4 and decode test files (`tests/test_nvfp4*.py`,
`tests/test_decode_gqa_in_place.py`, `tests/test_decode_fused_rope.py`,
GPU tests included):

| Env | main | this PR |
|---|---|---|
| torch 2.14.0 / Triton 3.8.0 | 146 passed, 8 failed (the new tests), 5
skipped | 154 passed, 5 skipped |
| torch 2.10.0 / Triton 3.6.0 | 203 passed, 10 failed, 3 skipped | 211
passed, 2 failed, 3 skipped |

The 2 remaining torch 2.10 failures,
`test_nvfp4_loader.py::test_lora_trains_on_the_packed_base_and_reloads[qwen3_5-*-False]`,
fail the same way on main.

torch.compile (`CompileCounter` plus `torch._dynamo.explain`, torch
2.14): `nvfp4_linear` forward and backward over rows 16 / 32 / 48 / 64 /
64 with `dynamic=True`, with and without a bias, with and without bf16
autocast, and `fast_linear_forward` decode with and without autocast: 0
graph breaks everywhere, and the same frame counts as main (2 for
`nvfp4_linear`, 1 for `fast_linear_forward`).

## Not covered

- `fast_linear_forward` with LoRA and no `temp_lora` scratch under mixed
autocast fails on every weight type (dense included), before and after
unslothai#14625: `torch.mv` / `torch.mm` autocast the LoRA product. That is an
older limitation and is not changed here.
- Decode outputs stay in the activation dtype, so a fp16 decode under
bf16 autocast can still overflow the same way a dense fp16 decode does.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant