Skip to content

FP8: skip the compiled wrapper for rowwise FP8 inference linears - #15584

Merged
danielhanchen merged 13 commits into
mainfrom
fp8-rowwise-overhead
Oct 28, 2026
Merged

danielhanchen merged 13 commits into
mainfrom
fp8-rowwise-overhead

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

fbgemm_fp8_linear (FbgemmFp8Linear checkpoints, compressed-tensors per-channel FP8 with UNSLOTH_COMPRESSED_TENSORS_FP8_KERNELS=1, and fp8_linear from matmul_lora / fast_linear_forward) was a torch.compiled function. Every call paid the compiled-call floor before any kernel ran: a compiled x + 1 alone costs 74 to 94 us on a Colab L4 host, and fbgemm_fp8_linear measured 120 to 170 us per call while its GPU work at decode and small prefill sizes is 10 to 80 us. Batch 32 decode of Qwen3-1.7B-FP8-dynamic makes 196 of these calls per token, so the linears were launch bound.

Change

  • The compiled body is now _fbgemm_fp8_linear_compiled; fbgemm_fp8_linear is a plain function in front of it.
  • When the call is not being traced, needs no autograd, and is a CUDA (non ROCm) bf16 / fp16 activation against a contiguous e4m3fn (N, K) weight with a contiguous (N, 1) scale, at most 4096 rows, and the backend is not FBGEMM, it launches the kernels Inductor would have generated directly:
    • more than 64 rows, N and K divisible by 16 (the existing scaled_mm branch): a one-launch Triton per-row activation quant (_fp8_act_quant_per_row_kernel) plus torch._scaled_mm;
    • otherwise (the existing dequant branch): a one-launch Triton dequant (_fp8_rowwise_dequant_kernel, fp32 multiply, one rounding, as Inductor fuses it) plus torch.matmul.
  • Outputs are bitwise equal to the compiled path, including NaN / inf rows, input_scale_ub, fp32 bias and fp16 activations.
  • Training (X requires grad), a user's torch.compile, the FBGEMM backend, transposed weight views, more than 4096 rows, ROCm and XPU all call the compiled wrapper exactly as before. UNSLOTH_FP8_ROWWISE_DIRECT=0 turns the new path off.
  • Routing thresholds (64 rows for scaled_mm vs dequant) are unchanged, so numerics are unchanged.

Results

RedHatAI/Qwen3-1.7B-FP8-dynamic, FastLanguageModel.for_inference, greedy, 64 new tokens. Base = main b6fc821, base and head interleaved in fresh processes with fresh compile caches, 3 reps each, median. A/A is the spread of the 3 base reps.

GPU, torch decode bsz 32 tok/s decode bsz 1 tok/s prefill bsz 1 x 1024 prefill bsz 4 x 512 prefill bsz 8 x 1024
L4, 2.10.0 449.6 -> 548.9 (+22.1%, A/A 0.9%) 23.1 -> 23.5 (+1.6%, A/A 2.8%) 83.7 -> 79.0 ms (-5.7%) 113.3 -> 111.3 ms (-1.8%) 515.9 -> 529.5 ms (+2.6%, A/A 2.0%)
L4, 2.14.1 466.2 -> 551.3 (+18.2%, A/A 3.1%) 22.6 -> 23.0 (+1.9%, A/A 4.8%) 80.0 -> 75.6 ms (-5.5%) 110.5 -> 109.3 ms (-1.1%) 506.1 -> 514.1 ms (+1.6%, A/A 2.6%)
RTX PRO 6000 (G4), 2.14.1 1846.8 -> 2201.0 (+19.2%, A/A 2.5%) 90.3 -> 91.2 (+1.0%) 19.0 -> 17.8 ms (-6.1%) 21.1 -> 19.3 ms (-8.6%) 68.2 -> 68.1 ms (-0.2%, A/A 0.2%)

Greedy sequences and last-token prefill logits are bitwise identical base vs head in every cell. The bsz 8 x 1024 prefill rows (8192 rows per linear) run the unchanged compiled path in both arms; the L4 differences there are within its run to run spread.

Per call (synthetic weights of Qwen3-1.7B and Llama-3-8B linear shapes, no grad, median us):

base head
L4 2.10, Qwen3-1.7B shapes, M 17 to 64 118 to 136 110 to 115
L4 2.10, Qwen3-1.7B shapes, M 128 to 512 133 to 137 127 to 133
G4 2.14, Qwen3-1.7B shapes, M 17 to 64 23.6 to 26.7 22.7 to 26.5
G4 2.14, host bound Qwen3-1.7B cases, M 128 to 2048 28.0 to 33.0 30.8 to 36.0
Llama-3-8B 14336 x 4096, M 17 to 64 (GPU bound) 1172 to 1192 (L4), 151 to 157 (G4) +0.4 to +0.5% (L4), +0.6 to +2.0% (G4)

On the G4 host the isolated scaled_mm route at 128 to 2048 rows is about 3 us slower per call than a hot single-entry compiled call (Triton launch plus eager _scaled_mm dispatch), while inside the model the same route makes prefill 6 to 9% faster there. One shape, Llama-3-8B 14336 x 4096 at M 128, reads +7 to +8% in the L4 sweep (G4: -5%); interleaving compiled and direct in one process on L4 gives 303 vs 304 us wall and 281 vs 277 us of kernel time, so I read it as L4 clock drift across the sweep, but it is not proven.

Checks

  • torch.compile(fullgraph=True) around fp8_linear and fbgemm_fp8_linear: 0 graph breaks, output bitwise equal to the eager call (L4 2.10 / 2.14, G4 2.14).
  • New tests/test_fp8_rowwise_direct_route.py: routing on fake CUDA tensors (runs on CPU, fails on main where no eager route exists), plus an sm89+ parity test against the compiled wrapper over several shapes (including K = 16400, the looped quant path), bf16 / fp16, fp32 / bf16 scales, bias, input_scale_ub, NaN and inf rows.
  • FP8 tests run on L4 (2.10.0, 2.14.1) and G4 (2.14.1): test_fp8_rowwise_direct_route, test_fp8_rowwise_backend, test_fp8_compile_fullgraph, test_compressed_tensors_fp8_kernel_route, test_fp8_device_gate, test_fp8_rowwise_gemv_rows, test_fp8_transposed_weight, test_fp8_fp16_scale_rounding, test_fp8_scale_dequant_one_pass: 278 passed, 2 skipped (FBGEMM not installed) on head; on main only the new file fails.

Not covered

  • FBGEMM backend GPUs (H100 with fbgemm-gpu-genai): the new path is not taken there by design; not run.
  • torch 2.6 to 2.9 (Triton 3.2 to 3.5), multi-GPU placement, ROCm and XPU (excluded by the route).

A compiled fbgemm_fp8_linear call costs 75-95 us of host time before any kernel runs,
which dominates decode and small prefill. Without autograd and outside a trace, launch
the kernels Inductor generates directly (per-row activation quant + _scaled_mm above 64
rows, fused dequant + matmul below), bitwise equal to the compiled path.
@danielhanchen danielhanchen self-assigned this Oct 27, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 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-28T07:31:06.442277Z 2aeda42 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0b8e619cd4

ℹ️ 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".

Comment thread unsloth/kernels/fp8.py Resolved
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: e7f23689d6

ℹ️ 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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 2aeda42e55

ℹ️ 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 772bff9 into main Oct 28, 2026
3 of 34 checks passed
@danielhanchen
danielhanchen deleted the fp8-rowwise-overhead branch October 28, 2026 15:58
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…6-bit weight spills L2 (sm89) (#15791)

Follows #15584 (merged).

## Summary

With the `scaled_mm` rowwise FP8 backend (sm89+ without FBGEMM, e.g.
L4), calls with 17 to 64 rows dequantize the weight to 16 bits on every
call and run a 16-bit GEMM. That is the right choice while the 16-bit
copy fits in L2: the call is launch bound and dequant is about 25 us
cheaper than activation quant plus `torch._scaled_mm`. Once the 16-bit
copy is larger than L2 the per-call dequant becomes memory bound, and on
L4 a Llama-3.1-8B MLP projection costs about 1180 us on the dequant
route against 255 to 300 us on `torch._scaled_mm`.

This PR sends 17 to 64 rows to activation quant plus `torch._scaled_mm`
only when `N * K * 2` bytes exceeds the device L2
(`get_device_properties().L2_cache_size`, cached per device and treated
as a constant under `torch.compile`). Everything else keeps the current
64 row threshold: 16 rows and below, more than 64 rows, an unknown L2,
and every L2-resident weight. `UNSLOTH_FP8_DEQUANT_MAX_ROWS=N` sets a
single threshold for every weight.

Which GPUs this touches: the backend is picked by a runtime probe. With
`fbgemm_gpu` installed and working (for example H100 with FBGEMM), the
FBGEMM backend is used. It quantizes activations at every row count, so
this PR does not change it. Without FBGEMM, sm89+ GPUs where
`torch._scaled_mm` rowwise works take the `scaled_mm` backend. The
large-weight gate only applies on sm89 (L4, RTX 40xx), the arch it was
measured on: the L2 probe reports 0 elsewhere, so H100 without FBGEMM
(50 MiB L2), RTX PRO 6000 / RTX 50xx and any other arch keep the 64 row
default exactly as in #15584.

## Decode throughput (tok/s, 64 new tokens, greedy)

L4, torch 2.14.1+cu130. Base is #15584 (now on main). Each side ran as 3
interleaved processes. torch 2.10 was not measured for this change.

| Model | Batch | Base | This PR | Change | Base A/A spread |
|---|---|---|---|---|---|
| Llama-3.1-8B-Instruct-FP8-dynamic | 24 | 171 | 326 | +90% | 0.4% |
| Llama-3.1-8B-Instruct-FP8-dynamic | 32 | 225 | 431 | +92% | 0.4% |
| Llama-3.1-8B-Instruct-FP8-dynamic | 48 | 321 | 639 | +99% | 0.3% |
| Qwen3-1.7B-FP8-dynamic | 24 / 32 / 48 | 393 / 531 / 792 | 393 / 528 /
784 | within noise | |

Routing counts per generate call:
- Llama: base makes 14112 dequant and 224 scaled_mm calls; this PR makes
8064 dequant and 6272 scaled_mm calls. Only the MLP projections move:
14336x4096 and 4096x14336, 112 MiB each in bf16. Attention projections
stay on dequant.
- Qwen3-1.7B: identical on both sides (12348 dequant, 196 scaled_mm). No
layer exceeds L4's 48 MiB L2.

RTX PRO 6000 (sm120, 128 MiB L2): no weight of either model exceeds L2.
Routing, outputs (logits KL 0, identical greedy tokens) and throughput
are unchanged (Llama 1101 / 1448 / 2069 tok/s on both sides).

## Accuracy (Llama-3.1-8B FP8-dynamic, L4)

- **Per-layer relative error vs an fp32 GEMM of the same quantized
weights** (median over 224 layers, real activations): dequant 0.0022 and
scaled_mm 0.0218 at every row count from 17 to 512. The 17 to 64 row
error is the same as what the existing above-64 route already has.
- **Greedy decode, 64 tokens:** dequant at decode vs this PR agree on
53% of tokens at batch 24 and 61% at batch 32. At batch 80, where the
base already uses `torch._scaled_mm`, the same comparison gives 58%.
- **Last-token logits:** top-1 is unchanged at every length tested.

## fp16 output fix (also on main above 64 rows)

On torch 2.10, rowwise `torch._scaled_mm` picks its CUTLASS output
element type from the bias dtype. With no bias it writes bf16 bits into
an `out_dtype=torch.float16` buffer, so every fp16 call that reaches
`_scaled_mm` returns garbage. On main this already happens for fp16
calls above 64 rows. With an all-ones input (Llama-8B 14336x4096), every
output should be 4096 but comes back as 5.5. torch 2.14 is correct.

`_scaled_mm_out_dtype` requests bf16 for fp16 activations at both call
sites (`_fp8_rowwise_direct` and `FbgemmFp8Linear_matmul`). The existing
tail already casts to the activation dtype.

Colab L4, Llama-8B 14336x4096, against an fp32 reference of the
dequantized weight:

| torch | dtype | M | main | this PR |
|---|---|---|---|---|
| 2.10 | fp16 | 128 (all-ones) | max abs 4090, output 5.5 | 0 |
| 2.10 | fp16 | 128 (random) | rel 6.03 | rel 2.65e-2 |
| 2.10 / 2.14 | bf16 | 32 (forced scaled_mm), 128 | rel 2.66e-2 |
bitwise identical |
| 2.14 | fp16 | 128 (random) | rel 2.65e-2 | rel 2.65e-2 (last-bit
differences from the extra rounding) |

- **bf16 per-call time** is unchanged: 309-319 us at M=128 on both
sides, on torch 2.10 and 2.14.
- **Tests:** `test_scaled_mm_asks_for_bf16_when_activations_are_fp16`
checks the dtype mapping.
`test_every_rowwise_scaled_mm_call_uses_the_out_dtype_helper` checks
that every data `_scaled_mm` call goes through the helper.

## Tests

`tests/test_fp8_dequant_max_rows.py` runs on CPU with fake tensors. It
checks:
- a Qwen-sized weight stays on dequant at 17 to 64 rows;
- a Llama-8B MLP weight moves to `torch._scaled_mm`;
- 16 and 65 rows are unchanged;
- an unknown L2 keeps 64;
- the env override and its parser;
- the L2 probe fallback, and that it reports 0 (gate off) on sm90 and
sm120;
- the `FbgemmFp8Linear_matmul` autograd path uses the same gate.

All of them fail on #15584, which has no gate. The direct-path parity
test now asks the route helper for the threshold instead of hard-coding
64.

## Not measured

- H100 without FBGEMM (`scaled_mm` backend, 50 MiB L2). Colab did not
grant an H100 within 25 minutes, so the gate is off there and H100
behaves as in #15584. Enabling it needs H100 numbers.
- RTX 40xx (sm89, gate on) was not measured; only L4 was.
- torch 2.10 with the gated route. The earlier per-call measurements of
both routes on L4 agreed between torch 2.10 and 2.14.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…ners (#15838)

On the AMD gfx1151 runner (ROCm 7.13, torch 2.11), 11 FP8 routing tests
from #15584 and #15791 fail:
- 6 in `tests/test_fp8_dequant_max_rows.py`: `assert None == 'dequant'`;
- 5 in `tests/test_fp8_rowwise_direct_route.py`: `assert 'compiled' ==
'direct'`.

`_fp8_rowwise_direct_route` deliberately keeps the direct path off on
ROCm (`torch.version.hip is None`). The tests check the NVIDIA routing
table but read the real `torch.version.hip`, so on a ROCm build the
route they expect never happens. FP8 outputs on that card are
bit-identical before and after those PRs, and the routing did not
change.

### Change
- Both routing fixtures pin `torch.version.hip = None`, so the NVIDIA
routing table is tested on every runner.
- New `test_rocm_keeps_the_compiled_path` sets a HIP version and checks
that inference calls at 32 and 128 rows stay on the compiled path.

### Tests
- On CPU: 22 passed, 2 skipped.
- With `torch.version.hip = "7.0"` set before pytest (simulating the
ROCm runner): main fails exactly these 11 tests (11 failed, 10 passed),
and this branch passes all 22.
danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Nov 1, 2026
…ed autocast (unslothai#15927)

Follow-up to unslothai#15584 (direct rowwise FP8 path) and unslothai#15791 (sm89
large-weight row threshold, fp16 `_scaled_mm` workaround). A recheck
found three correctness gaps. Two independent reviewers reproduced each
one on a B200. The first one, fp16 output rounded through bf16 on torch
2.14, is fixed on main by unslothai#16063. This branch now merges main and uses
its `_SCALED_MM_FP16_OUT_BROKEN` check (torch < 2.14, pre-releases of
2.14 included). This PR fixes the other two.

## 1. float32 activations sent to rowwise `_scaled_mm` before torch 2.14
(unslothai#15791)

Rowwise `_scaled_mm` accepts only bf16 / fp16 outputs on torch 2.10 -
2.13. On sm89 the new threshold sends 17 - 64 row calls with an over-L2
weight to `_scaled_mm`, so float32 activations there fail with
"out.dtype must be BFloat16 or Half". Before torch 2.14 they now keep
the dequant path, gated on the same `_SCALED_MM_FP16_OUT_BROKEN` check
as the fp16 workaround. That also covers the same failure above 64 rows,
which predates unslothai#15791. torch 2.14 can write float32, so it is unchanged.

## 2. Direct path under autocast in another dtype (unslothai#15584)

The direct path dequantizes into a buffer of X's dtype and then calls
`matmul`, which autocast may run in another dtype. The compiled path
fuses the dequant into autocast's GEMM. With fp16 X under bf16 autocast,
a finite weight times scale above 65504 overflows the fp16 buffer first:

| fp16 X = 1e-4, W = 1, row scale 1e5, bf16 autocast | before unslothai#15584 |
main |
|---|---|---|
| outputs | 5120 (finite) | inf / NaN |

Random inputs also differ from the compiled result, by up to 0.25 abs.
The direct route now returns None when CUDA autocast is enabled with a
dtype different from X's, so those calls keep the compiled path.
Same-dtype autocast and no autocast are unchanged.

## Tests

The CPU tests in `tests/test_fp8_dequant_max_rows.py` route through
FakeTensorMode. They sit beside the fp16 out dtype tests from unslothai#16063:
- float32 keeps dequant while the fp16 output is broken (before 2.14)
and keeps `_scaled_mm` after it;
- mismatched autocast keeps the compiled path, while matching autocast
still takes the direct path.

Results after merging main (9a1ea09):
- With main's `fp8.py`, 2 of the new cases fail (float32 gate, fp16 X
under bf16 autocast).
- With this PR, `test_fp8_dequant_max_rows.py` and
`test_fp8_rowwise_direct_route.py` give 29 passed, 2 skipped (CUDA
only).
- All `tests/test_fp8_*.py`, `tests/test_fp8linear_*.py` and
`tests/test_compressed_tensors_fp8_kernel_route.py` on torch 2.13 CPU:
328 passed, 470 skipped (CUDA only).

## GPU results (before merging main)

These runs predate the merge with main. Base = merge base fa7ad0d,
which still had the fp16 bf16 round trip on every torch version. The
fp16 rows of the earlier runs are now main's behaviour (unslothai#16063), so only
the rows below belong to this PR.

Colab L4, sm89, scaled_mm backend. One VM, each torch version in its own
uv venv, deleted between versions.

| case | 2.10 base | 2.10 head | 2.14 base | 2.14 head |
|---|---|---|---|---|
| bf16 autocast, fp16 X = 1e-4, scale 1e5 (ref 5120.85) | inf | 5120 |
inf | 5120 |
| float32 X, 32 rows, 14336 x 4096 | ValueError | dequant, rel err
4.4e-7 | scaled_mm, rel err 0.026 | bitwise equal to base |

Colab H100 80GB, sm90, same scripts and arms, torch 2.10.0 and 2.14.1:

| case (public `fbgemm_fp8_linear`) | 2.10 base | 2.10 head | 2.14 base
| 2.14 head |
|---|---|---|---|---|
| bf16 autocast, 16 rows, fp16 X = 1e-4, scale 1e5 (ref 5120.85) | inf |
5120 | inf | 5120 |
| bf16 autocast, 128 rows (scaled_mm) | 4896 | 4896 (same) | 4896 | 4912
|
| float32 X, 32 rows, 14336 x 4096 | dequant, rel err 8.1e-7 | same |
same | same |

- bf16 outputs are bitwise equal base vs head on both torch versions and
both GPUs.
- On sm90 the 32-row float32 call already took the dequant path on base,
so the L4's ValueError does not occur there.
- The 2.14 head runs above used a final release (2.14.1). Main's check
also keeps the bf16 detour on 2.14 pre-releases. On those, float32
activations take the dequant path as well.

Unchanged by this PR: calling `FbgemmFp8Linear_matmul.apply` directly in
eager mode under a mismatched autocast still overflows, the same as
main. The guard covers the public `fbgemm_fp8_linear` direct route.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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