Kernels: CUDA and Triton¶
A kernel is one function run by thousands of GPU threads at once, and writing a fast one is the craft of deciding which bytes live where, and when. Three ideas — coalesce your loads, reuse every byte from on-chip memory, and fuse operations so intermediates never touch HBM — explain nearly every kernel that made modern AI faster, from cuBLAS to FlashAttention.
10,000 ft
Every operation in a neural network, from a matrix multiply to a softmax, runs on the GPU as
a kernel. Most practitioners never write one: PyTorch calls NVIDIA's cuBLAS and cuDNN,
and torch.compile generates the rest. But the step changes in efficiency of the last few
years — FlashAttention making long
context affordable, fused optimisers, FP8 matmuls for mixed precision,
paged KV caches for serving, grouped GEMMs for
mixture of experts — were all custom kernels. This
page turns the machine model of how a GPU works into code: CUDA, which
programs individual threads, and Triton, which programs blocks of data and leaves the
thread-level choreography to a compiler. The point is less to make you a kernel engineer
than to let you read a profile, know which costs are fixable, and recognise when a custom
kernel is the right tool.
2,000 ft
A kernel gets fast by climbing a fixed ladder, each rung aimed at one limit from the roofline:
- Parallelise correctly: map output elements to threads and blocks; enough blocks to fill every SM.
- Coalesce: adjacent threads read adjacent addresses, so each warp's loads become a few wide transactions.
- Tile into shared memory: a block loads a tile once and all its threads reuse it.
- Tile into registers and tensor cores: each thread or warp computes a small output tile, reusing operands from registers; matrix tiles go to the tensor cores.
- Overlap: copy the next tile asynchronously while computing on this one.
- Fuse: do several operations per load, so intermediates stay on chip.
You can write all of this in CUDA C++, or write steps 1 and 6 in Triton and let its compiler do 2–5. Either way the result is lowered to the same machine code:
Ground level¶
What a kernel is¶
Here is the smallest useful CUDA kernel, an element-wise add, with its launch:
__global__ void add(const float* x, const float* y, float* out, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x; // this thread's element
if (i < n) out[i] = x[i] + y[i]; // guard the ragged last block
}
// host side: one thread per element, 256 threads per block
add<<<(n + 255) / 256, 256>>>(x, y, out, n);
__global__ marks a function that runs on the GPU and is launched from the CPU. The launch
<<<blocks, threads_per_block>>> creates a grid of \(\lceil n/256\rceil\) blocks of 256 threads;
every thread runs the same function and finds its element from the built-in indices
blockIdx, blockDim and threadIdx. Consecutive threads touch consecutive floats, so each
warp's 32 loads coalesce into one 128-byte transaction per array: this kernel already runs at
close to the HBM bandwidth limit, which for an element-wise add is the roofline. There is
nothing left to optimise inside it.
What remains is what happens between kernels. Every launch costs CPU time and a few microseconds of GPU scheduling, and every kernel boundary forces its output out to HBM so the next kernel can read it back. A transformer layer executed op by op in eager PyTorch launches dozens of small kernels, most of them memory-bound. Two techniques attack the two costs: CUDA graphs record a sequence of launches once and replay it with one call (removing launch overhead), and fusion merges kernels (removing the HBM round trips).
Fusion: the cheapest speed-up there is¶
Take the residual add and RMSNorm that sit between every pair of sublayers in a transformer block: \(h = x + r\), then \(y = h\cdot w / \sqrt{\operatorname{mean}(h^2)+\epsilon}\). In eager PyTorch that is a chain of separate operations — add, square, mean, add \(\epsilon\) and reciprocal square root, multiply, multiply — and each full-size intermediate is written to HBM and read back. Counting full-tensor passes, it reads about six and writes about four. A single fused kernel reads \(x\), \(r\) (and the small \(w\)) once and writes \(h\) (the new residual) and \(y\) once: four passes instead of about ten, and since the operation is memory-bound, roughly 2.5× faster.
The same arithmetic, from the Triton fused-softmax tutorial: a naive row-wise softmax over an \(M\times N\) matrix reads \(5MN+2M\) elements and writes \(3MN+2M\); the fused kernel reads \(MN\) and writes \(MN\), so the tutorial expects — and measures — about a 4× speed-up.
The fusion rule of thumb
For memory-bound chains, runtime ≈ (bytes of every intermediate written and read) / bandwidth. Fusion deletes intermediates. Any chain of element-wise and row-wise operations between two matmuls should be one kernel — and fusing it into the matmul's epilogue (the code that writes the output tile) is better still, because the matmul's output is already in registers.
This is the main job of torch.compile. TorchDynamo captures a graph of PyTorch operations from
your Python code; TorchInductor, its default backend, fuses element-wise and reduction chains
and generates Triton kernels for them on GPUs. The PyTorch 2 paper reports a 2.27× inference
and 1.41× training geometric-mean speed-up on an A100 across more than 180 real-world models
(Ansel et al., 2024), most of it from fusion
and reduced overhead.
The matmul ladder¶
Matrix multiplication is the opposite case: compute-bound if done right, so the job is maximising reuse. Simon Boehm's worklog optimises an FP32 matmul (no tensor cores) on \(4092\times4092\) matrices step by step against cuBLAS, and it is the best single lesson in GPU programming:
What each rung fixes:
- Naive — one thread per output element, each reading a full row of \(A\) and column of \(B\) from HBM. Boehm counts ~548 GB of memory traffic for a computation whose inputs and output total ~268 MB.
- Coalescing — remap threads so that a warp's 32 threads read consecutive addresses. Same algorithm, 6.4× faster.
- Shared-memory tiling — a block loads \(32\times32\) tiles of \(A\) and \(B\) into shared memory once and all threads reuse them. Traffic to HBM falls by the tile size.
- 1-D register tiling — each thread computes several outputs, so each value it loads from shared memory is used several times from registers. Shared memory bandwidth was now the limit.
- 2-D register tiling — each thread computes an \(8\times8\) block of outputs as a sum of outer products: 16 loads feed 64 FMAs.
- Vectorised access — 128-bit loads (
float4) and a transposed layout so shared-memory reads are wide too. - Autotuning — search tile sizes per GPU; the best choice differs between models.
- Warp tiling — an intermediate tile per warp, improving register locality and scheduling: 93.7% of cuBLAS.
The pattern generalises: every level of the memory hierarchy gets its own tile, sized to that level's capacity, so that each byte fetched from a slow level is used many times at a faster one.
Tensor cores and the Hopper toolbox¶
Boehm's kernels use the FP32 lanes. A BF16 matmul on tensor cores adds four more ideas, which Aleksa Gordić walks through on an H100 in Inside NVIDIA GPUs:
- Matrix instructions. On Ampere a warp issues
mma.syncon register fragments; on Hopper a warpgroup of four warps issues the asynchronouswgmma, which reads one operand straight from shared memory. Operands must be laid out (often swizzled, permuted to avoid shared-memory bank conflicts) exactly as the instruction expects. - The Tensor Memory Accelerator. One thread programs the TMA to copy a whole tile from HBM to shared memory; the copy proceeds while warps compute, and an mbarrier signals completion. Tiles can be multicast to every SM in a cluster, cutting L2 traffic.
- Warp specialisation. Instead of every warp both loading and computing, a producer warpgroup only issues TMA copies into a ring of shared-memory buffers while consumer warpgroups only run tensor-core math, synchronised by full/empty barriers. Copy and compute overlap completely.
- Persistent kernels. Launch exactly one block per SM; each loops over output tiles from a schedule (Gordić's uses a Hilbert curve for cache locality), so the epilogue of one tile overlaps the loads of the next and there is no wave-quantisation tail.
In the worklog Gordić follows, a basic tensor-core kernel with TMA reaches ~317 TFLOP/s and these refinements take it to ~764 TFLOP/s, at or slightly above cuBLAS on the target shapes. Nobody hand-writes this from scratch: CUTLASS (NVIDIA's C++ template library) and its layout algebra CuTe provide the building blocks; DeepSeek's DeepGEMM is a compact, readable library of FP8 GEMMs that reports up to 1,550 TFLOP/s on an H800; and ThunderKittens wraps these primitives in a small set of tile abstractions.
Triton: programming blocks, not threads¶
Triton (Tillet,
Kung and Cox, 2019; developed at OpenAI since) changes the unit of programming. A Triton
program handles one block of data — a tile — and you write operations on whole tiles:
load a tile, multiply two tiles, reduce a tile along an axis. The compiler decides how threads
and warps split the tile, coalesces the loads, stages data through shared memory, and emits
tensor-core instructions for tl.dot. You still choose the tiling, the grid and the fusion.
The element-wise add, in Triton (requires a CUDA or ROCm GPU; not run for this page):
import torch, triton
import triton.language as tl
@triton.jit
def add_kernel(x_ptr, y_ptr, out_ptr, n, BLOCK: tl.constexpr):
pid = tl.program_id(axis=0) # which block am I?
offs = pid * BLOCK + tl.arange(0, BLOCK) # a vector of BLOCK offsets
mask = offs < n # guard the ragged end
x = tl.load(x_ptr + offs, mask=mask)
y = tl.load(y_ptr + offs, mask=mask)
tl.store(out_ptr + offs, x + y, mask=mask)
def add(x, y):
out = torch.empty_like(x)
grid = (triton.cdiv(x.numel(), 1024),) # one program per 1,024 elements
add_kernel[grid](x, y, out, x.numel(), BLOCK=1024)
return out
A fused residual-add + RMSNorm, one program per row (assumes the row fits in one block, as for hidden sizes up to a few thousand):
@triton.jit
def add_rmsnorm(x_ptr, res_ptr, w_ptr, out_ptr, n_cols, eps, BLOCK: tl.constexpr):
row = tl.program_id(0)
cols = tl.arange(0, BLOCK)
mask = cols < n_cols
x = tl.load(x_ptr + row * n_cols + cols, mask=mask, other=0.0).to(tl.float32)
r = tl.load(res_ptr + row * n_cols + cols, mask=mask, other=0.0).to(tl.float32)
h = x + r
tl.store(res_ptr + row * n_cols + cols, h, mask=mask) # new residual stream
rms = tl.rsqrt(tl.sum(h * h, axis=0) / n_cols + eps) # statistics in FP32
w = tl.load(w_ptr + cols, mask=mask, other=0.0).to(tl.float32)
tl.store(out_ptr + row * n_cols + cols, h * rms * w, mask=mask)
Note the habits: compute statistics in FP32 even when tensors are BF16 (see mixed precision); mask every load and store; and write two outputs from one pass because the next layer needs both.
And a tiled matmul — the whole shared-memory/tensor-core machinery is the one line tl.dot:
@triton.jit
def matmul_kernel(a_ptr, b_ptr, c_ptr, M, N, K,
stride_am, stride_ak, stride_bk, stride_bn, stride_cm, stride_cn,
BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr):
pid_m, pid_n = tl.program_id(0), tl.program_id(1) # which C tile
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
offs_k = tl.arange(0, BLOCK_K)
a_ptrs = a_ptr + offs_m[:, None] * stride_am + offs_k[None, :] * stride_ak
b_ptrs = b_ptr + offs_k[:, None] * stride_bk + offs_n[None, :] * stride_bn
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) # FP32 accumulator
for k in range(0, tl.cdiv(K, BLOCK_K)): # walk along K
k_left = K - k * BLOCK_K
a = tl.load(a_ptrs, mask=(offs_m[:, None] < M) & (offs_k[None, :] < k_left), other=0.0)
b = tl.load(b_ptrs, mask=(offs_k[:, None] < k_left) & (offs_n[None, :] < N), other=0.0)
acc += tl.dot(a, b) # tensor cores
a_ptrs += BLOCK_K * stride_ak
b_ptrs += BLOCK_K * stride_bk
c_ptrs = c_ptr + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn
tl.store(c_ptrs, acc, mask=(offs_m[:, None] < M) & (offs_n[None, :] < N))
# launch: grid = (triton.cdiv(M, 128), triton.cdiv(N, 128))
# matmul_kernel[grid](a, b, c, M, N, K, *a.stride(), *b.stride(), *c.stride(),
# BLOCK_M=128, BLOCK_N=128, BLOCK_K=64)
The official matrix multiplication tutorial
adds two things this sketch omits: @triton.autotune over block sizes, warps and pipeline
stages, and grouped ordering of program ids so that consecutive programs share rows of \(A\) in
L2. With them it matches cuBLAS on many shapes. To fuse an activation, apply it to acc before
the store: that is an epilogue fusion.
| CUDA C++ (with CUTLASS) | Triton | |
|---|---|---|
| Unit you program | a thread (and warp, block) | a block of data (a program) |
| Shared memory, coalescing, tensor-core layout | you manage | compiler manages |
| Peak achievable | everything the hardware offers, first | close to peak for most kernels; newest features arrive later |
| Lines for a decent fused kernel | hundreds | tens |
| Where it shines | the very hottest kernels: GEMMs, attention, MoE dispatch | fused element-wise/reduction chains, custom attention variants, research |
As of 2026 the landscape also includes JAX's Pallas (Triton-like kernels for GPUs and TPUs), and Triton itself targets AMD GPUs. The lesson is stable across them: the programmer chooses tiles and fusion; the tool chooses the thread-level mapping.
Case study: FlashAttention¶
Attention is the cleanest demonstration of everything on this page. Standard attention computes \(S = QK^\top/\sqrt d\), \(P = \operatorname{softmax}(S)\), \(O = PV\) as separate kernels. For a sequence of \(N\) tokens, \(S\) and \(P\) are \(N\times N\): at \(N=8192\) that is 67 M elements per head, written to and read from HBM several times, while the matmuls themselves are small (\(d = 64\) or 128). The operation is memory-bound because of the intermediates, not the inputs.
FlashAttention (Dao et al., 2022) fuses the whole thing into one kernel and never writes \(S\) or \(P\):
The obstacle is softmax: each output row needs the maximum and the sum over the whole row of scores, but a tile only sees part of it. The fix is the online softmax: keep a running maximum \(m\) and running denominator \(\ell\), and when a new tile raises the maximum, rescale everything accumulated so far by \(e^{m_{\text{old}}-m_{\text{new}}}\). The result is exact, not an approximation (the derivation is in The maths, and the scalar version of the trick is in floating point and log-sum-exp). For the backward pass FlashAttention stores only the per-row log-sum-exp and recomputes \(S\) and \(P\) tile by tile — more FLOPs, far fewer bytes, a net win.
The paper reported a 3× speed-up on GPT-2 training at sequence length 1K and 15% end-to-end on BERT-large against the MLPerf 1.1 record, and memory linear rather than quadratic in \(N\), which is what made long context practical. Then the same idea was tuned to each generation:
- FlashAttention-2 (Dao, 2023) reduced non-matmul FLOPs (which run on the 15×-slower path), parallelised over the sequence as well as over batch and heads, and split work between warps to avoid shared-memory traffic: 50–73% of peak on an A100, and up to 225 TFLOP/s per A100 (72% MFU) training GPT-style models.
- FlashAttention-3 (Shah et al., 2024) used Hopper's asynchrony — warp specialisation, TMA, and overlapping the softmax of one tile with the matmul of the next — reaching ~740 TFLOP/s in FP16 (~75% of an H100) and close to 1.2 PFLOP/s in FP8.
Correctness: test like a numerical analyst¶
A fast kernel that is subtly wrong is worse than a slow one. Three habits:
- Compare against a reference with tolerances. Floating-point addition is not associative, so a kernel that sums in a different order gives different bits. Compare with a high-precision reference (FP32 or FP64) and set tolerances by dtype — BF16 results agree with an FP32 reference to roughly 2–3 significant digits, not 7. Check edge shapes: sizes that are not multiples of the block, length 1, empty.
- Watch reductions and atomics. Reductions that use atomic adds from many blocks finish in a nondeterministic order, so results can vary run to run. Fine for training noise, a problem for reproducibility tests and for debugging.
- Benchmark honestly. Warm up (the first call compiles or autotunes), synchronise the GPU
before stopping the clock, clear the L2 cache between runs for realistic memory-bound timings,
and report achieved bandwidth or FLOP/s as a fraction of peak, not just milliseconds.
triton.testing.do_benchdoes most of this.
History¶
CUDA (2007) made GPUs programmable as arrays of C threads; NVIDIA's libraries — cuBLAS for
linear algebra, and cuDNN (Chetlur et al., 2014) for
convolutions — then gave deep-learning frameworks fast kernels without each team writing them.
For years the frameworks were thin layers over these libraries, and anything not in them (a new
activation, a new attention variant) was slow. Philippe Tillet's Triton (published at MAPL 2019,
open-sourced by OpenAI in 2021) and compiler work in XLA and TVM (Chen et al., 2018)
attacked that gap. The IO-awareness argument of FlashAttention (2022) changed how the field
thinks about model efficiency: count bytes, not FLOPs. PyTorch 2.0 (2023) made Triton
generation the default path for fused kernels via torch.compile. On Hopper and Blackwell,
asynchronous, warp-specialised kernels became standard, and labs began publishing their kernels
(DeepSeek's DeepGEMM and DeepEP in 2025) as part of their efficiency story.
First principles¶
Why fusion is nearly free speed. For a chain of memory-bound operations \(f_1,\dots,f_k\) on a tensor of \(n\) elements, unfused time is about \(\sum_i (\text{in}_i + \text{out}_i)\cdot n\cdot b/\beta\); fused time is \((\text{in}_1 + \text{out}_k)\cdot n\cdot b/\beta\). Every intermediate written and read back costs \(2nb\) bytes, and the arithmetic in between is effectively free because it is far below the ridge. Fusion cannot help a compute-bound kernel, and it fails when an operation needs data from far away (a full row reduction that does not fit on chip, or a global sort).
Why tiling works. A matmul does \(2n^3\) FLOPs on \(3n^2\) data, so every input element is needed by \(n\) different products. Tiling just arranges for those \(n\) uses to happen while the element is on chip. The tile size is bounded by on-chip capacity, and traffic falls in proportion to the tile size (the derivation is on the GPU page).
Why the online softmax is exact. Softmax needs two statistics of a row, its maximum and its sum of exponentials. Both can be computed incrementally if you are allowed to rescale: the pair \((m, \ell)\) combines associatively, \((m_a,\ell_a)\oplus(m_b,\ell_b) = (\max(m_a,m_b),\ \ell_a e^{m_a-m} + \ell_b e^{m_b-m})\). Any associative combination can be computed in any blocking and any order — which is exactly the freedom a tiled kernel needs. The same algebra lets FlashDecoding split a long KV cache across blocks and merge the partial results.
Why recomputation beats storage. In FlashAttention's backward pass, recomputing \(S\) costs \(O(N^2d)\) FLOPs at tensor-core speed; storing and reloading it costs \(O(N^2)\) bytes at HBM speed. With intensity well above the ridge for the recompute and well below it for the load, the FLOPs are cheaper. The general rule: on modern hardware, trade FLOPs for bytes whenever the exchange rate is better than the ridge point.
The maths¶
Derivation: the online softmax and FlashAttention's update
For one query row with scores \(s_1,\dots,s_N\) and values \(\mathbf v_1,\dots,\mathbf v_N\), the output is
where subtracting \(m\) changes nothing mathematically but prevents overflow. Split the columns into blocks. After processing blocks \(1..t\) keep
A new block \(B\) with local max \(\tilde m\) gives \(m^{(t+1)}=\max(m^{(t)},\tilde m)\) and
Each old term \(e^{s_j-m^{(t)}}\) times \(e^{m^{(t)}-m^{(t+1)}}\) equals \(e^{s_j-m^{(t+1)}}\), so by induction \(\ell\) and \(\mathbf a\) are always the exact partial sums relative to the current maximum. At the end \(\mathbf o = \mathbf a/\ell\). FlashAttention-2 defers the division to the very end (one division per row instead of per block), one of its non-matmul savings.
IO complexity. With sequence length \(N\), head dimension \(d\) and on-chip memory of \(M\) elements (\(d \le M \le Nd\)), Dao et al. prove that standard attention needs \(\Theta(Nd + N^2)\) HBM accesses and FlashAttention \(\Theta(N^2d^2/M)\). The intuition: the query tile has \(B_r \approx M/d\) rows (it must fit on chip), and for each of the \(N/B_r\) query tiles the kernel streams all of \(K\) and \(V\), \(2Nd\) elements. Total \(\approx (N/B_r)\cdot 2Nd = 2N^2d^2/M\). For typical \(d = 64\)–128 and \(M\) of order 100 K, \(d^2/M\) is well below 1, so FlashAttention moves many times fewer bytes; they also prove no exact algorithm can do asymptotically better for all \(M\) in that range.
Fusion bytes. For a chain of \(k\) element-wise operations on \(n\) elements of \(b\) bytes, each reading one tensor and writing one:
Build it¶
A NumPy simulation of FlashAttention's forward pass: tiles of \(K\) and \(V\) stream past a tile of \(Q\) with the online softmax, and we count elements moved to and from "HBM" for standard and tiled attention. It checks that the tiled result is exact.
import numpy as np
def standard_attention(Q, K, V):
S = Q @ K.T / np.sqrt(Q.shape[1]) # N x N scores, written to HBM
P = np.exp(S - S.max(1, keepdims=True)) # read S, write P
P /= P.sum(1, keepdims=True)
N, d = Q.shape # HBM traffic in elements:
io = 3*N*d + N*N + 2*N*N + N*N + N*d # read QKV, write S, r/w P, read P, write O
return P @ V, io
def flash_attention(Q, K, V, Br=64, Bc=64):
"""FlashAttention-style forward: tiles of K,V stream past a tile of Q;
the softmax is computed online, so the N x N matrix never exists."""
N, d = Q.shape
O = np.zeros_like(Q); io = 0
for i in range(0, N, Br):
q = Q[i:i+Br] / np.sqrt(d); io += q.size # load Q tile once
m = np.full(len(q), -np.inf) # running row max
l = np.zeros(len(q)) # running denominator
acc = np.zeros((len(q), d)) # running numerator @ V
for j in range(0, N, Bc):
k, v = K[j:j+Bc], V[j:j+Bc]; io += k.size + v.size
s = q @ k.T # Br x Bc, on chip only
m_new = np.maximum(m, s.max(1))
scale = np.exp(m - m_new) # rescale old partial sums
p = np.exp(s - m_new[:, None])
l = l * scale + p.sum(1)
acc = acc * scale[:, None] + p @ v
m = m_new
O[i:i+Br] = acc / l[:, None]; io += acc.size # write O tile once
return O, io
rng = np.random.default_rng(0)
N, d = 4096, 64
Q, K, V = (rng.standard_normal((N, d)) for _ in range(3))
O1, io1 = standard_attention(Q, K, V)
print(f"standard: {io1/1e6:5.1f} M HBM elements, materialises a {N}x{N} matrix")
for Br in (64, 128, 256):
O2, io2 = flash_attention(Q, K, V, Br=Br)
print(f"flash Br={Br:3d}: {io2/1e6:5.1f} M HBM elements ({io1/io2:4.1f}x fewer), "
f"max |diff| = {np.abs(O1 - O2).max():.1e}")
standard: 68.2 M HBM elements, materialises a 4096x4096 matrix
flash Br= 64: 34.1 M HBM elements ( 2.0x fewer), max |diff| = 6.5e-16
flash Br=128: 17.3 M HBM elements ( 3.9x fewer), max |diff| = 6.5e-16
flash Br=256: 8.9 M HBM elements ( 7.6x fewer), max |diff| = 6.5e-16
The answers agree to rounding error, and traffic falls in proportion to the query-tile size \(B_r\) — the \(N^2d^2/M\) law, since the largest \(B_r\) you can afford is set by on-chip memory \(M\). The standard version's memory cost is worse than its traffic suggests: it needs the full \(N\times N\) matrix (67 MB per head in FP32 here) to exist at once; the tiled one needs a \(B_r\times B_c\) block.
Things to try
- Add a causal mask to
flash_attention: skip \(K,V\) tiles entirely above the diagonal and mask the diagonal tile. How much traffic and compute does skipping save? - Implement the backward pass for one query tile using the stored log-sum-exp \(m + \log\ell\), recomputing \(P\) tile by tile, and check gradients against finite differences.
- Split the K/V loop across two "blocks" that each return \((m, \ell, \mathbf a)\), then merge them with the \(\oplus\) rule from First principles. This is FlashDecoding's split-KV trick.
- With a CUDA GPU: run the Triton add and fused RMSNorm kernels, time them with
triton.testing.do_bench, and compute achieved GB/s against your GPU's peak. - Puzzle sets: GPU Puzzles (CUDA ideas in Numba) and Triton Puzzles by Sasha Rush build the intuitions here one exercise at a time.
In practice¶
- Reach for, in order: a better shape or dtype;
torch.compile; an existing fused kernel (FlashAttention viascaled_dot_product_attention, fused optimisers, a library like Transformer Engine); a Triton kernel; CUDA/CUTLASS. Each step down costs an order of magnitude more engineering. - Profile first. Find the top kernels by time, classify each as compute-, memory- or overhead-bound, and compare achieved throughput with the roofline. Fix the biggest gap.
- Launch overhead is real at small sizes. Decode steps of small models can be dominated by
CPU launch time; CUDA graphs (
torch.compile(mode="reduce-overhead")) remove most of it. - Kernels are hardware-specific. A kernel tuned for an H100's 228 KB of shared memory and
wgmmawill not run, or will run slowly, on an A100 or a consumer GPU. Keep a fallback path and autotune per device.
Common misconceptions¶
\"Writing it in CUDA makes it fast.\"
The naive CUDA matmul above runs at 1.3% of cuBLAS. Speed comes from the memory access pattern — coalescing, tiling, overlap — not the language. A well-tiled Triton kernel beats a naive CUDA one by orders of magnitude.
\"FlashAttention approximates attention.\"
It computes exactly the same function as standard attention (up to floating-point rounding, as the Build it shows); it only changes the order of operations and what is stored. It is an IO optimisation, unlike sparse or linear attention, which change the model.
\"torch.compile makes custom kernels unnecessary.\"
It fuses element-wise and reduction chains well and calls good matmul libraries, but it does not invent algorithmic changes such as FlashAttention's online softmax and recomputation, or MoE token dispatch overlapped with communication. Those still come from hand-written kernels.
Check yourself¶
Why is the CUDA add kernel above already optimal, and what could still make a model that uses it slow?
It does one FLOP per 12 bytes with perfectly coalesced access, so it runs at HBM bandwidth, which is the roofline for that operation. A model can still be slow because of what surrounds it: launch overhead, and the HBM round trip between this kernel and its neighbours. The fix is fusion or CUDA graphs, not a better add.
In Boehm's ladder, why did coalescing alone give a 6.4× speed-up without changing the algorithm?
The naive mapping made the 32 threads of a warp read addresses far apart, so each warp load became many separate memory transactions, most of each fetched sector wasted. Remapping threads so a warp reads 32 consecutive floats turns that into a single 128-byte transaction per warp — far more useful bytes per unit of bandwidth.
Estimate the speed-up from fusing GELU(x + b) for a BF16 activation of shape 8192 × 16384, unfused versus fused.
Unfused: add reads \(x\) (and the tiny \(b\)) and writes \(t\); GELU reads \(t\) and writes \(y\): four full passes of \(8192\times16384\times2\) B = 268 MB each, 1.07 GB, about 0.32 ms on an H100. Fused: read \(x\), write \(y\): 0.54 GB, 0.16 ms. About 2×, and better still if fused into the preceding matmul's epilogue, which removes the read of \(x\) too.
Write the online-softmax merge of two partial results (m₁, ℓ₁, a₁) and (m₂, ℓ₂, a₂).
\(m = \max(m_1,m_2)\); \(\ell = \ell_1e^{m_1-m}+\ell_2e^{m_2-m}\); \(\mathbf a = \mathbf a_1e^{m_1-m}+\mathbf a_2e^{m_2-m}\); output \(\mathbf a/\ell\). It is associative and commutative, so blocks can be combined in any order.
Why does FlashAttention recompute the attention matrix in the backward pass instead of saving it?
Saving it costs \(O(N^2)\) memory and \(O(N^2)\) HBM traffic at bandwidth speed; recomputing it from \(Q\), \(K\) and the saved log-sum-exp costs \(O(N^2d)\) FLOPs at tensor-core speed. Because attention's tiled recompute has intensity far above the ridge while reloading the matrix is far below it, recomputing is faster, and it also removes the quadratic memory.
Hard: FlashAttention-2 reaches 50–73% of A100 peak but FlashAttention-3 needed new techniques to exceed ~35% on H100. Why didn't the A100 design carry over?
The H100's tensor cores are ~3× faster than the A100's while the rest of the SM (FP32 lanes
for the softmax's exponentials, shared memory, registers) grew far less. The softmax and data
movement, which were hidden on the A100, became the bottleneck. FlashAttention-3 hid them
using Hopper-only features: asynchronous wgmma, TMA copies driven by producer warps, and
overlapping one tile's softmax with another tile's matmul. Each generation's kernel is shaped
by the ratio of matmul throughput to everything else.
Hard: when should a kernel recompute rather than load, in terms of the roofline?
Recomputing a value costs \(F\) FLOPs; loading it costs \(Q\) bytes. Recompute when \(F/P < Q/\beta\), i.e. when \(F/Q < P/\beta\) — when the recompute's FLOPs per byte saved is below the ridge point. With ridges near 300 FLOP/byte, recomputing anything cheaper than ~300 FLOPs per byte avoided is a win (if the FLOPs can run on tensor cores; on the FP32 lanes, divide that budget by ~15).
Go deeper¶
Papers
- FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness — Dao et al., 2022. Section 3 (algorithm and IO analysis) is the most important reading on this page.
- FlashAttention-2 — Tri Dao, 2023. How work partitioning across blocks and warps decides utilisation.
- FlashAttention-3 — Shah et al., 2024. The Hopper toolbox — warp specialisation, TMA, FP8 — applied to one kernel.
- Triton: An Intermediate Language and Compiler for Tiled Neural Network Computations — Tillet, Kung and Cox, MAPL 2019. The tile abstraction and why a compiler can handle the rest.
- PyTorch 2: Faster Machine Learning Through Dynamic Python Bytecode Transformation and Graph Compilation — Ansel et al., ASPLOS 2024. How
torch.compilecaptures graphs and generates Triton. - ThunderKittens: Simple, Fast, and Adorable AI Kernels — Spector et al., 2024. A minimal set of tile primitives that reach state-of-the-art speed.
- cuDNN: Efficient Primitives for Deep Learning — Chetlur et al., 2014. The library that let frameworks stop writing convolution kernels.
Articles and blog posts
- How to Optimize a CUDA Matmul Kernel for cuBLAS-like Performance — Simon Boehm. The ladder in this page, with code and profiles at every step. Do it, don't just read it.
- Inside NVIDIA GPUs: Anatomy of High Performance Matmul Kernels — Aleksa Gordić, 2025. The Hopper continuation: PTX/SASS, TMA, wgmma, warp specialisation, persistent kernels.
- FlashAttention-3 blog post — Tri Dao and co-authors. The ideas of the paper with diagrams of the overlapped pipeline.
- ThunderKittens blog post — Hazy Research, 2024. "GPUs go brrr": what an H100 rewards, from people who write its fastest kernels.
Videos and courses
- Getting Started With CUDA for Python Programmers — Jeremy Howard. From a Python loop to a CUDA kernel in a notebook; the gentlest on-ramp.
- GPU MODE lectures — GPU MODE community. Notebooks and slides for talks on profiling, Triton, CUTLASS, FlashAttention and more; videos on the channel.
- CUDA Programming Course – High-Performance Computing with GPUs — freeCodeCamp. A long, complete course if you want CUDA C++ properly.
Code and docs
- Triton tutorials — vector add, fused softmax, matmul, layer norm and fused attention; the canonical path into Triton.
- CUTLASS — NVIDIA. Templates and the CuTe layout algebra behind most fast CUDA GEMMs.
- flash-attention — Tri Dao. The production kernels; read the Triton version in the repo first.
- DeepGEMM — DeepSeek. Compact, readable FP8/BF16 GEMM kernels written for learning as well as speed.
- CUDA C++ Programming Guide — NVIDIA. The reference for every keyword and memory space used here.
Where this leads¶
- Mixed precision — the number formats tensor-core kernels consume, and how scaling factors travel with FP8 tiles.
- Serving LLMs — PagedAttention and speculative decoding are kernel problems as much as scheduling ones.
- KV cache and efficient attention — the model-side view of FlashAttention, MQA and GQA.
- Distributed training — when the bytes have to cross a wire instead of a memory hierarchy.
- Compute maths — turning kernel efficiency into MFU and cost.