Skip to content

FP8 block GEMM: find torchao 0.18 blockwise_fp8_gemm and route each call to the faster kernel - #15153

Merged
danielhanchen merged 4 commits into
mainfrom
torchao-blockwise-import
Oct 24, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
torchao-blockwise-import

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

torchao 0.18 moved blockwise_fp8_gemm from torchao.prototype.blockwise_fp8_inference.blockwise_quantization to torchao.kernel.blockwise_quantization. The import in unsloth/kernels/fp8.py only tried the old path, so with the current torchao every block FP8 linear silently uses the Triton pointer kernel. That includes training forwards and decode on every GPU. The fallback was logged only at info level.

Restoring torchao everywhere is not right either. torchao and the Triton kernels give bit-identical outputs, but which is faster depends on the GPU and on the row count. The B200 TMA kernel from #15136 is about 2x torchao.

Change

  • Import: try the old module path, then the new one, then fall back to None.
    • The 0.18 function has the same signature: blockwise_fp8_gemm(a, a_s, b, b_s, block_size).
    • It writes bf16 only and reads the weight scale with one block size for both dims.
  • Routing: fp8_block_matmul stays torchao when it imports. Per call, torchao_block_matmul hands the GEMM to w8a8_block_fp8_matmul_triton when any of these holds:
    • the output is not bf16 (torchao rounds through bf16; fp16 was 8x less accurate);
    • the block sizes are unequal;
    • int32 limits would be exceeded (as before);
    • the GPU is sm_89 (L4), at any row count;
    • the GPU is sm_100 with the TMA kernel usable and more than 64 rows. Above 64 rows the Triton function uses 128-row tiles and the TMA kernel; at 64 or fewer it would run the pointer kernel, which torchao beats.
  • Machines where every GPU is sm_89: fp8_block_matmul is the Triton function outright, so the fused small-M decode kernel stays on there.
  • Decisions run inside the existing opaque ops: M is read from the real tensor, so torch.compile adds no guard on a symbolic M.
  • ROCm and GPUs not measured here keep the previous preference (torchao when it imports).

Results

Llama-8B shapes, torch 2.14.1, torchao 0.18. Time is torchao divided by the Triton pointer kernel, so below 1 means torchao is faster. Activation quantization is included. 6 interleaved repeats; the A/A spread is 0.2% to 2.8%.

GPU up (8192 x 14336 x 4096) down (8192 x 4096 x 14336) QKV up, M 3000 routed to
H100 (Colab) 0.875 0.930 0.869 0.781 torchao
L4 (Colab) 0.934 1.732 0.975 0.940 Triton
RTX PRO 6000 (Colab G4) 0.963 0.992 0.962 0.969 torchao
B200 (shared card, 29-62% spread) 1.008 1.312 1.072 0.955 Triton TMA (about 2x both)

Decode (ms, up / down). Weights cycle through more than 600 MB of copies, so they are not served from L2.

GPU M Triton pointer Triton TMA torchao fused small-M
B200 1 .0259 / .0745 (pointer) .0188 / .0424 .0334 / .0571
B200 64 .0400 / .1268 (pointer) .0379 / .0539
B200 128 .0445 / .1435 .0229 / .0578 .0434 / .0796
H100 1 .0303 / .0681 .0261 / .0419 .0347 / .0569
L4 16 .2607 / .2556 .2644 / .2565 .2548 / .2501
L4 128 .3302 / .3786 .4376 / .3752

What the full B200 FP8 linear forward does at decode (no grad, main vs this PR):

  • 64 rows or fewer: up_proj is 1.06x to 1.8x faster and down_proj 1.9x to 2.4x. At M = 1, up goes from .0335 to .0188 ms and down from .0573 to .0297 ms.
  • 128 rows and more: unchanged, still on the TMA kernel.

Outputs are bit-identical between torchao and the Triton kernels on every shape tested (up, down, QKV, and M of 8191, 3000, 1000, 77 and 1) on B200, H100, L4 and RTX PRO 6000. The one exception is a 7.6e-6 maximum difference at down, M = 77 on B200. Both sit at the same error against an fp64 reference.

Tests

New tests/test_fp8_torchao_import_route.py (28 tests, CPU with the CUDA spoof, and GPU):

  • import fallback across both module paths and a missing torchao, using stub modules;
  • the per-call routing rules: dtype, block sizes, sm_89, and sm_100 by row count;
  • the startup selection on single-arch and mixed machines.

All FP8 test files on B200:

torch / torchao passed skipped
2.14.1, torchao 0.18 713 117
2.10.0, torchao 0.18 746 89
2.10.0, no torchao 812 23

With torchao installed, the small-M and GEMV router tests skip on B200, because B200 now routes to torchao. They run and pass in the no-torchao leg.

Not covered

  • Hardware: B200 timing used a shared card, not an exclusive one. RTX 4090 and other consumer sm_89 cards, A100 (no FP8 tensor cores) and ROCm were not measured.
  • Older torchao: no wheel older than 0.18 was run; the old import path is covered by the stub test.

torchao 0.18 moved blockwise_fp8_gemm from
torchao.prototype.blockwise_fp8_inference.blockwise_quantization to
torchao.kernel.blockwise_quantization, so the import failed and every
torchao 0.18 user silently took the Triton pointer kernel. Try both paths.

torchao and the Triton kernels give bit-identical bf16 outputs, so the
choice is speed only. Measured with torchao 0.18: torchao is 7-22% faster
on H100 and 1-4% faster on RTX PRO 6000 (sm_120), but 1.73x slower at
K=14336 on L4 (sm_89) and about 2x slower than the TMA kernel on sm_100.
Prefer the Triton function on sm_89 and sm_100, torchao elsewhere.

torchao_block_matmul also hands non-bf16 outputs (torchao writes bf16
only) and block_size[0] != block_size[1] (torchao indexes the N scale
with block_size[1]) to the Triton kernel.
Below 65 rows w8a8_block_fp8_matmul_triton picks BLOCK_SIZE_M < 128, so the
TMA kernel never engages and the pointer kernel runs; torchao 0.18 beats it
there by 1.1-1.4x (up_proj) and 1.8-2.4x (down_proj) on B200, and also beats
the fused small-M kernel. Select torchao_block_matmul on sm_100 too and hand
calls with more than 64 rows to the Triton function per call. M is read
from the concrete tensor inside the opaque op, so compiled callers add no
guard on it. Triton stays the outright choice only on sm_89, which keeps
the fused small-M kernel there; on sm_90 / sm_100 / sm_120 torchao or the
GEMV is faster at decode sizes.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 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-24T19:33:13.812713Z 475956e 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. 🚀

Reviewed commit: 984875f2d8

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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 475956e869

ℹ️ 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 8f8eaee into main Oct 24, 2026
5 of 30 checks passed
@danielhanchen
danielhanchen deleted the torchao-blockwise-import branch October 24, 2026 19:38
danielhanchen added a commit that referenced this pull request Oct 25, 2026
Follow-up to #15153.

Since #15153, `torchao_block_matmul` sends block FP8 GEMMs to torchao's
`blockwise_fp8_gemm` on every CUDA GPU except sm_89 when torchao 0.17+
is installed. torchao buckets M with `math.ceil(math.log2(M))`
(`torchao/kernel/blockwise_quantization.py:126` in 0.18), so an empty
activation raises `ValueError: math domain error`.

Before #15153 the torchao import missed on 0.17 / 0.18, so the Triton
kernel ran, and it handles M = 0.

Empty activations are real: an MoE expert that gets no tokens.
transformers' `OlmoeSparseMoeBlock` and FlexOlmo call every expert
without an empty check (`modeling_olmoe.py:607-615` in 4.57.6), so a
block FP8 OLMoE checkpoint crashed in forward and backward.

### Change
`torchao_block_matmul` routes `act_q.numel() == 0` to
`w8a8_block_fp8_matmul_triton`, next to the other cases torchao cannot
take.

### Tests
- **New CPU test** (meta tensors): M = 0 goes to Triton and M = 1 still
goes to torchao.
- **New GPU test:** a real empty block FP8 GEMM returns a `(0, N)` bf16
output.
- **Before / after on B200** (torch 2.14.1, torchao 0.18): both new
tests fail on main (routing assert, and `ValueError: math domain error`
from torchao) and pass with this change.
- **`fp8_linear` forward + backward:** with M = 0 it raises on main and
returns `(0, N)` / `(0, K)` with this change. M = 3 is unchanged.
- **Existing FP8 files:** `test_fp8_torchao_import_route.py`,
`test_fp8_tma_block_gemm.py` and `test_fp8_int64_offsets.py` give 53
passed.
danielhanchen added a commit that referenced this pull request Oct 27, 2026
… is selected (#15361)

## Problem

Since #15153 found torchao 0.18's `blockwise_fp8_gemm`, startup selects
`torchao_block_matmul` on sm_90 / sm_100 / sm_120 whenever torchao is
installed. `can_use_fp8_block_small_m` turns itself off whenever torchao
is the selected backend, because torchao beats the fused small-M kernel
for bf16.

torchao's kernel writes bf16 only, so `torchao_block_matmul` sends every
fp16 call back to `w8a8_block_fp8_matmul_triton`. fp16 decode therefore
lost the fused kernel and ran `act_quant` plus the Triton GEMM, two
launches instead of one, and never used torchao anyway.

## Fix

- `can_use_fp8_block_small_m` only declines for a non-fp16 input when
torchao is selected. bf16 still goes to torchao, and nothing changes
when the Triton GEMM is selected (sm_89, or no torchao).
- `_fp8_block_small_m_first` (100+ SM parts): with torchao selected, the
GEMV is tried before the fused kernel, so the decode calls it already
took (it skips `act_quant`) stay on it. With the Triton GEMM selected
the order is unchanged.

## Tests

`tests/test_fp8_small_m_torchao_route.py` needs no GPU. Kernels are
replaced by recorders and the routing is checked through
`FP8BlockQuantLinear.forward` and `_fp8_block_small_m_first`:

- fp16, M = 1 / 4 / 16, torchao selected: one fused call. Fails on main,
where `act_quant` plus the GEMM run.
- bf16 with torchao selected still runs `act_quant` plus torchao. Triton
selected runs the fused kernel for both dtypes. M above 16 and
`UNSLOTH_FP8_BLOCK_SMALL_M=0` keep two launches. The GEMV keeps its
calls with torchao selected.

On main: 4 failed, 10 passed. With this change: 14 passed. The existing
FP8 suites (`tests/test_fp8_*.py`,
`tests/test_compressed_tensors_fp8_kernel_route.py`) also pass on CPU:
263 passed, 458 skipped (GPU-only).

## Benchmark

RTX PRO 6000 Blackwell (sm_120), torch 2.13.0, torchao 0.18.0. Each arm
runs in its own long-lived process. Each round times base, head, then
the second base copy, and the next round reverses the order. That gives
12 rounds of 200 eager `fp8_linear` calls per arm, measured as host time
per call with a sync at the end. A/A is the second base copy over the
first.

fp16, GEMV on (default):

| N x K, M | main | this PR | head / main | A/A |
|---|---:|---:|---:|---:|
| 2048 x 2048, 1 | 42.1 us | 30.6 us | 0.73 | 0.96 |
| 6144 x 2048, 4 | 42.0 us | 24.5 us | 0.58 | 0.96 |
| 4096 x 4096, 1 | 41.7 us | 30.7 us | 0.74 | 0.98 |
| 14336 x 4096, 1 | 41.5 us | 24.4 us | 0.59 | 0.98 |
| 2048 x 6144, 16 (GEMV) | 30.1 us | 30.0 us | 1.00 | 0.99 |
| 4096 x 14336, 4 (GEMV) | 30.0 us | 30.0 us | 1.00 | 1.00 |

With the GEMV off, fp16 is 0.60 to 0.90 of main across all six shapes.
For bf16, every shape takes the same route as on main, and head / main
is between 0.99 and 1.01. That is inside the A/A spread of 0.97 to 1.04.

Outputs: bf16 is bit-identical to main for every shape. fp16 is
bit-identical to the same code without torchao installed, which is what
fp16 decode produced before #15153. Against main with torchao, the
largest fp16 difference is 3.9e-3, and the error against an fp64
reference is the same on both sides. On L4 (sm_89, where the Triton GEMM
is selected), every output is bit-identical to main and timings are
unchanged.

## Not covered

- Hopper (sm_90) and B200 (sm_100) were not timed; the routing is the
same as on sm_120.
- The bf16 torchao route still autotunes 48 configurations for each new
token-count bucket on the first call. This PR does not change that.

---------

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