Skip to content

FP8 block GEMM: TMA descriptor kernel with a 4-stage K loop on B200 - #15136

Merged
danielhanchen merged 3 commits into
mainfrom
fp8-tma-block-gemm
Oct 24, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
fp8-tma-block-gemm

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The block FP8 forward GEMM (w8a8_block_fp8_matmul_triton, 128 x 128 weight blocks) loads and stores its tiles through masked pointers. On B200 this kernel takes 1.7 ms for an 8192-token Llama-8B MLP projection. Moving A, B and C through TMA tensor descriptors, with a 4-stage K loop, makes it 1.9x to 2.4x faster with bitwise identical outputs. The idea came from comparing against the TMA GEMMs in NVIDIA TileGym.

Change

unsloth/kernels/fp8.py gets _w8a8_block_fp8_matmul_tma.

  • Same math: it uses the same tile schedule (GROUP_SIZE_M = 8), the same per-K-block scale multiply and the same accumulation order as _w8a8_block_fp8_matmul. Only the loads and stores change:
    • TMA zero-fills out-of-range rows and the K tail on load, and clips the store.
    • tl.range(..., num_stages = 4) pipelines the K loop.
  • When it runs (_fp8_tma_gemm_ok): all of these must hold, otherwise the existing pointer kernel runs unchanged.
    • sm_100 (CUDA, not ROCm). 4 stages of 128 x 128 fp8 A and B tiles need 128 KB of shared memory, more than sm_120 or sm_89 have.
    • 128 x 128 blocks and BLOCK_SIZE_M == 128, so small-M decode tiles keep their own path.
    • K % 16 == 0, a 16-byte aligned output row pitch, and 16-byte aligned A, B and C pointers.
    • No 64-bit indexing needed, output in bf16 / fp16 / fp32, and triton.tools.tensor_descriptor importable.
  • Self check: once per device, a ragged case (M 200, K 400, so a partial M tile and a K tail) must match the pointer kernel bit for bit. A mismatch or a launch error disables the TMA path with a warning. OOM and dynamo / inductor errors still raise. The check is skipped during CUDA graph capture, where it would allocate and sync.
  • Under torch.compile: the GEMM is already an opaque custom op, so the compiled graph is unchanged.
  • Opt-out: UNSLOTH_FP8_TMA_GEMM=0 keeps the pointer kernel everywhere.
  • Who runs this kernel: block FP8 training forwards go through fp8_block_matmul. It is torchao's kernel when torchao.prototype.blockwise_fp8_inference imports, otherwise this Triton kernel. torchao 0.18 (the current release) no longer has that module, so with torchao 0.18 or without torchao every block FP8 forward with M above the small-M path runs here.

Results

B200, torch 2.14.1, Triton 3.8. 8192 tokens, bf16 activations quantized per 128-wide group, FP8 weights with 128 x 128 block scales. Base and head alternated, 6 repeats each.

shape (M, N, K) main this PR speedup A/A spread (main)
Llama-8B up / gate (8192, 14336, 4096) 1.788 ms 0.799 ms 2.24x 0.1%
Llama-8B down (8192, 4096, 14336) 1.739 ms 0.727 ms 2.39x 0.2%
QKV (8192, 6144, 4096) 0.640 ms 0.339 ms 1.89x 0.3%
  • Accuracy: outputs are bitwise equal to main's. The error against an fp64 reference is the same on both sides.
  • Backward: unchanged. It does not go through this kernel, and its timings tie.

Tests

New tests/test_fp8_tma_block_gemm.py:

  • bitwise equality with the pointer kernel on 5 shapes, including ragged M, N and K, for bf16, fp16 and fp32 output. Each case asserts the TMA launch ran for the GEMM under test, so a silent fallback fails it;
  • the env opt-out and small M take the pointer kernel;
  • sm_75, sm_80, sm_89, sm_90 and sm_120 never route to the TMA kernel.

With tests/test_fp8_block_small_m.py, 91 passed on B200 with torch 2.10.0 (Triton 3.6), 2.13.0 (Triton 3.7.1) and 2.14.1 (Triton 3.8).

Not covered

  • Other GPUs: H100 (sm_90) also has TMA, but it is gated off because it was not measured; that can follow separately. sm_120, Ampere, T4 and AMD keep the pointer kernel by construction.
  • End to end: no full FP8 training run timing, only the GEMM.
  • torchao 0.17 and older: they keep torchao's kernel, so they see no change. The torchao import path itself (0.18 moved blockwise_fp8_gemm to torchao.kernel.blockwise_quantization) is left for a separate change.

The pointer-based w8a8 block GEMM is the path taken whenever torchao's
blockwise_fp8_gemm import fails (torchao 0.18 moved it). On B200 the
same tile math fed by TMA descriptors and a 4-stage pipelined K loop is
2.2-2.4x faster at 8192-token Llama-3.1-8B shapes and bitwise identical
to the pointer kernel. Gated to sm_100 with a per-device bitwise self
check, a fallback on launch failure, and UNSLOTH_FP8_TMA_GEMM=0.
@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-24T15:42:36.326181Z 77d9df9 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. Delightful!

Reviewed commit: 77d9df9769

ℹ️ 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 8f6e39d into main Oct 24, 2026
5 of 29 checks passed
@danielhanchen
danielhanchen deleted the fp8-tma-block-gemm branch October 24, 2026 15:47
maxkongerskov pushed a commit to maxkongerskov/unsloth that referenced this pull request Oct 24, 2026
…all to the faster kernel (unslothai#15153)

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 unslothai#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.

---------

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 27, 2026
## Problem

Since #15136, every block FP8 GEMM that takes the TMA kernel on sm_100
builds three `TensorDescriptor`s per call through
`TensorDescriptor.from_tensor` (`unsloth/kernels/fp8.py`,
`_launch_fp8_tma_gemm`). `from_tensor` validates every field again on
each call, and `A.view` / `C.view` add two more tensor ops. For short
eager GEMMs that host work is a visible part of the call.

## Fix

`_fp8_tma_descriptor` builds each descriptor from the tensor-independent
fields (block shape, padding, and so on) that `from_tensor` validated
once per (dtype, block shape). Per call it sets only the live tensor,
shape and strides. A contiguous tensor of `rows * cols` elements already
has `(cols, 1)` strides as a 2D view, so no view is built on that path.
Anything else (a sliced weight whose row pitch is not its width, an
empty dimension) goes through `from_tensor` as before, which reads the
real strides and still raises on an empty dimension. `_fp8_tma_gemm_ok`
already checks the 16-byte alignment of bases and row pitches.

Nothing is cached per tensor: the cache holds no reference to any GEMM's
tensors, and a weight that is replaced, edited in place, or has its
`.data` swapped is read fresh on the next call. Every call returns a new
descriptor object with its own `block_shape` list, and Triton encodes
the tensor map by value at launch, so threads and captured CUDA graphs
never share mutable descriptor state.

Routing is unchanged: the same calls take TMA as on main, in eager,
under CUDA graph capture and under `torch.compile`. An earlier revision
also kept eager GEMMs below 2**34 multiply-adds on the pointer kernel.
On B200 that kernel is 1.39-1.77x slower on the GPU than TMA at every
such shape (table below), so that part was dropped.

## B200 timing

B200 (sm_100), torch 2.13.0+cu130, Triton 3.7.1, bf16 output, frozen FP8
weights with 128x128 scales, `w8a8_block_fp8_matmul_triton`. Main and
this branch ran as separate fresh processes, 3 per arm, interleaved,
with a second main arm as A/A. Each cell is the median over the 3
processes of the per-process median microseconds per call.

- eager: back-to-back calls, host-bound at these sizes.
- eager, GPU-bound: a GPU sleep lets the host queue 50 calls ahead, so
CUDA events time the kernels alone.
- graph: 20 calls captured in one CUDA graph and replayed.

| M x N x K | eager main | eager A/A | eager this PR | GPU-bound main |
GPU-bound this PR | graph main | graph this PR | bitwise |
|---|---:|---:|---:|---:|---:|---:|---:|---|
| 128 x 4096 x 4096 | 63.3 | 61.2 | 55.6 | 18.0 | 18.0 | 15.4 | 15.4 |
yes |
| 256 x 4096 x 4096 | 83.8 | 64.3 | 55.4 | 18.5 | 18.5 | 15.8 | 15.8 |
yes |
| 512 x 4096 x 4096 | 62.9 | 61.3 | 54.4 | 19.2 | 19.2 | 17.8 | 17.9 |
yes |
| 1023 x 4096 x 4096 | 62.2 | 61.8 | 55.7 | 35.0 | 34.9 | 32.1 | 32.1 |
yes |
| 1024 x 4096 x 4096 | 62.2 | 64.4 | 66.0 | 35.0 | 34.9 | 32.3 | 32.2 |
yes |
| 2048 x 4096 x 4096 | 62.2 | 63.1 | 62.1 | 64.7 | 64.8 | 59.7 | 59.7 |
yes |
| 4096 x 4096 x 4096 | 107.7 | 107.1 | 107.0 | 110.7 | 110.8 | 106.4 |
106.1 | yes |
| 256 x 14336 x 4096 | 62.8 | 63.8 | 59.9 | 34.5 | 34.5 | 31.4 | 31.6 |
yes |
| 2048 x 4096 x 1024 | 62.6 | 61.8 | 54.8 | 26.7 | 26.7 | 24.3 | 24.3 |
yes |

How to read this:

- GPU-bound eager and graph times match main within 0.5% at every shape,
against an A/A band of at most 1.3% (6.8% and 4.8% at 4096 x 4096 x
4096). Every call took the TMA kernel on both sides: 1 per eager call
and 20 per graph.
- Outputs are bitwise identical to main in every cell, eager and graph.
- Host-bound eager calls are about 7 us faster (55 vs 62 us) at most
sizes. The eager A/A band on this shared host was 3-14% in most cells
(39% at 2048 x 4096 x 1024, 72% at 256 x 4096 x 4096), so cells inside
it are not a result. At 1024 and 2048 x 4096 x 4096 the difference is
inside the band.
- On CPU, building the three descriptors costs 5.5-6.5 us per launch on
main. The first revision of this change cut that to 4.5-5.3 us, about 1
us saved, because it still built the view and compared strides on every
call. Checking contiguity instead brings it to 2.0-2.9 us.

Dropped eager threshold, same harness (pointer kernel vs TMA, GPU-bound,
microseconds per call):

| M x N x K | TMA (main) | pointer kernel (dropped threshold) | ratio |
|---|---:|---:|---:|
| 128 x 4096 x 4096 | 17.7 | 30.8 | 1.74 |
| 256 x 4096 x 4096 | 18.4 | 30.9 | 1.68 |
| 512 x 4096 x 4096 | 19.2 | 32.4 | 1.69 |
| 1023 x 4096 x 4096 | 34.8 | 60.0 | 1.72 |
| 256 x 14336 x 4096 | 34.4 | 60.8 | 1.77 |
| 2048 x 4096 x 1024 | 26.7 | 37.0 | 1.39 |

## Tests

`tests/test_fp8_tma_eager_host_cost.py` (CPU, no GPU needed):

- routing: eager GEMMs take TMA at M = 128 to 2048, 2D and batched, and
so do graph-captured ones; a capture before any eager call keeps the
pointer kernel, as on main.
- descriptors: fields match `from_tensor` for fp8 / bf16 / fp16; warm
launches never call `from_tensor`; a sliced row pitch falls back to
`from_tensor`; the cache keeps no tensor alive; an empty dimension still
raises.
- staleness: a weight edited in place, replaced by a new tensor, or with
`.data` swapped to a different shape always gives a descriptor for the
current tensor and shape.

On B200, `tests/test_fp8_tma_block_gemm.py` (including the sm_100
bitwise test of TMA against the pointer kernel) plus the file above: 41
passed.

## Not covered

- sm_103 and other Blackwell parts were not timed; only B200.
- torchao was blocked in the timing harness so both arms use the Triton
launcher. Routing to torchao is unchanged by this PR.
- 3D inputs and fp32 outputs were checked for descriptor equality on
CPU, not timed on GPU.

---------

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