Before you start: words you need#
| Word | Plain meaning |
|---|---|
| GEMM | General matrix multiply, C = A × B (plus optional scaling and bias). The operation behind every linear layer (11.c). |
| CTA tile | The block of C that one CTA (or CTA pair) computes, e.g. 128 × 256. |
| Mainloop | The loop over K that loads A and B slices and accumulates into the tile. |
| Wave | One round of CTAs filling all SMs. 512 tiles on 148 SMs need 4 waves; the last one is only partly full. |
| Persistent kernel | A kernel that launches about one CTA per SM, and each CTA loops over many tiles instead of exiting after one (25.j). |
| Rasterisation | The order in which tiles are visited. Visiting nearby tiles together keeps their A and B slices in L2. |
| Split-K / Stream-K | Splitting the K dimension of a tile across several CTAs, then adding the partial results, to use all SMs when there are too few tiles. |
| Swap A/B | Computing Cᵀ = Bᵀ × Aᵀ so that a small M (few tokens) lands on the tensor core’s flexible N dimension. |
1. What is it?#
This lesson follows one GEMM — BF16, C = A × B, M = N = K = 8192 — from a correct but slow kernel
to one that matches cuBLAS, adding one idea at a time. Each step names the problem it removes. The
steps follow NVIDIA’s own CuTe DSL Blackwell tutorial (fp16_gemm_0.py … fp16_gemm_6.py in CUTLASS
4.8.1) and Triton’s Gluon tutorials, so you can run every stage yourself.
Then it turns to the shapes inference actually runs: small M (decode), skinny N (MoE experts, 25.h), and shapes that do not divide the GPU evenly.
Facts checked on 13 November 2026.
2. Why does it matter?#
GEMMs are 60–90 % of the FLOPs of a transformer forward pass (11.c), and in prefill they are compute-bound, so their efficiency is the prefill throughput. In decode they are memory-bound, and the question becomes whether the kernel streams weights at full HBM bandwidth (2.e).
You will rarely beat cuBLAS on a plain square BF16 GEMM. You will meet cases where the library is not tuned: unusual shapes, new low-precision formats (25.g), fused epilogues, grouped MoE GEMMs (25.h), GEMMs fused with communication (25.i). Knowing the steps tells you which one a slow kernel is missing.
3. Simple analogy#
Painting a huge mural (C) from two stacks of paint cards (A rows and B columns).
- Naive: every painter fetches their own cards from the warehouse for every brushstroke.
- Tiling: each team takes a rectangle and keeps the cards it needs on a table (shared memory).
- Pipelining and specialisation: a runner keeps the table stocked while the painters paint.
- Pairing and multicast: two neighbouring teams share one delivery.
- Persistence and rasterisation: teams stay on site, take the next rectangle from a list ordered so that neighbouring rectangles reuse the same cards still in the van (L2).
- Stream-K: when there are fewer rectangles than teams, split the last rectangles’ work so nobody stands idle.
4. Tiny example: the ladder#
Approximate fractions of BF16 dense peak on an 8192³ problem. The first rows are rough (they depend heavily on details); the later rows are the authors’ published figures.
| Step | Idea added | Problem removed | Rough % of peak |
|---|---|---|---|
| 0 | one thread per output element, reading HBM | — | < 1 % |
| 1 | CTA tiles in shared memory (4.d) | every element read from HBM N times | 5–10 % |
| 2 | tensor cores via mma.sync (4.f) | CUDA cores are 10–30× slower | 30–50 % (Hopper) |
| 3 | TMA + multi-stage mbarrier ring (25.a) | load latency; address arithmetic | 60–70 % |
| 4 | wgmma / tcgen05.mma with swizzled operands | warp-level MMA cannot reach Hopper/Blackwell peak | 70–80 % |
| 5 | warp specialisation, register reallocation (25.b) | copy and MMA issue in one instruction stream | 80–85 % |
| 6 | CTA pairs + TMA multicast (Blackwell) | shared memory too small for enough stages; L2 traffic | 85–90 % |
| 7 | persistent CTAs + tile scheduler + overlapped epilogue | launch/prologue/epilogue cost per tile | ~90 % |
| 8 | rasterisation (grouped order), L2 prefetch | L2 misses as the grid sweeps A and B | +1–3 % |
| 9 | Stream-K or split-K for awkward shapes | wave quantisation | shape-dependent |
The Gluon tutorial’s warp-specialised persistent kernel (steps 3–7) measured 1,180–1,320 TFLOP/s versus cuBLAS’s 1,300–1,430 at M = N = 8192 on a B200, and its multi-CTA tutorial goes further (Triton authors’ figures). For Hopper, FlashAttention-3’s and DeepGEMM’s published numbers show the same ladder: DeepGEMM reports up to 1,550 TFLOP/s FP8 on H800.
5. Technical explanation#
Steps 1–2: tiles and tensor cores (recap)#
A CTA computing a BM × BN tile reads (BM + BN) × K elements and does 2 × BM × BN × K FLOPs, so it performs BM·BN / (BM + BN) FLOPs per byte of BF16 operands (section 7 tabulates it). Bigger tiles mean more reuse, limited by shared memory, registers or TMEM. Tensor cores need operands in specific fragment layouts (4.f, 25.c).
Step 3–4: TMA ring and asynchronous MMA#
The mainloop becomes the ring of 25.b: TMA fills stage s, the MMA consumes it, the tensor core
frees it. Operand tiles are stored with a 128-byte swizzle (25.c) so that wgmma/tcgen05.mma can
read them from shared memory through descriptors. CuTe DSL’s cutlass.range(num_k_tiles, prefetch_stages=ab_stages - 2) generates the prologue automatically.
Step 5: warp specialisation#
Separate load, MMA and epilogue warps (25.b). CUTLASS’s tutorial comments that the gain is largest when K is small, where prologue and epilogue are a bigger share — exactly the inference case.
Step 6: CTA pairs and multicast (Blackwell)#
With cta_group::2, two SMs compute a 256 × 256 tile together, each holding half of B. The tutorial
works it out: one stage of A is 128 × 64 × 2 B = 16 KB; of B, 32 KB for one CTA but 16 KB per CTA in a
pair. So a single CTA fits ⌊227 / 48⌋ = 4 stages, a pair 7 per CTA — 512 × 6 ≈ 3,000 cycles of
latency hidden instead of 1,500. TMA multicast inside a cluster then delivers each A or B tile to
several CTAs with one L2 read: for a (m, n) cluster, L2 traffic per tile drops from up to 48 KB to
16/n + 32/m KB (24 KB for 2 × 1, 12 KB for 4 × 4).
Step 7: persistence and tile schedulers#
Launch ~one CTA (or cluster) per SM, and loop:
while (tile = scheduler.next()) is valid:
mainloop(tile) # producer and MMA warps, ring keeps running across tiles
epilogue(tile) # epilogue warps, overlapped via 2 TMEM accumulators- Static scheduler: tile i goes to CTA i mod grid. Simple, deterministic, but unbalanced if some SMs are busy with another kernel.
- Dynamic scheduler with Blackwell’s cluster launch control: a CTA that finishes asks the
hardware to cancel a not-yet-launched CTA and takes its tile (
clusterlaunchcontrol.try_cancel). CuTe DSL calls itClcDynamicPersistentTileScheduler(fp16_gemm_3_1.py). - Preferred and fallback clusters (SM100): launch with a preferred 2 × 2 cluster but allow
2 × 1 on SMs left over, so cluster shape does not strand SMs (
fp16_gemm_4.py).
Step 8: rasterisation and L2#
If tiles are visited row by row, each row of tiles reads all of B, and B falls out of L2 before the
next row reuses it. Grouped (swizzled) rasterisation visits a band of G tile-rows column by
column, so a band reuses the same B slices while they are still in L2. Triton’s matmul tutorial
(GROUP_SIZE_M) and CUTLASS’s max_swizzle_size implement it. fp16_gemm_5.py adds TMA L2
prefetch: requesting the k-tile prefetch_dist ahead into L2 before the real TMA load.
Step 9: wave quantisation, split-K and Stream-K#
A 4096 × 4096 GEMM with 128 × 256 tiles has 512 tiles; on 148 SMs that is 3.46 waves, so the fourth wave runs at 46 % occupancy and the whole GEMM at 86 % (section 7). Fixes:
- Smaller or different tiles (more, smaller tiles; less reuse).
- Split-K: split K into S parts, compute partial tiles in parallel, then reduce (in a workspace,
or with TMA reduce-add,
cp.reduce.async.bulk.tensor). Good when M × N is small and K is large — common for decode. - Stream-K (Osama et al., 2023): give every SM the same number of MAC-loop iterations, crossing tile boundaries; tiles split between CTAs are fixed up at the end. Removes the partial last wave. CUTLASS ships Stream-K schedulers for Hopper and Blackwell.
Step 10: the epilogue and PDL#
- Subtiled epilogue: drain the TMEM accumulator in slices (e.g. 4 × 64 columns), converting and
TMA-storing each while loading the next, to cap register use and overlap
st.sharedwith the TMA store (fp16_gemm_0.py,fp16_gemm_2.py). - Fused epilogues: scales, bias, activation, residual add, quantisation of the output for the next layer (25.g). Every fused op saves a full read and write of C.
- Programmatic dependent launch (PDL): the next kernel’s prologue (barrier init, TMEM alloc,
descriptor prefetch) overlaps the previous kernel’s tail (
griddepcontrol,fp16_gemm_6.py). For decode, where a GEMM lasts only a few microseconds, this is worth several percent.
Inference shapes#
| Shape | Where | What changes |
|---|---|---|
| M = 1–64, N, K = 4–30 K | decode linear layers | memory-bound: stream weights at full HBM bandwidth; swap A/B; split-K; small BN tiles; low-bit weights (25.g) |
| M = 64–512 | decode at large batch, MoE experts | near the ridge point; tile choice and wave quantisation matter most |
| M ≥ 2048 | prefill, chunked prefill | compute-bound: the full ladder above |
| many small GEMMs | MoE experts, LoRA | grouped GEMM (25.h) |
Swap A/B. Tensor-core instructions have a large fixed M (64 or 128 rows) but a flexible N
(multiples of 8 up to 256 for tcgen05.mma kind::f16). With 16 tokens, putting tokens on M fills
16 of 128 rows; computing Cᵀ = Bᵀ Aᵀ puts the weight’s output dimension (thousands) on M and the 16
tokens on N. In the memory-bound regime the wasted rows cost little arithmetic, but the swapped
layout gives many more tiles along the weight dimension to spread across 148 SMs and smaller
activation tiles, and it keeps paying as M approaches the ridge point. vLLM v0.32.0’s Blackwell FP8
CUTLASS dispatch (scaled_mm_sm100_fp8_dispatch.cuh) has swap-A/B configurations for its M = 16 and
M = 64 buckets, and TensorRT-LLM’s MoE kernels have swap-A/B variants too.
6. Under the hood: one persistent Blackwell GEMM CTA pair#
cluster of 2 CTAs (SM a, SM b), each 6 warps + 1 epilogue warpgroup
SM a, warp 0 (MMA, leader of the pair): for each tile from the scheduler:
wait acc_empty[b] # TMEM buffer b free?
for k: wait full[s]; tcgen05.mma.cta_group::2 [acc_b] ...; tcgen05.commit -> empty[s] (both CTAs)
tcgen05.commit -> acc_full[b]
SM a and SM b, warp 2 (TMA): for each tile, for each k:
wait empty[s]; expect_tx; TMA A-half (own), TMA B-half (own), multicast where cluster allows
SM a and SM b, warps 4-7 (epilogue): for each tile:
wait acc_full[b]; for 4 subtiles: tcgen05.ld -> cvt -> st.shared -> fence -> TMA store
arrive acc_empty[b]
warp 1 (scheduler): CLC try_cancel -> next tile id -> broadcast through shared memory + mbarrierOnly the leader CTA’s MMA warp issues the pair’s MMAs; the peer’s tensor core participates through
cta_group::2. TMEM in both SMs holds half of the 256-row accumulator each.
7. Performance implications: reuse, waves and small M#
// gemmplan.go — three numbers that decide a GEMM's tile choice on a B200:
// operand reuse per tile, wave quantisation, and wasted tensor-core rows at small M.
package main
import "fmt"
const sms = 148 // B200
func ceil(a, b int) int { return (a + b - 1) / b }
// reuse: FLOPs per byte of A+B loaded into shared memory for one BM x BN tile (BF16).
func reuse(bm, bn int) float64 { return float64(bm*bn) / float64(bm+bn) }
// waves: how full the last wave of tiles is.
func waves(m, n, bm, bn int) (tiles, w int, eff float64) {
tiles = ceil(m, bm) * ceil(n, bn)
w = ceil(tiles, sms)
return tiles, w, float64(tiles) / float64(w*sms)
}
func main() {
fmt.Println("tile FLOP/byte reuse")
for _, t := range [][2]int{{64, 64}, {128, 128}, {128, 256}, {256, 256}} {
fmt.Printf("%3dx%-3d %6.0f\n", t[0], t[1], reuse(t[0], t[1]))
}
fmt.Println("\nM x N (tile 128x256) tiles waves SM-time used")
for _, s := range [][2]int{{8192, 8192}, {4096, 4096}, {2048, 2048}, {8192, 1536}} {
tiles, w, eff := waves(s[0], s[1], 128, 256)
fmt.Printf("%5d x %-5d %5d %5d %10.0f%%\n", s[0], s[1], tiles, w, eff*100)
}
fmt.Println("\ndecode GEMM, M tokens rows used, M on MMA-M (min 128) swap A/B: M on MMA-N (min 8)")
for _, m := range []int{1, 8, 16, 64} {
normal := float64(m) / 128
swapped := float64(m) / float64(ceil(m, 8)*8)
fmt.Printf("%22d %31.1f%% %25.0f%%\n", m, normal*100, swapped*100)
}
}tile FLOP/byte reuse
64x64 32
128x128 64
128x256 85
256x256 128
M x N (tile 128x256) tiles waves SM-time used
8192 x 8192 2048 14 99%
4096 x 4096 512 4 86%
2048 x 2048 128 1 86%
8192 x 1536 384 3 86%
decode GEMM, M tokens rows used, M on MMA-M (min 128) swap A/B: M on MMA-N (min 8)
1 0.8% 12%
8 6.2% 100%
16 12.5% 100%
64 50.0% 100%Reading it:
- Reuse. B200’s ridge point from HBM is about 2,250 / 8 ≈ 280 FLOP/byte (6.a). A single tile’s reuse (85 for 128 × 256) is below that; the rest comes from L2 hits across neighbouring tiles (step 8) and multicast (step 6). That is why rasterisation and clusters are not optional.
- Waves. Only the very large square GEMM fills the GPU. Common transformer shapes lose 10–15 % to the last wave unless the library uses Stream-K or picks tiles per shape.
- Small M. On the normal mapping, a 16-token decode GEMM uses 1/8 of every MMA. Swap A/B fixes the shape mismatch; the kernel then lives or dies on streaming weights at HBM speed.
8. Production implications#
- Profile before tuning. In Nsight Systems, find the top GEMM kernels by time; in Nsight Compute, compare achieved TFLOP/s (prefill) or DRAM throughput (decode) with the roofline (6.d).
- Library heuristics are per shape. cuBLASLt picks a kernel per (M, N, K, dtype, layout); engines
add their own choices (vLLM’s CUTLASS FP8 dispatch files pick tile shapes by M bucket). A new model
with unusual dimensions can land on a poor choice: run
cutlass_profileror cuBLASLt’s autotuning for your shapes. - CUDA graphs fix the shape set (5.f, 13.k). Decode GEMMs see only the captured batch sizes, so tuning a handful of M values covers most of decode time.
- Fuse at the epilogue, not after. Output quantisation (FP8/FP4 for the next layer), bias, SiLU and residual adds belong in the GEMM epilogue. A separate kernel costs a full read and write of C.
- Expect a new tuning pass per GPU generation (and for B300 vs B200, whose FP4 rate differs).
9. Common mistakes#
- Benchmarking only square 8192³. Your model’s shapes are 16 × 7168 × 2048 and similar.
- Ignoring wave quantisation. A 10 % gap to cuBLAS can be the last wave, not the mainloop.
- Measuring without L2 flushing or with warm caches only. Small GEMMs look faster than they will be in a real step (25.l).
- Over-sizing tiles. Bigger tiles mean more reuse but fewer tiles and fewer stages; past a point the GEMM loses on waves or latency hiding.
- Putting a tiny M on the MMA’s M dimension instead of swapping A and B.
- Unfused epilogues that write BF16 C, then read it back to quantise.
- Forgetting PDL and graphs for microsecond-scale decode GEMMs, where launch gaps rival kernel time.
10. Hands-on exercise#
- Run CUTLASS’s CuTe DSL tutorial
fp16_gemm_0.pythroughfp16_gemm_6.pyon a B200 at--mnk 8192,8192,8192and at--mnk 4096,4096,4096. Tabulate TFLOP/s per step againsttorch.matmul. Which step gives the biggest jump at each size? - Use the Go program to find a tile shape that keeps 4096 × 4096 above 95 % SM-time. What reuse do you give up?
- Benchmark
torch.matmulfor M ∈ {1, 8, 16, 32, 64, 128, 256}, N = K = 8192, BF16. Convert to achieved GB/s and TFLOP/s and find where it crosses from memory-bound to compute-bound. - Read the Triton matmul tutorial’s grouped ordering and explain, with a sketch of L2 contents, why
GROUP_SIZE_M = 8beats row-major order.
11. Interview questions#
- Walk through the steps from a naive GEMM to cuBLAS-level performance on Blackwell. Which problem does each step remove?
- Why does a Blackwell GEMM use CTA pairs? Give the shared-memory arithmetic.
- What is wave quantisation? Compare split-K and Stream-K as fixes.
- How does tile rasterisation affect L2 hit rate?
- What is swap A/B, and when does it matter?
- A decode GEMM reaches 40 % of HBM bandwidth. List the likely causes in order of probability.
- What does programmatic dependent launch overlap, and why does it matter most for decode?
12. Further reading#
Checked on 13 November 2026.
- [REFERENCE] CuTe DSL Blackwell GEMM tutorial, steps 0–6 (CUTLASS 4.8.1)
- [REFERENCE] Triton Gluon tutorials 07 (persistence), 08 (warp specialisation), 14 (multi-CTA)
- [REFERENCE] Triton matrix multiplication tutorial — grouped ordering
- [ESTABLISHED] Osama et al., “Stream-K: Work-centric Parallel Decomposition for Dense Matrix-Matrix Multiplication on the GPU” (2023)
- [REFERENCE] DeepGEMM — a compact, readable SM90/SM100 FP8 GEMM
- [REFERENCE] JAX Pallas: writing a Blackwell matmul — the same ladder in Pallas
- Related lessons: GEMM and GEMV (11.c), roofline (6.a), profiling (6.d), CUDA graphs in serving (13.k)