Skip to content

NVFP4 fused dX: skip split K on sm89 when the output already fills the GPU - #14536

Merged
danielhanchen merged 1 commit into
mainfrom
nvfp4-split-policy
Oct 21, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
nvfp4-split-policy

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

On L4 (sm89), the fused NVFP4 dX kernel with up to 32 rows runs 11 to 17% faster without split K once its output tiles alone cover every SM. For a Llama-3-8B / Qwen3-8B down_proj dX, _fused_config picked split 4 there.

Change

In _fused_config (unsloth/kernels/nvfp4.py), a dX call on sm89 with M <= 32 whose output tiles are at least the SM count returns split 1. Unchanged:

  • every other arch;
  • the forward split policy;
  • M > 32;
  • narrower outputs;
  • _FUSED_ROW_GATE. Every changed cell was already routed to the fused kernel, so no fused vs dense decision moves.

Validation

Device time per call, L2 flushed before each call and a GPU sleep queued first, so host time is not in the interval. Arms in fresh processes, 3 repeats, an A/A arm with a 3x longer sleep. Split 1 / current, below 1 = faster:

GPU phase shapes M split 1 / current A/A
L4 dX down (4096 x 14336, 4096 x 12288) 1 to 32 0.83 to 0.89, 32 of 32 cells, torch 2.10 and 2.14, bf16 and fp16 1.4% or less
L4 dX q / kv / up 1 to 32 median 1.15 (kept) 4.3% or less
L4 fwd 6 projection shapes 1 to 256 median 1.08 to 1.10 (kept) 5.8% or less
A100 dX down 1 to 32 1.17 to 1.52 (kept) 1.5% or less
A100 fwd and dX 6 shapes 1 to 256 median 1.17 to 1.99 (kept) 8.6% or less

An earlier back-to-back timing showed split 1 as 1.3 to 1.47x faster on both GPUs at M = 32 and 128. That was host time: on Colab CPUs one call costs about 160 to 200 us of launch overhead, more than the kernel. Split 1 saves the partials allocation and the split-sum launch (about 45 us). Measured as kernel time it reverses on A100, so the rule stays narrow.

Tests:

  • tests/test_nvfp4_fused_gate_shape.py: 7 CPU cases with capability and SM count faked, for the new rule and for the paths it must leave alone (forward, A100, sm120, M = 64, narrow outputs). 2 fail on main.
  • tests/test_nvfp4_fused_gemm.py::test_sm89_unsplit_dx_matches_split: the unsplit dX matches split 4 under the existing tolerances.
  • The six NVFP4 test files on Colab A100 and L4, torch 2.10.0 and 2.14.1: 135 passed on main, 146 here. All new tests pass and no shared test changes status.
  • The same 11 failures appear on both sides, unrelated to this change:
    • 7 loader tests, from a notebook without bitsandbytes; they pass 31 / 31 on both sides with it.
    • 4 runs of test_split_reduction_matches_unsplit, which is order dependent through monkeypatch.undo().
  • torch.compile: 0 graph breaks and 0 recompiles on both sides, A100 and L4, both torch versions.

Kernel time through the real code, L4, main / this PR / main:

  • all 16 changed cells (both torch versions, both dtypes, M 1 to 32) run at 0.831 to 0.904 of main;
  • the 64 unchanged cells per torch version stay at 0.985 to 1.014;
  • A/A spread is 0.5% or less on the changed cells.

End to end, LoRA SFT step time (median of steps 10 to 40), main / this PR / main:

GPU / model path main this PR main again fused fwd / dX calls
L4 / RedHatAI Llama-3.1-8B NVFP4 FastModel, 32 tokens 389.0 ms 377.3 ms 376.5 ms 18144 / 8960
A100 / TinyLlama-1.1B NVFP4A16 FastModel, 32 tokens 234.9 ms 233.6 ms 228.8 ms 12474 / 0
  • The new rule runs on L4 (8960 fused dX calls). The saving is about 0.9 ms per step (28 us x 32 down layers), below the run to run spread, so it is not visible end to end at this size.
  • Losses match to the 4th decimal (fp32 summation order).

Not covered:

  • other sm89 parts (RTX 40xx, L40S, which have more SMs; the rule is keyed on the SM count but was only measured on L4);
  • RTX PRO 6000, H100 and T4 (not swept; unchanged);
  • MoE expert widths (only the 6 dense projection shapes were measured).

…e GPU

On L4 (sm89) the fused dX kernel with up to 32 rows runs 11-17% faster
unsplit once its output tiles alone cover every SM (the Llama-3-8B /
Qwen3-8B down_proj dX: split 4 -> 1). Measured as device time with a cold
L2 on torch 2.10 and 2.14, bf16 and fp16, beyond the A/A spread in every
cell. A100 keeps split K there (split 1 is 1.2-1.5x slower), and the
forward split policy is unchanged on every GPU.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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 ⚠️ Failed 2026-10-21T16:39:35.951963Z
We couldn’t complete this review. Comment @codex review to try again.
ed94697 PR opened
🔒 Security Review ⚠️ Failed 2026-10-21T16:39:24.261990Z
We couldn’t complete this review. Comment @codex security review to try again.
ed94697 PR opened
ℹ️ 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

The account paying for this security review has reached its Codex usage limits. The payer can check the Codex usage dashboard. For personal accounts, using credits requires enabling “Use credits for security reviews” in Code review settings. If you do not manage the paying account, contact this repository's admins.

@danielhanchen
danielhanchen merged commit 0b124ea into main Oct 21, 2026
@danielhanchen
danielhanchen deleted the nvfp4-split-policy branch October 21, 2026 16:56
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 22, 2026
…nslothai#14625)

## Problem

Two issues in the NVFP4 fused decode GEMM added in unslothai#13840 (gate refined
in unslothai#14122 and unslothai#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 unslothai#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 unslothai#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 unslothai#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

- No A100 / L4 / RTX PRO 6000 run, so the dX slowdown on unaligned K
that the gate now avoids is unslothai#13840's measurement, not re measured here.
- Backward run inside an autocast region (not recommended by PyTorch)
still computes fused dX in the grad dtype; with the forward fix, the
grad dtype is already the autocast dtype in the normal flow.
- Non CUDA devices are unchanged (the fused path is CUDA only).
- With a bias, the output is still cast back to `X.dtype` after the bias
add, exactly as before unslothai#13840 (dense and fused alike). Only the
bias-free path changes dtype under autocast.
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