Repository navigation
NVFP4 fused GEMM: honor autocast dtype and check K alignment for dX - #14625
Merged
Merged
Conversation
_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.
Member
Author
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Chef's kiss. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Two issues in the NVFP4 fused decode GEMM added in #13840 (gate refined in #14122 and #14536).
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 inX.dtypeand 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
Xof shape[4, 128]filled with 1000, packed weights0x22(every decoded weight is 1), unit scales,torch.autocast("cuda", dtype=torch.bfloat16):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).
Fused dX skips the K alignment check.
_fused_okchecksinner % 64andN % 64. In the forward passinneris 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.forwardcastsXto the active CUDA autocast dtype before calling the matmul op, outside the opaquetorch.libraryop. The fused path, the dense path and the fake impl then all return the autocast dtype, andgrad_Xis still returned inX.dtypeas before. Without autocast nothing changes. Autocast state is already a dynamo guard, so no new graph breaks or recompiles._fused_okchecks N and K alignment directly (packed.shape[0] % 64andpacked.shape[1] % 32) in both directions.UNSLOTH_NVFP4_FUSED=1still 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).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.tests/test_nvfp4*.py, GPU tests included):test_nvfp4_loader.py::test_peft_merge_dequantizes_the_routed_base[nvfp4-True], fails the same way on main (pre-existing, not touched here).Not covered
X.dtypeafter the bias add, exactly as before NVFP4: decode weight tiles inside the GEMM for small-batch forward and dX #13840 (dense and fused alike). Only the bias-free path changes dtype under autocast.