Skip to content
AI systems and infrastructure Core 30 min read

How a GPU works: SMs, tensor cores, memory, roofline

A GPU is a machine for doing one thing to a great many numbers at once, built on the bet that there is always more parallel work waiting. Its arithmetic is so fast that the real question for almost every AI workload is not "how many FLOPs?" but "can the bytes arrive in time?" The roofline model turns that question into one number you can compute on a napkin.

10,000 ft

Deep learning became practical when it moved onto graphics processors: AlexNet's 2012 ImageNet win came from "a very efficient GPU implementation of convolutional nets" (Krizhevsky, Sutskever and Hinton), and every large model since has been trained on chips built around the same idea: thousands of simple arithmetic units, fed from a memory hierarchy, running dense matrix products. This page is the foundation of the systems track. Kernels are programs written for this machine; mixed precision exists because its fastest units only speak narrow number formats; distributed training starts when one GPU's 80 GB is not enough; and compute maths, quantisation and serving are all applications of the roofline you will meet here. Architecture choices, too, are shaped by the hardware: FlashAttention, grouped-query attention and mixture of experts are as much about bytes as about modelling.

2,000 ft

A GPU trades the CPU's low latency for enormous throughput. Hold six facts:

  1. Many small cores, grouped. An H100 has 132 streaming multiprocessors (SMs). Each SM has four sub-partitions, each with a scheduler, a slice of the register file, 32 FP32 lanes and one tensor core.
  2. Threads run in warps. You launch a grid of thread blocks; each block lands on one SM; its threads execute 32 at a time in lockstep as a warp.
  3. Tensor cores do the real work. They multiply small matrix tiles in one instruction and provide ~15× the FLOP/s of the ordinary FP32 lanes. Only matrix multiplication can use them.
  4. Memory is a hierarchy. Registers and shared memory on the SM are fast and tiny; the L2 cache is shared; HBM is large (80 GB) but hundreds of cycles away.
  5. Latency is hidden, not avoided. While one warp waits for memory, the scheduler runs another. Keeping enough warps and enough bytes in flight is the programmer's job.
  6. The roofline decides. Time \(\ge \max(\text{FLOPs}/\text{peak},\ \text{bytes}/\text{bandwidth})\). Divide FLOPs by bytes (arithmetic intensity) and compare with the chip's ridge point — about 295 FLOP/byte on an H100 — to know which limit you hit.

Inside an H100: from HBM to a tensor core
Inside an H100: from HBM to a tensor core. HBM3 · 80 GB 3.35 TB/s · ~480 cycles away, L2 cache · 50 MB shared by all SMs, Streaming multiprocessor (×132), Shared memory / L1 256 KB · ~30 cycles, 4 sub-partitions, each with, warp scheduler 1 instruction / clock, register file 64 KB, 32 FP32 lanes, tensor core 512 BF16 FMA / clock, every byte crosses hereInside an H100: from HBM to a tensor core. HBM3 · 80 GB 3.35 TB/s · ~480 cycles away, L2 cache · 50 MB shared by all SMs, Streaming multiprocessor (×132), Shared memory / L1 256 KB · ~30 cycles, 4 sub-partitions, each with, warp scheduler 1 instruction / clock, register file 64 KB, 32 FP32 lanes, tensor core 512 BF16 FMA / clock, every byte crosses here

Ground level

Two ways to spend a transistor budget

A CPU core is built to finish one instruction stream as soon as possible. Most of its silicon goes to making a single thread fast: large caches so data is usually close, branch predictors, out-of-order execution that finds independent instructions to run while one waits. It is a latency machine.

A GPU makes the opposite bet. It assumes the program has far more independent work than there are arithmetic units — a million output pixels, a billion multiply-adds in a matrix product — and spends its transistors on arithmetic and on holding many threads at once, rather than on making any one thread fast. When a thread stalls waiting for memory, the GPU does not try to predict around the stall; it simply switches to another thread whose data has arrived. It is a throughput machine.

The bet pays off spectacularly for neural networks, whose work is overwhelmingly dense linear algebra with no data-dependent branching. It fails for code with little parallelism or lots of divergent control flow — which is why the CPU still runs your data loader, tokeniser and Python interpreter, and why the most common performance bug in deep learning is the GPU waiting on the CPU.

Anatomy of an H100

NVIDIA's H100 (Hopper architecture, 2022) trained most frontier models of 2023–2025 and is the reference point for this track. Its numbers, from NVIDIA's Hopper architecture deep dive and data sheet (SXM version):

Level What it is H100 SXM
GPU the whole chip 132 SMs enabled (of 144 on the full die), 50 MB L2, 80 GB HBM3 at 3.35 TB/s, up to 700 W
SM the unit a thread block runs on 4 sub-partitions, 128 FP32 lanes, 4 tensor cores, 256 KB register file, 256 KB combined L1/shared memory (up to 228 KB as shared memory), up to 2,048 resident threads (64 warps)
Sub-partition one quarter of an SM one warp scheduler issuing one warp-instruction per clock, 16,384 32-bit registers, 32 FP32 lanes, one tensor core
Tensor core a matrix-multiply unit multiplies small tiles: ~512 dense BF16 fused multiply-adds per clock (derived below)

Every number on the peak-throughput line comes from multiplying these counts. FP32 on the ordinary lanes: 132 SMs × 128 lanes × 2 FLOPs per fused multiply-add (FMA) × 1.98 GHz ≈ 67 TFLOP/s, which is what the data sheet says. BF16 on the tensor cores: the data sheet says 989 TFLOP/s dense; dividing by 528 tensor cores and the 1.83 GHz clock NVIDIA uses for tensor-core peaks gives 1,024 FLOPs, or 512 FMAs, per tensor core per clock (Glenn Lockwood's H100 notes do the same arithmetic). The ratio between the two paths is 989 / 67 ≈ 15×. Anything that is not a matrix multiplication — softmax, normalisation, activation functions, the optimiser update — runs on the slow path.

Read the asterisk

NVIDIA's data sheets list tensor-core peaks "with sparsity": 1,979 TFLOP/s BF16 for the H100. That figure assumes 2:4 structured sparsity (two of every four weights zero), which ordinary training does not use. The dense peak is half. Every number on this site is dense unless it says otherwise.

The programming model: grids, blocks, warps

A GPU program is a kernel: one function, launched over a grid of threads that all run it, each with its own index. The hierarchy of software concepts maps one to one onto the hardware:

The CUDA programming model maps onto the hardware
The CUDA programming model maps onto the hardware. Grid the whole kernel launch, Thread block up to 1,024 threads, Warp 32 threads in lockstep, Thread its own registers, GPU 132 SMs, One SM runs several blocks at once, Sub-partition issues 1 warp-instruction / clock, Lane one ALU slot, split into, 32 of, runs on, scheduled onto, issued by, executes inThe CUDA programming model maps onto the hardware. Grid the whole kernel launch, Thread block up to 1,024 threads, Warp 32 threads in lockstep, Thread its own registers, GPU 132 SMs, One SM runs several blocks at once, Sub-partition issues 1 warp-instruction / clock, Lane one ALU slot, split into, 32 of, runs on, scheduled onto, issued by, executes in
  • A thread block is guaranteed to run on a single SM, so its threads can share that SM's fast shared memory and synchronise with a barrier. Blocks cannot rely on each other: the hardware schedules them in any order, onto any SM, as resources free up. That independence is what lets the same program scale from a laptop GPU with 20 SMs to an H100 with 132.
  • A warp is 32 threads that share one instruction stream (NVIDIA calls this SIMT: single instruction, multiple threads). If threads in a warp take different branches of an if, the warp runs both branches one after the other with some lanes masked off — divergence, which wastes lanes. Neural-network kernels rarely diverge, which is part of why they map so well.
  • Hopper added a level between block and grid, the thread block cluster: up to 16 blocks guaranteed to run at the same time on neighbouring SMs, which can read each other's shared memory directly ("distributed shared memory").

How many warps an SM can hold at once is called occupancy, and it is limited by the scarcest per-SM resource. The register file has 65,536 registers per SM; a kernel that needs 128 registers per thread can have at most 65,536 / 128 = 512 threads resident, which is 16 warps, 25% of the maximum 64. A block that asks for 100 KB of shared memory leaves room for only two such blocks per SM. Occupancy is not a goal in itself — the fastest matmul kernels run at low occupancy with huge register tiles — but it is the first thing to check when a memory-bound kernel is slower than the roofline says it should be.

Tensor cores: where the FLOPs are

A tensor core executes a small matrix multiply-accumulate, \(D = A B + C\), as a single instruction across a whole warp (or, on Hopper, a warpgroup of four warps). The operands live in registers or shared memory; the inputs are narrow (FP16, BF16, FP8, and on Blackwell FP4) and the accumulator is usually FP32. Each generation has widened the unit:

Generation (year) Tensor cores Dense FMA per tensor core per clock (FP16) Chip dense FP16/BF16 peak
Volta V100 (2017) 8 per SM × 80 SMs 64 125 TFLOP/s
Ampere A100 (2020) 4 per SM × 108 SMs 256 312 TFLOP/s
Hopper H100 (2022) 4 per SM × 132 SMs ~512 (derived) 989 TFLOP/s
Blackwell B200 (2024) 4 per SM × 148 SMs not published 2,250 TFLOP/s

Sources: the Ampere deep dive for V100 and A100 per-clock rates; the HGX spec table for B200 (36 PFLOP/s sparse for eight GPUs, so 2.25 PFLOP/s dense each); the SM count for B200 from How to Scale Your Model. Check the A100 line yourself: 108 SMs × 4 tensor cores × 256 FMA × 2 FLOPs × 1.41 GHz = 311.9 TFLOP/s.

Two consequences follow. First, dimensions matter. A tensor core multiplies fixed-size tiles, so a matrix whose dimensions are not multiples of the tile shape wastes work in the ragged edge. NVIDIA's matrix-multiplication guide recommends dimensions that are multiples of 8 for FP16 (64 on an A100 for best efficiency). nanoGPT pads GPT-2's 50,257-token vocabulary to 50,304, "the nearest multiple of 64 for efficiency", in its model file. Second, the slow path dominates whatever the fast path does not cover. If the matmuls in a transformer layer took 70% of the time on FP32 lanes and they move to tensor cores 15× faster, the remaining 30% of element-wise work becomes most of the runtime. That is Amdahl's law, and it is why kernel fusion matters as much as faster matmul units.

The memory hierarchy

The arithmetic can only run as fast as operands arrive. Each level of the hierarchy is larger, slower and farther away than the one before:

Level H100 capacity Approximate latency Bandwidth
Registers 256 KB per SM (33.8 MB total) ~1 cycle feeds the ALUs every cycle
Shared memory / L1 256 KB per SM ~30 cycles 128 bytes/clock/SM, ~33 TB/s chip-wide at 1.98 GHz
L2 cache 50 MB ~260 cycles ~5.5 TB/s (measured)
HBM3 80 GB ~480 cycles 3.35 TB/s
NVLink to another GPU — microseconds 450 GB/s each way
InfiniBand to another node — microseconds 400 Gb/s = 50 GB/s per GPU

Latencies are microbenchmark measurements on Hopper (an H800) from Luo et al. (2024); the L2 bandwidth figure and network numbers are from How to Scale Your Model. Exact values vary by part and clock; the ratios are what you should remember. Going one level down costs roughly 10× in latency and 5–10× in bandwidth, and going off the GPU costs another order of magnitude.

registersshared memory / L1 L2 cacheHBM 256 KB/SM · 1 cycle256 KB/SM · ~30 cycles · ~33 TB/s 50 MB · ~260 cycles · ~5.5 TB/s80 GB · ~480 cycles 3.35 TB/s faster, smallerslower, larger
The H100 memory hierarchy. A fast kernel loads each byte from HBM once, then reuses it many times from shared memory and registers. Latencies from Luo et al. (2024), measured on Hopper.

Two rules govern how you use HBM:

  • Coalescing. Memory is fetched in aligned chunks (32-byte sectors, grouped into 128-byte lines). When the 32 threads of a warp read 32 consecutive 4-byte floats, the hardware serves them with one 128-byte transaction. When they read with a stride, each thread may need its own transaction and most of every fetched sector is wasted. Aleksa Gordić measured a naive matmul kernel on an H100 PCIe dropping from about 3,171 to 243 GFLOP/s — 13× — just by making its reads uncoalesced (Inside NVIDIA GPUs).
  • Reuse. A byte loaded from HBM should be used many times before it is evicted. This is the whole art of writing fast matrix kernels, and the subject of the kernels page.

Hiding latency: Little's law

A load from HBM takes about 480 cycles, roughly 0.3 µs. If the GPU issued one load and waited, it would achieve almost nothing. Instead it keeps many loads in flight. Little's law from queueing theory says how many: to sustain a throughput \(X\) through a pipe with latency \(\lambda\), you need \(X\cdot\lambda\) items in flight.

\[ \text{bytes in flight} = 3.35\times10^{12}\ \text{B/s} \times 0.3\times10^{-6}\ \text{s} \approx 1\ \text{MB}. \]

Spread over 132 SMs, that is about 7.6 KB in flight per SM, all the time. If each thread loads one 4-byte float and then waits for it, you need ~1,900 threads per SM — nearly the 2,048 maximum — just to saturate bandwidth. That is the deep reason GPUs hold so many threads, and why good memory-bound kernels load wide vectors (16 bytes per thread per instruction) or use the asynchronous copy engines: Ampere's cp.async and Hopper's Tensor Memory Accelerator (TMA), a unit a single thread can program to move a whole multidimensional tile from HBM to shared memory while the warps compute on the previous one.

The roofline model

Put the two limits together. A kernel that performs \(F\) floating-point operations and moves \(Q\) bytes between HBM and the chip, on hardware with peak \(P\) FLOP/s and bandwidth \(\beta\) B/s, cannot finish faster than

\[ t \ge \max\left(\frac{F}{P},\ \frac{Q}{\beta}\right). \]

Divide both sides into \(F\) and define the arithmetic intensity \(I = F/Q\) (FLOPs per byte). The attainable throughput is

\[ \text{attainable FLOP/s} = \min(P,\ I\cdot\beta). \]

On a log–log plot that is a sloped line (bandwidth-bound) meeting a flat roof (compute-bound) at the ridge point \(I^\ast = P/\beta\). This is the roofline model of Williams, Waterman and Patterson (2009).

vector add (0.08)GEMV / decode (1)batch-64 GEMM (63)GEMM (2,048) H100 roof 989 TFLOP/sslope = 3.35 TB/s A100 (dashed) ridge 295 0.010.11101001k10karithmetic intensity (FLOP per HBM byte) 10 G100 G1 T10 T100 T1 P
The roofline for an H100 (solid) and A100 (dashed), BF16 tensor-core peak. Kernels from the Build it section sit where the model puts them: anything left of the ridge is limited by HBM bandwidth, whatever its FLOP count.

Worked examples on an H100

Run the numbers for the kernels a transformer actually executes (the code is in Build it):

  • Element-wise add of two FP32 vectors: 1 FLOP per element, 12 bytes moved (read two, write one). \(I = 0.083\). Bound by bandwidth at 0.03% of peak. Every activation function, residual add, dropout mask and optimiser update lives here.
  • Softmax over a 50k vocabulary in BF16: about 5 FLOPs per element, 4 bytes (read, write). \(I\approx1.25\). Memory-bound. The only way to speed it up is to read and write fewer bytes — fuse it into its neighbours.
  • Matrix–vector product (decoding one token through an \(8192\times8192\) BF16 layer): each weight is read once (2 bytes) and used in one FMA (2 FLOPs). \(I\approx1\). This is why generating text at batch size 1 runs at well under 1% of the tensor cores' peak and why serving is a batching problem.
  • Same layer, 64 tokens at once: each weight is now used 64 times. \(I\approx63\): still below the ridge, at 21% of peak.
  • Same layer, 4,096 tokens (a training step or a long prefill): \(I\approx2{,}048\), far right of the ridge. Compute-bound, and a good kernel reaches 70–80% of peak.

The rule that falls out, and that compute maths derives formally: for a linear layer applied to \(T\) tokens, arithmetic intensity is about \(T\) FLOPs per byte in BF16. The number of tokens sharing each weight read is the intensity.

Tile and wave quantisation

Two discretisation effects make real matmuls fall below the roofline in steps, and both are worth recognising in a profile. A GEMM kernel cuts the output into tiles, say \(256\times128\), and gives each tile to one thread block.

  • Tile quantisation: if a dimension is not a multiple of the tile, the last row of tiles is partly empty but costs as much as a full one.
  • Wave quantisation: tiles are processed in waves of one per SM. NVIDIA's guide gives the A100 example: with \(M=2304\) and \(256\times128\) tiles there are 9 tiles down; at \(N=1536\) there are \(9\times12 = 108\) tiles, exactly one wave on 108 SMs. At \(N=1544\) there are \(9\times13=117\) tiles: one full wave plus a tail of 9 tiles that occupies 8% of the GPU for nearly a full wave's time. Throughput roughly halves for a 0.5% larger matrix.

The practical rule: choose hidden sizes, head dimensions, vocabulary sizes and batch sizes with plenty of factors of two, and benchmark the shapes you actually run rather than trusting the average.

Generations: the ridge keeps rising

GPU (year) Dense BF16/FP16 HBM capacity HBM bandwidth Ridge (FLOP/byte)
V100 (2017) 125 TFLOP/s 16–32 GB 0.9 TB/s 139
A100 80 GB (2020) 312 TFLOP/s 80 GB 2.0 TB/s 153
H100 SXM (2022) 989 TFLOP/s 80 GB 3.35 TB/s 295
B200 (2024) 2,250 TFLOP/s 180 GB 8 TB/s 281

B200 per-GPU figures are the DGX B200 system totals divided by eight (1,440 GB and 64 TB/s HBM3e). Two trends matter. FLOP/s grows faster than bandwidth — Gholami et al. (2024) estimate server peak FLOP/s grew 3.0× every two years over two decades, against 1.6× for DRAM bandwidth and 1.4× for interconnect — so ridge points drift upward and more workloads become memory-bound. And each generation adds a narrower number format with double the throughput (FP8 on Hopper, FP4 on Blackwell: 4.5 and 9 PFLOP/s dense per B200), which is the subject of mixed precision and quantisation. As of 2026, Blackwell systems (B200, B300 and the rack-scale GB200 NVL72, which puts 72 GPUs in one NVLink domain) are shipping, and the H100 remains the most common training chip in the public literature.

Other accelerators, same physics

The roofline does not care who made the chip.

  • Google TPUs replace SMs with a few very large systolic arrays: grids of multiply-accumulate cells through which operands flow in lockstep, each value reused across a whole row or column of the array without touching memory. They are less flexible than GPUs and even more dependent on large, regular matmuls. How to Scale Your Model is written around them.
  • AMD Instinct GPUs (MI300 series) follow the same SM-like design ("compute units") with larger HBM capacity per chip, programmed through ROCm/HIP; Triton targets them too.
  • Apple silicon uses unified memory: CPU and GPU share one pool, so a laptop can hold a model too large for a gaming GPU, but its bandwidth is far below HBM and token generation speed follows directly; see on-device AI.

History

Graphics chips became programmable shaders in the early 2000s, and researchers began disguising general computations as pixel shading ("GPGPU"). NVIDIA released CUDA in 2007, exposing the GPU as a grid of C threads with explicit shared memory — the model on this page. Neural-network researchers adopted it early; the decisive moment was AlexNet (2012), trained for between five and six days on two GTX 580 cards with 3 GB each, which won ImageNet by a wide margin and made "train it on GPUs" the default. NVIDIA then reshaped the chip around deep learning: Volta (2017) introduced tensor cores; Ampere (2020) added BF16, TF32 and 2:4 sparsity; Hopper (2022) added FP8, the TMA and thread block clusters; Blackwell (2024) added FP4 and microscaled formats and pushed NVLink domains to rack scale. Meanwhile Google built the TPU (first deployed in 2015) on the systolic-array idea from 1970s VLSI research. The history track covers the industry side in hardware, chips and deep tech.

First principles

Why throughput beats latency for this workload. Power, not transistor count, has limited chips since the mid-2000s, when Dennard scaling (shrinking transistors at constant power density) ended and single-thread clock speeds stalled around 3–5 GHz. Performance per watt is then won by doing more operations per unit of control logic. A warp shares one instruction fetch, decode and schedule across 32 lanes; a tensor core amortises one instruction over hundreds of multiply-adds. The narrower the number and the larger the tile, the more of each joule goes into arithmetic rather than bookkeeping.

Why matrix multiplication is special. Multiplying two \(n\times n\) matrices does \(2n^3\) FLOPs on \(3n^2\) numbers. Compute grows faster than data, so given enough on-chip storage the intensity \(\propto n\) can always beat the ridge. Element-wise operations do \(O(1)\) work per element and can never escape the bandwidth slope. A chip that makes matmul 15× faster than everything else is a bet that the model's work is mostly matmul — and neural-network architects have answered by designing models that are: almost all of a transformer's FLOPs are in its weight matmuls (compute maths).

Why on-chip memory sets the ceiling on intensity. The intensity a matmul actually achieves against HBM is set by how big a tile you can keep on chip, not by \(n\). A thread block computing a \(T\times T\) output tile while streaming the inner dimension does \(2T^2\) FLOPs per \(2T\) elements loaded per step, so intensity against HBM is about \(T/b\) FLOPs per byte for \(b\)-byte numbers (derived below). Shared memory and registers are limited (228 KB and 256 KB per SM), so \(T\) is a few hundred at most, and caches (L2, cluster multicast) supply the rest. Every generation's larger on-chip storage exists to raise this number to match the rising ridge.

What breaks if you ignore it. Unfused attention in a 2020-era transformer materialised the full \(s\times s\) score matrix in HBM, read it back for softmax, wrote it again, and read it for the value product: memory-bound operations taking a large share of runtime despite few FLOPs (Ivanov et al., 2020). FlashAttention's speed-ups came from not moving those bytes, not from doing fewer FLOPs.

The maths

Roofline. For a kernel with \(F\) FLOPs and \(Q\) HBM bytes, on a chip with peak \(P\) and bandwidth \(\beta\):

\[ t_{\min} = \max\!\left(\frac{F}{P},\frac{Q}{\beta}\right),\qquad I=\frac{F}{Q},\qquad \frac{F}{t_{\min}} = \min(P,\ I\beta),\qquad I^\ast=\frac{P}{\beta}. \]

If computation and memory traffic do not overlap at all, the time is the sum rather than the max, so the roofline is optimistic by up to 2×; good kernels overlap them (double buffering, TMA, warp specialisation) to approach the max.

Little's law. In a steady-state pipeline, items in flight \(=\) throughput \(\times\) latency: \(N = X\lambda\). For HBM, \(N = \beta\lambda\) bytes must be outstanding at all times; divided by the number of SMs and by the bytes each thread requests per load, it gives the minimum number of concurrent threads (or asynchronous copies) needed to reach full bandwidth.

Derivation: the intensity of a tiled matrix multiply

Compute \(C = AB\) with \(A\in\mathbb{R}^{M\times K}\), \(B\in\mathbb{R}^{K\times N}\), elements of \(b\) bytes. Partition \(C\) into tiles of \(T_m\times T_n\); one thread block owns one tile and loops over \(K\) in steps of \(T_k\). At each step it loads a \(T_m\times T_k\) slab of \(A\) and a \(T_k\times T_n\) slab of \(B\) into shared memory and performs \(2T_mT_nT_k\) FLOPs on them.

Bytes loaded per step: \(b(T_m+T_n)T_k\). FLOPs per step: \(2T_mT_nT_k\). So the intensity against the level the tiles come from is

\[ I_{\text{tile}} = \frac{2T_mT_n}{b\,(T_m+T_n)} \;\xrightarrow{T_m=T_n=T}\; \frac{T}{b}. \]

Total traffic: there are \((M/T_m)(N/T_n)\) tiles, each reading \(b(T_m+T_n)K\) bytes, so \(Q = bMNK\,(1/T_n + 1/T_m)\). With square tiles, \(Q = 2bMNK/T\): tiling divides the naive traffic (\(2bMNK\), every product reading two operands) by exactly \(T\). The Build it code measures this.

Worked numbers: a \(128\times256\) BF16 tile gives \(I_{\text{tile}} = 2\cdot128\cdot256 / (2\cdot384) \approx 85\) FLOP/byte — below the H100 ridge of 295. Real kernels close the gap because neighbouring blocks read the same slabs of \(A\) and \(B\), which then come from L2 rather than HBM (and on Hopper can be multicast to a cluster of SMs with one TMA load), and because the scheduler orders tiles so that blocks sharing data run at the same time.

Peak FLOP/s from first principles.

\[ P = n_{\text{SM}} \times n_{\text{TC/SM}} \times \text{FMA per TC per clock} \times 2 \times f_{\text{clock}}. \]

For the A100: \(108\times4\times256\times2\times1.41\times10^9 = 3.12\times10^{14}\).

Build it

NumPy, no GPU required. The first snippet is a roofline calculator for the kernels above on four GPU generations.

# Dense BF16 tensor-core peak (FLOP/s) and HBM bandwidth (B/s), from NVIDIA data sheets
GPUS = {"V100": (125e12, 0.90e12), "A100": (312e12, 2.039e12),
        "H100": (989e12, 3.35e12), "B200": (2250e12, 8.0e12)}

def roofline(flops, bytes_, gpu):
    peak, bw = GPUS[gpu]
    t = max(flops / peak, bytes_ / bw)              # the slower of the two limits
    return t, flops / bytes_, "compute" if flops / peak > bytes_ / bw else "memory"

def matmul(m, k, n, b=2):                           # C = A @ B, b bytes per element
    return 2 * m * k * n, b * (m * k + k * n + m * n)

ops = {
    "vector add, 1e8 fp32":   (1e8, 12 * 1e8),      # read 2, write 1, 4 B each
    "softmax 4096x50k bf16":  (5 * 4096 * 50257, 2 * 2 * 4096 * 50257),
    "GEMV decode 8k x 8k":    matmul(1, 8192, 8192),
    "GEMM batch 64 tokens":   matmul(64, 8192, 8192),
    "GEMM 4096 tokens":       matmul(4096, 8192, 8192),
    "GEMM 8192^3":            matmul(8192, 8192, 8192),
}
for g, (p, bw) in GPUS.items():
    print(f"{g}: ridge = {p / bw:5.0f} FLOP/byte")
print()
print(f"{'operation':24s}{'FLOP/B':>9s}{'H100 time':>12s}{'bound':>9s}{'% peak':>8s}")
for name, (f, by) in ops.items():
    t, I, bound = roofline(f, by, "H100")
    print(f"{name:24s}{I:9.2f}{t * 1e6:10.1f} us{bound:>9s}{100 * f / t / 989e12:7.1f}%")
V100: ridge =   139 FLOP/byte
A100: ridge =   153 FLOP/byte
H100: ridge =   295 FLOP/byte
B200: ridge =   281 FLOP/byte

operation                  FLOP/B   H100 time    bound  % peak
vector add, 1e8 fp32         0.08     358.2 us   memory    0.0%
softmax 4096x50k bf16        1.25     245.8 us   memory    0.4%
GEMV decode 8k x 8k          1.00      40.1 us   memory    0.3%
GEMM batch 64 tokens        63.02      40.7 us   memory   21.3%
GEMM 4096 tokens          2048.00     555.9 us  compute  100.0%
GEMM 8192^3               2730.67    1111.7 us  compute  100.0%

Notice the GEMV and the batch-64 GEMM take the same 40 µs: both are dominated by reading the same 134 MB weight matrix, and the 64× extra arithmetic is free. The second snippet simulates what a GPU matmul kernel does — tile the output, stream tiles of the inputs through "shared memory", accumulate in "registers" — and counts the elements read from "HBM".

import numpy as np

def tiled_matmul(A, B, T):
    """C = A @ B computed tile by tile, counting elements read from 'HBM'.
    Each (T x T) output tile is one thread block: it streams T x T tiles of A
    and B through 'shared memory' and keeps its C tile in 'registers'."""
    n = A.shape[0]
    C = np.zeros((n, n), dtype=np.float32)
    loads = 0
    for i in range(0, n, T):                 # every output tile ...
        for j in range(0, n, T):
            acc = np.zeros((T, T), dtype=np.float32)       # registers
            for k in range(0, n, T):         # ... walks along K
                a = A[i:i+T, k:k+T]          # HBM -> shared memory
                b = B[k:k+T, j:j+T]
                loads += a.size + b.size
                acc += a @ b                 # reused T times each, on chip
            C[i:i+T, j:j+T] = acc
    return C, loads

rng = np.random.default_rng(0)
n = 256
A = rng.standard_normal((n, n), dtype=np.float32)
B = rng.standard_normal((n, n), dtype=np.float32)
naive = 2 * n**3                             # every product re-reads a and b
print(f"naive (no reuse): {naive:>12,} element loads")
for T in (8, 32, 128):
    C, loads = tiled_matmul(A, B, T)
    assert np.allclose(C, A @ B, atol=1e-3)
    print(f"tile {T:3d}:        {loads:>12,} element loads  "
          f"= 2n^3/T  -> {naive // loads}x less traffic, intensity {2*n**3/(4*loads):.0f} FLOP/B fp32")
naive (no reuse):   33,554,432 element loads
tile   8:           4,194,304 element loads  = 2n^3/T  -> 8x less traffic, intensity 2 FLOP/B fp32
tile  32:           1,048,576 element loads  = 2n^3/T  -> 32x less traffic, intensity 8 FLOP/B fp32
tile 128:             262,144 element loads  = 2n^3/T  -> 128x less traffic, intensity 32 FLOP/B fp32

The traffic falls exactly as \(2n^3/T\) and the intensity rises as \(T/4\) in FP32 (\(T/2\) in BF16), as derived in The maths. To reach an H100's ridge of 295 with square tiles alone you would need \(T\approx600\) in BF16, and a \(600\times600\) FP32 accumulator alone is 1.4 MB, more than five times an SM's register file. That gap is what L2 reuse, clusters and careful tile scheduling close.

Things to try

  • Add an RMSNorm over a \(4096\times8192\) BF16 activation (≈ 4 FLOPs per element, read once and write once). Where does it sit, and how long does it take compared with the 4,096-token GEMM that follows it?
  • Find the batch size at which a decode GEMV crosses the ridge on each GPU. Why is it larger on an H100 than an A100, even though the H100 is faster?
  • Change tiled_matmul to use rectangular tiles \(T_m\times T_n\) and check the traffic formula \(Q = MNK(1/T_m + 1/T_n)\) elements.
  • Add a "sum" mode to roofline that returns \(F/P + Q/\beta\) (no overlap) and see how much the prediction changes for a kernel near the ridge.
  • On a machine with a CUDA GPU, time torch.matmul for \(n = 1024, 1032, 2048, 2056\) in BF16 and look for tile- and wave-quantisation steps.

In practice

  • Profile before you optimise. The PyTorch profiler shows per-kernel time; Nsight Compute shows, for one kernel, achieved FLOP/s and bandwidth as a percentage of peak — a roofline for your actual code. A kernel that is memory-bound and already at 80–90% of bandwidth is done; one at 20% has a coalescing, occupancy or launch problem.
  • Three regimes, three fixes. Horace He's essay splits time into compute, memory bandwidth and overhead (Python, kernel launches, CPU work). If the GPU is idle between kernels, no kernel optimisation helps; use larger batches, CUDA graphs or torch.compile.
  • Shapes. Keep matmul dimensions multiples of 64 (or 128), pad vocabularies, and check that the batch × sequence product gives enough tiles to fill every SM several times over.
  • Don't trust nvidia-smi utilisation. It reports the fraction of time some kernel was running, not how hard the SMs worked; see compute maths.
  • Know your part. "H100" covers SXM (700 W, 3.35 TB/s) and PCIe (lower clocks and power, 114 SMs) versions with different peaks; cloud instances may also cap power.

Common misconceptions

\"More TFLOP/s means faster LLM inference.\"

Token generation at small batch is a matrix–vector product with intensity ≈ 1. It runs at the speed of HBM, not of the tensor cores. A chip with twice the FLOP/s and the same bandwidth generates tokens at the same speed.

\"A GPU core is like a CPU core, just more of them.\"

The 16,896 "CUDA cores" in an H100 are lanes, not cores: 32 of them share one instruction stream. The closer analogue of a CPU core is the SM, of which there are 132. And most of the FLOPs are not in the CUDA cores at all, but in 528 tensor cores.

\"High occupancy means a fast kernel.\"

Occupancy is a means of hiding latency. The fastest matmul kernels deliberately run few warps with large register tiles, hiding latency with asynchronous copies instead. Measure achieved FLOP/s and bandwidth, not occupancy.

Check yourself

What are a warp, a thread block and an SM, and which one can share shared memory?

A warp is 32 threads executing one instruction stream in lockstep. A thread block is a group of up to 1,024 threads (so up to 32 warps) guaranteed to run on one SM. An SM is the hardware unit with its own registers, shared memory, schedulers and tensor cores. Threads in the same block share that SM's shared memory and can synchronise; different blocks cannot (except within a Hopper cluster, via distributed shared memory).

Compute the arithmetic intensity of y = x + b for FP32 vectors, and the time for 10^9 elements on an H100.

1 FLOP per element; bytes: read \(x\) and \(b\) (8 B), write \(y\) (4 B) = 12 B. \(I = 1/12 \approx 0.083\). Time ≈ \(12\times10^9 / 3.35\times10^{12} \approx 3.6\) ms, set entirely by bandwidth; the FLOPs alone would take 15 µs on the FP32 lanes.

Why does decode at batch 1 reach under 1% of an H100's peak, and what are the two ways to fix it?

Every weight is read from HBM once per token and used for one multiply-add, so \(I\approx1\) FLOP/byte against a ridge of 295. Fixes: raise intensity (serve many sequences per weight read: batching; or verify several tokens per read: speculative decoding), or move fewer bytes (quantised weights, smaller KV caches).

A kernel uses 96 registers per thread and 48 KB of shared memory per 256-thread block. How many blocks fit on one H100 SM?

Registers: 96 × 256 = 24,576 per block; 65,536 / 24,576 = 2.67 → 2 blocks. Shared memory: 228 / 48 = 4.75 → 4 blocks. Threads: 2,048 / 256 = 8 blocks. The minimum is 2 blocks (16 warps, 25% occupancy), limited by registers. (Real allocation granularity can shave this further.)

Using Little's law, how many bytes must be in flight to saturate an A100's 2.0 TB/s if HBM latency is ~470 cycles at 1.41 GHz?

Latency ≈ 470 / 1.41×10⁹ ≈ 0.33 µs. In flight ≈ 2.04×10¹² × 0.33×10⁻⁶ ≈ 0.68 MB, or about 6.3 KB per SM across 108 SMs — about 1,600 threads per SM each waiting on one 4-byte load, or 400 if each loads 16 bytes.

Hard: why does the ridge point matter more for inference than for training, and why do rising ridges hurt inference more?

Training multiplies every weight by thousands of tokens (batch × sequence), so its matmuls sit far right of any ridge. Inference decode multiplies each weight by only the number of sequences in the batch, often tens. As FLOP/s grows faster than bandwidth, the ridge moves right, and decode — whose intensity is fixed by the batch size — falls further below it, using a smaller fraction of each new chip. That is why bandwidth (and capacity, which allows bigger batches) is the headline spec for inference hardware.

Hard: a 128×128 BF16 tile kernel achieves only 60% of peak on a large square GEMM on an H100 even though n is huge. Give two reasons from this page.

(1) Intensity against the level the tiles come from is only \(T/b = 64\) FLOP/byte, below the ridge, so unless L2 reuse is excellent the kernel is still partly bandwidth-bound; bigger or rectangular tiles, cluster multicast and better tile ordering raise it. (2) Without asynchronous copies and double buffering, loads and math do not overlap, so time tends toward the sum of the two limits. Other candidates: wave quantisation if the tile count is not a multiple of 132, and not using Hopper's warpgroup MMA instructions.

Go deeper

Papers

Official documentation

Articles and blog posts

Videos and courses

Where this leads

  • Kernels: CUDA and Triton — write code for this machine: coalesced loads, tiled matmul, fusion, FlashAttention.
  • Mixed precision — why the tensor cores want BF16 and FP8, and how to train with them safely.
  • Compute maths — the roofline scaled up to whole models: FLOPs, memory and cost.
  • Distributed training — the next level of the hierarchy: NVLink and InfiniBand.
  • Serving LLMs — the decode roofline turned into an engineering discipline.