Before you start: words you need#
| Word | Plain meaning |
|---|---|
| GEMM | “General matrix multiply”: a matrix times a matrix. |
| GEMV | “General matrix-vector multiply”: a matrix times a single vector. |
| BLAS | Basic Linear Algebra Subprograms, the standard list of these routines since 1979. Every GPU maths library (cuBLAS, rocBLAS) follows its naming. |
| M, N, K | The sizes in C(M×N) = A(M×K) · B(K×N). In a transformer layer, M is the number of tokens, K the input width and N the output width. |
| Arithmetic intensity | FLOPs done per byte moved from memory (2.f). High means compute bound; low means memory bound. |
| Ridge point | The intensity where a chip’s compute limit and memory limit meet: peak FLOP/s ÷ bandwidth. About 295 FLOP/byte on an H100 (6.a). |
| Tile | A small block of the output that one group of GPU threads computes together. |
| Epilogue | The last step of a GEMM kernel, where extra work (bias, activation, scaling) is done before the result is written. |
1. What is it?#
- GEMM:
C = A · B. Matrix times matrix. BLAS calls it “level 3”. - GEMV:
y = A · x. Matrix times vector. BLAS calls it “level 2”.
The difference that matters: a GEMM reuses each number it loads many times; a GEMV uses each weight exactly once. Multiplying an M×K matrix by a K×N matrix does about 2·M·N·K FLOPs on about M·K + K·N + M·N numbers, so the work grows faster than the data. A GEMV has M = 1: the work and the data grow together.
2. Why does it matter?#
Because, in an LLM, prefill is GEMM and decode at small batch is GEMV, and they behave completely differently on the same hardware with the same weights.
Prefill, 2,048 tokens: (2048, 4096) @ (4096, 4096) intensity ≈ 1,000 FLOP/byte
Decode, one token: (1, 4096) @ (4096, 4096) intensity ≈ 1 FLOP/byteAgainst a ridge point of about 295, the first runs the tensor cores flat out and the second leaves them idle 99% of the time. Understanding why is the single most useful piece of mechanical knowledge in LLM inference.
3. Simple analogy#
A photocopier down the corridor.
Copying one page: walk to the machine, wait for it to warm up, copy, walk back. Ninety seconds for one page.
Copying 500 pages: the same walk and the same warm-up, then 500 copies.
Loading a weight matrix from GPU memory is the walk. A GEMV pays it to serve one token. A GEMM pays it once for hundreds.
4. Tiny example: when does GEMV become GEMM?#
The program takes one 4096 × 4096 BF16 weight matrix and feeds it M rows of input at a time. For each M it predicts the time as the larger of “time to move the bytes” and “time to do the FLOPs”, using what an H100 really reaches (about 3.0 TB/s and 700 TFLOP/s), not the datasheet peaks.
// gemm.go — one 4096 x 4096 BF16 weight matrix, M input rows at a time.
// Predict when the operation stops being a GEMV (memory bound) and becomes a GEMM (compute bound).
package main
import "fmt"
func main() {
const (
K, N = 4096.0, 4096.0
bytesPer = 2.0 // BF16
bandwidth = 3.0e12 // bytes/s: an H100 SXM reaches ~90% of its 3.35 TB/s
peak = 700e12 // FLOP/s: a well-tuned BF16 GEMM on H100, ~70% of 989 TFLOP/s
)
fmt.Println(" M time TFLOP/s GB/s FLOP/byte")
for _, M := range []float64{1, 2, 8, 32, 64, 128, 256, 512, 2048, 8192} {
flops := 2 * M * K * N
bytes := bytesPer * (M*K + K*N + M*N) // read A, read W, write C
t := max(bytes/bandwidth, flops/peak)
fmt.Printf("%5.0f %8.1f us %8.1f %8.0f %9.1f\n",
M, t*1e6, flops/t/1e12, bytes/t/1e9, flops/bytes)
}
}Output:
M time TFLOP/s GB/s FLOP/byte
1 11.2 us 3.0 3000 1.0
2 11.2 us 6.0 3000 2.0
8 11.2 us 23.9 3000 8.0
32 11.4 us 94.5 3000 31.5
64 11.5 us 186.2 3000 62.1
128 11.9 us 361.4 3000 120.5
256 12.6 us 682.7 3000 227.6
512 24.5 us 700.0 1709 409.6
2048 98.2 us 700.0 684 1024.0
8192 392.7 us 700.0 427 1638.4From M = 1 to M = 256 the time barely moves. You do 256 times the work for 13% more time, because the cost is reading the 33.6 MB weight matrix, and that is paid once whatever M is. Past the ridge (here about M = 256) the FLOPs take over and time grows in step with M.
This is why batching is not optional in LLM serving: 64 users decoding together cost about the same per step as one user alone (12.j). Real kernels are less tidy than this model, especially at small M, but measured curves on an H100 have the same flat-then-rising shape.
5. Technical explanation#
Why GEMV cannot be fast#
GEMV: y = W x, W is (N, K)
FLOPs = 2·N·K
Bytes ≈ 2·N·K (the BF16 weights; x and y are tiny)
Intensity ≈ 1 FLOP/byteEvery weight is read once and used once. That is not a weakness of some implementation; it is a property of the operation. On an H100, the best a GEMV can reach is about 1/295 of peak compute. No kernel can fix this. There are only three ways out:
- Use more rows: batch requests together, so M > 1 (12.j). The GEMV becomes a GEMM.
- Move fewer bytes per weight: quantize to 8, 4 or fewer bits (13.b).
- Get more tokens out of each read: speculative decoding checks several tokens per pass (12.n); mixture-of-experts reads only a few experts’ weights per token (14.g).
Almost every decode optimization in this material is one of those three.
How a GEMM kernel is built#
A fast GEMM is a hierarchy of tiles, each level matched to a level of GPU memory (4.d):
Thread-block tile, e.g. 128 × 128 of C, per SM
loops over K in slices of 64
copies slices of A and B from HBM into shared memory
Warp or warpgroup tile, e.g. 64 × 128
each group of threads works on its own part of the block tile
Tensor-core instruction (4.f)
Ampere: mma.sync on a 16 × 8 × 16 fragment held in registers
Hopper: wgmma, 128 threads issue one large MMA reading shared memory directly
Blackwell: tcgen05.mma, one thread issues it; accumulators live in tensor memory (TMEM)
Epilogue
apply bias, activation, scale or quantize to the accumulators
write C to HBM onceThe techniques that make it fast:
- Pipelining. Load the next K slice while computing on the current one, with several slices in flight.
- Asynchronous copies.
cp.asyncon Ampere and the TMA engine on Hopper and Blackwell copy tiles from HBM to shared memory without tying up threads (4.d). - Swizzled shared-memory layouts that avoid bank conflicts (11.g).
- Split-K. When M and N are small but K is large, there are too few output tiles to keep 132 SMs busy. Split the K loop across several blocks and add their partial sums at the end. This is how decode-shaped GEMMs fill the GPU.
Tile and wave quantization#
Work is handed out in whole tiles and whole “waves” of tiles across the SMs, so sizes just past a boundary waste capacity:
Tile quantization
M = 129 with 128-row tiles → 2 tile rows, the second holding 1 real row
useful work: 129 / 256 = 50%
Wave quantization
133 tiles on 132 SMs → 2 waves, the second running 1 tile
useful work: 133 / 264 = 50%Plot GEMM time against M and you see a sawtooth. Model dimensions are multiples of 64 or 128 for this reason; the dimension that varies is M, the token count, which the engine controls (11.j).
Batched and grouped GEMM#
Batched GEMM many independent GEMMs of the SAME shape in one launch
e.g. one per attention head: cublasGemmStridedBatched
Grouped GEMM many GEMMs of DIFFERENT shapes in one launch
mixture-of-experts: each expert gets a different number of tokens (14.h)
multi-LoRA serving: each adapter has its own small matrices (18.g)Grouped GEMM is what makes MoE serving efficient. Without it, an engine would launch one small GEMM per expert per layer. CUTLASS provides grouped GEMM, and DeepSeek’s open-source DeepGEMM library provides FP8 grouped kernels written for MoE.
Quantized weights change the kernel#
With 4-bit weights and 16-bit activations (“W4A16”), the kernel loads the packed 4-bit weights, unpacks and rescales them in registers, then feeds the tensor cores. The 4-bit form is what crosses HBM, which is the point (13.c). Libraries such as cuBLAS do not cover these mixed-format shapes well, so engines ship their own kernels: Marlin for Ampere-class GPUs and Machete for Hopper in vLLM, among others.
6. Under the hood: which kernel ran?#
The kernel name in a profile (Nsight Systems or Nsight Compute, 22.h) tells you what the library chose. An A100 cuBLAS FP16 kernel name, for example:
ampere_h16816gemm_128x128_ldg8_stages_64x3_tn
^arch ^type, MMA shape 16x8x16
^tile ^loads ^pipeline ^layoutHopper and Blackwell kernels have longer names in the same spirit: the architecture (sm90,
sm100), data types, tile size, cluster shape and layout. The last letters (tn, nn, nt)
say whether each input is read transposed. To see cuBLASLt’s choices directly:
export CUBLASLT_LOG_LEVEL=5 # print each matmul call and the algorithm chosenFor decode-sized M, cuBLAS often picks a split-K GEMM or a GEMV-style kernel. That is expected. What you are looking for is a surprise: a tiny tile for a big M, or a generic fallback kernel after a library upgrade.
7. Performance implications#
| Shape | Regime | Rough share of peak reached |
|---|---|---|
| M = 1 (decode, batch 1) | memory bound | under 1% of FLOPs, 80–90% of bandwidth |
| M = 8 to 64 (typical decode batch) | memory bound | a few % to 20% of FLOPs |
| M = 128 to 512 | crossing the ridge | 40–70% of FLOPs |
| M ≥ 1,024 (prefill) | compute bound | 60–80% of FLOPs |
A practical rule: if your decode GEMMs reach 80–90% of the GPU’s peak bandwidth, the kernels are about as good as they can be. Look for gains elsewhere: fewer bytes (quantization), more tokens per read (batching, speculation).
8. Production implications#
- Merge projections that share an input. Q, K and V become one
qkv_projGEMM; gate and up become onegate_up_proj(11.a). Fewer, larger GEMMs fill the GPU better and launch fewer kernels. Engines do this when loading the weights. - Use the engine’s quantized GEMM kernels (Marlin, Machete, CUTLASS-based FP8 and FP4 paths) rather than “unpack the weights to BF16, then call cuBLAS”, which moves the full-size weights and loses the benefit.
- Re-check kernel choice after any library or driver upgrade. Library heuristics change, and sometimes regress for your exact shapes.
- Know your batch-size distribution. Decode GEMMs live in the M = 1 to 256 region where time is nearly flat, so raising concurrency is almost free until the ridge.
9. Common mistakes#
- Trying to speed up a GEMV by reducing its FLOPs. It is memory bound; reduce bytes instead.
- Running Q, K and V as three separate GEMMs. More launches, worse tiles, three reads of the input.
- Ignoring tile quantization. M = 257 can cost as much as M = 384.
- Writing your own GEMM for production. CUTLASS, cuBLAS and the engines’ tuned kernels represent years of work. Write one to learn (6.e), not to ship.
- Assuming the library always picks the best kernel. Its heuristics are good but not perfect for unusual shapes; cuBLASLt offers a ranked list of algorithms you can time yourself.
10. Hands-on exercise#
- Run
gemm.go. Change the matrix to Qwen3-8B’sgate_up_proj(K = 4096, N = 24576). Does the ridge move? Why not? - On a GPU, time
torch.matmulfor the same M values and plot TFLOP/s and GB/s against M on log axes. Mark where your measured curve leaves the bandwidth line. - Sweep M from 120 to 140 one step at a time and plot the time. Find the tile-quantization jump.
- Time three
(M, 4096) @ (4096, 4096)GEMMs against one(M, 4096) @ (4096, 12288)at M = 1 and M = 2048. Explain the difference at each end. - Use
nsysto find which kernel runs at M = 1, 64 and 2048. Decode the names.
11. Interview questions#
- What is the arithmetic intensity of a GEMV, and why can no kernel improve it?
- Name the three ways out of GEMV-bound decode.
- Describe the tiling hierarchy of a modern GEMM kernel, and what changed on Hopper and Blackwell.
- What are tile quantization and wave quantization? How do you avoid them?
- What is split-K and when does it help?
- What is grouped GEMM, and which workloads need it?
- Your decode GEMMs reach 90% of peak bandwidth. What is left to optimize?
12. Further reading#
Checked on 12 November 2026.
- NVIDIA, Matrix Multiplication Background User’s Guide, including tile and wave quantization
- Goto and van de Geijn, “Anatomy of High-Performance Matrix Multiplication” (ACM TOMS, 2008)
- NVIDIA CUTLASS
- cuBLAS documentation, cuBLASLt API
- DeepGEMM: FP8 GEMM and grouped GEMM kernels (DeepSeek)
- Marlin: a mixed-precision W4A16 GEMM kernel (IST Austria)