← TextbooksZero to Beating cuBLAS — A CUDA Kernel Engineering TextbookContents
A CUDA Kernel Engineering Textbook
Zero to Beating cuBLAS
Hardware, kernels, profiling, and the path to outperforming NVIDIA's own library on a specific matrix multiply shape.
Target Hardware
NVIDIA Ampere · sm_80 / sm_86
Prerequisites
C++, Python, undergrad CS
Outcome
Ship a kernel that beats cuBLAS
Toolchain
nvcc 12.x · Nsight Compute · CUTLASS
A note on numbers
Every concrete number in this textbook is annotated with its source. Where a number was derived (e.g. ridge points, arithmetic intensities), the formula is shown. Where it was measured by a third party, the source is named. Re-verify hardware claims against the latest NVIDIA whitepapers and product pages before publishing or quoting them in production work. Architectures and metric names drift between toolkit versions; the structure of the analysis is the durable part.
00
Chapter 00
Foundations: The Atoms Beneath the GPU
Learning goal. Build the conceptual atoms the rest of the book stands on: how numbers are stored in hardware, what a matrix multiply is as an operation count and a memory-traffic problem, the laws of parallel speedup, the architectural lineage that produced the modern GPU, and the vocabulary (latency, throughput, intensity, occupancy) you will use on every page that follows. Each idea is an atomic note with explicit links to what it depends on and what it leads into.
How to read this chapter
If you've taken an undergraduate "computer organization" plus a numerical-methods course, skim §0.2 and §0.4, then read §0.5 (parallelism laws) and §0.6 (GPU lineage) carefully. If you came from pure software, read every atomic note in order. Each note is short on purpose — return to them as reference cards while reading later chapters.
The textbook is laid out as a directed graph of atomic notes. Each note explains exactly one idea — what it is, why it exists, the smallest example that makes it true, and a short list of the other notes that lead into and out of it. The links carry semantics:
[[A0.1.1]]
The four link types you will see everywhere
meta
prereq "You cannot meaningfully understand this note without first understanding the linked one." The linked note answers a sub-question the current note assumes.
builds-on "This note uses the linked one as a black box." Not strictly a prerequisite — you can read this note with only a one-sentence summary of what it builds on — but the formal definitions live in the linked note.
used-by "These later notes apply or extend this one." Forward edges in the graph; how to navigate downstream.
related "Sibling concept worth comparing." No direct dependency — usually a contrast or an alternative formulation.
contrast "Easy to confuse with this one." When the two concepts share vocabulary but have different mechanics (e.g. occupancy vs utilization, latency vs latency-hiding).
The visual concept map at the end of the book (Ch 9 — Knowledge Graph) renders these edges as a force-directed diagram. Until then, the chips at the bottom of each card are the graph.
"Given a matrix multiply of a chosen shape, write a CUDA kernel that runs faster than NVIDIA's cuBLAS on the same GPU, and prove it." Every chapter is a layer of context that question demands:
What is a matrix multiply, exactly? → §0.3 (linear algebra) and [[A0.3.4]].
Why this section exists. Every CUDA program is, at its core, a function that loads numbers, does some arithmetic on them, and stores numbers back. The width of those numbers — 32 bits or 16 bits or 8 bits — sets your memory bandwidth, your tensor-core throughput, your numerical accuracy budget, and whether the kernel even fits in registers. You cannot reason about a kernel without first knowing what its operands physically are.
[[A0.2.1]]
Positional binary encoding — the floor of the stack
representation
A binary integer is just a sum of powers of two with coefficients in {0, 1}. The number 1011 means 1·2³ + 0·2² + 1·2¹ + 1·2⁰ = 11. Every other format on this page — signed integers, fixed-point, floating-point — is a deliberate encoding on top of this primitive, trading bits between three things: the range it can express, the resolution within that range, and how cheap the arithmetic circuits are.
Two's-complement signed integers (used by int32_t, int8_t, the GPU's integer ALU) are the simplest such trade: the top bit is the sign, but the value is encoded so that the same addition circuit works for signed and unsigned. That circuit reuse is why GPUs and CPUs both default to two's-complement — not because mathematicians liked it.
IEEE 754 expresses a real number as (−1)s · 1.mantissa · 2exponent − bias. Three fields, all integers: a sign bit, a biased exponent, and a fractional mantissa with an implicit leading 1 (the "hidden bit"). The bias keeps the exponent unsigned in hardware so a single compare-and-subtract aligns two numbers' exponents before adding their mantissas. Every floating-point format you will see is just a re-budgeting of bits across (sign, exponent, mantissa).
FIG 0.2.A · 32 BITS, THREE FIELDS
FP32 bit layout (IEEE 754 binary32)
S
E (8 bits, bias 127)
M (23 bits, +1 hidden)
■ 1 sign · range [−∞, +∞]
■ 8 exponent · range ≈ 10±38
■ 23 mantissa · ≈ 7 decimal digits
Five special exponent encodings: all-zeros mantissa with E=0 → zero (signed); non-zero mantissa with E=0 → subnormal (no hidden bit; gradual underflow); E=all-ones with zero mantissa → ±∞; E=all-ones with non-zero mantissa → NaN; everything else → a normal number with the hidden 1.
FP32 (binary32) — the unit of GPU compute, until it isn't
format
32 bits, 1 sign / 8 exponent / 23 mantissa, ~7 decimal digits of precision, dynamic range ≈ 10±38. On NVIDIA hardware FP32 is the "natural" CUDA core width: every regular ALU operation issued by an SM executes at FP32 rate, and FP64 is a small fraction of that rate on consumer GPUs (1:64 on a 3090, 1:2 on a server-class A100). FP32 is what you use when you don't know what you need; it is also the dominant cost when memory bandwidth dominates, because at four bytes per scalar a 4 KB row vector burns one whole L2 sector per 64 elements.
FP16 (binary16, "half") — the deep-learning starter format
format
16 bits, 1 / 5 / 10. Range ≈ 6.1·10−5 to 6.55·104. Half the bytes of FP32, half the memory traffic, and on Tensor Cores (Volta and later) 8× the FLOP rate when used as an MMA input. Its weakness is the narrow 5-bit exponent: activation tensors with values like 1·10−5 or 7·104 sit at the edge of the range and overflow to inf, which is why training pipelines use loss scaling and accumulate matrix products in FP32.
16 bits, 1 / 8 / 7. Same exponent budget as FP32, so the dynamic range matches (≈ 10±38); only the mantissa is sacrificed. The implication for training: BF16 will not overflow on activations that would have killed FP16, at the cost of ~3 decimal digits of precision. Introduced by Google for TPUs, supported by NVIDIA Tensor Cores from Ampere onward.
TF32 — Tensor Float, a 19-bit input format that looks like FP32
format
TF32 is an internal tensor-core format introduced on Ampere. The register is 32 bits, but only 19 of them are actually consumed by the MMA datapath: 1 sign + 8 exponent (FP32's range) + 10 mantissa (FP16's precision). The extra 13 mantissa bits the application passed in are discarded. The trick is that you can feed it ordinary float registers and get an ~8× speedup over CUDA-core FP32 — at the cost of mantissa precision the network often doesn't notice. NVIDIA enables it by default on Ampere when an FP32 GEMM hits cublasGemmEx; you opt out via CUBLAS_PEDANTIC_MATH or by setting CUBLAS_TF32_TENSOR_OP_MATH off.
Common confusion
"My FP32 GEMM on an A100 only matches a CPU FP64 reference to 3 decimal places — is something wrong?" Almost certainly not: cuBLAS silently dispatched a TF32 tensor-core kernel.
Hopper (sm_90) and later support two FP8 formats whose names you must memorize because they are not interchangeable: E4M3 (1 sign / 4 exponent / 3 mantissa, narrower range, finer steps) and E5M2 (1 / 5 / 2, IEEE-like, wider range, coarser steps). The standard recipe in FP8 training: weights and forward activations in E4M3, gradients in E5M2. Both formats deviate from IEEE 754 in subtle ways (no inf in E4M3; special NaN encodings).
Mixed-precision: input format ≠ accumulator format
numerics
A tensor-core D = A·B + C almost never accumulates in its input format. The MMA reads FP16 (or BF16, INT8, FP8) operands, multiplies them, and accumulates the dot products into wider registers — typically FP32. This is what keeps GEMM stable: K-deep sums of small noisy numbers do not lose precision the way they would in pure FP16. When you see "FP16 GEMM" in cuBLAS or CUTLASS it almost always means "FP16 inputs, FP32 accumulator." When the accumulator is also FP16 (the HMMA.1688.F16 SASS variant), expect numerical disasters at K > 256.
If the input fits in fewer bytes than the output, the kernel is mixed-precision. Output precision dominates correctness; input precision dominates speed and bandwidth.
Floating-point arithmetic has to round after every operation that produces more mantissa than the format can store. IEEE 754 defines five rounding modes: round-to-nearest-ties-to-even (the default everywhere serious), ties-to-away (used in financial software), toward zero (truncation), toward +∞, toward −∞. CUDA exposes them as intrinsics: __fadd_rn / _rz / _ru / _rd. On Tensor Cores the rounding mode is hardwired per format and per generation; you cannot change it from the kernel. Hopper introduced stochastic rounding for FP8 to address a specific training instability: when a small gradient is added many times to a large weight, deterministic rounding loses every increment to the same direction; stochastic rounding turns the bias into noise.
INT8 / INT4 — integer matmul as quantization target
format
Tensor cores can also consume signed/unsigned integers: INT8 since Turing, INT4 since Turing (sm_75) but deprecated for new code on Hopper. The semantics are different from float MMA: the multiply is integer (so two INT8 operands fit in an INT16 product), and the accumulator is INT32. INT8 GEMM throughput is 2× the FP16 tensor-core rate on most NVIDIA parts. The catch is that to use it you have to quantize: pick per-tensor or per-channel scales s, store x_q = round(x / s) as INT8, then dequantize after the MMA with another multiply by s. That quantization is application-level, not hardware-level.
Kahan summation — why long dot-products go bad without compensation
numerics
Summing K floating-point numbers in a naive loop accumulates an error that grows as O(Kε) in the worst case, where ε is the machine epsilon. For a K=4096 FP16 dot product with ε ≈ 9.8·10−4, the bound is ~4 — much larger than the answer for many inputs. Kahan's compensated-summation trick maintains an auxiliary "lost low-order bits" running variable and folds it back in on each step, reducing the bound to O(ε) independent of K. CUDA programmers rarely run Kahan inside the inner GEMM loop because it costs ~3× the FLOPs; instead, they sidestep the problem by using an FP32 accumulator (see [[A0.2.8]]) and, for ultra-stable reductions, by reshaping the algorithm into a pairwise tree (see Ch 7 — reductions).
Reading order. Vectors → matrices → matrix-vector → matrix-matrix → BLAS levels. Each step adds one dimension's worth of structure and roughly an order of magnitude of arithmetic intensity. The whole textbook is about why level-3 BLAS is where GPUs win.
[[A0.3.1]]
Vector — a 1-D array of numbers, with a contract
linalg
A vector of length n is an n-tuple of numbers, stored contiguously. The contract that makes it a "vector" rather than just an array is that only certain operations preserve meaning: addition componentwise, scalar multiplication, dot product, norm. A "vector" in CUDA code is usually a pointer plus a length plus a stride. The stride is not the same as the length: two vectors that share a stride but are offset can be views into different rows of the same matrix without copying.
Matrix layout — row-major vs column-major and leading dimension
linalg
An M×N matrix flattened to memory needs an ordering convention. Row-major (C, NumPy default): row 0 contiguous, then row 1, etc.; element (i,j) sits at offset i·N + j. Column-major (Fortran, BLAS, cuBLAS): column 0 contiguous; offset is i + j·M. Most working CUDA kernels actually carry a leading dimension (often called lda): the stride in memory between successive rows or columns, which can be larger than the logical dimension to satisfy alignment constraints. Bug class: confusing lda with the matrix dimension, getting addresses right for the first few elements, and producing silently wrong results far from the corner.
cuBLAS inherited Fortran column-major from netlib BLAS. To call it from row-major C code you typically swap the operands and the transpose flags: cublasSgemm(...A, B...) on row-major is equivalent to cublasSgemm(...Bᵀ, Aᵀ...) on column-major. This is the single most common cuBLAS bug for newcomers.
GEMV — matrix-vector multiply, the "memory-bound" canary
linalg
y = αAx + βy. For an M×K matrix and a length-K vector, the FLOP count is 2·M·K and the memory traffic is M·K + K + M reads/writes. Arithmetic intensity is therefore ≈ 2 FLOPs / element of A read — almost identical to a streaming copy. On any modern accelerator GEMV is dead memory-bound; it is the lower bound on a GEMM's intensity if you fail to reuse A. The decode step of an autoregressive LLM is just a stack of GEMVs and that's why those decode tokens are slow.
C = αA·B + βC, with A being M×K, B being K×N, C being M×N. FLOP count: 2·M·N·K. Memory traffic if nothing is reused: M·K + K·N + 2·M·N. Arithmetic intensity if nothing is reused: ≈ 2·K elements of work per element of memory loaded, which for K=4096 is ~8 KFLOPs/byte (FP16) — well into compute-bound territory. That intensity is the entire reason GPUs and tensor cores exist for matmul.
The catch: nothing is reused only holds if you actually do the reuse. A naive triply-nested loop has the same intensity as GEMV because each thread reloads A and B from global memory K times. The job of every kernel in Ch 2, every tile transformation in Ch 3, and every cuBLAS trick in Ch 5 is to capture the intensity that the algebra promises.
GEMM offers ~K FLOPs per byte of A or B, but only if your kernel reuses each loaded element ~K times before evicting it. Reuse is the whole game.
Level 2 Matrix-vector ops: gemv, trsv, ger. O(n²) work, O(n²) memory. Intensity ~2. Memory-bound on any modern accelerator.
Level 3 Matrix-matrix ops: gemm, syrk, trsm. O(n³) work, O(n²) memory. Intensity scales with the tile dimension. The only level where the GPU can saturate its FLOP rate.
BLAS originated as a Fortran linear-algebra library standard in the 1970s–80s. cuBLAS, MKL, OpenBLAS all implement the same interface. The library taxonomy maps to the roofline (§1.6) exactly: Levels 1 and 2 live on the memory-bound slope; Level 3 lives on the compute-bound ceiling — if you tile it right.
Latency vs throughput — the two costs of every operation
arch
Latency is "how long does one of these take?" — measured in cycles or nanoseconds. Throughput is "how many can finish per unit time?" — measured in operations/cycle or operations/second. A long-latency unit can still have high throughput if the hardware pipelines it. Example: a Tensor Core mma.sync on Ampere has latency ≈ 16 cycles, but an SM can issue a new one every 4 cycles per scheduler → throughput is 4× higher than latency suggests. CPUs hide latency with out-of-order execution and branch prediction; GPUs hide latency with thread-level parallelism. Same physics, opposite micro-architectures.
Flynn's taxonomy — SISD, SIMD, MIMD, and where SIMT fits
arch
Michael Flynn (1966): classify processors by how many instructions and data items they handle per cycle. SISD = one of each (the classical von Neumann CPU). SIMD = single instruction, multiple data lanes (AVX-512, NEON). MIMD = multiple instructions, multiple data streams (multicore CPUs). NVIDIA coined SIMT — single instruction, multiple threads — to describe the GPU model: 32 threads (a warp) execute one PTX instruction together, but each thread has its own register state, program counter (post-Volta), and conditional-execution mask. SIMT looks like MIMD to the programmer and like SIMD to the hardware. This is the single most useful framing for everything in §1.3.
Cache fundamentals — line size, associativity, and locality
arch
A cache trades capacity for speed by storing copies of recently used memory close to the compute unit. Three numbers describe one: capacity (how much), line size (how much it fetches per miss — almost always 32, 64, or 128 bytes — never one byte), and associativity (how many places a given address can live). A cache "hit" returns in 1–10s of cycles; a "miss" punts the request down to the next level and costs orders of magnitude more. Spatial locality says "addresses near a hit are likely to hit too"; temporal locality says "an address that just hit is likely to hit again soon." Coalesced loads (§1.4) are the GPU's way of forcing spatial locality at the warp level.
The memory wall — why bandwidth gets harder, not easier
arch
Compute has grown ~50%/year for decades; DRAM bandwidth has grown ~7%/year. The ratio of FLOPs to bytes a chip can supply rose roughly two orders of magnitude over the 2000s and 2010s. Every algorithmic technique in this book — tiling, shared memory, register reuse, cp.async, software pipelining, TMA — is some flavor of "do more arithmetic with the bytes I already paid to move." The memory wall is the meta-reason the rooflines tilt the way they do.
A modern functional unit is a pipeline: instruction i is in stage 4 while i+1 is in stage 3 and i+2 is in stage 2 — all in the same cycle. The throughput is one instruction per cycle even though the latency is 4 cycles. Instruction-Level Parallelism (ILP) extends this by issuing multiple independent instructions in the same cycle when no two depend on the same register. On GPUs ILP is one of two latency-hiding strategies (the other is TLP, thread-level parallelism). The compiler discovers ILP by reordering independent instructions in the SASS; you help it by writing inner loops that have multiple independent accumulators.
Little's Law — the universal latency-hiding equation
arch
In steady state for any system: in-flight requests = throughput × latency. On a GPU memory subsystem with 936 GB/s bandwidth and ~500 ns DRAM latency, the number of bytes that must be "in flight" to keep DRAM saturated is ≈ 936·109 · 500·10−9 ≈ 468 KB. That number — not "more threads is better" — is the reason occupancy matters: you need enough threads, each making enough outstanding loads, to cover that 468 KB. Little's Law is the equation behind every "why is my kernel slow even though it has lots of threads?" diagnosis.
Amdahl, Gustafson, work-span, and the synchronization tax
[[A0.5.1]]
Amdahl's Law — the serial fraction is your ceiling
parallelism
If a fraction s of a program is inherently serial and the rest is perfectly parallelizable across p processors, total speedup is bounded by 1 / (s + (1−s)/p). As p → ∞ the speedup approaches 1/s. A 5% serial section caps you at 20× speedup no matter how many cores you throw at it. On GPUs the "serial section" usually hides in: launch overhead, host↔device copies, kernel-to-kernel barriers, single-threaded prologue/epilogue code. The first thing to optimize on a slow GPU pipeline is almost never the kernel — it is the serial glue.
Gustafson's Law — bigger problems are easier to parallelize
parallelism
Amdahl assumes the problem size is fixed. Gustafson observed that in practice we make the problem larger as we get more cores: the serial section's runtime is roughly constant while the parallel section's runtime scales with problem size. So scaled speedup = p − s·(p−1), which grows linearly with p. This is why GPUs feel so productive on training: doubling the batch size doubles the parallel work but keeps the serial bookkeeping flat.
Strong scaling = fixed total work, varying core count. Bounded by Amdahl. Weak scaling = work per core fixed, varying core count. Bounded mostly by communication. For GEMM at fixed shape (the question this book asks) we care about strong scaling. For training across many GPUs we care about weak scaling, which is why multi-GPU is its own chapter.
Two complexity measures of a parallel algorithm, ignoring the hardware: workT1 is total operations across all processors; spanT∞ is the longest dependency chain — the critical path. Their ratio T1/T∞ is the parallelism, an upper bound on the speedup any scheduler can ever achieve. A parallel reduction over n elements has work O(n) and span O(log n) → parallelism n / log n. GEMM has work O(n³) and span O(log n) → parallelism O(n³ / log n), which is essentially unbounded for any n a real GPU runs.
A data race is two unsynchronized accesses to the same memory location where at least one is a write. C++ and CUDA both say it is undefined behavior. A race condition is a broader notion: the program's result depends on a timing nondeterminism, even when no memory access is racy in the C++-language sense (e.g., who completes an atomic first decides which value sticks). A benign race is one the programmer has analyzed and decided is safe — for example, all threads writing the same value to the same address. Compilers and tools (compute-sanitizer's racecheck) don't know which of your races are benign; they flag them all. Treat every flagged race as real until you've written down why it isn't.
The modern GPU did not arrive in one step. Each generation answered the previous generation's bottleneck and is the reason a particular CUDA feature exists. Knowing which generation introduced what makes nvcc error messages, compute-capability flags, and PTX manuals legible. Pick your target SM (sm_80 / sm_86 for Ampere, sm_90 for Hopper) and the table below tells you which features are real for you.
Gen
Year
Compute Cap
What it introduced (in one line)
G80 (Tesla)
2006
sm_10
CUDA itself — unified shaders + a C language for them
Compute capability — the version number that gates every feature
toolchain
Every NVIDIA GPU has a "compute capability" like sm_80 (A100), sm_86 (RTX 3090), sm_90 (H100). It is a two-digit version number: the first digit is the architecture family (Volta=7, Ampere=8, Hopper=9), the second distinguishes SKUs within it. Compute capability decides three things: (1) which PTX instructions exist, (2) which shared-memory budget and register file size you get, (3) which Tensor Core MMA shapes you can issue. When you compile with nvcc -arch=sm_86 you're asking the compiler to emit SASS for that target; -arch=compute_86 emits PTX that the driver JITs at load time. We will revisit this in §2.x — toolchain.
Three reasons. (1) It is the sweet spot of availability: an RTX 3090 is the most common high-end consumer card with full FP16 Tensor Cores; A100 is the most common data-center part. (2) It is the first generation with all the modern primitives: cp.async, async barriers, BF16, TF32, sparse Tensor Cores. Everything you learn here applies to Hopper; Hopper adds new primitives but does not remove these. (3) The documentation is mature: every Ampere quirk has by now been written about, profiled, and decoded in public. Hopper has more headroom for novel work but a thinner public corpus.
Throughout the rest of this book "the GPU" means an Ampere SM unless we say otherwise. Hopper-only material is collected in §3.6 and an Ampere/Hopper cross-reference lives in §6.1.
State the bit layout of FP32 and explain what each field encodes.
Explain why FP16 needs FP32 accumulation for stable GEMMs.
Define arithmetic intensity in one sentence and compute it for GEMM.
Quote Amdahl's Law and identify the serial sections in a CUDA pipeline.
Use Little's Law to estimate how many bytes must be in flight to saturate HBM.
Pick the right compute capability for a given GPU and explain what it controls.
01
Chapter 01
The Machine Underneath: GPU Architecture
Learning goal. By the end of this chapter you can explain — without reference material — how a GPU executes code at the hardware level: what an SM is, what a warp is, the full memory hierarchy, what occupancy means, and how to use the roofline model to classify any operation as compute-bound or memory-bound.
1.1Why GPUs Exist: The Parallelism Imperative
A divergence of design philosophies
A CPU and a GPU both move bits around, but they were built to solve completely different problems. A CPU is a latency-minimizing machine — its job is to get a single thread through a complicated instruction stream as quickly as possible. Out-of-order execution, deep speculation, large branch predictors, multi-megabyte caches, and tightly clocked single-thread pipelines all serve one goal: drive the wall-clock time of one task as low as possible.
A GPU is a throughput-maximizing machine. It does not care that any single thread is slow. It cares that tens of thousands of threads, taken together, finish their work in less time than a CPU could. The chip is therefore organized to keep as many arithmetic units busy as physically possible. Where a CPU spends roughly four-fifths of its silicon area on caches and control logic, a GPU spends roughly four-fifths of its silicon on arithmetic units. The cache is small, the control logic is shared across many lanes, and the pipeline depth per lane is shallow.
The free lunch is over
The shift to GPUs is not a fashion. It is a forced response to physics. Until roughly the mid-2000s, every new CPU generation gave you a faster single thread for free — clock frequencies climbed, transistors got smaller, voltages dropped, and the same code simply ran faster on next year's silicon. This was Dennard scaling. It broke down around 2005–2007 as leakage current and thermal density made further voltage reduction impractical. Herb Sutter's essay The Free Lunch Is Over (Dr. Dobb's, March 2005) named the moment for the software industry.[1]
Since the free lunch ended, performance growth has come almost entirely from parallelism — more cores, wider vector units, specialized accelerators. GPUs are the most aggressive expression of that trend: instead of a few fast cores, thousands of slow ones; instead of speculation, brute parallel coverage; instead of large per-core caches, a small shared on-chip memory that the programmer manages explicitly.
Matrix multiply: the canonical parallel workload
Consider the operation at the heart of nearly every modern neural network and scientific computing kernel:
C[i,j]=Σk A[i,k]· B[k,j] for all i, j
Every output element C[i,j] is computed from a row of A and a column of B, completely independently of every other output element. For an M×N output matrix, that is M·N independent dot products. There is no data dependency between them. They could all run at once if the hardware existed. That is the entire reason GPUs exist — they are the hardware that exists.
Figure 1.1 — Interactive
CPU vs GPU: How the silicon is spent
Hover over each region to see what it is. The exact areas are stylized — the figure is meant to convey the budget split, not exact floorplans. Real chip plots are published by NVIDIA and Intel in their architecture whitepapers.
The mental model
A CPU is a sports car: fast off the line, narrow, optimized for one driver getting from A to B in record time. A GPU is a freight train: enormous payload per trip, terrible if you need to make a sudden turn, unbeatable if your problem looks like move ten thousand identical things from A to B. Matrix multiply, attention, convolution, n-body simulation, ray-triangle intersection, and most of computer graphics look like that. That is why GPUs run them.
// ============================================================
// CPU: one thread, one big triple nested loop.
// Wall-clock time scales with M * N * K.
// ============================================================
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
float acc = 0.f;
for (int k = 0; k < K; k++) {
acc += A[i * K + k] * B[k * N + j];
}
C[i * N + j] = acc;
}
}
// ============================================================
// GPU: launch M*N threads. Each one computes ONE output element.
// Wall-clock time scales with K (the inner loop), not M*N*K,
// because the M*N axis runs in parallel across thousands of cores.
// ============================================================
__global__ void gemmKernel(const float* A, const float* B, float* C,
int M, int N, int K) {
int i = blockIdx.y * blockDim.y + threadIdx.y; // row
int j = blockIdx.x * blockDim.x + threadIdx.x; // col
if (i >= M || j >= N) return;
float acc = 0.f;
for (int k = 0; k < K; k++) {
acc += A[i * K + k] * B[k * N + j];
}
C[i * N + j] = acc;
}
// Launch: one thread per (i, j) — M*N threads total.
dim3 block(16, 16);
dim3 grid((N + 15) / 16, (M + 15) / 16);
gemmKernel<<<grid, block>>>(A, B, C, M, N, K);
Mental model worth keeping
If your problem has an outer loop where every iteration is independent, you have GPU work. The whole game is identifying that loop, mapping iterations to threads, and feeding the resulting army of threads from memory fast enough to keep them busy.
1.2The Streaming Multiprocessor (SM)
The actual compute unit you need to understand
A modern NVIDIA GPU is, in the end, a collection of Streaming Multiprocessors (SMs) glued together with a memory system. Every CUDA optimization you will ever do is, ultimately, an attempt to keep the arithmetic units inside an SM busy. So you need to know what is inside one.
The numbers vary by generation. On the RTX 3090 (Ampere, GA102, compute capability sm_86) there are 82 SMs.[2] On the A100 (Ampere, GA100, sm_80) there are 108. On the H100 (Hopper, sm_90) there are 132. The internals of an SM, however, follow a recognizable pattern across generations.
Inside an Ampere SM
An Ampere SM is divided into four processing blocks (sometimes called SM sub-partitions, abbreviated SMSP). Each sub-partition is, for our purposes, a self-contained mini-SM:
Its own warp scheduler and dispatch unit.
Its own slice of the SM's register file (16,384 32-bit registers per sub-partition × 4 = 65,536 per SM).
16 FP32 CUDA cores (so 64 per SM) and 16 INT32 ALUs that can co-issue with the FP32 units on Ampere — this is why the GA10x marketing material counts 128 "CUDA cores" per SM (the FP32-capable lanes including the dual-purpose ones).
One third-generation Tensor Core — so 4 per SM. Each can do a fairly large matrix multiply-accumulate per clock.
4 Special Function Units (SFUs) for transcendentals (sin, cos, rcp, rsqrt).
8 load/store units.
Above the four sub-partitions, the entire SM shares:
128 KB of combined L1 cache and shared memory, split configurably (e.g. 32 KB L1 / 96 KB shared, or other ratios up to a maximum shared-memory allotment per block defined by the architecture).
A texture/L1 unit (l1tex in Nsight Compute) handling global-memory loads, texture, and shared-memory traffic.
A constant cache.
What each piece does — in one sentence
CUDA core (FP32 lane). One floating-point multiply-add per clock. Your scalar workhorse.
Tensor Core. A whole small matrix multiply-accumulate per clock. Where the real teraflops live.
Register file. The fastest memory on the chip. Each thread owns a slice.
Warp scheduler. Picks one eligible warp per cycle and issues an instruction.
Dispatch unit. Sends the instruction to the right execution pipe.
Load/Store unit. Issues memory transactions to L1/L2/DRAM.
SFU. Computes sin, cos, rcp, rsqrt on its own pipe so they don't block the FP32 cores.
Figure 1.2 — Diagram
Anatomy of one Ampere SM (sm_86)
Per-SM resource counts above are for GA10x-class Ampere parts (RTX 3090, RTX 30-series). The A100 (GA100, sm_80) has the same sub-partition shape but counts cores differently (64 dedicated FP32 + 32 FP64 — the 1:2 FP64:FP32 ratio that distinguishes data-center Ampere from consumer Ampere) and ships up to 192 KB of unified L1/SMEM per SM. Source: NVIDIA Ampere whitepapers.[3][4]
Why this matters for your kernel
Every choice you make later — block size, shared-memory layout, tile shape, register pressure — is really a choice about how to fill one of those sub-partitions with eligible warps and useful work. When Nsight Compute later tells you "Warp State: long_scoreboard 60%," what it is really saying is "the warp scheduler for some sub-partition keeps looking for a ready warp and finding none, because every warp is waiting on global memory."
1.3Threads, Warps, Blocks, and Grids
The execution hierarchy you write code against
CUDA exposes four nested concepts. They map onto hardware in very specific ways. Get the mapping wrong and your kernel will be slow for reasons that are not obvious from the source code.
Thread
A thread is the atomic unit of execution. One thread runs one instance of your kernel function from start to finish. It has its own program counter, its own slice of the register file, and its own values of threadIdx and blockIdx. You will routinely launch tens of millions of threads.
Warp
A warp is a group of 32 threads that the hardware schedules and executes together. This is the most important number in CUDA. Warp size has been 32 on every NVIDIA GPU shipped to date. The 32 threads in a warp share a single instruction stream — when the warp scheduler issues an instruction, all 32 lanes execute it on their own data. NVIDIA calls this SIMT (Single Instruction, Multiple Thread), which is essentially SIMD with a per-lane predicate and a per-lane register file.
You do not control warps directly. You set a block size, and the hardware partitions the block into warps of 32 threads in linear order: threads 0–31 are warp 0, 32–63 are warp 1, and so on (using row-major order over the multi-dimensional threadIdx).
Warp divergence
Because all 32 threads in a warp share a program counter, an if/else that splits the warp is expensive. The hardware serializes the two paths: it runs the if branch with the else threads masked off, then runs the else branch with the if threads masked off. Both branches contribute to runtime; only the active threads contribute to useful work.
The rule that follows: keep all 32 threads of a warp on the same execution path. Branches that depend on threadIdx.x / 32 (i.e. on the warp ID) are free; branches that depend on threadIdx.x % 32 are the worst case.
Thread block
A thread block is a programmer-defined group of up to 1024 threads. The hardware promises three things about a block:
All threads in the block run on the same SM. They never migrate.
They share a single allocation of that SM's shared memory.
They can synchronize with __syncthreads() — every thread in the block must reach the barrier before any thread can proceed past it.
Block size is the lever you use to trade off occupancy, shared-memory tile size, and per-thread register budget. Common values are 128, 256, or 512 threads per block (i.e. 4, 8, or 16 warps). 1024 is the hardware maximum.
Grid
The grid is the collection of all thread blocks launched by one kernel call. The grid can be 1D, 2D, or 3D. The runtime distributes blocks across SMs in an order you do not control. You cannot assume any ordering of block execution and you cannot synchronize between blocks within a kernel launch (with the exception of cooperative-grid kernels and grid-wide barriers introduced later in CUDA, which are out of scope here).
Launch syntax
// Launch 256 blocks of 128 threads each. Total: 32,768 threads.
myKernel<<<256, 128>>>(args...);
// 2D launch for a matmul. One block computes one TILE x TILE
// output tile. Each thread in the block computes one element of that tile.
const int TILE = 32;
dim3 grid((N + TILE - 1) / TILE, (M + TILE - 1) / TILE);
dim3 block(TILE, TILE); // 1024 threads = 32 warps
matmulKernel<<<grid, block>>>(A, B, C, M, N, K);
// Inside the kernel:
// threadIdx.x in [0, TILE)
// threadIdx.y in [0, TILE)
// blockIdx.x in [0, gridDim.x)
// blockIdx.y in [0, gridDim.y)
// blockDim.{x,y} == TILE
// gridDim.{x,y} == ceil(N/TILE), ceil(M/TILE)
//
// Global thread coordinates for the (i,j) output element:
// int j = blockIdx.x * blockDim.x + threadIdx.x; // col
// int i = blockIdx.y * blockDim.y + threadIdx.y; // row
Figure 1.3 — Interactive
Grid → Block → Warp: the execution hierarchy
Grid (block.x × block.y)4 × 4 blocks = 16
Block (threads)8 × 8 = 64 threads
Warps / block2 warps × 32
Total threads1,024
Divergence (warp 0)
Click "Convergent" to see all 32 lanes executing the same instruction. Click "Divergent if" to see the 32 lanes split across two branches — only the active lanes contribute to useful work in each phase.
Rule of thumb
Pick a block size that is a multiple of 32. Otherwise the last warp of every block has dead lanes from the start, and you waste hardware on every cycle. 128 or 256 is almost always the right default before any tuning.
Atomic-note deep dive — §1.3
[[A1.3.1]]
SIMT in practice — one program counter, 32 lanes
execution
Pre-Volta, a warp shared a single program counter across all 32 lanes; a divergent branch serialized the two sides under a hardware mask. Volta (sm_70) introduced independent thread scheduling: each lane has its own PC and call stack, and the scheduler tracks reconvergence explicitly. The programmer-visible consequence is that you can no longer assume warp-lockstep behavior at byte-level granularity — you must call __syncwarp() when one branch of a warp publishes a value the other branch reads. This is the silent cause of "it works on my Pascal but breaks on my Ampere" bugs.
Warp scheduler — picks one ready warp per cycle per partition
execution
Each SM sub-partition (4 per Ampere SM) owns a warp scheduler. Every cycle each scheduler examines its pool of resident warps — typically 16 — and picks one warp that has at least one instruction whose operands are all ready, then issues that one instruction to the appropriate functional unit (FP32 ALU, FP64 ALU, Tensor Core, LSU, SFU). Because the scheduler only "fires" when there is a ready warp, the entire latency-hiding game reduces to: keep at least one warp ready per cycle. That single sentence is the unifying explanation for occupancy, ILP, cp.async, double-buffering, and software pipelining.
A warp scheduler does not wait; it idles. Your job is to make sure it never has to.
When threads in a warp take different branches of a conditional, the hardware executes both paths sequentially with a predicate mask: lanes not on the active path are predicated off (their results are discarded) but they still consume a cycle. Worst case: 32 lanes take 32 different paths, the warp takes 32× longer. Two redemption modes: (1) data-dependent divergence on data sorted ahead of time so warp boundaries align with branch boundaries; (2) predicated short branches the compiler fuses into a single selp instruction. The nvcc diagnostic --ptxas-options=-v tells you when a branch was predicated vs branched.
Kernel launch cost — the constant you cannot amortize away
execution
A <<<grid, block>>> launch costs ≈ 5–20 µs on the host side and ≈ 1–5 µs on the device side. For a kernel that does 100 µs of real work the overhead is invisible; for one that does 2 µs of real work the overhead dominates. Mitigations, in order of preference: batch small kernels into bigger ones; use CUDA Graphs (one record-and-replay per pipeline) to fold launches into a single submission; keep persistent kernels running across iterations. Ch 2 — streams & graphs covers the API.
If you remember one thing from this chapter, remember this: kernel optimization is memory hierarchy management. Compute on GPUs is comparatively cheap; getting data to the compute units is comparatively expensive. The hierarchy below is the entire physical reason your naive kernel is slow and your optimized kernel is fast.
Level
Location
Latency
Aggregate BW
Size
Scope
Registers
On-chip, per-thread
~1 cycle
~20 TB/s
255 regs/thread max
per-thread
Shared / L1
On-chip, per-SM
~20–30 cyc
~19 TB/s
128 KB / SM
per-block
L2 Cache
On-chip, GPU-wide
~200 cyc
~5–7 TB/s
6 MB (3090)
GPU-wide
Global (DRAM)
Off-chip HBM/GDDR
~400–800 cyc
936 GB/s (3090)
24 GB
GPU-wide
PCIe ↔ Host DRAM
Off-chip, host
tens of µs
~32 GB/s (PCIe 4.0 x16)
system RAM
host
Latencies and aggregate bandwidths are characteristic values for an Ampere consumer card and are commonly cited in NVIDIA documentation, the CUDA C Programming Guide's Performance Guidelines, and microbenchmark studies such as Jia et al. (2021).[5] Exact numbers vary by clock and chip variant.
Registers
Every thread has private access to the register file. On Ampere, the per-thread register limit is 255 32-bit registers; the per-SM register file is 65,536 32-bit registers. Register allocation is done by the compiler at compile time — you do not allocate registers; you write code, and nvcc decides.
If your kernel uses too many registers per thread, two things happen, both bad. First, occupancy drops, because fewer threads' worth of registers fit in the SM (covered in §1.5). Second, the compiler can spill excess values to local memory, which despite its name is a per-thread region of global memory. A register spill is catastrophic — what should be a single-cycle read is now a 400+ cycle global memory load. You can see spills in the compiler output by passing -Xptxas -v to nvcc.
Shared memory
Shared memory is your primary optimization lever. It is software-managed cache — you decide what goes in and when. On Ampere, 128 KB per SM is shared between the L1 cache and shared memory; you can request a particular split. A single thread block can request up to about 99 KB of shared memory on sm_86 (and up to roughly 163 KB on sm_80, the A100) via the cudaFuncSetAttribute opt-in.
Shared memory has approximately the same latency as L1 and an aggregate bandwidth measured in TB/s per SM. That is roughly 100× the latency advantage over global memory and roughly 20× the bandwidth advantage. The reason tiling works is that every element of a tile is loaded from global memory once into shared memory and then re-read from shared memory many times.
Bank conflicts
Shared memory is organized into 32 banks, each handling 4 bytes per cycle. If 32 threads in a warp access 32 different banks in one cycle (one address per bank), they all complete in parallel — peak throughput. If two or more threads access different addresses on the same bank, the hardware serializes them — a bank conflict, and your shared-memory throughput drops in proportion to the conflict count.
The classic example is loading a tile of float with stride 32. If you index smem[threadIdx.x * 32], every thread hits the same bank — a 32-way bank conflict, and your kernel runs 32× slower on that load. The classic fix is padding: declare __shared__ float smem[32][33] (one extra column) so that consecutive rows fall on different banks.
Global memory coalescing
When a warp issues a load from global memory, the memory subsystem services it in sector transactions — 32-byte sectors on Ampere, grouped into 128-byte cache lines.[6] If all 32 threads of the warp request addresses within a single 128-byte aligned region, the request becomes one 128-byte transaction. If each thread reaches into a different 128-byte region, the warp issues 32 transactions — 32× the bus traffic for the same FLOPs.
This is coalescing, and it is the single most-checked thing in a CUDA code review. The rule, almost universal: thread i in a warp should access address base + i. Indexing patterns that follow base + i get coalesced; patterns like base + i * stride for any stride greater than 1 do not.
// Assume float A[N]. tid = threadIdx.x in [0, 32).
// 'base' is the warp-wide starting offset.
// =================== COALESCED (1 transaction) ===================
// Consecutive threads -> consecutive 4-byte slots
// -> one 128-byte aligned segment fully covered.
float x = A[base + tid];
// ================== UNCOALESCED (up to 32 trx) ==================
// Each thread reads with stride 32 floats = 128 bytes.
// Every thread lands in a DIFFERENT 128-byte segment.
float y = A[base + tid * 32];
// ============ NEAR-COALESCED, OFFSET BUT CONTIGUOUS ============
// Misaligned by 4 bytes -> 2 transactions instead of 1.
// Penalty depends on how much spills across the 128-byte boundary.
float z = A[base + tid + 1];
L2 cache
L2 sits between every SM and the DRAM controllers. It is the only cache that is shared across all SMs. On the RTX 3090 it is 6 MB; on the A100, 40 MB; on the H100, 50 MB. If two thread blocks running on different SMs happen to load the same data, the second one hits L2 instead of DRAM.
L2 hit rate is one of the most diagnostic metrics in Nsight Compute. A high L2 hit rate means your workload's working set fits — you are getting effective reuse across SMs. A low L2 hit rate means each block is pulling new data from DRAM, and the only knob you have is to reuse data within an SM via shared memory.
Global memory (HBM / GDDR)
This is the chip's off-chip memory — HBM2e on data-center parts, GDDR6X on consumer cards. The RTX 3090 has 24 GB GDDR6X on a 384-bit bus at 19.5 Gbps, yielding 936 GB/s of peak bandwidth.[2] The A100 80GB has roughly 2 TB/s of HBM2e bandwidth; the H100 SXM, around 3.35 TB/s of HBM3.
The latency, however, is brutal: 400–800 clock cycles. The GPU hides this latency by switching warps — while one warp waits on its load, another runs. This works only if there are enough warps; that is the next section.
Figure 1.4 — Reference
The memory hierarchy as a pyramid
__shared__ float As[32][32];
__shared__ float Bs[32][32];
// 1. Cooperative load: each of the 32x32 = 1024 threads in the block
// loads ONE element from global into SMEM.
// Indexing chosen so consecutive threadIdx.x values hit consecutive
// addresses in A and B -> coalesced.
As[threadIdx.y][threadIdx.x] = A[ globalRowA * K + globalColA ];
Bs[threadIdx.y][threadIdx.x] = B[ globalRowB * N + globalColB ];
// 2. Barrier. NEEDED — otherwise some threads read As/Bs before
// other threads have filled them.
__syncthreads();
// 3. Compute. Each thread reads many As/Bs elements (reuse!) and
// accumulates a partial dot product in a register.
float acc = 0.f;
for (int k = 0; k < 32; k++) {
acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
}
// 4. Barrier. NEEDED — so no thread starts overwriting As/Bs in
// the next iteration before its peers have finished reading them.
__syncthreads();
The single most important sentence in this chapter
Every GEMM optimization in this book — tiling, register accumulation, vectorized loads, Tensor Cores, cp.async pipelining — is a different way of squeezing more arithmetic out of each global-memory byte you spend. That ratio has a name (arithmetic intensity, §1.6) and a graph (the roofline). Internalize that, and every optimization slots into one of two buckets: move my workload right on the roofline (more reuse) or move it up (better instruction mix).
Atomic-note deep dive — §1.4
[[A1.4.1]]
Shared-memory banking — the arithmetic of conflicts
memory
Shared memory is split into 32 banks, each 4 bytes wide. The bank number for address a (in bytes) is (a / 4) % 32. A warp's 32 lanes can issue 32 simultaneous accesses; if every lane targets a different bank or all 32 target the same address (broadcast), the access completes in one cycle. If two or more lanes hit the same bank but different addresses, the hardware serializes them — an N-way conflict costs N cycles. The classic pathology is row-major access of a 32-column FP32 array: every lane lands in bank 0, giving a 32-way conflict and a 32× slowdown.
The classic fix is padding: declare the array as __shared__ float tile[32][33] instead of [32][32]. The extra column shifts every row by one bank, eliminating the conflict at the cost of 32 wasted floats. A more advanced fix is swizzling: XOR the column index with a function of the row so accesses spread evenly across banks without padding. CUTLASS and Hopper TMA descriptors rely on swizzled layouts.
The memory subsystem services a warp's 32 loads in sectors: chunks of 32 contiguous bytes aligned to a 32-byte boundary. If all 32 lanes of a warp load 4-byte elements from a 128-byte aligned region, exactly four sectors are fetched — one full transaction per quarter-warp — and "coalescing" has happened. Any other access pattern fetches strictly more sectors than necessary. The hardware does not punish you for non-coalesced access; it just does more work. Coalescing is a property of the address pattern, not the loop nest; the same code path with permuted indices can shift from full coalescing to 32× over-fetch.
L2 cache — the GPU-wide last-level you can hint to
memory
L2 sits between the SMs and HBM. On A100 it is 40 MB; on RTX 3090 it is 6 MB; on H100 it is 50 MB. L2 is the only level shared by every SM, so it is the only place where data brought in by one SM can be cheaply reused by another. Ampere introduced persisting access policy windows: a kernel can mark a buffer as "expected to be reused" via cudaAccessPolicyWindow, and L2 will preferentially keep it resident, evicting transient data first. This is the only programmer-visible knob on the L2 replacement policy; everything else is hardware LRU.
HBM2/HBM3 is not a flat pool. The physical memory is organized as stacks, each containing multiple channels, each containing multiple banks. A read transaction is "activate the bank's row buffer, then burst-out 32 bytes (HBM2) or 64 bytes (HBM3)." If two consecutive requests target the same bank with different rows, the bank must precharge and re-activate, costing ≈ 10 ns. Spreading accesses across banks and channels — which the GPU's address scrambler already tries to do — is the difference between 75% and 95% of peak HBM bandwidth in practice. The metric to watch in Nsight Compute is dram__throughput.avg.pct_of_peak_sustained_elapsed.
A naive reading of the latency numbers in §1.4 is alarming. A global memory load takes ~500 cycles. Multiply that by the millions of loads per kernel, and nothing should run. In practice, GEMMs hit a sizeable fraction of peak. The reason is latency hiding by warp switching.
When a warp issues an instruction whose result is not yet available (a load, a Tensor Core op, etc.), the warp goes to sleep on a hardware scoreboard. The warp scheduler on that sub-partition immediately looks for another warp that is ready to issue, and runs that one instead. As long as there is always an eligible warp available, the SM never stalls. The 500-cycle load is invisible — it is fully covered by useful work from other warps.
What occupancy is
Occupancy is the ratio of active warps on an SM to the maximum warps the SM can hold:
occupancy= active_warps_per_SM / max_warps_per_SM
On Ampere, the maximum is 48 warps per SM (= 1,536 threads).[2] So an "occupancy of 50%" means the SM is sustaining 24 active warps. An occupancy of "100%" (or "1.0") means 48.
What limits occupancy
Three resources compete for the SM:
Registers per thread. If your kernel needs 64 registers per thread and the SM has 65,536 registers, the SM can hold 65,536/64 = 1,024 threads = 32 warps. That alone caps occupancy at 32/48 ≈ 67%.
Shared memory per block. If your block uses 32 KB of SMEM and the SM allots ~96 KB to SMEM, only 3 blocks fit. If each block has 8 warps, that is 24 active warps — 50%.
Block size limits. Max 1024 threads/block; max 16 blocks/SM on Ampere (32 on Hopper). These ceilings matter most for tiny blocks.
The limiting resource is whichever gives the smallest number. Your job during tuning is to know which one is binding and decide whether to relax it (e.g. spill some registers to gain a warp) or accept it (e.g. trade occupancy for better per-thread ILP).
The "high occupancy is not always optimal" trap
It is tempting to treat 100% occupancy as a goal. It is not. High occupancy is one strategy for hiding latency; the other is instruction-level parallelism within a single warp. A kernel that uses 128 registers per thread and runs at 33% occupancy can outperform a kernel that uses 32 registers at 100% occupancy, if the high-register kernel keeps more outstanding loads per thread and does more independent compute between them. Vasily Volkov's well-known talk Better Performance at Lower Occupancy (GTC 2010) is the canonical reference for this counter-intuitive result; the underlying observation is now reflected in CUDA's best-practice guidance.[7]
Practically: chase occupancy only until your kernel stops being limited by warp stalls. Beyond that, more occupancy buys you nothing.
Figure 1.5 — Interactive calculator
Occupancy on Ampere (sm_86 limits)
Threads / block256
Registers / thread32
Shared mem / block (KB)16 KB
Active warps / SM
—
— of 48
Active blocks / SM
—
of 16 max
Limiting factor
—
Move the sliders. The calculator applies the SM-86 hardware ceilings (65,536 regs/SM, 99 KB max SMEM/block, 48 warps/SM, 16 blocks/SM, 1024 threads/block, register allocation granularity 256 per warp). The "Limiting factor" tells you which resource is binding — that is the one to relax if you want more occupancy.
Practical guidance
On Ampere, anything above about 50% occupancy is usually enough to hide DRAM latency in a well-written GEMM. The remaining performance comes from compute throughput (Tensor Cores), good memory access patterns, and pipelining — not from squeezing out more occupancy.
Atomic-note deep dive — §1.5
[[A1.5.1]]
TLP vs ILP — the two flavors of parallelism your kernel exposes
execution
Thread-Level Parallelism (TLP) is what occupancy measures: more resident warps means the scheduler has more pools to pick from when the current warp stalls. Instruction-Level Parallelism (ILP) is what each warp exposes through independent operations the scheduler can keep in flight. A high-occupancy kernel with low ILP needs DRAM to be saturated by lots of small threads; a low-occupancy kernel with high ILP needs each thread to keep dozens of FMAs in flight. Modern GEMM kernels use both: 4–8 warps per SM and 4–8 independent register accumulators per thread, multiplying out to ~32 in-flight FMAs per scheduler.
The register-budget trap — why "use more registers" can lose
execution
An SM has a fixed register file (65,536 32-bit registers on Ampere). If each thread uses R registers and a block has B threads, the SM can host at most 65536 / (R·B) blocks. Past a register budget the kernel spills: the compiler stores excess live values to "local memory," which lives in L1 / L2 / DRAM. A spill costs orders of magnitude more than the register access it replaced. Diagnose with --ptxas-options=-v (look for "stack frame: N bytes spill stores") or with NCU's source view (look for STL/LDL instructions). The fix is one of: lower --maxrregcount, set __launch_bounds__, restructure to shorten live ranges, or accept lower occupancy if the ILP wins.
The Roofline Model was introduced by Williams, Waterman, and Patterson at Berkeley in 2008 and has since become the standard one-page summary for kernel performance.[8] It plots achievable performance against a single number — arithmetic intensity — and bounds every kernel above by two ceilings: peak compute and peak memory bandwidth. Whichever ceiling you hit first is your bottleneck.
Arithmetic intensity
I= FLOPs executed / bytes moved from DRAM
Units: FLOP/byte. High intensity means lots of compute per byte of DRAM traffic (good for compute-bound work). Low intensity means lots of DRAM traffic per FLOP (memory-bound). Two kernels with the same FLOP count can have radically different intensity depending on data reuse.
The two ceilings
Performance P in FLOPS for a kernel with intensity I running on a machine with peak compute C and peak DRAM bandwidth B is bounded by:
P≤min(C,I·B)
When you plot this with I on a log-scale x-axis and P on a log-scale y-axis, you get a horizontal "ceiling" of height C and a diagonal of slope B that intersects at the ridge point, I* = C / B. Kernels left of the ridge are memory-bound; kernels right of it are compute-bound.
Ridge point for the RTX 3090 (FP16 Tensor Core, dense)
C=142,000 GFLOPS (NVIDIA-published peak FP16-TC w/ FP32 acc, no sparsity)B=936 GB/s (GDDR6X, 384-bit, 19.5 Gbps)I*= C / B =142000 / 936≈151.7 FLOP/byte
Algorithmic vs realized intensity — read this twice
The 1365 FLOP/byte above is the algorithmic upper bound — it assumes each input and output element is read from DRAM exactly once. It is what a perfectly tiled kernel can reach.
A naive kernel that re-reads A from DRAM for every output column achieves a realized intensity of roughly 1 FLOP/byte — and that is exactly why naive kernels sit far below the roofline. Tiling chases the upper bound by reusing data through shared memory and registers. Always ask which number you mean.
1365 ≫ 152, so a 4096³ FP16 GEMM is massively compute-bound on the RTX 3090 — provided you implement it well enough to realize the available reuse. This is why GEMM should be Tensor-Core throughput limited, not bandwidth limited, and why cuBLAS-class kernels run at > 90% of FP16-TC peak on large square shapes.
Figure 1.6 — Interactive chart
Roofline (RTX 3090, FP16 Tensor Core)
GPU
Your kernel intensity (FLOP/byte)100
Achieved efficiency (% of roof)60%
The horizontal line is the compute roof; the diagonal line is the bandwidth roof. Their intersection is the ridge point. Your kernel's position relative to the ridge tells you which roof you are pushing against. cuBLAS-class GEMM kernels for a 4096³ FP16 problem land at the right of the chart, just below the compute roof.
Atomic-note deep dive — §1.6
[[A1.6.1]]
Arithmetic intensity, formally
performance
For a kernel that performs F floating-point operations while moving B bytes between DRAM and the chip, the arithmetic intensity is I = F / B, measured in FLOPs/byte. There are two flavors to be careful about: operational intensity uses the bytes actually transferred (depends on cache behavior and the access pattern), while algorithmic intensity uses the minimum bytes the math requires. Roofline plots usually mean the operational one; the algorithmic one is a theoretical upper bound on it.
For a tiled GEMM with tile size T, the operational intensity rises linearly with T because each tile reused for T inner-loop iterations amortizes its load over T FLOPs per byte. That linear knob is why "make tiles bigger" almost always helps — until you exhaust register or shared-memory budget.
The ridge point — single number that classifies your kernel
performance
The ridge point is the intensity I* where the bandwidth roof equals the compute roof: I* = Ppeak / β, where Ppeak is peak FLOP/s and β is peak DRAM bandwidth. Kernels with I < I* are memory-bound; with I > I* they are compute-bound. For an A100 in FP16 with 312 TFLOPs and 1555 GB/s, I* ≈ 200 FLOPs/byte. For the same A100 in FP32 (non-tensor-core) with 19.5 TFLOPs, I* ≈ 12 FLOPs/byte. The ridge is much higher when you turn on tensor cores; that fact alone explains why "tensor cores didn't help" almost always means "the kernel was still memory-bound."
Before continuing, verify you can answer each — click to mark complete.
What is a warp, and why is the number 32 load-bearing for every CUDA performance argument?
What causes warp divergence, what is its runtime cost, and which kinds of branches are safe vs catastrophic?
Define memory coalescing. Write the warp-thread-to-address mapping that yields a single 128-byte transaction.
On an RTX 3090, what are the sizes of: register file per SM, shared memory per SM, L2, global memory? What is the latency of each?
Compute, from first principles, whether a 4096×4096 FP16 GEMM is compute-bound or memory-bound on the RTX 3090. Show the FLOP count, the byte count, the intensity, and the ridge point.
Define occupancy. Name the three resources that can limit it, and one common reason maximum occupancy is not the right target.
Jia, Z., Maggioni, M., Smith, J., Scarpazza, D. Dissecting the NVIDIA Ampere GPU Architecture through Microbenchmarking. 2021. arXiv:2106.10499. arxiv.org/abs/2106.10499
Volkov, V. Better Performance at Lower Occupancy. GPU Technology Conference, 2010. Talk slides commonly hosted at nvidia.com (GTC 2010 archive).
Williams, S., Waterman, A., Patterson, D. Roofline: An Insightful Visual Performance Model for Multicore Architectures. Communications of the ACM 52(4), 2009. DOI 10.1145/1498765.1498785. dl.acm.org/doi/10.1145/1498765.1498785
02
Chapter 02
CUDA Programming: From Syntax to Shared Memory
Learning goal. Write, compile, and run a correct CUDA kernel. Understand the programming model deeply enough to walk a GEMM from naive → coalesced → shared-memory tiled → register-tiled → vectorized, and time each version honestly.
2.1The CUDA Programming Model
A small surface area on top of C++
CUDA is a small dialect of C++ — about a dozen keywords and a couple of built-in variables. Everything else is ordinary C++. The keywords you must know cold:
Keyword
Meaning
Example
__global__
Kernel: callable from host, runs on device, returns void.
__global__ void k(...){}
__device__
Helper function callable only from device code.
__device__ float relu(float)
__host__
Runs on the CPU (default for ordinary functions). Combinable with __device__ for dual-mode functions.
__host__ __device__ int min(...)
__shared__
Allocates memory in the SM's shared memory; per-block scope.
__shared__ float t[32][32];
__constant__
Read-only memory cached in a dedicated constant cache. 64 KB total per kernel.
__constant__ float cf[64];
__syncthreads()
Block-wide barrier. Every thread in the block must reach it.
__syncthreads();
<<<grid, block>>>
Kernel launch syntax. Takes 1D, 2D, or 3D grid and block dimensions.
k<<<128, 256>>>(x);
threadIdx, blockIdx, blockDim, gridDim
Built-in uint3-like variables visible inside every kernel.
int t = threadIdx.x;
warpSize
Built-in constant. Always 32 today; coded as a variable for forward compatibility.
if (t < warpSize) ...
Host ↔ device execution model
The host (CPU) launches a kernel asynchronously — control returns to the host as soon as the launch is enqueued; the GPU runs the kernel concurrently with subsequent host code. You synchronize explicitly with cudaDeviceSynchronize() or, more idiomatically, by recording a cudaEvent_t and waiting on it. All cudaMemcpy calls without a stream argument are implicitly synchronous; the asynchronous variant is cudaMemcpyAsync.
Error handling
Every CUDA API call returns cudaError_t. Kernel launches return errors through the next call to cudaGetLastError(). Wrap every CUDA call; otherwise a failed kernel will silently corrupt your output and you will spend hours blaming your algorithm.
#include <cuda_runtime.h>
#include <cstdio>
#include <cstdlib>
#define CUDA_CHECK(x) do { \
cudaError_t _e = (x); \
if (_e != cudaSuccess) { \
fprintf(stderr, "CUDA error %s at %s:%d -> %s\n", \
cudaGetErrorName(_e), __FILE__, __LINE__, \
cudaGetErrorString(_e)); \
std::exit(1); \
} \
} while (0)
// Device helper — runs on the GPU, callable only from device code.
__device__ float relu(float x) { return x > 0.f ? x : 0.f; }
// Kernel — entry point. Called from host, runs on device.
__global__ void scaleAndReluKernel(float* __restrict__ out,
const float* __restrict__ in,
float scale,
int N)
{
// Map this thread to one element of the output.
int idx = blockIdx.x * blockDim.x + threadIdx.x;
// Always bounds-check: the grid is rounded up, so the last
// block has more threads than there is work.
if (idx < N) {
out[idx] = relu(in[idx] * scale);
}
}
int main() {
const int N = 1 << 20; // 1,048,576 elements
const size_t bytes = N * sizeof(float);
// 1) Allocate host buffers and initialize input.
float* h_in = (float*)std::malloc(bytes);
float* h_out = (float*)std::malloc(bytes);
for (int i = 0; i < N; ++i) h_in[i] = (float)(i - N/2);
// 2) Allocate device buffers.
float *d_in, *d_out;
CUDA_CHECK(cudaMalloc(&d_in, bytes));
CUDA_CHECK(cudaMalloc(&d_out, bytes));
// 3) Copy input H->D.
CUDA_CHECK(cudaMemcpy(d_in, h_in, bytes, cudaMemcpyHostToDevice));
// 4) Launch: block of 256 threads, ceil(N / 256) blocks.
const int blockSize = 256;
const int gridSize = (N + blockSize - 1) / blockSize;
scaleAndReluKernel<<<gridSize, blockSize>>>(d_out, d_in, 2.5f, N);
CUDA_CHECK(cudaGetLastError()); // catch launch-config errors
CUDA_CHECK(cudaDeviceSynchronize()); // catch run-time errors
// 5) Copy result D->H.
CUDA_CHECK(cudaMemcpy(h_out, d_out, bytes, cudaMemcpyDeviceToHost));
// 6) Quick sanity check on a few elements.
printf("out[0] = %f out[N-1] = %f\n", h_out[0], h_out[N-1]);
// 7) Cleanup.
CUDA_CHECK(cudaFree(d_in));
CUDA_CHECK(cudaFree(d_out));
std::free(h_in);
std::free(h_out);
return 0;
}
// Compile (Ampere consumer):
// nvcc -O3 -arch=sm_86 -o scale scale.cu
// Compile (A100):
// nvcc -O3 -arch=sm_80 -o scale scale.cu
// Compile with line info for source-level profiling (chapter 4):
// nvcc -O3 -arch=sm_86 -lineinfo -o scale scale.cu
What the compile flags mean
-O3: aggressive C++ optimization, same as host-side g++/clang.
-arch=sm_86: generate SASS for Ampere GA10x consumer cards. sm_80 for A100, sm_89 for Ada (RTX 40-series), sm_90 for Hopper (H100). Wrong arch == suboptimal codegen at best, compile failure at worst.
-lineinfo: emit SASS↔source line correlation. Required for Nsight Compute's Source View. Adds zero performance cost.
-Xptxas -v: print per-kernel register, SMEM, and stack-frame usage at compile time — invaluable when chasing occupancy.
--use_fast_math: enable approximated transcendentals (sin, cos, log) — only for kernels where you have audited that loss of precision.
2.2Kernel 1 — Naive GEMM
The simplest correct kernel, and why it is slow
The simplest GEMM kernel: launch one thread per output element. Each thread loops over K, accumulating into a register. This is correct, easy to read, and slow.
// Computes C = A * B where A is M x K, B is K x N, C is M x N (row-major, FP32).
__global__ void gemmNaive(const float* __restrict__ A,
const float* __restrict__ B,
float* __restrict__ C,
int M, int N, int K)
{
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row >= M || col >= N) return;
float acc = 0.f;
for (int k = 0; k < K; ++k) {
acc += A[row * K + k] * B[k * N + col]; // 2 global loads per inner iter
}
C[row * N + col] = acc; // 1 global store
}
// Launch: 16x16 = 256 threads/block.
const int TX = 16, TY = 16;
dim3 block(TX, TY);
dim3 grid((N + TX - 1) / TX, (M + TY - 1) / TY);
gemmNaive<<<grid, block>>>(d_A, d_B, d_C, M, N, K);
Why it is slow — by the numbers
For M = N = K = 4096, FP32, on the RTX 3090:
Total threads: M·N = 16,777,216.
Global loads per thread: 2·K = 8,192.
Total global loads: 2·M·N·K = 1.37 × 1011, at 4 bytes each, ≈ 549 GB.
At the RTX 3090's peak DRAM bandwidth of 936 GB/s, just moving the loads takes 549 / 936 = 0.587 s. Add in poor coalescing, cache pressure, and the fact you can never reach peak bandwidth in practice, and the naive kernel measures in hundreds of milliseconds on a problem that cuBLAS finishes in ones of milliseconds.
The fundamental waste: every element of A is read N times and every element of B is read M times. The same word of DRAM crosses the memory bus thousands of times. Tiling exists to read each word from DRAM once and reuse it from on-chip memory thereafter.
Figure 2.2 — Interactive
One thread, one output, K loads of A and K loads of B
2.3Kernel 2 — Memory Coalescing
The cheapest 5×–10× you will ever get
Look closely at the naive kernel's inner-loop loads:
// Warp = 32 threads with consecutive threadIdx.x, same threadIdx.y.
// row = blockIdx.y * blockDim.y + threadIdx.y -> constant across the warp
// col = blockIdx.x * blockDim.x + threadIdx.x -> consecutive across the warp
// LOAD 1: A[row * K + k]
// Index does not depend on threadIdx.x -> ALL 32 threads load the SAME address.
// The hardware broadcasts this single value to the whole warp -> 1 transaction. Good.
// LOAD 2: B[k * N + col]
// col = ... + threadIdx.x -> consecutive threads hit consecutive columns of B.
// In a row-major B, that means consecutive 4-byte words -> ONE 128-byte
// transaction per warp. Good.
So this mapping is already coalesced. The hazard arises when programmers reverse the axes by accident. Swap the row/col definitions:
int row = blockIdx.x * blockDim.x + threadIdx.x; // consecutive across warp
int col = blockIdx.y * blockDim.y + threadIdx.y; // constant across warp
float acc = 0.f;
for (int k = 0; k < K; ++k) {
// LOAD: B[k * N + col]
// col is constant across the warp -> broadcast load. Fine.
// LOAD: A[row * K + k]
// row is consecutive across the warp -> consecutive ROWS of A,
// strided by K elements per row -> up to 32 separate cache lines.
// That is a 32x bandwidth waste per inner iteration.
acc += A[row * K + k] * B[k * N + col];
}
The lesson is not "swap row and col." The lesson is: pick the loop nest and the thread layout so the fast-varying thread axis runs along the fast-varying memory axis. For row-major matrices, that means threadIdx.x indexes columns.
What you can prove by reading PTX
Compile both versions with nvcc -arch=sm_86 -ptx -O3. In the well-formed kernel, the inner-loop loads from B compile to ld.global.f32 instructions whose addresses differ by 4 bytes across consecutive threads — which the hardware turns into a single 128-byte transaction. In the swapped version, the same instruction appears, but the addresses differ by 4·N bytes — and the hardware issues up to 32 separate transactions. The SASS (cuobjdump --dump-sass) shows the same number of LDG instructions for both kernels; the bus traffic and the L1 sector counts differ wildly. This is why looking only at the source code or only at the instruction count lies to you about cost.
Diagnostic
Nsight Compute exposes the coalescing penalty as the ratio between "Sectors / Request" and the ideal of 1.0 in the Memory Workload Analysis. A ratio of 4× means each warp is touching four 32-byte sectors when one would have sufficed.
2.4Kernel 3 — Shared-Memory Tiling
The single most important optimization in GPU computing
The naive kernel re-reads each element of A from DRAM N times and each element of B from DRAM M times. If we could read each element from DRAM once and then keep it on-chip, we would multiply our arithmetic intensity by roughly the tile dimension, and we would shift the kernel decisively from memory-bound to compute-bound. That is exactly what shared-memory tiling does.
The algorithm
Each thread block computes one TILE × TILE output tile of C.
The block loops over "phases" of K. In each phase it loads a TILE × TILE tile from A and a TILE × TILE tile from B into shared memory, cooperatively.
Threads synchronize on __syncthreads(). Now the entire tile of A and B is visible to all threads in the block.
Each thread computes a partial sum, reading TILE values out of shared memory.
Threads synchronize again, so no thread overwrites the SMEM tile in the next phase before its peers have finished reading.
After K / TILE phases, each thread writes its accumulator to C.
Why exactly two__syncthreads()
The barriers are not aesthetic. Each one prevents a specific data race:
Barrier 1 (after loading). If thread A starts computing using As before thread B has finished writing its piece of As, A reads stale data. Without this barrier you get silent wrong answers, usually with one or two wrong elements per tile.
Barrier 2 (after computing). If thread A starts loading the next phase's tile into As before thread B has finished reading the current phase, B reads garbage. The visible failure mode is occasional wrong answers that change depending on warp scheduling.
#define TILE 32
__global__ void gemmTiled(const float* __restrict__ A,
const float* __restrict__ B,
float* __restrict__ C,
int M, int N, int K)
{
// Shared-memory tiles: one for a row-block of A, one for a col-block of B.
__shared__ float As[TILE][TILE];
__shared__ float Bs[TILE][TILE];
// Coordinates of THIS thread's output element in C.
int row = blockIdx.y * TILE + threadIdx.y;
int col = blockIdx.x * TILE + threadIdx.x;
// Accumulator lives in a register — fastest memory on the chip.
float acc = 0.f;
// Number of phases along the K dimension.
const int nPhases = (K + TILE - 1) / TILE;
for (int p = 0; p < nPhases; ++p) {
// ============== STAGE: COOPERATIVE LOAD ===============
// Each thread in the block loads ONE element of A and ONE of B
// into shared memory. Together the block fills both TILE x TILE tiles.
int aCol = p * TILE + threadIdx.x;
int bRow = p * TILE + threadIdx.y;
// Bounds-check the global edges (last phase may be partial).
As[threadIdx.y][threadIdx.x] =
(row < M && aCol < K) ? A[row * K + aCol] : 0.f;
Bs[threadIdx.y][threadIdx.x] =
(bRow < K && col < N) ? B[bRow * N + col] : 0.f;
__syncthreads(); // (1) tiles are now fully loaded for everyone
// ============== STAGE: COMPUTE ===============
// Each thread does a TILE-element dot product against the tiles.
// All loads here are from SMEM -> ~20 cycles instead of ~500.
#pragma unroll
for (int k = 0; k < TILE; ++k) {
acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
}
__syncthreads(); // (2) safe to overwrite As/Bs in next phase
}
if (row < M && col < N) {
C[row * N + col] = acc;
}
}
// Launch: one block per output tile.
dim3 block(TILE, TILE);
dim3 grid((N + TILE - 1) / TILE, (M + TILE - 1) / TILE);
gemmTiled<<<grid, block>>>(d_A, d_B, d_C, M, N, K);
Why the index layout is As[threadIdx.y][threadIdx.x] and not the reverse
Shared memory has 32 banks; consecutive 4-byte words go to consecutive banks. When a warp executes As[threadIdx.y][k], all 32 threads in the warp have the same threadIdx.y (recall: warps span the x dimension first) and the same k. They all hit the same address → broadcast, one transaction, no bank conflict.
When the same warp executes Bs[k][threadIdx.x], all 32 threads have the same k and consecutive threadIdx.x values. They hit 32 consecutive 4-byte words → 32 different banks → no conflict, one transaction.
If you index As[threadIdx.x][threadIdx.y], you swap the fast and slow axes and create a 32-way bank conflict in the load. The kernel is suddenly 32× slower for the same source. Bank-conflict-free shared-memory indexing is the most easily-broken correctness-equivalent optimization in CUDA.
How much intensity did we just buy?
Per output tile (TILE² = 1024 output elements), the block reads K/TILE phases × 2·TILE² elements per phase = 2·K·TILE elements from DRAM, and performs 2·K·TILE² FLOPs.
For TILE = 32, that is 8 FLOP/byte — versus ~0.25 FLOP/byte for the naive kernel (1 FMA per 2 loads × 4 bytes each = 0.25 FLOP/byte). A 32× jump in intensity. That is what moves the kernel decisively to the right on the roofline.
To get the rest of the way to peak, we need to push intensity further still — by giving each thread multiple output elements (§2.5), by loading larger words at a time (§2.6), and finally by using the Tensor Cores (§3).
In the tiled kernel, each thread produces one output element. That means the entire SMEM tile of As and Bs is loaded for TILE² threads to produce TILE² outputs — one each. We can buy more arithmetic per SMEM load by giving each thread multiple outputs.
Concretely, let each thread compute a TM × TN sub-tile of C (often called the register tile, because the accumulators live in registers). The block now needs only (TILE_M/TM) × (TILE_N/TN) threads to cover the same output tile. Each thread has TM × TN accumulator registers, loads a strip of As and a strip of Bs into registers, and FMAs them all together.
#define BM 128 // output tile rows handled by one block
#define BN 128 // output tile cols handled by one block
#define BK 16 // K-strip loaded per phase
#define TM 8 // each thread handles 8 output rows
#define TN 8 // each thread handles 8 output cols
// Per block: (BM/TM) x (BN/TN) = 16 x 16 = 256 threads.
__global__ void gemmRegTile(const float* __restrict__ A,
const float* __restrict__ B,
float* __restrict__ C,
int M, int N, int K)
{
__shared__ float As[BM][BK];
__shared__ float Bs[BK][BN];
// Each thread's top-left output element in this block's tile:
int threadRow = threadIdx.y; // 0..(BM/TM - 1)
int threadCol = threadIdx.x; // 0..(BN/TN - 1)
int blockRowOrigin = blockIdx.y * BM;
int blockColOrigin = blockIdx.x * BN;
// Per-thread register file for the output sub-tile.
float regC[TM][TN] = {0.f};
const int nPhases = (K + BK - 1) / BK;
for (int p = 0; p < nPhases; ++p) {
// ============ COOPERATIVE LOAD ============
// 256 threads cooperatively load BM*BK + BK*BN elements.
// Each thread loads multiple elements (loop over the slack).
const int totalA = BM * BK;
const int totalB = BK * BN;
const int tid = threadRow * (BN / TN) + threadCol;
const int nTh = (BM / TM) * (BN / TN);
#pragma unroll
for (int i = tid; i < totalA; i += nTh) {
int r = i / BK, c = i % BK;
int gR = blockRowOrigin + r;
int gC = p * BK + c;
As[r][c] = (gR < M && gC < K) ? A[gR * K + gC] : 0.f;
}
#pragma unroll
for (int i = tid; i < totalB; i += nTh) {
int r = i / BN, c = i % BN;
int gR = p * BK + r;
int gC = blockColOrigin + c;
Bs[r][c] = (gR < K && gC < N) ? B[gR * N + gC] : 0.f;
}
__syncthreads();
// ============ COMPUTE: TM x TN register block ============
// Outer loop along the K-strip.
#pragma unroll
for (int kk = 0; kk < BK; ++kk) {
// Load a column of As (size TM) and a row of Bs (size TN) into regs.
float aReg[TM], bReg[TN];
#pragma unroll
for (int i = 0; i < TM; ++i)
aReg[i] = As[threadRow * TM + i][kk];
#pragma unroll
for (int j = 0; j < TN; ++j)
bReg[j] = Bs[kk][threadCol * TN + j];
// FMA the outer product into the register accumulator block.
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int j = 0; j < TN; ++j)
regC[i][j] += aReg[i] * bReg[j];
}
__syncthreads();
}
// Write the TM x TN block back to C.
#pragma unroll
for (int i = 0; i < TM; ++i) {
int gR = blockRowOrigin + threadRow * TM + i;
#pragma unroll
for (int j = 0; j < TN; ++j) {
int gC = blockColOrigin + threadCol * TN + j;
if (gR < M && gC < N) C[gR * N + gC] = regC[i][j];
}
}
}
What changed and why it pays
Each thread now does TM × TN = 64 FMAs per inner-loop iteration, but reads only TM + TN = 16 values from shared memory (the rest are already in registers). The compute-to-SMEM-load ratio jumps from 1× to 4× — and SMEM throughput stops being the bottleneck. The cost is register pressure: each thread now holds TM·TN = 64 accumulator registers plus the temporaries. At 64 registers per thread you can still hit ~50% occupancy on Ampere, which is plenty.
Boehm's well-known SGEMM walkthrough shows the same kernel family climbing from a few TFLOPS to roughly 70–90% of cuBLAS SGEMM on Ampere consumer parts, with 2D register tiling being the single largest jump in the FP32 path before warp-tiling and double-buffering.[1]
2.6Kernel 5 — Vectorized Memory Access
Four loads in one instruction
The hardware supports loads in widths of 32, 64, and 128 bits. CUDA exposes the wide loads through the built-in vector types float2, float4, int4, etc. A float4 load is a single 128-bit transaction — one instruction, one memory request, one register-file write of four floats.
For coalesced patterns, a 128-bit-wide load by every thread in a warp results in four 128-byte transactions to global memory and fills 4 × 32 = 128 floats with one instruction. The same data using 4 separate float loads would also take four transactions — but you would have spent four times the instruction issue slots. On a kernel that is instruction-throughput-limited, vectorization removes the instruction tax.
// Requires: A is aligned to 16 bytes (cudaMalloc guarantees this).
// Requires: index is a multiple of 4.
// Scalar version — 4 separate 32-bit loads.
float a = A[idx + 0];
float b = A[idx + 1];
float c = A[idx + 2];
float d = A[idx + 3];
// Vector version — one 128-bit load.
float4 v = *reinterpret_cast<const float4*>(&A[idx]);
// v.x v.y v.z v.w are now in registers.
// In the tiled kernel, store with the same pattern:
*reinterpret_cast<float4*>(&C[gIdx]) = make_float4(r0, r1, r2, r3);
The same idea applies to shared memory: a float4 SMEM load is one instruction and accesses 4 banks per thread. As long as the per-thread base is on a 16-byte boundary, you get conflict-free 4-bank-wide access. Vectorized SMEM loads are a standard trick in mature GEMM kernels and are essential when feeding Tensor Cores (chapter 3).
Diagnostic
If you forget to align — e.g. you cast an odd-offset pointer to float4* — the kernel may compile but will hit a misaligned-address fault at run time, reported by cudaGetLastError() as cudaErrorMisalignedAddress.
2.7Benchmarking Correctly
Most "kernel is faster" claims are measurement artifacts
The single most common mistake in CUDA performance work is timing the wrong thing. The cardinal rules:
Use CUDA events, not std::chrono or clock_gettime. The host clock will measure host time, which includes kernel-launch overhead, driver queuing, and may miss the actual GPU work entirely if the launch is asynchronous.
Warm up the GPU. The first kernel launch pays JIT compilation costs (if PTX is loaded), driver setup, and clock ramp-up. Throw away the first 5–10 runs.
Run many iterations (≥ 100, often 500–1000) and report mean and standard deviation. Variance under 1% is the bar for "stable enough to claim a winner."
Lock GPU clocks before benchmarking. Without locking, the boost clock drifts with temperature and you compare apples to oranges. (Covered in §5.4.)
Always run a correctness check against a CPU reference (or against a trusted GPU reference). A "30% faster" kernel that produces wrong answers is worse than a slow correct kernel.
#include <cuda_runtime.h>
#include <chrono>
#include <vector>
#include <numeric>
#include <cmath>
#include <cstdio>
struct BenchResult {
double mean_ms;
double stddev_ms;
double gflops;
};
template <typename Launcher>
BenchResult benchmarkKernel(Launcher launch,
long long flops, // 2*M*N*K for GEMM
int warmup = 10,
int iters = 500)
{
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
// 1) Warmup.
for (int i = 0; i < warmup; ++i) launch();
cudaDeviceSynchronize();
// 2) Timed runs.
std::vector<float> times_ms(iters);
for (int i = 0; i < iters; ++i) {
cudaEventRecord(start);
launch();
cudaEventRecord(stop);
cudaEventSynchronize(stop);
cudaEventElapsedTime(×_ms[i], start, stop);
}
// 3) Stats.
double mean = std::accumulate(times_ms.begin(), times_ms.end(), 0.0) / iters;
double var = 0.0;
for (float t : times_ms) var += (t - mean) * (t - mean);
var /= iters;
double sd = std::sqrt(var);
cudaEventDestroy(start);
cudaEventDestroy(stop);
// 4) Convert to GFLOPS. flops / (ms * 1e6) = GFLOPS.
double gflops = (double)flops / (mean * 1e6);
return { mean, sd, gflops };
}
// Usage:
// long long flops = 2LL * M * N * K;
// auto r = benchmarkKernel([&]() {
// gemmTiled<<<grid, block>>>(d_A, d_B, d_C, M, N, K);
// }, flops);
// printf("mean=%.3f ms stddev=%.3f ms %.1f GFLOPS\n",
// r.mean_ms, r.stddev_ms, r.gflops);
Correctness check
// CPU reference (slow but trusted).
void gemmRef(const float* A, const float* B, float* C, int M, int N, int K) {
for (int i = 0; i < M; ++i)
for (int j = 0; j < N; ++j) {
float s = 0.f;
for (int k = 0; k < K; ++k) s += A[i*K + k] * B[k*N + j];
C[i*N + j] = s;
}
}
// Compare with a relative-tolerance threshold.
bool verify(const float* test, const float* ref, int N, float rtol = 1e-3f) {
int wrong = 0;
double maxrel = 0.0;
for (int i = 0; i < N; ++i) {
float r = ref[i];
float t = test[i];
float denom = std::max(std::abs(r), 1.0f);
float rel = std::abs(t - r) / denom;
if (rel > maxrel) maxrel = rel;
if (rel > rtol) ++wrong;
}
printf("verify: %d/%d wrong, max rel err = %.2e\n", wrong, N, maxrel);
return wrong == 0;
}
// rtol = 1e-3 is appropriate for FP16; tighten to 1e-5 or so for FP32.
2.8The CUDA Software Stack — From .cu to SASS
What actually happens when you press nvcc
Reading order. Every box in the compile pipeline (preprocessor → CUDA front-end → PTX → SASS → cubin → fatbin) is a checkpoint where something can go wrong silently and you must know how to peek. The atomic notes below split the pipeline into its inspectable stages.
[[A2.8.1]]
Runtime API vs Driver API — two front doors to the same hardware
toolchain
CUDA exposes two C APIs that target the same underlying driver. The Runtime API (cuda_runtime.h, cudaMalloc, cudaMemcpy, cudaLaunchKernel) is what you use 95% of the time; it hides the context, module loading, and module unloading behind global per-process state. The Driver API (cuda.h, cuMemAlloc, cuLaunchKernel) exposes those — CUcontext, CUmodule, CUfunction — explicitly. Use the Driver API when you need to JIT load PTX at runtime, manage multiple contexts on one process, or implement a library others embed; for kernels and applications, the Runtime API is the right level.
You can call the two from the same process — the runtime is implemented on top of the driver — but mixing handles (driver CUstream vs runtime cudaStream_t) is a recipe for confusion. They are type-compatible on most platforms but not on all.
Host/device split.cudacc splits a .cu file into host-only and device-only intermediate files. The host file is shipped to your usual C++ compiler (g++/clang/cl); the device file goes to the CUDA front-end.
CUDA front-end → PTX. NVIDIA's Clang-based front-end lowers the device file into PTX — a virtual ISA in textual form. nvcc --ptx stops here. PTX is forward-compatible across architectures; the driver can JIT-compile it at load time.
ptxas → SASS.ptxas consumes PTX and emits SASS — the actual instructions for a specific compute capability (-arch=sm_86). This is where register allocation, instruction scheduling, and most peephole optimization happen. --ptxas-options=-v prints register and shared-memory usage; -keep keeps the intermediate SASS as .cubin.
fatbin packaging.fatbinary bundles one or more cubins (different architectures) plus optionally the original PTX into a "fat binary" that the runtime can dispatch from based on the device it finds at load time.
Driver load & JIT. At cuModuleLoad time (or implicitly during the first kernel launch), the driver picks the best cubin for the running device; if none matches, it JIT-compiles the embedded PTX to SASS, caching the result in ~/.nv/ComputeCache.
Inspecting the output of each stage is how you debug the compiler. cuobjdump --dump-ptx and cuobjdump --dump-sass extract PTX and SASS from a finished binary. nvdisasm disassembles a cubin into human-readable SASS. nvprof --print-gpu-trace (older) or ncu --target-processes all (newer) tells you which cubin was actually selected on a particular GPU.
Fatbin and -gencode — shipping one binary that runs everywhere
toolchain
A typical release-time compile looks like nvcc -gencode arch=compute_80,code=sm_80 -gencode arch=compute_86,code=sm_86 -gencode arch=compute_86,code=compute_86 .... The third entry, code=compute_86, embeds PTX so unknown future GPUs can JIT-compile it. Ship without it and your binary fails to launch on any device newer than what you compiled for; ship with it and the driver pays a one-time JIT cost on first launch (a few seconds in extreme cases). The right compile policy: ship cubins for every architecture you care about plus PTX for the newest architecture, so future GPUs can still run.
__launch_bounds__ and --maxrregcount — telling ptxas your contract
toolchain
Two ways to constrain the register usage of a kernel: a per-kernel attribute or a global compile flag. __launch_bounds__(maxThreadsPerBlock, minBlocksPerSM) tells ptxas "this kernel will run with at most maxThreadsPerBlock threads, and I want enough register room to host minBlocksPerSM blocks simultaneously." ptxas then targets a register budget of 65536 / (maxThreadsPerBlock · minBlocksPerSM) and spills if the kernel needs more. --maxrregcount=N is the global, less precise version. Prefer __launch_bounds__ because it's local to the kernel and survives refactoring.
Sharp edge
A too-tight launch_bounds can murder a Tensor-Core-heavy kernel: the compiler will spill rather than refuse, and the spills cost orders of magnitude more than the occupancy you bought. Profile both versions.
Barriers, fences, atomics, and the CUDA memory model
[[A2.9.1]]
__syncthreads() — the all-block barrier with a sneaky guarantee
sync
Three things __syncthreads() does in a single instruction: (1) blocks every thread in the block until all have reached the call, (2) acts as an acquire/release fence for shared memory within the block, (3) flushes any pending shared-memory writes so subsequent reads see them. Calling it inside a divergent region is undefined behavior — if any thread in the block fails to reach the same barrier, the block deadlocks. The compiler will sometimes silently place a __syncthreads() inside an if because it inlined a function for you. Look at the SASS (BAR.SYNC) when in doubt.
Within a single warp, threads share data faster than shared memory permits via warp-shuffle intrinsics. Five families to know:
__shfl_sync Exchange a register value across lanes by lane id. The basis for fast warp reductions.
__shfl_xor_sync Swap with the lane whose id differs by a fixed XOR mask. The natural butterfly pattern for log-step reductions.
__ballot_sync Every lane reports a one-bit predicate, returns a 32-bit mask of where the predicate was true. Used to compress sparse data.
__any_sync / __all_sync Boolean reductions across the warp.
__syncwarp The warp-only barrier; Volta+ needs it whenever a warp publishes through registers/shared memory and another part of the same warp reads.
All of these take a mask argument — a 32-bit value naming which lanes participate. Passing a wrong mask (a stale one from before a branch) is the #1 source of "intermittent NaNs only on Ampere" bugs.
atomicAdd, atomicMax, atomicCAS, and friends. Read-modify-write to a single address that is atomic with respect to every other thread in the device. Two costs to know: (1) atomics on the same address serialize — N threads colliding on one address means N sequential ops; (2) atomics on shared memory are ~10× faster than atomics on global memory because they hit the SM-local L1 alias rather than going out to L2. A privatized histogram (one bin-counter per thread block in shared memory, then one global atomic merge at the end) often turns a 100×-slow naive global-atomics histogram into a ~peak-bandwidth kernel.
Async barriers (cuda::barrier / mbarrier.* PTX) — the post-Ampere primitive
sync
Ampere introduced an async-friendly barrier that lives in shared memory. Unlike __syncthreads, it counts arrivals and completions separately, so a thread can "arrive" (declare its work is in flight) and then go do unrelated computation while the hardware drains its async copies; only when the thread later "waits" does it block. This is the synchronization primitive behind cuda::pipeline and the production-quality cp.async pipelines covered in §3.5. Hopper extends this with the TMA's barrier and "elect-one" optimizations.
Cooperative Groups — typed views of synchronization scopes
sync
The Cooperative Groups header (cooperative_groups.h) wraps the hand-rolled mask-and-shuffle pattern in C++ types: cg::thread_block, cg::coalesced_threads, cg::thread_block_tile<32>, cg::grid_group. Each group has a .sync() method, an .any(), an .reduce(...). The big win is grid-wide synchronization: with a cudaLaunchCooperativeKernel launch and cg::this_grid().sync(), you can write a single-kernel multi-pass algorithm without going back to the host. The cost is that all blocks must fit on the GPU simultaneously, which caps the grid size.
The CUDA memory model — relaxed by default, scoped on demand
sync
The CUDA memory model is patterned after C++11's: every memory operation has a memory order (relaxed / acquire / release / acq_rel / seq_cst) and a scope (thread, block, device, system). Most reads and writes are implicitly relaxed; you bring in stricter ordering by using cuda::atomic_ref, __threadfence_block(), __threadfence(), or __threadfence_system(). The scope argument tells the hardware how far the fence has to reach — thread_scope_block uses only the local L1 fence; thread_scope_device drains L2; thread_scope_system reaches host memory. Tighten only when correctness requires it; each step out costs cycles.
How to keep the GPU busy when one kernel isn't enough
[[A2.10.1]]
CUDA stream — a queue of work the device executes in order
async
A cudaStream_t is a FIFO of operations (kernel launches, memcopies, events) that the device guarantees to execute in submission order. Operations in different streams may overlap or reorder. Stream 0 (the "default stream") has special blocking semantics in most legacy modes — it serializes against every other stream — so use a named stream from cudaStreamCreate when overlapping work. Per-thread default streams (-default-stream per-thread) restore parallelism for multi-threaded host code.
A cudaEvent_t is a hardware-recorded timestamp in a stream. Three uses: (1) timing — record one before and one after a kernel, then cudaEventElapsedTime gives sub-microsecond runtime; (2) cross-stream dependencies — cudaStreamWaitEvent(stream2, event_from_stream1) makes stream2 wait without involving the host; (3) host polling — cudaEventQuery tells you whether the event has fired. For benchmarking always prefer events over std::chrono: host clocks see launch overhead but not actual device time.
Host-to-device copies happen at PCIe bandwidth, and that bandwidth is only achievable from pinned host memory (cudaMallocHost / cudaHostAlloc). Pageable allocations cost ~2× because the runtime stages them through an internal pinned buffer. cudaMemcpyAsync on a non-default stream lets you overlap copy with computation in another stream — the classic three-stream "stage-execute-drain" pipeline that hides PCIe behind compute.
A CUDA Graph is a captured DAG of kernel launches, memcopies, events, and host callbacks. You build it once (via stream capture — record the work submitted on a stream, or via the explicit cudaGraphAdd* APIs) and then replay it with one cudaGraphLaunch call. The win is amortization: for a pipeline of 50 small kernels, the per-launch overhead drops from ~50 × 5 µs to a single launch of a few microseconds. Graphs are the canonical fix for "my GPU is 80% idle in the timeline view." Use them whenever the same sequence of work runs many times — every training step, every inference call, every iteration of a numerical solver.
Trap
Graph capture turns runtime API calls into recorded nodes; if a kernel inside the capture depends on a value computed by the host, you must either bake it into the graph as a memcpy node or use cudaGraphExecKernelNodeSetParams to update it before each replay. Modifying a captured graph is much more constrained than rebuilding one.
cudaMallocManaged returns a pointer valid on both host and device. The driver page-faults data between host and device on first touch, transparent to the program. Productivity-wise, brilliant; performance-wise, treacherous: every page fault is ~10 µs, and a 4 KB page fault to load a single FP32 row hides nothing. Mitigations: cudaMemPrefetchAsync to push data ahead of time, cudaMemAdvise with cudaMemAdviseSetReadMostly or SetPreferredLocation to bias placement, and oversubscription support on Pascal+ for problems that don't fit. For peak performance use explicit cudaMalloc + cudaMemcpyAsync; for prototyping or for codes whose access patterns the driver can predict, managed memory is fine.
Stream-ordered allocator (cudaMallocAsync) — the modern default
memory
Since CUDA 11.2, cudaMallocAsync / cudaFreeAsync allocate and free in a stream, using a per-device memory pool. Three wins: (1) freed memory can be reused by a later allocation in the same stream without synchronizing, (2) the pool can be size-trimmed via cudaMemPoolSetAttribute, (3) allocations are dirt cheap after the first one of a size class. Use this as the default; fall back to cudaMalloc only when integrating with code that needs a synchronous allocator.
Sticky errors — why one bad kernel breaks every later call
debugging
CUDA errors are sticky: once a kernel triggers a fault (illegal memory access, misaligned address), every subsequent runtime call on the same context returns the same error until you cudaDeviceReset(). That's why the error you actually print is rarely from the line that caused the problem; it is from the next cudaMemcpy that propagates the sticky state. Always wrap launches with cudaGetLastError() immediately afterward, and call cudaDeviceSynchronize() before declaring success in a unit test — kernels return asynchronously, and a fault inside one can land in the next Test's setup.
racecheck Shared-memory data races, including the subtle "missing __syncthreads" pattern.
initcheck Reads of uninitialized memory.
synccheck Misuse of __syncthreads across divergent paths.
leakcheck Allocations never freed before context teardown.
Run them on every new kernel before benchmarking; the overhead is large (5–50×) but the output is the difference between "ship it" and "two days of git-bisect."
Write the 2D thread→element index calculation for a matmul kernel from memory, including bounds checking.
Explain what __syncthreads() does and prove that the tiled algorithm needs exactly two of them per phase.
Define a bank conflict, show one source-level pattern that causes a 32-way conflict, and one common pattern that avoids it.
Calculate the arithmetic intensity of your tiled kernel with TILE = 32. Compare against the naive kernel.
Write a correct CUDA-events timing block, including warmup, multiple iterations, and a correctness check.
List four nvcc compile flags and what each does for kernel performance or debugging.
References — Chapter 2
Boehm, S. How to Optimize a CUDA Matmul Kernel for cuBLAS-like Performance: a Worklog. 2022. siboehm.com/articles/22/CUDA-MMM — ten-kernel SGEMM walkthrough on a single Ampere consumer card; the closest public companion to this chapter.
NVIDIA Developer Blog. How to Access Global Memory Efficiently in CUDA C/C++ Kernels.developer.nvidia.com
Volkov, V., Demmel, J. Benchmarking GPUs to Tune Dense Linear Algebra. SC'08. The foundational SGEMM-on-GPU paper; still relevant for the reuse arguments.
03
Chapter 03
Tensor Cores & PTX: The Hardware Acceleration Layer
Learning goal. Understand what a Tensor Core actually is at the hardware level. Write a working WMMA kernel. Drop down to raw PTX mma.sync and cp.async to extract the last 10–20% of performance that the high-level API leaves on the table.
3.1What Tensor Cores Are
Specialized silicon for one operation, executed brilliantly
A Tensor Core is a piece of silicon that performs a small matrix multiply-accumulate in a single hardware instruction. Where a CUDA core does one scalar FMA per clock — d = a·b + c, three inputs, one output — a Tensor Core does D = A·B + C with A, B, C, D all small dense matrices. One instruction; several hundred FMAs of useful work.
Generations
Gen
Architecture
Year
First Card
Native shapes
Notable additions
1
Volta (sm_70)
2017
V100
m16n16k16 (FP16→FP32)
The original. Hidden behind WMMA in CUDA 9.
2
Turing (sm_75)
2018
T4, RTX 20-series
+ m8n8k16 (FP16); INT8/INT4 modes
First mass-market TCs. Quantized inference.
3
Ampere (sm_80, sm_86)
2020
A100, RTX 30-series
m16n8k16 / m16n8k8 (FP16, BF16, TF32)
2:4 structured sparsity; BF16; TF32; cp.async; doubled FP16 throughput per TC vs Turing.
Public details from NVIDIA whitepapers and CUDA toolkit headers.
Each generation roughly doubles per-SM Tensor-Core throughput at the previous generation's precision and adds a new lower-precision mode. The key consequence for you: the throughput ceiling you measure against is set by the Tensor-Core peak of your specific architecture, not the CUDA-core peak.
Throughput on the RTX 3090 (Ampere, sm_86)
Reproducible from NVIDIA's published numbers and microbenchmark studies:[1][2]
Mode
Peak (dense)
Peak (2:4 sparse)
Notes
FP32 CUDA cores
35.6 TFLOPS
—
Scalar FMA
FP16 CUDA cores
~71 TFLOPS
—
Packed half2
FP16 Tensor Core (FP32 acc)
142 TFLOPS
284 TFLOPS
The headline number
BF16 Tensor Core
142 TFLOPS
284 TFLOPS
Same as FP16-TC throughput
TF32 Tensor Core
~71 TFLOPS
142 TFLOPS
Truncated-mantissa FP32
INT8 Tensor Core
284 TOPS
568 TOPS
Inference-oriented
The ratio FP16-TC / FP32-CUDA is approximately 4×. That is the entire reason a tensor-core GEMM lives at 142 TFLOPS while a hand-rolled FP32 CUDA-core GEMM tops out near 35 TFLOPS. You do not get there by writing more clever scalar code. You get there by using Tensor Cores.
Figure 3.1 — Chart
RTX 3090 throughput by precision and execution unit
Hardware modes use different operation countsArchived textbook specifications for RTX 3090, dense modes. Integer TOPS and floating-point TFLOPS have different units; these are separate rows, not a single common-scale ranking.
Mode
Reported peak
Unit
FP32 CUDA core
35.6
TFLOPS
FP16 CUDA core
71
TFLOPS
TF32 Tensor Core
71
TFLOPS
FP16 Tensor Core
142
TFLOPS
BF16 Tensor Core
142
TFLOPS
INT8 Tensor Core
284
TOPS
Peak throughput is a hard ceiling; real kernels achieve a fraction of it. The Tensor Core peaks are what define your "% of cuBLAS" denominator when chasing the leaderboard.
3.2The WMMA API: An Entry Point
High-level Tensor-Core access, since CUDA 9
The WMMA (Warp Matrix Multiply-Accumulate) API is in <mma.h>, namespace nvcuda::wmma. It works at the warp level — every Tensor-Core operation in WMMA is collective across all 32 threads in a warp.
The model is: declare opaque fragment types for the A, B, and accumulator/result matrices; load global or shared memory into a fragment; call mma_sync; store the result fragment back. The fragment's storage is distributed across the warp's registers, but you do not see how — the library hides the layout.
#include <cuda_runtime.h>
#include <mma.h>
using namespace nvcuda;
// Computes a single 16x16 output tile of D = A * B + C, where:
// A is 16 x 16 (FP16), row-major
// B is 16 x 16 (FP16), col-major
// C, D are 16 x 16 (FP32), row-major
// One WARP executes this — 32 threads cooperating.
__global__ void wmmaTileKernel(const half* A, const half* B, float* D,
int M, int N, int K)
{
// Each block is a single warp (32 threads).
// Compute origin of this warp's tile in the output.
int tileM = blockIdx.y * 16;
int tileN = blockIdx.x * 16;
// Fragments live in registers (distributed across the warp).
wmma::fragment<wmma::matrix_a, 16, 16, 16, half, wmma::row_major> aFrag;
wmma::fragment<wmma::matrix_b, 16, 16, 16, half, wmma::col_major> bFrag;
wmma::fragment<wmma::accumulator, 16, 16, 16, float> cFrag;
wmma::fill_fragment(cFrag, 0.0f);
// K-loop: accumulate over slabs of 16.
for (int k = 0; k < K; k += 16) {
const half* aPtr = A + tileM * K + k; // row-major
const half* bPtr = B + k * N + tileN; // col-major-equiv
wmma::load_matrix_sync(aFrag, aPtr, K); // leading dim = K
wmma::load_matrix_sync(bFrag, bPtr, N); // leading dim = N
wmma::mma_sync(cFrag, aFrag, bFrag, cFrag); // D = A*B + C, in place
}
// Store result tile.
float* dPtr = D + tileM * N + tileN;
wmma::store_matrix_sync(dPtr, cFrag, N, wmma::mem_row_major);
}
// Launch: one warp (32 threads) per 16x16 output tile.
dim3 block(32);
dim3 grid(N / 16, M / 16);
wmmaTileKernel<<<grid, block>>>(d_A, d_B, d_D, M, N, K);
What WMMA buys you, and where it hurts
Portable across Volta → Hopper. The same source compiles to wmma.mma on Volta and to mma.sync on Ampere/Hopper.
Zero PTX in your source. Easier to read, easier to onboard.
BUT the register layout of fragments is hidden. You cannot pipeline loads optimally because you cannot see which thread holds which element. You cannot fuse other warp-level operations with the fragment efficiently. You cannot use the most efficient ldmatrix.sync load pattern without dropping to PTX anyway.
WMMA typically gets you to ~70–80% of cuBLAS for a well-tuned shape. To close the last 15–25%, you drop one level deeper.
3.3PTX and Inline Assembly
The intermediate representation NVIDIA exposes to you
PTX (Parallel Thread Execution) is NVIDIA's virtual instruction set. nvcc compiles your CUDA C++ to PTX, and the driver's JIT compiler (or ptxas ahead-of-time) lowers PTX to SASS, the actual machine code for a specific compute capability. PTX is to CUDA what LLVM IR is to C++: a portable, stable, readable intermediate that the next stage of the compiler turns into hardware-specific code.
You can ask nvcc for the PTX of a kernel with -ptx or for the final SASS with cuobjdump --dump-sass. The PTX ISA reference, maintained by NVIDIA, is the authoritative document for every instruction.[3]
Inline PTX syntax
CUDA C++ supports inline PTX via the asm keyword, identical in spirit to GCC inline asm:
// Pattern: asm( "ptx-template" : outputs : inputs : clobbers );
// Trivial example: 32-bit integer add.
int a = 5, b = 3, c;
asm volatile("add.s32 %0, %1, %2;"
: "=r"(c) // output 0: 32-bit reg
: "r"(a), "r"(b)); // input 0,1: 32-bit regs
// c == 8
// Constraints (most common):
// "r" -> .u32/.s32 (32-bit int register)
// "l" -> .u64/.s64 (64-bit int register)
// "f" -> .f32 (32-bit float register)
// "d" -> .f64 (64-bit float register)
// "h" -> .b16 (16-bit, e.g. half storage)
// prefix "=" means write-only output; "+" means read+write.
// volatile: prevents the compiler from reordering or eliding the asm.
The PTX template uses %0, %1, ... as placeholders for the operands in declaration order (outputs first, then inputs). Everything else is verbatim PTX. The compiler validates the operand types against the constraints — a type mismatch is caught at compile time, not at run time. This is one of the reasons inline PTX in CUDA is safer than inline ASM in GCC.
3.4The mma.sync PTX Instruction
Where the tensor cores actually live
On Ampere, the PTX instruction for an FP16-input / FP32-accumulator Tensor-Core MMA looks like:
mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32{%0,%1,%2,%3}, // D — accumulator out, 4 × f32 per thread{%4,%5,%6,%7}, // A — 4 × b32 per thread (8 fp16 packed){%8,%9}, // B — 2 × b32 per thread (4 fp16 packed){%10,%11,%12,%13};// C — accumulator in, 4 × f32 per thread
Every token in the mnemonic carries meaning:
mma — matrix multiply-accumulate.
sync — synchronizes the warp; all 32 threads must execute together.
aligned — operand addresses are assumed properly aligned.
m16n8k16 — the operation tile shape: A is 16 (M) × 16 (K), B is 16 (K) × 8 (N), C and D are 16 (M) × 8 (N).
row.col — A is row-major, B is column-major (the "TN" form, the most natural for the hardware).
f32.f16.f16.f32 — the precisions of D, A, B, C respectively. So FP16 inputs, FP32 accumulators.
The register-layout requirement
The catch — and the reason this PTX is not for the faint of heart — is that each operand fragment is distributed across the 32 threads of the warp in a hardware-mandated pattern. For m16n8k16 FP16:
A (16×16, FP16): each thread owns 8 FP16 elements = 4 × 32-bit registers, in a specific (lane → element) mapping defined in the PTX ISA.
B (16×8, FP16): each thread owns 4 FP16 elements = 2 × 32-bit registers.
C, D (16×8, FP32): each thread owns 4 FP32 elements = 4 × 32-bit registers.
If you load the wrong element into the wrong lane, the multiply produces garbage. There is no run-time error and no way to discover this except by checking the output.
ldmatrix.sync — the partner instruction
Manually shuffling 32 lanes into the right layout is error-prone and slow. NVIDIA provides ldmatrix.sync, a PTX instruction that loads up to four 8×8 FP16 matrices from shared memory directly into the register pattern expected by mma.sync. It is the canonical loader.
// Load four 8x8 fp16 matrices from shared memory.
// %0..%3 are output: 4 × .b32 registers per thread (each register holds 2 fp16).
// %4 is input: shared-memory address (each lane provides its own address;
// the hardware reads the addresses from 8 of the 32 lanes per matrix).
//
// .x4 = four 8x8 matrices loaded in one call
// .trans = optional, transposes each 8x8 (so A can be loaded as row-major from
// col-major shared memory, or vice versa).
//
// Usage from CUDA C++:
uint32_t r0, r1, r2, r3;
uint32_t smem_addr = __cvta_generic_to_shared(&smem_ptr[some_index]);
asm volatile(
"ldmatrix.sync.aligned.m8n8.x4.shared.b16 "
"{%0, %1, %2, %3}, [%4];\n"
: "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3)
: "r"(smem_addr));
End-to-end: a warp-level mma.sync tile
// One warp computes a 16x8 output tile of C using mma.sync.
// In practice, you call this inside a loop over the K dimension and
// inside a larger block-level tiling scheme (see Chapter 5).
__device__ inline void mma_m16n8k16_fp16_fp32(
float d[4], // output accumulator
const uint32_t a[4], // 4 × b32 from ldmatrix
const uint32_t b[2], // 2 × b32 from ldmatrix
const float c[4]) // input accumulator
{
asm volatile(
"mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 "
"{%0, %1, %2, %3}, " // D
"{%4, %5, %6, %7}, " // A
"{%8, %9}, " // B
"{%10, %11, %12, %13};\n"
: "=f"(d[0]), "=f"(d[1]), "=f"(d[2]), "=f"(d[3])
: "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]),
"r"(b[0]), "r"(b[1]),
"f"(c[0]), "f"(c[1]), "f"(c[2]), "f"(c[3]));
}
// Typical inner-loop usage inside a larger kernel:
//
// load A_tile and B_tile into shared memory (see §3.5 for cp.async)
// __syncthreads();
//
// for each k-slab in the SMEM tile:
// uint32_t a[4], b[2];
// ldmatrix into a[] from As
// ldmatrix into b[] from Bs
// mma_m16n8k16_fp16_fp32(acc, a, b, acc);
//
// write acc back to global C
Figure 3.4 — Interactive
m16n8k16 fragments: which thread holds which element
The exact (lane, register slot) → matrix element mapping is normative and lives in the PTX ISA, §"Warp Level Matrix Multiply-Accumulate Instructions."[3] The high-level idea — that the warp distributes a small matrix across 32 lanes — is the part you need to internalize; the exact map is what ldmatrix.sync exists to handle for you.
When to choose each abstraction level
WMMA. Prototyping; portability across Volta/Turing/Ampere/Hopper; learning. ~70–80% of peak.
mma.sync + ldmatrix. Production-grade hand-written kernels; competitive with cuBLAS. ~85–95% of peak.
CUTLASS templates. When you want production-grade and portability and don't want to maintain it yourself. Often within 1–3% of cuBLAS, sometimes ahead on awkward shapes.
Hopper wgmma + TMA. H100-only. Async, much larger tiles, dramatically different programming model. Out of scope here but the same architectural ideas.
3.5cp.async and Software Pipelining
Overlap load with compute, by hand
Without async loads, the inner loop of a tiled GEMM looks like: load tile → barrier → compute → barrier → load next tile → barrier → compute → .... Each barrier idles the entire block. The compute and load phases never overlap. The Tensor Cores sit silent while DRAM loads finish.
Ampere added cp.async — an asynchronous memory copy from global memory directly into shared memory, bypassing the register file. The thread issues the copy and continues executing. The copy completes in the background. The thread synchronizes only when it actually needs the data.[4]
With cp.async you can double-buffer: while the Tensor Cores compute on buffer A, fire off the load for buffer B. When the compute is done, swap roles. The compute and the load are now happening at the same time. If the compute time and the load time are similar, you double throughput.
The control-flow primitives
Three PTX instructions form the loop primitives:
cp.async.<size>.shared.global [dst], [src], size; — issue a copy. The thread does not block.
cp.async.commit_group; — close out the most recent batch of cp.async requests; they form a "group."
cp.async.wait_group N; — block until at most N outstanding groups remain. wait_group 0 = wait for everything.
// Convenience CUDA intrinsic (since CUDA 11):
__device__ inline void cp_async_16B(void* smem_dst,
const void* global_src)
{
// Convert the generic shared-memory pointer to a 32-bit shared address.
uint32_t smem_int = __cvta_generic_to_shared(smem_dst);
// 16-byte cp.async — the canonical width for FP16 tile loads.
asm volatile(
"cp.async.ca.shared.global [%0], [%1], %2;\n"
:: "r"(smem_int), "l"(global_src), "n"(16)
);
}
__device__ inline void cp_async_commit() {
asm volatile("cp.async.commit_group;\n" ::);
}
__device__ inline void cp_async_wait_all() {
asm volatile("cp.async.wait_group 0;\n" ::);
}
// Wait until at most N groups remain in flight (lets earlier groups
// finish while later ones keep going — basis for multi-stage pipelines).
template <int N>
__device__ inline void cp_async_wait_group() {
asm volatile("cp.async.wait_group %0;\n" :: "n"(N));
}
Double-buffered inner loop, sketched
// Two SMEM buffers, ping-pong.
__shared__ half As[2][BM][BK];
__shared__ half Bs[2][BK][BN];
int load = 0; // buffer being loaded
int comp = 1; // buffer being computed on
bool first = true;
// Prime the pipeline: issue load for the first phase.
issueLoadsInto(As[load], Bs[load], /*phase=*/0);
cp_async_commit();
for (int p = 0; p < nPhases; ++p) {
if (p + 1 < nPhases) {
// Issue the NEXT phase's load while we compute on this phase.
std::swap(load, comp); // ping-pong roles
issueLoadsInto(As[load], Bs[load], p + 1);
cp_async_commit();
}
// Wait until the buffer we want to COMPUTE on is fully loaded.
cp_async_wait_group<1>(); // keep one in-flight load (the next phase)
__syncthreads();
// Tensor-core compute using mma.sync, consuming As[comp]/Bs[comp].
runMmaLoop(As[comp], Bs[comp], /*accumulator=*/regC);
// No second barrier needed here as long as the next phase will
// load into a DIFFERENT buffer (the swapped one).
}
// Drain the pipeline.
cp_async_wait_all();
Figure 3.5 — Interactive
Without vs with cp.async pipelining
In the bottom timeline, the next phase's load is in flight while the current phase's mma runs. If the load is shorter than the MMA, the load is fully hidden. CUTLASS uses 3–5 stage pipelines on Ampere for even tighter overlap; the trade-off is more shared memory per block.
Why this is the last big lever before peak
On Ampere consumer parts, well-tuned mma.sync kernels without async pipelining typically land around 80–85% of FP16-TC peak. Adding 2- or 3-stage cp.async pipelining pushes that into the low-90% range and lets the kernel cross the cuBLAS line on selected shapes.
3.6Tensor-Core Numerics — What Precision Actually Buys
Format choice as a first-class optimization knob
Goal. Make the precision/throughput trade-off mechanical instead of guess-and-test. Each format is one node in §0.2; this section says exactly when each one is appropriate on a Tensor Core and what happens at the SASS level when you pick.
[[A3.6.1]]
Accumulator policy — the silent half of every MMA
numerics
Every Tensor Core MMA has two precisions you can pick independently: the operand precision (A and B) and the accumulator precision (C). The hardware allows several combinations per generation; the most useful ones on Ampere are FP16 × FP16 → FP32 and BF16 × BF16 → FP32. The FP16 → FP16 variant exists but is dangerous for K > 256: cumulative round-off blows up. Always default to FP32 accumulators unless you have proved otherwise on real data.
From CUDA 11 on Ampere, cublasSgemm on default math mode actually runs TF32 tensor cores internally — a 10-bit-mantissa input format (see [[A0.2.6]]). You get 8× throughput vs CUDA-core FP32 at the cost of mantissa precision. To force "real" FP32 numerics call cublasSetMathMode(handle, CUBLAS_PEDANTIC_MATH) or set the math mode to CUBLAS_TF32_TENSOR_OP_MATH_DISALLOW. The throughput-vs-accuracy budget for TF32 is the single biggest "why does my reference disagree" gotcha in cuBLAS.
Ampere introduced a 2:4 structured-sparsity feature on Tensor Cores: in every contiguous group of 4 elements of A, exactly 2 must be zero. Storing this as a 50%-dense matrix with a 2-bit-per-quad selection metadata cuts memory traffic in half and doubles MMA throughput. The catch is the sparsity pattern is structured, not arbitrary; pruning a dense network to 2:4 typically costs a few percent accuracy and requires fine-tuning. The PTX is mma.sp.sync. Used by NVIDIA's structured-sparse Transformer kernels in cuSPARSELt.
FP16's smallest normal positive value is ≈ 6·10−5. Gradients in deep nets routinely land below that and underflow to zero — training silently stalls. The fix is loss scaling: multiply the loss by a large constant (1024–65536), do the backward in FP16, then divide gradients by the same constant before the optimizer step. The intermediate exponents climb back into the FP16 normal range. BF16 has FP32's exponent and does not need loss scaling. PyTorch's autocast and CUDA's NVIDIA::amp automate this; if you write kernels at this level you almost never have to think about it.
What sm_90 added on top of everything in this chapter
Most of this textbook targets Ampere. Hopper (H100, sm_90) keeps every Ampere primitive but adds four big features that change the kernel-engineering shape of GEMM. Even if you do not own an H100, you should know what these are because the next-generation public CUTLASS kernels assume them.
[[A3.7.1]]
TMA — Tensor Memory Accelerator
hopper
The TMA is a hardware unit that copies multi-dimensional tiles from global memory to shared memory described by a tensor descriptor. Instead of one thread issuing one address per cp.async, one elect-one thread issues a single cp.async.bulk.tensor instruction with a tile descriptor and the unit fetches the entire 2D/3D/4D tile, optionally swizzled, into shared memory. The win: zero address-arithmetic instructions on the warps, perfect coalescing for free, asynchronous completion signaled by an mbarrier. Functionally, TMA replaces the entire load-prologue of an Ampere GEMM with a couple of PTX instructions. Required for wgmma performance.
wgmma — warp-group MMA, async at the M-N tile level
hopper
Hopper's MMA instruction is wgmma.mma_async: it operates over a warp group (4 warps = 128 threads) and is asynchronous. The warp group issues the instruction, sets a fence, then can keep doing math while the Tensor Cores grind in the background. Combined with TMA-fed shared memory and async barriers, the inner loop of a Hopper GEMM is essentially three independent streams: TMA loads, wgmma execution, and accumulator updates — all overlapping. Output tile sizes are huge by Ampere standards (m64n256k16 is a common micro-tile). Ampere kernels do not port directly; Hopper requires a different scheduling model.
Thread block clusters and distributed shared memory
hopper
Hopper added a new layer above blocks: a thread block cluster, up to 8 (or 16) cooperating blocks that share access to each other's shared memory via "Distributed Shared Memory" (DSMEM). A block can directly load from a sibling block's SMEM without going to L2. The use case is split-K GEMMs and FlashAttention-class kernels where the natural tile sizes exceed one SM's SMEM budget: clusters let you spread one tile across multiple SMs while keeping data on-chip. The PTX is ld.shared::cluster, declared via cluster_dim_x/y/z in the launch grid.
Hopper Tensor Cores accept FP8 (E4M3/E5M2) inputs. To use them productively in training, NVIDIA's Transformer Engine library maintains running statistics of each tensor's amax (max absolute value), then rescales tensors per-step so they fit in the narrow FP8 range without overflow. The hardware does the matmul in FP8 but accumulates into FP32; the amax statistics live in extra small tensors that the framework keeps. The end-to-end speedup vs FP16 is roughly 2× at sufficient batch size; the engineering cost is non-trivial.
Jia, Z., Maggioni, M., Smith, J., Scarpazza, D. Dissecting the NVIDIA Ampere GPU Architecture through Microbenchmarking. arXiv:2106.10499. arxiv.org/abs/2106.10499
NVIDIA. CUTLASS GitHub repository — production reference for tiled mma.sync, ldmatrix, and pipelined cp.async patterns. github.com/NVIDIA/cutlass
NVIDIA. Hopper H100 Architecture Whitepaper and NVIDIA Hopper Tuning Guide — the next generation's wgmma + TMA model.
04
Chapter 04
Nsight Compute: Seeing Inside Your Kernel
Learning goal. Profile any CUDA kernel with Nsight Compute. Read every metric in the Summary, Memory Workload Analysis, Warp State Statistics, and Source views. Diagnose the dominant bottleneck and know which optimization to apply next — every time.
4.1Nsight Compute Architecture
What it does, and what its measurements are worth
NVIDIA ships two profilers. They sound similar, do different things, and you need both.
Nsight Systems (nsys): system-wide timeline. Shows CPU threads, CUDA API calls, kernel launches, memory copies, and CPU ↔ GPU synchronization. Use this to see the shape of your program — gaps between kernels, host-side bottlenecks, launch overhead, multi-stream behavior. Lightweight, almost no slowdown.
Nsight Compute (ncu): per-kernel deep dive. Counts hundreds of hardware performance counters during kernel execution and gives you the data needed to diagnose why a kernel is slow. Heavy — it slows your program down enormously while profiling. Use this on the kernels Nsight Systems flagged.
How ncu gets its numbers — and why this matters
The GPU has a fixed number of hardware counter slots — much smaller than the number of metrics you might want. When you ask ncu for a metric set that exceeds the slots in one pass, the tool transparently replays the kernel. Each replay collects a different subset of counters. ncu stitches the results together into a single report. This is called kernel replay, and it has two practical consequences:
Profiling makes the kernel run many times. If your kernel has side effects (e.g. writes to memory the next launch reads), enable kernel replay isolation (the default since recent versions) so each replay sees the same input state.
Profiled timings are not real timings. Counter-collection inflates kernel duration by 2–100×. Use ncu timings only relatively — to compare two kernel versions in the same report. For absolute timing, use CUDA events.
Other replay modes exist (Application Replay, Range Replay) and matter for complex workloads with cross-kernel state.[1]
4.2Running the Profiler
The CLI commands you will use 95% of the time
# 1) Full profile of every kernel launch in the program.
# Writes report.ncu-rep, which opens in the Nsight Compute UI.
ncu --set full -o report ./my_program
# 2) Default profile (smaller metric set, much faster).
ncu -o report ./my_program
# 3) Profile just a few named metrics — fastest, scriptable.
ncu --metrics sm__throughput.avg.pct_of_peak_sustained_active,\
dram__throughput.avg.pct_of_peak_sustained_elapsed,\
l1tex__throughput.avg.pct_of_peak_sustained_active \
./my_program
# 4) Skip warmup launches, profile only the steady-state kernel.
# --launch-skip N : skip first N kernel launches
# --launch-count M : then profile M of them
ncu --launch-skip 5 --launch-count 1 -o report ./my_program
# 5) Filter to a particular kernel by name (regex).
ncu --kernel-name regex:gemmTiled.* --launch-count 1 -o report ./my_program
# 6) Source-level profiling — requires nvcc -lineinfo at compile time.
# The Source view in the UI then shows per-line PTX and SASS with cycle counts.
nvcc -O3 -arch=sm_86 -lineinfo -o my_program my_program.cu
ncu --set full --import-source on -o report ./my_program
# 7) Multi-process apps (e.g. distributed training): follow children.
ncu --target-processes all -o report ./launch_script.sh
# 8) Compare two builds. ncu does NOT have a --diff flag — comparison
# is done in the UI by adding a baseline:
# File -> Open baseline.ncu-rep
# File -> Add Baseline optimized.ncu-rep
# Or, equivalently, from the CLI summary table:
ncu --import optimized.ncu-rep --baseline baseline.ncu-rep --csv > diff.csv
The baseline workflow is the most underused feature
Always profile both your old and new kernel into separate .ncu-rep files, then add the old one as a baseline when viewing the new one. The UI shows a delta column for every metric. Every optimization in this book should be validated by exactly this workflow: profile, change one thing, re-profile, verify the metric you targeted moved and nothing else regressed.
The key flags worth memorizing
Flag
Effect
--set full
Collect every metric in the "full" section set — the most comprehensive built-in set. Slow but complete.
--set default
Default. Balanced cost/coverage.
--set basic
Minimal. Fastest. Just SM and memory speed-of-light.
Dump metrics as CSV to stdout — for scripted regression checks.
4.3Reading the Summary View
What each section means and what it tells you to do
Opening a .ncu-rep in the UI, the kernel's Summary page is your first stop. It is organized into named sections; here is what each one means and how to read it.
GPU Speed Of Light (SOL)
The single most important section. Two numbers:
Compute (SM) Throughput — metric sm__throughput.avg.pct_of_peak_sustained_active. The fraction of peak SM throughput your kernel achieved.
Memory Throughput — the equivalent for the memory subsystem; on most reports this rolls up DRAM, L2, and L1.
The diagnostic table is short:
SM %
Memory %
Diagnosis
What to try next
> 80%
any
Compute-bound. You are near peak.
Switch to a lower-precision Tensor Core. Reduce instruction count. Better mma fragments. Approach the roof.
Latency-bound. Neither pipe is busy; warps are stalled.
Check warp-state statistics — what are they waiting on? Increase occupancy. Increase ILP. Reduce per-thread sync.
> 60% both
> 60% both
Balanced; both pipes have headroom. Likely launch-overhead or occupancy issue.
Increase work per kernel. Use streams. Increase block count.
Compute Workload Analysis
Per-pipe utilization: ALU (FP32/INT32 CUDA cores), FMA, TENSOR, FP64, FP16, XU (transcendentals), LSU (load/store), ADU (address). If you wrote a Tensor-Core kernel and TENSOR throughput is low, you are not actually hitting the Tensor Cores — usually because mma.sync issue is starved by SMEM bandwidth or the wrong fragment layout.
Memory Workload Analysis
Per memory level: traffic in/out, request counts, sector counts, hit rates. The most diagnostic numbers:
L1/TEX Hit Rate. Low = your global-memory access pattern is wasting cache. Often a coalescing issue.
L2 Hit Rate. Low = the working set is not living in L2. Often a tiling issue.
Sectors / Request. 1.0 is perfect. 4.0 means every load is fetching 4× the cache lines it needed. Coalescing failure.
Shared Memory Wavefronts. The bank-conflict counter. A 32-way conflict shows up as 32× more wavefronts than requests for that load.
Warp State Statistics
Where your warps spend cycles when they are not issuing. Each "stall reason" is its own metric and each tells a different story:[2]
Stall reason
What it means
Fix
long_scoreboard
Waiting on an L1TEX (global/local/surface/tex) operation. Effectively: global memory latency.
Hide it with more outstanding warps (occupancy) or more outstanding loads per warp (ILP). Or just reduce loads (tile).
short_scoreboard
Waiting on an MIO operation — shared memory, special math units, or dynamic branching.
Usually shared-memory access dominates. Check bank conflicts; reduce SMEM traffic via register reuse.
mio_throttle
The MIO pipe queue is saturated. Too many shared/special instructions piling up.
Reduce shared-memory pressure. Replace SMEM ops with register-resident accumulators.
barrier
Waiting at __syncthreads for slower threads in the block.
Balance work across threads; check for divergent paths converging at the barrier.
wait
Generic dependency wait (e.g. mma.sync result not yet available).
More ILP between dependent instructions; double-buffer the operands.
not_selected
Warp was eligible but scheduler chose another. This is good — means you have issue slack.
Nothing. High values here are a healthy signal.
imc_miss
Constant-memory cache miss.
Move data out of __constant__ or restructure access pattern.
tex_throttle
Texture pipe saturated.
Rarely relevant for GEMM. Indicates over-use of texture loads.
Figure 4.3 — Interactive Mock UI
Nsight Compute Summary view, three kernels compared
Show kernel
Mock-up of the metrics you would see in Nsight Compute for three versions of the GEMM. The shape of the table — SOL ratios, stall reasons, throughput per pipe — is what you should be able to read at a glance. Numbers are illustrative.
4.4The Roofline in Nsight Compute
Same plot as §1.6, now with your real kernel
Recent ncu versions include a built-in roofline plot in the GPU Speed Of Light Roofline Chart section (it is generated whenever the relevant metrics are collected, which they are with --set full and most analysis sets). The plot has the same shape as §1.6: arithmetic intensity on the x axis, GFLOPS on the y axis, the compute roof horizontal, the memory roof diagonal, your kernel as a single dot.
The diagnostic is simple. If the dot is on the diagonal, you are memory-bound. If it is below the horizontal roof on the right, you are compute-bound but not at peak — instruction mix or fragment layout. If it is in free space below both roofs, you are latency-bound — too few outstanding warps. Hopper-era reports also show hierarchical rooflines (DRAM, L2, L1, SMEM) so you can see which memory level you are bounded by.
# If your default set does not include roofline, the explicit metrics are:
ncu --metrics \
sm__sass_thread_inst_executed_op_fadd_pred_on.sum,\
sm__sass_thread_inst_executed_op_fmul_pred_on.sum,\
sm__sass_thread_inst_executed_op_ffma_pred_on.sum,\
dram__bytes.sum.per_second,\
gpc__cycles_elapsed.avg.per_second \
--launch-count 1 \
-o roofline_report ./my_program
4.5Memory Workload Analysis Deep Dive
Diagnosing the memory subsystem in detail
The Memory Workload Analysis page shows traffic at every level: instructions issued, requests sent to each cache, sectors hit and missed, wavefronts on shared memory, and bytes ultimately reaching DRAM.
Reading the request → wavefront → sector cascade
When a warp issues a memory instruction, the L1TEX unit produces requests. Each request is split into sectors (32 bytes each on Ampere) and serviced as wavefronts through the cache. In the ideal case — perfectly coalesced 32-thread reads of contiguous floats — one request becomes one wavefront becomes four 32-byte sectors all in one cache line.
Two ratios reveal trouble:
Sectors / Request > 1: cache lines being only partially used (uncoalesced or strided access). A ratio of 4× means you are doing four trips for the data of one.
Wavefronts / Request > 1 in shared memory: bank conflicts. A 32-way conflict shows up as 32 wavefronts per request. The fix is padding or restructured indexing.
Hit rates by level
L1 Hit Rate. High = your global reads are being served by L1 thanks to spatial locality. Low + uncoalesced sectors = coalescing problem. Low + already coalesced = the working set is bigger than L1.
L2 Hit Rate. The cross-SM cache. High = different blocks are sharing data. Low + large working set = you are saturating DRAM. Low + small working set = you are evicting your own data; try a smaller tile or persistent kernels.
Texture cache hit rate (if you use texture loads or __ldg): same idea, separate unit.
4.6Source-Level Profiling
Per-line PTX and SASS with cycle counts
The Source view in Nsight Compute is the closest thing GPU programming has to perf annotate. With -lineinfo at compile time, every SASS instruction can be traced back to a source line, and counters tell you how many cycles were spent at each line.
The view has three correlated columns — source, PTX, SASS — that scroll in lock-step. Click a source line to highlight the SASS instructions it generated and see their per-instruction execution counts and stall reasons.
Reading SASS
SASS (Streaming Assembler) is the actual machine code for a specific compute capability. Reading it tells you whether the compiler made good decisions. The mnemonics that matter for GEMM:[3]
Mnemonic
What it does
Why you care
FFMA
Float-32 fused multiply-add. The CUDA-core workhorse.
Many FFMAs per LDG = compute-bound work.
HFMA2
Packed half-precision FMA.
Indicates the compiler vectorized your FP16 path.
HMMA
Half-precision MMA — the Tensor-Core instruction at the SASS level.
Appears if and only if your kernel actually uses Tensor Cores. No HMMAs = no tensor-core work.
BMMA / IMMA / QMMA
Bit / integer / FP8 variants of MMA.
For quantized kernels.
LDG
Load from global memory.
Many LDGs per FFMA = memory-bound.
LDS
Load from shared memory.
SMEM throughput cost; look for high LDS counts paired with short_scoreboard stalls.
STG / STS
Store global / shared.
Output traffic. STG outside the inner loop is good; inside is suspect.
BAR
__syncthreads barrier.
Count of BARs tells you how synchronization-heavy the kernel is.
BRA / SSY
Branch / set sync point (for handling divergence).
Many of these in the inner loop = divergent code paths.
The key ratio to internalize: FFMA (or HMMA) count vs LDG count. In a well-tiled GEMM, this ratio should be in the tens or hundreds — many compute instructions per global load. In a naive kernel the ratio is close to 1:1, and you can see it directly in the SASS listing.
# Compile with line correlation
nvcc -O3 -arch=sm_86 -lineinfo -o gemm gemm.cu
# Dump SASS to a file you can read
cuobjdump --dump-sass gemm > gemm.sass
# Or just look at one kernel:
cuobjdump --dump-sass --function gemmTiled gemm
# Or look at the intermediate PTX:
nvcc -O3 -arch=sm_86 -ptx -o gemm.ptx gemm.cu
# In ncu, open the .ncu-rep, navigate to the Source view, and you will
# see per-line counts of: FFMA, LDG/STG, LDS/STS, HMMA, BAR, BRA, ...
The fastest debugging loop
For tight optimization work: write the kernel, run a single-pass profile (ncu --launch-count 1 -o r.ncu-rep ./prog), open in UI, jump to the Source view, find the hot line, ask "is the SASS what I expected?" If yes, look at the warp-state metric for that line. If no, change the C++ to coax the compiler. Repeat.
cuBLAS API logging — what the dispatcher chose
cuBLAS picks an internal kernel based on (M, N, K, dtype, transposition). To see which it picked — sometimes you can learn the right tile size from this — enable cuBLAS API logging via environment variables:
export CUBLAS_LOGINFO_DBG=1
export CUBLAS_LOGDEST_DBG=stdout # or a filename
# Optional, newer versions: verbosity 1..5
export CUBLAS_LOGLEVEL_DBG=5
./my_cublas_program
# stdout will now show the cuBLAS internal kernel name, tile size,
# and dispatch heuristic for every cuBLAS call.
Note: the precise env-var names are CUBLAS_LOGINFO_DBG and CUBLAS_LOGDEST_DBG. Some older blog posts say CUBLASAPI; that is not the actual variable. Use NVIDIA's cuBLAS documentation page on logging as the authoritative reference.[4]
4.7Profiler Theory — Sampling, Replay, and PM Counters
What the numbers in Nsight Compute actually are
Why this section exists. The default Nsight Compute output looks like a stream of dashboard numbers. Each one is the output of a specific measurement strategy with specific costs and biases. The atomic notes below let you read the dashboard with the right amount of skepticism — and choose the right tool (NCU vs Nsight Systems vs nvbprof vs CUPTI) for each question.
[[A4.7.1]]
Sampling vs instrumentation — two ways to measure code
profiling
Sampling profilers interrupt the program at fixed intervals and record the PC. They are cheap (≤ 1% overhead), statistical, and miss anything rarer than the sample interval. Instrumentation profilers insert measurement code at events of interest (entry/exit of every function, every memory access). Exact, but slow — orders of magnitude. Nsight Systems is a sampler; it answers "what is the GPU doing over time?" Nsight Compute is hardware-instrumented via PM counters; it answers "what exactly happened inside one kernel launch?" Use them in that order: Sys to find which kernel matters, Compute to dissect that kernel.
Each SM has a fixed set of Performance Monitoring counters: free-running integers wired to events (cycles where the warp scheduler issued an instruction, sectors hitting L1, etc). There are far more interesting events than counters, so Nsight Compute replays the kernel many times, configuring different counter sets each pass and stitching the results into one report. The kernel-replay strategy explains two NCU quirks: (1) profiling makes a kernel run 20–100× longer wall-clock; (2) the kernel must be deterministic across replays or the report is garbage (set deterministic CUDA random seeds, lock graphics clocks, run on an idle GPU).
FBPA Frame Buffer Partition — the HBM controller. dram__bytes events live here.
MIO Memory I/O scheduler within the SM. Issue stalls show up as MIO throttle metrics.
IDC Indexed Constant cache. Almost always saturated by constant-memory loads; rarely a bottleneck.
Knowing which sub-system a metric belongs to is the difference between "L2 hit rate is 80%" being good or bad. If your kernel's bandwidth bottleneck is at FBPA, an LTS hit rate of 100% would not save you. Read top-down: SM → L1TEX → LTS → FBPA — the answer is at whichever level is closest to saturated.
Warp state taxonomy — selected, eligible, stalled, the three big stall reasons
profiling
Every cycle, the warp scheduler classifies each resident warp into one of three states: selected (this warp issued an instruction), eligible (ready but not picked), stalled (waiting). The stall reasons NCU exposes most usefully:
long_scoreboard Waiting on a global or shared memory load. The single most common stall in a memory-bound kernel.
short_scoreboard Waiting on a math result (e.g., a register-dependent instruction). High share = ILP-bound.
mio_throttle Memory I/O pipeline is backed up. Usually means too many memory ops issued per cycle.
barrier Waiting on __syncthreads. High share = imbalanced work across the block.
not_selected Warp is ready but the scheduler picked someone else. Counterintuitively, some not_selected is good; it means TLP is doing its job.
CUPTI (CUDA Profiling Tools Interface) is the library Nsight is built on. Your code can use it to subscribe to events ("kernel started", "memcpy began"), read counters at runtime, and inject custom metrics. Few application engineers touch CUPTI directly; library authors (PyTorch's profiler, TensorRT's diagnostics) do. NVTX (NVIDIA Tools Extension) is the lighter-weight API: nvtxRangePushA("forward") ... nvtxRangePop() turns your code's logical structure into colored ranges in Nsight Systems' timeline. Always wrap your training/inference loop's logical phases in NVTX ranges; it makes Nsight Systems' output legible.
Modern GPUs change their clock based on temperature, power, and workload. If you benchmark a kernel cold, then again warm, the second run will sit at a higher boost clock and look faster — even if your "optimization" is just running it twice. nvidia-smi -lgc <min,max> locks the graphics clock; nvidia-smi -lmc locks the memory clock. For consumer cards, the application clocks may be capped by power limits — check nvidia-smi -q -d CLOCK after locking to verify what you actually got. Without clock locking your before/after numbers are not comparable.
Learning goal. Understand exactly why cuBLAS does not win every shape, identify a shape where a custom kernel can beat it, execute the full optimization stack, and validate the result with a benchmark protocol a stranger could reproduce.
5.1How cuBLAS Actually Works
A library of pre-compiled kernels and a dispatch heuristic
cuBLAS is a closed-source CUDA library that ships pre-compiled GEMM kernels for many common shapes, dtypes, and transposition modes. When you call cublasGemmEx for a specific configuration, an internal heuristic picks a kernel from the library based on (M, N, K, dtype, transpose flags, alpha/beta, hardware). The picked kernel is then launched.
Three properties of this design matter for your strategy:
cuBLAS kernels are extraordinarily good for "large square" shapes in common dtypes (FP32, TF32, FP16) — they routinely hit 90–95% of the corresponding Tensor-Core peak. Beating them on these shapes is hard.
The dispatch heuristic is fallible. For atypical (M, N, K) — small batch sizes, non-power-of-two dims, very tall/skinny matrices — the heuristic sometimes picks a tiled kernel whose tile shape mismatches your problem and leaves a lot on the table.
cuBLAS only does GEMM. It does not fuse subsequent elementwise operations (bias add, activation, scaling). For any kernel that follows GEMM with arithmetic, a fused custom kernel saves one full pass over the output matrix in global memory.
You can see which internal kernel cuBLAS picked by enabling its logging (see §4.6). The kernel name encodes its tile shape and architecture. Knowing this is genuinely useful: if cuBLAS picked a 128×128 tile for a problem where 64×256 would obviously fit better, you have your opening.
5.2Where cuBLAS Is Vulnerable
The four families of shapes that admit a custom win
1. Small batch / decode shapes (M = 1, GEMV-like)
During LLM inference's decode phase, you compute one token at a time. The GEMM degenerates to a vector-matrix product with M = 1 and N, K in the thousands. The arithmetic intensity is near 1 FLOP/byte — fundamentally memory-bound. cuBLAS exposes cublasGemv for this shape but the wrapper has fixed overheads, and the dispatched kernel is not specialized to your specific N/K. A custom kernel that hand-tunes the load pattern (vectorized 128-bit reads of B, K-direction reduction in registers) can outpace it by 10–30%, especially for batch=1 inference.
2. Non-power-of-two shapes
cuBLAS tiles are typically 64, 128, or 256 elements wide. For M = N = K = 3072 (= 1024×3, not a power of two), the dispatcher may pick a 128-tile kernel and pay the cost of partial last-tile padding on three sides. A custom kernel tiled at, say, 96×96 — divides evenly — avoids the padding entirely and can win by a few percent.
3. Fused operations
Almost every neural-network linear layer is followed by add-bias-and-activate. cuBLAS computes C = α·A·B + β·C; it does not apply ReLU or GELU. The follow-on elementwise pass reads C from DRAM and writes it back — at 4096² FP16, ~33 MB in and out, costing roughly 0.07 ms at 936 GB/s. A fused kernel does the activation while C is still in registers and saves the entire DRAM round-trip. This is the single most consistent way to beat cuBLAS in real ML workloads.
4. Newer / less-common precisions
INT8 and FP8 cuBLAS paths are newer and less comprehensively tuned across shapes than the FP16 path. INT8 INT4 quantization for inference is a particularly active area where custom kernels routinely beat cuBLAS — see e.g. the techniques used by tinygrad, llama.cpp's CUDA backend, and various INT4 inference papers.
Recommended target for this project
A concrete, defensible target
Shape: M = N = K = 4096, FP16 inputs with FP32 accumulate. Hardware: RTX 3090 (sm_86), GPU clocks locked. Baseline: cuBLAS via cublasGemmEx. Win condition: > 100% of cuBLAS, sustained across >500 iterations, verified by Nsight Compute and bit-identical (within fp16 tolerance) output.
This shape is large enough that the workload is firmly compute-bound (intensity ~1365 vs ridge ~152, see §1.6), small enough to fit in 24 GB, exactly square so cuBLAS picks a well-tuned kernel — and yet community results have repeatedly shown that hand-tuned mma.sync + cp.async kernels can edge past it by a few percent on Ampere consumer parts. A defensible, reproducible, satisfying target.
5.3The Full Optimization Stack (Applied)
Each kernel, what it adds, what it buys
The table below walks every kernel from naive to peak. Numbers are plausible community-class results for the target shape (M = N = K = 4096, FP16 → FP32, RTX 3090). They are not from a single source; they are the kind of progression you should expect to see in your own measurements. The cuBLAS baseline is ~125 TFLOPS (≈ 88% of the 142 TFLOPS FP16-TC peak); the "% cuBLAS" column is the kernel's measured TFLOPS divided by that baseline.
Version
Key technique
TFLOPS
% peak (142)
% cuBLAS
K1 Naive
One thread / output, global loads in inner loop
~0.5
0.4%
0.4%
K2 Coalesced
Index swap so thread.x → fast memory axis
~3
2.1%
2.4%
K3 SMEM tile 32×32
Shared-memory tiling, double __syncthreads
~15
10.6%
12%
K4 Reg tile 128×128, TM=TN=8
Each thread owns 8×8 accumulator tile
~45
31.7%
36%
K5 Vector loads (float4)
128-bit global & SMEM loads
~65
45.8%
52%
K6 WMMA Tensor Cores
16×16×16 fragment GEMM
~100
70.4%
80%
K7 mma.sync + ldmatrix
Raw PTX, controlled fragment layout
~118
83.1%
94%
K8 + cp.async pipelined (2-stage)
Overlap next load with current mma
~130
91.5%
104%
Two columns appear because they answer different questions. % of peak tells you how close you are to the hardware ceiling — the absolute scoreboard. % of cuBLAS tells you whether you have crossed the line you set out to cross — the win condition. cuBLAS itself sits at 88% of peak in this estimate, so passing 88% of peak is roughly the threshold for beating cuBLAS.
Figure 5.3 — Chart
Optimization progression vs cuBLAS
Archived example: K8 is 104% of the stated cuBLAS referenceValues retained from the textbook; not re-run for this reading edition. RTX 3090 · M=N=K=4096 · FP16 with FP32 accumulation. The stated cuBLAS reference is 125 TFLOPS.
Kernel
TFLOPS
Reference
K1 Naive
0.5
0.4%
K2 Coalesced
3
2.4%
K3 SMEM tile 32×32
15
12.0%
K4 2D register tile
45
36.0%
K5 float4 vectorized
65
52.0%
K6 WMMA Tensor Core
100
80.0%
K7 mma.sync + ldmatrix
118
94.4%
K8 + cp.async pipeline
130
104.0%
The vertical dashed line is the cuBLAS baseline (~125 TFLOPS). Bars to the left are orange (not yet winning); the bar crossing it is green. The shape of the curve is typical: long ramp through algorithmic optimizations (K1→K5), big jump on first Tensor-Core use (K6), final 10–20% from PTX-level loading and pipelining (K7→K8).
What each step actually changed in Nsight Compute
K1 → K2 (Coalescing).Sectors / Request drops from ~16 to 1. DRAM bandwidth utilization roughly doubles.
K2 → K3 (SMEM tiling). DRAM bytes per kernel drop by ~32×; L1 hit rate skyrockets; SM throughput begins to be a meaningful share of time.
K4 → K5 (Vectorization). Total instructions issued drops by ~3×. The "Issue Active" SOL metric goes up.
K5 → K6 (Tensor Cores).HMMA SASS instructions appear; the TENSOR pipe shows up in Compute Workload Analysis at 30–50%. The FFMA / HFMA2 pipes go quiet.
K6 → K7 (mma.sync). The mix of LDS / HMMA shifts: LDS becomes LDSM (ldmatrix); the lanes-per-MMA arithmetic is now optimal.
K7 → K8 (cp.async). The barrier (BAR) count per inner loop drops; long_scoreboard stalls fall; "Issue Active" climbs into the high 80s.
For a complete walkthrough of an FP32 SGEMM optimization path on the same architecture (RTX A6000, the workstation sibling of the 3090), Simon Boehm's worklog is the closest public companion and walks through analogous percentage gains kernel-by-kernel.[1] Maharshi Pandya's "Outperforming cuBLAS on H100" worklog covers the same arc on Hopper with wgmma.[2]
5.4Proving the Win: The Benchmark Protocol
If a stranger cannot reproduce your number, it does not exist
The credibility of a "I beat cuBLAS" claim is determined entirely by the protocol you used to measure it. The following is the minimum bar for a reproducible result.
1. Lock the GPU clocks
Without locking, the boost clock varies with temperature and silicon lottery. Two runs five minutes apart can differ by 8%. Lock to a stable value:
# Need: sudo, NVIDIA driver with persistence mode on.
sudo nvidia-smi -pm 1 # persistence mode
# Query clock ranges:
nvidia-smi -q -d SUPPORTED_CLOCKS | head -40
# Lock SM clock to a value within the supported range.
# 1695 MHz is the RTX 3090 boost-clock spec; 1395 MHz is base.
# Pick a value the silicon can hold under sustained load.
sudo nvidia-smi -lgc 1695 # lock graphics (SM) clock
# Optional: lock memory clock.
sudo nvidia-smi -lmc 9501 # GDDR6X mem clock
# After benchmarking, reset:
sudo nvidia-smi -rgc # reset graphics clock
sudo nvidia-smi -rmc # reset memory clock
State the locked clock in your published report. "RTX 3090, SM clock locked to 1695 MHz, memory clock locked to 9501 MHz" is the level of precision required.
2. Warm up and timing protocol
10 warmup iterations, results discarded.
500 timed iterations, report mean and stddev in milliseconds.
Variance < 1% of the mean. If not, raise iteration count or fix a clock instability.
Each iteration must be independent: the same input, the same output buffer, no result carried between iterations.
3. FLOP counting
Use the standard convention: a GEMM of (M, N, K) does 2·M·N·K FLOPs — one multiply and one add per inner-loop iteration. Do not count fused biases or activations in the headline FLOP number unless you are honest about it.
TFLOPS= 2 · M · N · K / (mean_ms · 10⁹)
4. Correctness
Compare the kernel's output against a trusted reference (cuBLAS or a CPU implementation) within a precision-appropriate tolerance. FP16 GEMM accumulating to FP32 typically agrees to ~1e-3 relative error on most elements; outliers up to ~1e-2 on long reductions are normal. Use the verify() helper from §2.7. If correctness fails, the benchmark is meaningless.
5. cuBLAS baseline — the apples-to-apples call
#include <cublas_v2.h>
cublasHandle_t handle;
cublasCreate(&handle);
// IMPORTANT: cuBLAS treats matrices as COLUMN-MAJOR. To compute the
// row-major product C = A * B, call as gemm(B^T, A^T) -> C^T,
// or pass transA = T and transB = T appropriately. The shape M,N,K
// stays the same; the leading dims differ.
// IMPORTANT: cublasGemmEx with CUBLAS_COMPUTE_32F expects the alpha/beta
// scalars to be in the COMPUTE precision (FP32), not the input precision.
const float alpha = 1.0f;
const float beta = 0.0f;
cublasGemmEx(
handle,
CUBLAS_OP_N, CUBLAS_OP_N, // no transpose
N, M, K, // shapes (note swap for row-major view)
&alpha,
d_B, CUDA_R_16F, N, // B and its leading dim
d_A, CUDA_R_16F, K, // A and its leading dim
&beta,
d_C, CUDA_R_16F, N, // C and its leading dim
CUBLAS_COMPUTE_32F, // FP32 accumulate
CUBLAS_GEMM_DEFAULT_TENSOR_OP); // tensor cores allowed
// Time the same way as your custom kernel (Listing 2.7-A).
6. Report format
The published table should look like this — and nothing else, because anything more invites cherry-picking:
// Pseudocode shape — wire to your existing kernels.
struct KernelEntry {
const char* name;
std::function<void(half* dA, half* dB, half* dC, int, int, int)> launch;
};
void run_suite(int M, int N, int K) {
// Allocate device buffers, fill with random data, allocate result.
// Allocate a reference buffer and compute cuBLAS once for verification.
std::vector<KernelEntry> kernels = {
{"cuBLAS", [&](auto a, auto b, auto c, int m, int n, int k){ cublasLaunch(a, b, c, m, n, k); }},
{"gemmNaive", [&](auto a, auto b, auto c, int m, int n, int k){ gemmNaive<<<...>>>(...); }},
{"gemmCoalesced", ... },
{"gemmTiled", ... },
{"gemmReg", ... },
{"gemmVec", ... },
{"gemmWmma", ... },
{"gemmMma", ... },
{"gemmMmaCpAsync", ... },
};
long long flops = 2LL * M * N * K;
printf("Shape: M=%d N=%d K=%d FP16->FP32\n", M, N, K);
printf("%-22s | %-16s | %8s | %9s\n", "Kernel", "Time (ms)", "TFLOPS", "% cuBLAS");
printf("---------------------- | ---------------- | -------- | ---------\n");
double cublas_tflops = 0.0;
for (auto& k : kernels) {
// Verify correctness ONCE (skip naive if you're impatient — it's slow).
k.launch(d_A, d_B, d_C, M, N, K);
cudaDeviceSynchronize();
bool ok = verifyAgainst(d_C, d_ref, M*N, /*rtol=*/1e-2f);
if (!ok) { printf("%-22s | INCORRECT — skipping\n", k.name); continue; }
auto r = benchmarkKernel([&]() {
k.launch(d_A, d_B, d_C, M, N, K);
}, flops);
if (strcmp(k.name, "cuBLAS") == 0) cublas_tflops = r.gflops / 1000.0;
double pct = (r.gflops / 1000.0) / cublas_tflops * 100.0;
printf("%-22s | %7.3f ± %5.3f | %8.1f | %8.1f %%\n",
k.name, r.mean_ms, r.stddev_ms, r.gflops / 1000.0, pct);
}
}
The roofline plot with all 8 kernels positioned (export from your profiler or generate from the CSV).
Hardware: model, driver, CUDA toolkit, locked clocks.
Reproduction: git clone → make → ./bench in three lines.
The headline Nsight Compute screenshots showing SOL throughput > cuBLAS.
A one-paragraph "why this works" — the key insight that let your kernel win.
The technical writeup
Format: a single blog post or Twitter thread. Lead with the roofline plot — that picture tells the entire story in one frame. Follow with the table. Then 4–6 paragraphs walking through the kernel-by-kernel optimizations, focusing on the bottleneck each one solved (Nsight Compute metric → code change → measured delta). Close with a falsifiable claim, e.g. "On RTX 3090 with locked clocks, M = N = K = 4096 FP16 GEMM, my kernel sustains 130 TFLOPS vs 125 TFLOPS for cuBLAS 12.2, verified across 500 iterations."
What "reproducible" actually means
A stranger should be able to clone your repo, run one script, and within ten minutes have a table on their console that they can compare against yours. If they can't — if there are manual steps, magic environment variables, or missing baseline runs — the result is unverifiable and will be discounted, regardless of how good your kernel is.
◆ Chapter 5 Checkpoint
Click each item to mark complete.
Name three families of shapes or configurations where cuBLAS is most beatable, and explain why each is vulnerable.
Why must you lock GPU clocks before benchmarking? What command does it on Linux?
A colleague says their kernel is "5% faster." List the eight protocol questions you ask before accepting the claim.
What is cuBLAS logging? What environment variables enable it, and what does it tell you that no other tool can?
Sketch a repo layout that lets a stranger reproduce your benchmark in under ten minutes.
References — Chapter 5
Boehm, S. How to Optimize a CUDA Matmul Kernel for cuBLAS-like Performance. 2022. siboehm.com/articles/22/CUDA-MMM — the canonical FP32 SGEMM-to-cuBLAS walkthrough on Ampere.
Pandya, M. Outperforming cuBLAS on H100: A Worklog.cudaforfun.substack.com — Hopper-era analogue covering wgmma.
NVIDIA. CUTLASS — open-source reference implementations that match or exceed cuBLAS on selected shapes. github.com/NVIDIA/cutlass
He, H. Making Deep Learning Go Brrrr From First Principles.horace.io/brrr_intro.html — the compute-vs-memory framing this entire book inherits from.
Dao, T. et al. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. NeurIPS 2022. arxiv.org/abs/2205.14135 — the textbook example of fused-kernel wins over a vendor-library baseline (cuBLAS + softmax).
Learning goal. A working reference set you can return to, plus a clear map of which projects to pick up next once your "beat-cuBLAS" repo is live.
6.1Hardware Reference Table
The numbers you will need in every back-of-envelope calculation
Spec
RTX 3090
A100 80GB
H100 SXM
RTX 4090
Architecture
Ampere (GA102)
Ampere (GA100)
Hopper (GH100)
Ada Lovelace (AD102)
Compute capability
sm_86
sm_80
sm_90
sm_89
SM count
82
108
132
128
FP32 CUDA cores
10,496
6,912
16,896
16,384
FP32 TFLOPS (peak)
~35.6
~19.5
~67
~82.6
FP16 TC TFLOPS (dense)
142
312
989
330
BF16 TC TFLOPS (dense)
142
312
989
330
TF32 TC TFLOPS (dense)
~71
156
495
~165
FP8 TC TFLOPS (dense)
n/a
n/a
1979
660
INT8 TC TOPS (dense)
284
624
1979
660
Memory technology
GDDR6X
HBM2e
HBM3
GDDR6X
Memory capacity
24 GB
80 GB
80 GB
24 GB
Memory bandwidth
936 GB/s
~2,039 GB/s
~3,350 GB/s
~1,008 GB/s
L2 cache
6 MB
40 MB
50 MB
72 MB
Shared mem / SM (max)
128 KB
192 KB
228 KB
128 KB
Shared mem / block (max)
99 KB
163 KB
228 KB
99 KB
Registers / SM (32-bit)
65,536
65,536
65,536
65,536
Max threads / block
1024
1024
1024
1024
Max warps / SM
48
64
64
48
Max blocks / SM
16
32
32
24
Tensor Cores / SM
4 (3rd gen)
4 (3rd gen)
4 (4th gen)
4 (4th gen)
Native mma.sync shape (FP16→FP32)
m16n8k16
m16n8k16
m64nKk16 via wgmma
m16n8k16
Numbers are NVIDIA-published peaks. Always reconfirm against the product page and architecture whitepaper for your specific SKU — variants of the same architecture (e.g. A100 40GB vs 80GB, H100 SXM vs PCIe, RTX 3090 vs 3090 Ti) differ on bandwidth, clock, and sometimes core counts. Hopper Tensor-Core throughput numbers depend on sparsity assumptions — the dense numbers are listed here.
Load 4× 8×8 FP16 matrices from SMEM into mma.sync register layout.
Partner instruction to mma.sync.
cp.async.ca.shared.global [smem], [global], 16;
Async 16-byte global → shared copy (Ampere+).
Pipeline next tile while computing current.
cp.async.commit_group;
Close out the current group of cp.async ops.
Boundary between pipeline stages.
cp.async.wait_group N;
Wait until ≤ N groups remain in flight.
Sync before consuming a buffer.
cvt.rn.f16.f32 %h, %f;
Convert FP32 to FP16, round-to-nearest-even.
Mixed-precision storage.
setp.lt.s32 %p, %r, %r2;
Predicate set: p = r < r2.
Bounds checks.
@%p bra TARGET;
Conditional branch on predicate.
If/else compilation.
fma.rn.f32 %f, %fa, %fb, %fc;
Fused FP32 multiply-add, round-to-nearest.
Inner-loop FMA (CUDA-core path).
add.f32 %f, %fa, %fb;
Add (no fused multiply).
Rarely emitted; compiler prefers FMA.
For the complete instruction set, see NVIDIA's PTX ISA document, which is updated with every CUDA toolkit release.[1] The relevant sections for this project are Data Movement and Conversion Instructions (load/store, cp.async) and Warp Level Matrix Multiply-Accumulate Instructions (mma.sync, ldmatrix, wgmma).
If you intended TC and see this high, your kernel fell back to FFMA.
L1/TEX Hit Rate
Fraction of global loads served by L1.
Reuse working.
Coalescing or sizing problem.
Coalesce; reorder loads; smaller working set.
L2 Hit Rate
Fraction of L1-misses served by L2.
Cross-SM reuse.
DRAM-bound or evicting own data.
Tile; persistent kernel; reorder block schedule.
Metric names follow NVIDIA's PerfWorks naming convention. The exact suffix (.pct vs .ratio) and prefix (dram__ vs gpu__dram_) drift between Nsight Compute versions; consult ncu --query-metrics on your installed version to get the authoritative list.[2]
6.4The CUTLASS Connection
The library that does what you just did, in templates
Every pattern in this textbook — tiled blocking, register accumulators, vectorized loads, mma.sync, ldmatrix, cp.async pipelining — is implemented in NVIDIA's open-source CUTLASS library. CUTLASS is an aggressively templated C++ header collection that lets you compose GEMMs and convolutions out of reusable tile- and warp-level pieces.
If your goal is shipping a fast GEMM in production rather than learning, CUTLASS is your starting point. If your goal is learning, you have done the hard part already, and reading CUTLASS source becomes legible — every WarpMma, ThreadblockMma, and PipelinedMma template you encounter is a name for a pattern this book just walked you through.
What to look at first
cutlass/include/cutlass/gemm/device/gemm.h — the high-level entry point, parametrized by tile shapes, dtypes, and pipeline stages. Reading the template parameters is half the education.
cutlass/include/cutlass/gemm/warp/mma_tensor_op.h — the warp-level mma.sync wrapper. Compare against your Listing 3.4-B.
cutlass/include/cutlass/arch/mma_sm80.h — per-architecture mma.sync intrinsics. Read this and the matching PTX side-by-side.
The cute sub-library (CUTLASS 3.x). A layout algebra that lets you describe register/SMEM/global mappings as composable tensors. The mental model is more powerful than anything in CUTLASS 2.x and is the right next investment if you intend to write production kernels.
The CUTLASS profiler — runs every internal kernel against your shape and reports TFLOPS, giving you instant comparable numbers across hundreds of tile configurations.
Repository: github.com/NVIDIA/cutlass. The accompanying NVIDIA Developer Blog posts give a guided tour.[3]
6.5What Comes Next
Five projects, each one a credible follow-up
Project
Why it's a good next step
Key references
Flash Attention
Apply the same IO-aware tiling philosophy to attention. The S = Q·KT matrix is never materialized; softmax, masking, and Q·K → P·V fuse into a single kernel. The result was a ~3× wall-clock speedup over PyTorch attention and is now standard in every modern transformer stack.
Dao et al., FlashAttention (NeurIPS 2022); FlashAttention-2 (2023); FlashAttention-3 (2024).
Quantized GEMM (INT8, FP8, INT4)
Modern LLM inference runs in INT4/INT8; the cuBLAS/cuDNN paths are less mature than FP16. Plenty of room to win, and the techniques (per-channel scaling, group quantization, lookup-table mul) generalize.
SmoothQuant, GPTQ, AWQ papers; llama.cpp CUDA backend; bitsandbytes.
Stream-K GEMM
An alternative work decomposition: tile along K instead of M/N, so all SMs share the K-reduction and stay busy on awkward shapes where M/N tiling leaves SMs idle. CUTLASS implements it. Worth reading and reimplementing.
Osama et al., "Stream-K" (PPoPP 2023); CUTLASS Stream-K examples.
Persistent kernels
Instead of launching a fresh kernel per work item, launch one kernel that loops over work items pulled from a queue. Amortizes launch cost; enables cross-kernel state in registers/SMEM.
Triton and CUTLASS persistent-kernel docs.
Multi-GPU GEMM (NCCL, NVLink)
Sharding a GEMM across 8 GPUs requires reasoning about communication overlap, ring/all-reduce primitives, and NVLink bandwidth. The tile-level mental model from this book transfers; the systems-level concerns are new.
OpenAI Triton lets you write GPU kernels in a Python DSL that compiles to PTX. The performance ceiling is close to hand-written CUTLASS for many shapes. Once you know what good PTX looks like, reading Triton-generated code becomes diagnostic rather than mysterious.
Triton tutorials at triton-lang.org; the flash-attn Triton reference.
None of these are a step backward in difficulty from the cuBLAS project. Pick the one whose application area you care about (attention if you care about LLMs, quantized GEMM if you care about inference deployment, multi-GPU if you care about training infrastructure) and execute it with the same protocol discipline as chapter 5. The point of this textbook is not just to ship one fast kernel — it is to give you the toolset to ship the next ten.
A useful career-shaped observation
The community of people who can write production GPU kernels is small enough that one credible, reproducible, well-documented kernel project changes how interviewers, collaborators, and senior engineers treat you. The leverage is real. Ship the repo.
NVIDIA. CUTLASS.github.com/NVIDIA/cutlass — code, docs, profiler. The accompanying NVIDIA Developer Blog series ("CUTLASS 2.x", "CUTLASS 3.x and CuTe") is the best guided tour.
NVIDIA. CUDA C++ Programming Guide.docs.nvidia.com/cuda/cuda-c-programming-guide/ — the reference doc; the architecture-capability appendices are gold for register/SMEM/warp limits per sm_*.
Osama, M. et al. Stream-K: Work-centric Parallel Decomposition for Dense Matrix-Matrix Multiplication on the GPU. PPoPP 2023.
Williams, S., Waterman, A., Patterson, D. Roofline. CACM 2009 — the model used throughout chapters 1, 4, and 5.
Jia, Z. et al. Dissecting the NVIDIA Ampere GPU Architecture through Microbenchmarking. arXiv:2106.10499 — hard numbers for SM, cache, and Tensor-Core throughput.
He, H. Making Deep Learning Go Brrrr From First Principles.horace.io/brrr_intro.html — best one-essay summary of the compute-vs-memory perspective.
07
Chapter 07
Reductions, Scans, and Building-Block Kernels
Learning goal. GEMM is the headline event, but the supporting cast — reductions, scans, transposes, histograms, sorts, and split-K dispatchers — is what makes a real kernel library. This chapter atomically breaks down each pattern: warp reduction, block reduction, grid reduction, Hillis-Steele scan, Blelloch scan, decoupled-lookback, privatized histograms, radix sort, and the persistent-kernel idiom. Every pattern is one node in the dependency graph and is used by a real production kernel.
Reduce 32 values held in lane registers to a single scalar in 5 steps with the XOR-butterfly pattern: each step swaps with the lane k bits away and accumulates. No shared memory, no barriers, ~5 cycles per step. The idiom every CUDA programmer must memorize:
for (int offset = 16; offset > 0; offset /= 2)
val += __shfl_xor_sync(0xFFFFFFFF, val, offset);
After the loop, every lane in the warp holds the same total. To turn a warp-reduce into a warp-broadcast, the answer is already broadcast. To get only one lane to write it out, gate with if (laneIdx() == 0).
7.2Block Reduce — Compose Warp Reduces with Shared Memory
[[A7.2.1]]
Two-stage block reduction
reduction
Stage 1: every warp reduces its 32 lanes to one value via [[A7.1.1]]. Stage 2: lane 0 of each warp writes its result to __shared__ float warp_sums[32]; one __syncthreads; then warp 0 reads the 32 partial sums (one per warp), does another warp reduction, and lane 0 of warp 0 owns the block total. Total cost: 2 warp reductions plus one barrier. For a 1024-thread block that is ~10 cycles of math plus the barrier latency — orders of magnitude faster than a shared-memory tree.
Trap
If your block has fewer than 32 warps (block size < 1024), the warp-0 reduction at stage 2 must guard inactive lanes — they hold garbage, not zero. Either zero-initialize warp_sums, or pass an identity value, or gate the second reduce by laneIdx() < numWarps.
Atomic add Each block does its own reduction, then lane 0 calls atomicAdd to a single device-side accumulator. Simple, fast for ≤ a few hundred blocks; serializes for thousands.
Two-pass Kernel 1: each block writes its reduction to out[blockIdx.x]. Kernel 2: a small launch reduces the partial results. Standard portable pattern; one extra launch.
Cooperative gridcg::this_grid().sync() after stage 1, then stage 2 inside the same kernel. Eliminates the second launch but requires a cooperative launch and bounds your grid to "fits on the device."
For a 4 GB tensor on an A100, all three reach > 90% of peak bandwidth. Pick atomic for small grids, two-pass for portability, cooperative for tight per-step kernels (e.g., per-iteration norm-of-residual in a numerical solver).
At step k, every thread reads the value at offset 2k behind it and accumulates. After log₂ n steps, every position holds the prefix sum. Work is n log n — suboptimal — but span is log n and the implementation is one warp-shuffle per step. Right answer for small problems (a single block) where the constant matters more than the asymptotic work.
Phase 1 (up-sweep): build a binary tree of partial sums in place, like a heap. Phase 2 (down-sweep): propagate prefixes back down. Total work is exactly 2n − 2 — work-optimal — and the span is still O(log n). Standard library scans (CUB BlockScan, Thrust inclusive_scan) use Blelloch variants for the within-block stage.
A textbook grid-wide scan needs two passes: compute block partials, then offset each block by the prefix of its partials. Decoupled lookback (Merrill & Garland, 2016) fuses both into one pass. Each block, after its local scan, publishes a status flag and waits for the previous block's flag, then aggregates the previous block's prefix. With careful memory-fencing this runs at near-peak HBM bandwidth in a single kernel. CUB's DeviceScan uses it; it is the production-grade primitive.
Privatized histogram — per-block bins in shared memory
building-block
Naive histogram: every thread does atomicAdd(&hist[bin], 1) in global memory. For a highly skewed distribution every thread targets the same bin → 32-way serialization → 100×-slow kernel. Privatized fix: each block keeps its own histogram in shared memory (atomicAdd on shared is ~10× faster), then once at the end the block reduces its private histogram into the global histogram with one atomic per bin. Memory traffic equals the input size and a small constant. This is the canonical "atomics ≠ slow, atomics on global ≠ atomics on shared" lesson.
Naive transpose has half-coalesced loads or half-coalesced stores — whichever dimension you stride. The standard fix: load a 32×32 tile into shared memory with row-major coalescing, __syncthreads, then store it out column-major. Without padding the store is a 32-way bank conflict; pad to [32][33] (see [[A1.4.1]]) and the conflict disappears. This is the canonical bank-conflict teaching example.
Comparison sorts have a hard n log n lower bound; radix sort doesn't, because it pre-commits to a fixed bit-width. Per pass: count keys by their k-bit digit (histogram), compute the per-digit offsets (scan), scatter keys into their new positions (memcpy by index). Each pass is two memory-bound kernels; for 32-bit keys, 4 passes of 8-bit radix = 8 kernels total. CUB DeviceRadixSort is the reference implementation; for a 1 G-element array it hits ~80% of HBM bandwidth on an A100.
A persistent kernel launches enough blocks to fill the GPU exactly (numSMs × max blocks/SM) and each block loops over work items pulled from a work queue. The pattern eliminates per-iteration launch overhead and lets blocks dynamically rebalance load. The cost: you give up the GPU's scheduler — you have to write your own work-stealing loop and worry about fairness. Use for: latency-critical inference, fine-grained per-iteration solvers, anywhere the launch overhead is a measurable fraction of runtime.
Standard GEMM parallelism is over the (M, N) output tile grid. When M and N are small but K is huge (the canonical "wide GEMM" of a fully-connected layer's tall input), few output tiles exist and the GPU sits idle. Split-K cuts the K dimension into s chunks, launches s times more blocks, and reduces the partial outputs into the final tile via either a second-kernel reduction or atomic accumulation. The work doubles slightly (the reduction); occupancy quadruples. cuBLAS picks split-K automatically when the shape calls for it; in custom kernels you have to plan for it.
Stream-K (Osama et al., 2023; landed in CUTLASS 2.10) merges split-K and persistent: each SM processes a continuous range of the K dimension across multiple output tiles, dynamically picking up the next chunk. The scheduler avoids the "last wave" inefficiency where a few stragglers finish long after the rest of the GPU is idle. On highly variable-shape workloads it can be 1.5–2× faster than the best static split-K. The implementation is non-trivial; for a portfolio GEMM kernel, CUTLASS's stream-K is the reference to study.
Write a warp-reduce in 4 lines that does not use shared memory.
Explain why two-pass grid reduce is safer than atomic grid reduce on huge arrays.
State the work and span of Hillis-Steele vs Blelloch scans.
Diagnose: a histogram kernel is 100× slower than a copy of the same data — what is the first thing you check?
Explain when split-K helps and the price you pay for it.
08
Chapter 08
Multi-GPU and Distributed CUDA
Learning goal. Understand the physical topology that connects two or more GPUs, what NCCL actually does behind one ncclAllReduce call, and how training-scale parallelism (data, tensor, pipeline, sequence) maps to those wires. The atomic notes below give you the vocabulary and the trade-offs without committing to one framework.
8.1Physical Topology — PCIe, NVLink, NVSwitch
[[A8.1.1]]
Bandwidth tiers — PCIe Gen4 vs NVLink vs NVSwitch
interconnect
PCIe Gen4 x16 ≈ 32 GB/s per direction. The fallback path between any GPU and the CPU.
PCIe Gen5 x16 ≈ 64 GB/s per direction (H100 and later).
NVLink 3.0 12 lanes per A100 → 600 GB/s aggregated per GPU.
NVLink 4.0 18 lanes per H100 → 900 GB/s aggregated.
NVSwitch An on-PCB switch that lets every GPU talk to every other at full NVLink rate. The difference between "DGX" (NVSwitched) and "HGX" (point-to-point) topologies.
One sentence to remember: NVLink is ~20× faster than PCIe. The first sanity check when scaling across GPUs is which path your transfers actually take — nvidia-smi topo -m prints the topology matrix.
Peer-to-peer (P2P) — letting one GPU read another's HBM directly
interconnect
With cudaDeviceEnablePeerAccess, GPU A can issue load/store instructions to addresses mapped to GPU B's memory. The traffic goes over NVLink if available, PCIe otherwise. P2P is the foundation under NCCL: it lets a single GPU's kernel pull data straight from a neighbor without bouncing through host memory. NVSwitch makes P2P uniform; on multi-socket PCIe-only systems some P2P paths cross NUMA nodes and are slower.
All-reduce — the operation that consumes most distributed-training time
collective
All-reduce takes one tensor per GPU and combines them with a reduction op (typically sum), leaving every GPU with the same result. Three classical algorithms in NCCL:
Ring Each of N GPUs holds 1/N of the tensor; N−1 reduce-scatter steps, then N−1 all-gather steps. Bandwidth-optimal: every GPU sends and receives at full link rate.
Tree A binary tree of reductions on the way up, then a broadcast on the way down. Lower latency (log N steps) but uses bandwidth less efficiently than ring.
2D / 3D rings On NVSwitched systems, NCCL builds rings along multiple dimensions to exploit the fully-connected topology.
NCCL chooses between them automatically based on message size and topology. The relevant performance number is busBw, NCCL's effective per-GPU bandwidth across the collective; for an all-reduce, busBw ≈ algoBw × (N−1)/N.
NCCL ships these and more. All-gather concatenates one shard per GPU into a full copy on every GPU. Reduce-scatter reduces along GPUs and leaves each with a shard. (All-reduce = reduce-scatter then all-gather.) Broadcast copies from one GPU to all. All-to-all sends a different shard from every GPU to every other; the workhorse of expert-parallel MoE. The collective you reach for tells you the parallelism strategy you implicitly chose.
Data parallelism — replicate the model, split the batch
parallelism
Every GPU holds the full model, processes its own micro-batch, and after backward they all-reduce gradients. Simple, scales to "the model fits on one GPU." Overhead = one all-reduce per step. With ZeRO sharding, the model state itself is partitioned and an all-gather is inserted before each forward pass — trades extra communication for memory savings.
Tensor parallelism — split a matrix multiply across GPUs
parallelism
A linear layer Y = X·W can be split by column: each GPU holds W's slice and computes its slice of Y; an all-gather assembles the full Y. Or by row: each GPU holds the right W slice and computes a partial product; an all-reduce finishes it. Megatron's transformer layout uses column-then-row to merge two communications into one all-reduce per attention block and one per MLP. The collective cost is per layer; communication therefore scales with depth.
Stage 1 of the model lives on GPU 0, stage 2 on GPU 1, etc. Micro-batches stream through. Communication is point-to-point (only adjacent stages talk), bandwidth-light, latency-sensitive. The pipeline has a bubble: at the start and end of each batch the GPUs at the far ends idle. GPipe, 1F1B, and interleaved 1F1B (Megatron) are schedules that shrink the bubble. The right size of pipeline parallelism is "as many stages as you need to fit one micro-batch in GPU memory, no more."
For very long contexts, the activation tensors get too big for one GPU's HBM even at modest batch sizes. Sequence parallelism splits the sequence dimension across GPUs and synchronizes only at operations that mix tokens (attention's softmax row). Ring-attention is the formulation that does this with overlapping communication. Used in 100K-token+ training of modern LLMs.
Quote the bandwidth ratio between PCIe Gen4 and NVLink 3.0.
Sketch the ring all-reduce on 4 GPUs and explain why it is bandwidth-optimal.
Pick a parallelism strategy for a 70 B-parameter model on 8 H100s and justify the choice.
Diagnose: training throughput dropped 3× when you scaled from 1 to 2 GPUs — what is your first hypothesis?
09
Chapter 09
The Knowledge Graph and Atomic-Notes Index
Learning goal. Visualize the conceptual structure of the entire book. The diagram below is the rendered dependency graph between the atomic notes you read; the alphabetical index that follows lets you jump to any one directly. Use this chapter as a long-term reference — bookmark it.
Learning goal. Stop treating nvcc as a black box. By the end of this chapter you can name every binary on the compilation path, read PTX and SASS side-by-side with the C++ that produced them, control register usage and spill behavior, JIT-compile kernels at runtime with NVRTC, and use cuobjdump / nvdisasm / cu++filt to extract the truth from any compiled binary. The compiler is not your enemy — once you can read it, it is the single most reliable source of information about what your kernel will do.
10.1The nvcc Pipeline — Every Stage Named
What happens between nvcc kernel.cu and a runnable binary
Cluster.nvcc is a driver, not a compiler. It dispatches host code to your system C++ compiler (g++, clang, MSVC) and device code through three dedicated front- and back-end stages. Understanding the boundaries between them is what turns "the compiler stripped my variable" from a mystery into a debuggable event.
[A10.1.1]
The Six-Stage Compilation Pipeline
toolchain · pipeline
A single foo.cu traverses six logical phases. Each stage has a binary you can invoke directly when debugging.
cudafe++ — a CUDA-aware C++ front-end. Splits the .cu source into a host stub (calls to cudaLaunchKernel) and a device stub (kernels and __device__ functions). Produces foo.cpp1.ii (host) and foo.cpp4.ii (device).
cicc — the NVVM (LLVM-IR) optimizer. Translates the C++ AST to NVVM IR, runs optimization passes (inlining, SROA, GVN, loop unrolling, instruction selection), emits PTX (foo.ptx).
ptxas — assembles PTX into SASS (machine code) for one or more SM architectures. This is where register allocation, instruction scheduling, and the final ABI are decided. Output is a cubin (ELF) per architecture.
fatbinary — concatenates multiple cubins (and optionally the PTX itself for forward compat) into a single fat-binary blob.
Host C++ compiler — gcc/clang/MSVC processes the host stub, embedding the fatbinary as a const array via __cudaRegisterFatBinary.
Host linker — links the host objects with libcudart (or statically with cudadevrt for device-side new/printf). Final ELF/PE has both host CPU code and embedded device code.
The fat-binary embedded in your executable is read at load time by the CUDA driver. If a section matches your GPU's compute capability, the driver maps that cubin directly. Otherwise the driver JIT-compiles the embedded PTX. This is why distributing PTX makes your binary forward-compatible — and why omitting PTX (-arch=sm_80 --no-ptx) makes it smaller but architecture-locked.
Top track is host code (CPU). Bottom track is device code (GPU). They merge in the fatbinary and finally at the linker. Every arrow is a separate process you can intercept with --keep --verbose.
# --verbose prints every subprocess; --keep retains intermediate files
nvcc --verbose --keep -arch=sm_80 kernel.cu -o kernel 2>&1 | grep -E "cudafe|cicc|ptxas|fatbinary"
# Files left behind by --keep:
ls kernel.cudafe1.cpp # host stub
ls kernel.cpp1.ii # preprocessed host
ls kernel.ptx # PTX
ls kernel.cubin # SASS (binary)
ls kernel.fatbin # fatbinary blob
# Dump the PTX to stdout
nvcc -arch=sm_80 -ptx kernel.cu -o /dev/stdout | head -80
# Only emit a cubin (skip linking)
nvcc -arch=sm_80 -cubin kernel.cu -o kernel.cubin
Tip
Add -Xptxas -v to any compile to print per-kernel register count, spill stores/loads, shared-memory bytes, and constant-memory bytes. This single flag is the difference between guessing and knowing whether your latest tile-size change blew the register budget.
10.2ptxas, Register Pressure, and Spills
Why the same C++ runs 2× faster depending on a single __launch_bounds__
[A10.2.1]
The Register File Is a Shared Resource
registers · occupancy
Each SM owns a fixed register file: 65,536 × 32-bit registers on Ampere (sm_80/86) and Hopper (sm_90). All threads resident on that SM split it. If your kernel uses 64 registers/thread, an SM can host at most 65536 / 64 = 1024 threads — i.e. 32 warps, or 50% of the architectural max of 2048. Use 128 registers/thread and you crash to 25% occupancy.
The trade-off is spilling. If ptxas cannot allocate everything you need into registers, it generates loads and stores to local memory — which on the GPU is actually global memory backed by L1/L2. A single spill can cost 100s of cycles per access. The compiler does its best, but you set the budget.
Three knobs control this:
-maxrregcount=N — hard cap, applies to every kernel in the TU.
__launch_bounds__(maxThreadsPerBlock, minBlocksPerSM) — per-kernel, ptxas computes the register cap from the desired occupancy.
-Xptxas -O3 (default) vs -O0 — affects how aggressively cicc/ptxas inline and unroll, which directly grows register pressure.
The verbose output is one line per kernel and tells you everything that matters in two seconds:
ptxas info : Compiling entry function 'sgemm_kernel' for 'sm_80'
ptxas info : Function properties for sgemm_kernel
1024 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads
ptxas info : Used 96 registers, 16384 bytes smem, 388 bytes cmem[0]
Decode:
Stack frame — non-zero means you have local arrays or a recursive call. Try to drive to 0; even 0 spill stores can mask large stack frames.
Spill stores/loads — bytes per thread written/read to local memory because the register allocator ran out. Anything > 0 is a red flag.
Used registers — divide 65,536 by this to find max threads/SM, then divide by your block size for blocks/SM.
smem — bytes of static shared memory. Combine with dynamic shared mem to validate against the 100 KB/SM limit (sm_80) or 228 KB/SM (sm_90).
cmem[0] — bytes loaded from kernel param + global constant memory bank 0.
Worked Example — Pushing a Kernel Over the Spill Cliff
Suppose you have an 8×8 register-tiled GEMM (§2.5) using 72 registers/thread, 256 threads/block. Per-SM occupancy: 65536 / 72 ≈ 910 threads → 3 blocks of 256 → 768 threads → 37.5% occupancy. You want more occupancy so you set __launch_bounds__(256, 4), asking for 4 blocks/SM = 1024 threads.
ptxas must now squeeze into 65536 / 1024 = 64 registers/thread. The compiler spills 8 bytes/thread to local memory. Profiling shows a 3× slowdown despite the "higher occupancy." Spills moved hot operands to global memory and burned bandwidth that was already saturated.
Lesson: Occupancy is a secondary metric. The primary metric is "no spills, instructions per cycle high, memory throughput high." Pick the register count that lets your inner loop keep its operands in registers; let occupancy fall out of that decision, not lead it.
Pitfall
A struct passed by value to a __device__ function may force ptxas to reserve a stack frame even with no spills. Pass by const& or break the function up. Symptom: non-zero "bytes stack frame" with zero spills.
10.3SASS — The Real Machine Code
PTX is a virtual ISA. SASS is what the SM actually executes.
Cluster. PTX is portable — one binary covers many GPUs, and the driver JIT-compiles to SASS at load time. But the same PTX can yield different SASS on different architectures. When you need to understand "why is my kernel slow on this card and fast on that one," SASS is the answer.
[A10.3.1]
SASS Instruction Anatomy
SASS · decoding
A SASS instruction has four parts:
Predicate guard (e.g. @P0) — runs only if the predicate register is true. Replaces small if/else with branchless predication.
Scoreboard / yield bits (sm_70+) — control how the warp scheduler tracks dependencies; visible only in the raw control-code section.
# Show the cubin sections embedded in your executable
cuobjdump ./my_program
# Extract SASS for a specific arch (everything readable on stdout)
cuobjdump --dump-sass ./my_program
# Or compile -> cubin -> disasm in one shot
nvcc -arch=sm_80 -cubin kernel.cu -o kernel.cubin
nvdisasm --print-line-info kernel.cubin # correlates SASS lines with .cu source lines
# Decode SASS control codes (sm_70+) — yield/reuse/stall bits
nvdisasm --print-instruction-encoding kernel.cubin
# Show PTX, then SASS, then both with source interleaved
cuobjdump --dump-ptx ./my_program
cuobjdump --dump-sass --gpu-architecture=sm_80 ./my_program
When the kernel doesn't exist until your data does
[A10.4.1]
Why JIT a CUDA Kernel
NVRTC · jit
NVRTC is a libcuda subsystem that compiles a CUDA C++ source string to PTX at runtime, which the driver then loads. Use cases:
Shape specialization — bake matrix dimensions into the kernel as compile-time constants for full unrolling. Most Triton-backed engines (vLLM, TensorRT-LLM) do this.
Fusion engines — assemble an epilogue (bias add + activation) at run-time based on user input.
Plugin systems — let end users supply custom ops without recompiling the entire library.
The compile cost is usually tens of milliseconds, so cache the produced PTX/cubin keyed by the source hash and arch.
#include <nvrtc.h>
#include <cuda.h>
#include <iostream>
const char* src = R"(
extern "C" __global__ void axpy(float a, float* x, float* y, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) y[i] = a * x[i] + y[i];
})";
int main() {
nvrtcProgram prog;
nvrtcCreateProgram(&prog, src, "axpy.cu", 0, nullptr, nullptr);
const char* opts[] = { "--gpu-architecture=compute_80", "--use_fast_math" };
nvrtcCompileProgram(prog, 2, opts);
size_t ptxSize; nvrtcGetPTXSize(prog, &ptxSize);
std::string ptx(ptxSize, '\0'); nvrtcGetPTX(prog, ptx.data());
nvrtcDestroyProgram(&prog);
CUmodule mod; cuModuleLoadData(&mod, ptx.data());
CUfunction fn; cuModuleGetFunction(&fn, mod, "axpy");
// launch as usual with cuLaunchKernel...
}
Caveat
NVRTC has no access to your host headers. You must include any CUDA headers the kernel references as additional strings, or rely on what NVRTC bundles. Common gotcha: <cuda_fp16.h> works; <cooperative_groups.h> needs extra plumbing.
10.5The CUDA ABI & Separate Compilation
How __device__ functions cross translation-unit boundaries
[A10.5.1]
Relocatable Device Code (-rdc=true)
linking
By default nvcc compiles each .cu in whole-program mode: every device function must be visible (and inlinable) at the same translation unit as the kernel that calls it. With -rdc=true the device code is emitted as a relocatable cubin and a separate nvlink stage resolves cross-TU symbols, exactly like the host linker. Required for:
Calling a __device__ function defined in a different .cu.
Using dynamic parallelism (a kernel that launches another kernel) — that needs -rdc=true -lcudadevrt.
Linking against CUTLASS templates split across multiple files.
Costs: ~20% larger binaries, missed inlining (~5–10% perf on hot inner loops), and slower link times. Profile before assuming you need it.
[A10.5.2]
Name Mangling and cu++filt
debugging
CUDA mangles device symbols using the Itanium C++ ABI plus a _Z…-style scheme for templates. Read them with cu++filt:
Use this whenever Nsight Compute shows mangled names. Profile reports become readable.
10.6Compile-Time Tooling Cheat Sheet
Every flag you should know, in one screen
Flag
What it does
When to reach for it
-arch=sm_80
Target compute capability
Always. Pin to your hardware to avoid JIT cost.
-gencode arch=compute_80,code=sm_80
Fat binary entry
Multi-GPU deploys. Add one per arch.
-Xptxas -v
Verbose ptxas (regs, smem, spills)
Every optimization step.
-Xptxas -O3
Aggressive ptxas opt
Default. Lower to debug compiler bugs.
-Xcompiler "-fopenmp"
Pass flag to host compiler
When host code needs OpenMP, sanitizers, etc.
-G
Generate device debug info (NO opt)
cuda-gdb only. Will tank perf.
-lineinfo
Source line correlation, full opt
Profiling. Always use for Nsight Compute.
-use_fast_math
Approx math, FTZ, fast div
When you accept the numerical hit.
-prec-div=false -prec-sqrt=false
Fine-grained fast math
Per-knob control vs blanket fast-math.
-maxrregcount=N
Hard register cap
Force occupancy. Better: use launch_bounds.
--ptxas-options=--warn-on-spills
Surface spills as warnings
CI gates.
-rdc=true
Relocatable device code
Cross-TU device calls or dynamic parallelism.
--expt-relaxed-constexpr
Allow host constexpr in device code
Header-only libraries (CUTLASS, Thrust).
--extended-lambda
Device-side lambdas with capture
Thrust / Cub algorithms.
-Werror cross-execution-space-call
Catch host-from-device misuse
Production builds.
Checkpoint 10
Can you do each of these from memory?
Name every binary on the nvcc pipeline and what it consumes/emits.
Read a -Xptxas -v line and compute the resulting theoretical occupancy.
Disassemble a cubin to SASS and identify the inner loop's FFMA/LDG/STG sequence.
Explain when you'd use NVRTC instead of static compilation.
Decide whether -rdc=true is required for a given codebase.
Demangle a SASS symbol with cu++filt.
11
Chapter 11
Advanced Memory: Banks, Swizzles, Caches, & the Wires
Learning goal. Chapter 1 introduced the memory hierarchy as a layered diagram. This chapter walks down every layer with a microscope: how the 32 shared-memory banks actually arbitrate accesses, why XOR swizzles eliminate bank conflicts in Tensor-Core kernels, how to set L2 cache persistence policies for repeated reads, the physical structure of HBM2e/HBM3 versus GDDR6X, when pinned vs unified vs stream-ordered allocators matter, and how Hopper's TMA box-copies an entire tile asynchronously. By the end you will never again be surprised by a memory metric.
11.1Shared-Memory Banks — The Real Picture
32 banks, 4-byte words, one warp request — what arbitration looks like
[A11.1.1]
The Bank Model
shared memory
Shared memory on every modern NVIDIA arch is organized as 32 banks, each 4 bytes wide, interleaved across addresses. Bank b of word w holds byte address 4*(32*w + b). A warp issuing one shared-memory access produces 32 addresses. The hardware groups them by bank; per-cycle a bank can serve exactly one 32-bit word. Two cases:
No conflict — each thread hits a distinct bank, or all 32 threads hit the same word in the same bank (broadcast). One cycle.
N-way conflict — 2 ≤ N ≤ 32 threads each hit a different word in the same bank. The hardware serializes into N cycles.
Bank conflicts are a per-warp, per-instruction property — not per kernel. The metric to watch in Nsight Compute is l1tex__data_bank_conflicts_pipe_lsu_mem_shared_op_*.
Three solutions to the column-stride conflict: pad the row (wastes one bank per row), XOR-swizzle the index (no waste — used by CUTLASS), or transpose the tile in shared memory.
// Conflict-free row access, 32-way conflict column access
__shared__ float Tile1[32][32];
// One-pad trick — 4 KB wasted but trivial
__shared__ float Tile2[32][33];
// XOR swizzle — no padding, no conflict.
// Compute the storage index from (row, col):
__device__ inline int swizzle(int row, int col) {
return row * 32 + (col ^ ((row & 0x7) << 2));
}
__shared__ float Tile3[32 * 32]; // accessed via swizzle(r,c)
// Store-side write uses the same swizzle, so reads/writes are symmetric.
Tile3[swizzle(r, c)] = value;
float v = Tile3[swizzle(r, c)];
11.2XOR Swizzles & ldmatrix Layouts
Why CUTLASS never pads anything
[A11.2.1]
Swizzle as a Permutation
layout
A swizzle is a bijection on memory addresses such that for every access pattern your kernel issues, the addresses land in distinct banks. CUTLASS expresses swizzles as three integers: Swizzle<B, M, S> meaning "XOR the top B bits of the column index, shifted by S, into the row-offset whose lowest M bits we mask." The pattern is parameterized so that for a given tile shape and target instruction (ldmatrix.x4.b16, etc.) you can pick the swizzle that makes both loads and stores conflict-free.
The most useful concrete recipes:
16×16 FP16 fragment (Tensor Core m16n8k16) → Swizzle<3,3,3> over a row-major tile.
16×8 FP16 fragment → Swizzle<2,3,3>.
32×32 FP32 tile (no Tensor Core) → Swizzle<2,3,2> or just the XOR-by-row-bits pattern in Listing 11.1-A.
Mental model
"Bank-conflict free" means the 32 addresses produced by one warp instruction map onto 32 distinct (bank, word) pairs. Padding achieves this by inserting empty bytes; swizzling achieves it by mixing the row bits into the column bits. Padding wastes capacity and complicates pointer arithmetic; swizzling is free at runtime and reversible.
11.3L2 Carveout & Persisting Access Policies
Pin hot data into L2 — the secret weapon for small-K GEMMs and embeddings
[A11.3.1]
The L2 Cache Is Programmer-Visible (sm_80+)
cache
Ampere's L2 is 40 MB on A100, 6 MB on RTX 3090. Hopper H100 has 50 MB. The driver lets you reserve a fraction of L2 as a persistent carveout for a designated address range. Reads/writes inside that range are tagged "persistent" and the cache replacement algorithm protects them from being evicted by streaming traffic. Use it when:
The same weights are reused across many launches (LLM decoder weights between tokens).
A small lookup table is hit by every thread (embedding tables, position encodings).
A GEMM has a small K — the operand traffic dominates and reuse is cross-tile.
cudaStream_t stream;
cudaStreamCreate(&stream);
// 1. Reserve up to 30 MB of L2 as the persistent carveout.
size_t persist_bytes = 30 * 1024 * 1024;
cudaDeviceSetLimit(cudaLimitPersistingL2CacheSize, persist_bytes);
// 2. Attach a stream attribute that maps a memory range to persistent policy.
cudaStreamAttrValue attr = {};
attr.accessPolicyWindow.base_ptr = weight_ptr;
attr.accessPolicyWindow.num_bytes = weight_bytes;
attr.accessPolicyWindow.hitRatio = 1.0f;
attr.accessPolicyWindow.hitProp = cudaAccessPropertyPersisting;
attr.accessPolicyWindow.missProp = cudaAccessPropertyStreaming;
cudaStreamSetAttribute(stream, cudaStreamAttributeAccessPolicyWindow, &attr);
// 3. Launch kernels on this stream — accesses inside [weight_ptr, +weight_bytes)
// are treated as persistent.
my_decoder_kernel<<<grid, block, 0, stream>>>(weight_ptr, /*…*/);
// 4. Reset when you're done so the next phase doesn't inherit the policy.
attr.accessPolicyWindow.num_bytes = 0;
cudaStreamSetAttribute(stream, cudaStreamAttributeAccessPolicyWindow, &attr);
cudaCtxResetPersistingL2Cache(); // optional: drop any persistent lines
Pitfall
Set num_bytes > the carveout size, and you don't get a warning — you get false-positive hit rates because the hardware refuses to mark over-capacity lines as persistent. Always check the L2 hit-rate metric afterward; if it didn't move, the carveout was misconfigured.
11.4HBM, GDDR, and the Memory Subsystem
Why "global memory bandwidth" hides three different physical realities
[A11.4.1]
HBM2e/HBM3 vs GDDR6X — Same Goal, Different Trade-offs
DRAM
HBM (High Bandwidth Memory) stacks 4–8 DRAM die on a silicon interposer right next to the GPU die. The interface is 1024 bits wide per stack, with 4–6 stacks per GPU. A100 has 5 HBM2e stacks at 2.4 Gbit/s, giving 1.6 TB/s. H100 has 5 HBM3 stacks at 5.2 Gbit/s = 3.35 TB/s. The cost: HBM doubles GPU die cost and limits you to data-center thermal envelopes.
GDDR6X sits on a PCB and talks to the GPU over a 256–384-bit bus. RTX 4090 has 384-bit GDDR6X at 21 Gbit/s = 1.0 TB/s. Cheaper, easier to manufacture, but lower bandwidth and higher latency.
Implication for kernel design: HBM rewards large contiguous transfers (cp.async, TMA). GDDR rewards L2 hit rate because the L2-to-HBM ratio is lower. Same kernel often wants different tile sizes on consumer cards vs data center cards.
Pageable — default malloc. The CUDA driver must first copy your data into a hidden pinned staging buffer before DMA. Effective H2D bandwidth: ~6 GB/s on PCIe Gen4.
Pinned (cudaMallocHost or cudaHostAlloc) — page-locked, eligible for direct DMA. Effective bandwidth: PCIe peak (~26 GB/s Gen4 x16, ~52 GB/s Gen5). Down-side: pinned pages cannot be swapped, so allocating GBs of pinned memory starves the OS.
Mapped pinned (cudaHostAllocMapped) — pinned plus accessible by the GPU through a unified address. Useful for tiny, latency-critical writes (e.g., a kernel signaling completion to the host). For large transfers, an explicit memcpy is still faster because the driver can stream batches.
[A11.5.2]
Stream-Ordered Memory (cudaMallocAsync)
allocator · pools
Since CUDA 11.2 each device has a default memory pool. cudaMallocAsync(ptr, n, stream) queues an allocation that completes when stream reaches it; the pool reuses freed blocks instead of returning them to the driver. Benefits:
Allocation cost drops from microseconds to a handful of instructions for typical sizes.
Correctness across streams is automatic via cudaMemPoolAttrReleaseThreshold and stream events.
Works inside CUDA Graphs (legacy cudaMalloc does not).
Always prefer cudaMallocAsync for short-lived per-iteration buffers in training/inference loops.
// Tunable pool: keep up to 4 GB of freed blocks, never trim below 256 MB.
cudaMemPool_t pool; cudaDeviceGetDefaultMemPool(&pool, 0);
uint64_t threshold = 4ull * 1024 * 1024 * 1024;
cudaMemPoolSetAttribute(pool, cudaMemPoolAttrReleaseThreshold, &threshold);
cudaStream_t s; cudaStreamCreate(&s);
for (int iter = 0; iter < 1000; ++iter) {
float* tmp;
cudaMallocAsync(&tmp, N * sizeof(float), s); // O(1) — reuses pool memory
my_kernel<<<grid, block, 0, s>>>(tmp, /*...*/);
cudaFreeAsync(tmp, s); // queued, no host stall
}
cudaStreamSynchronize(s);
11.6TMA & Async Bulk Copy (Hopper)
Move an entire tile with a single descriptor
[A11.6.1]
What the Tensor Memory Accelerator Actually Does
hopper · tma
On Ampere, copying an N-element tile from global to shared takes N/4 cp.async instructions, each issued by a thread. On Hopper, the TMA does it in one instruction (cp.async.bulk.tensor) issued by a single elected thread, given a precomputed descriptor that encodes:
Global base pointer and per-dimension strides.
Tile shape (up to 5-D).
Shared-memory destination, with optional swizzle pattern (SWIZZLE_NONE, SWIZZLE_32B, SWIZZLE_64B, SWIZZLE_128B).
Out-of-bounds policy (zero-fill or padding).
The TMA computes addresses, issues coalesced loads, and signals completion via an mbarrier. The warps doing math never compute an address. Result: more compute units do useful work, and the address-generation pressure that limited Ampere disappears.
64 KB of read-only memory cached by a small dedicated cache per SM. The win condition: all threads in a warp read the same address. The hardware broadcasts the value to all 32 lanes in a single cycle. Different addresses serialize. Use for: scalar hyperparameters, RoPE base/scale, lookup tables shared by every thread.
Kernel parameters (the arguments of __global__) live in constant bank 0 implicitly — that's the cmem[0] in ptxas output.
[A11.7.2]
Texture & Surface — Still Useful in 2026
texture · surface
Texture memory is global memory accessed through a special read path that adds (a) hardware bilinear interpolation, (b) clamp/wrap addressing, (c) 8-/16-/32-bit normalized loads, and (d) a separate cache that does not pollute L1. Modern uses:
Image and volume processing where bilinear interpolation is free.
Look-up tables larger than constant memory where reads are spatially correlated.
Sparse/scattered reads where you want a cache distinct from L1.
The __ldg(ptr) intrinsic gives you the read-only cache without the texture object machinery — usually enough for modern kernels.
Checkpoint 11
From memory, before turning the page
Diagram the 32-bank model and predict the conflict count for stride-1, stride-2, stride-32 access.
Compute a swizzled shared-memory address by hand for a 16×16 FP16 tile.
Configure an L2 persisting carveout for a 32 MB weight buffer.
State the bandwidth and latency trade-offs between HBM3 and GDDR6X.
Pick the right allocator (pageable/pinned/mapped/async pool) for three scenarios.
Explain why TMA frees the warp's address-generation budget.
12
Chapter 12
Numerical Methods: What FP32 Promises and What It Actually Delivers
Learning goal. Floating-point math on a GPU is not the same as floating-point math you grew up with. Order of operations changes results, parallel reductions are non-deterministic by default, tensor cores accumulate to a different precision than they multiply with, and a "fast-math" flag can silently change your model's accuracy. This chapter teaches you to predict the numerical behavior of a kernel, prove it, and choose the right precision strategy.
12.1IEEE 754 Beyond the Bit Layout
Rounding modes, subnormals, ULPs, and what NVIDIA chose
[A12.1.1]
Rounding Modes
IEEE 754
IEEE 754 defines four rounding modes. NVIDIA hardware supports all four per instruction, but the compiler default is round-to-nearest-even (RTNE). The PTX suffixes are .rn (nearest-even), .rz (toward zero / truncation), .rm (toward −∞), .rp (toward +∞). Use cases:
.rn — default, lowest expected error.
.rz — required by some quantization schemes that want symmetric clipping.
.rm/.rp — interval arithmetic, error bounds.
Rounding mode is part of the SASS instruction; you cannot change it at runtime. Set it per-FMA with intrinsics like __fmul_rn, __fmaf_rz.
[A12.1.2]
Subnormals & Flush-to-Zero
denormals
Numbers smaller than the smallest normal float (2−126 for FP32) are subnormals. They preserve relative precision near zero, but on most hardware they cost extra cycles. NVIDIA GPUs handle subnormals at full speed for FP32 add/multiply on sm_53+, but a few transcendentals are flushed to zero unconditionally.
The -use_fast_math flag enables FTZ globally: every operation that would produce a subnormal returns ±0. This is fine for inference and most training, but breaks careful numerical code (Kahan summation, ill-conditioned linear solvers).
To probe what FTZ is doing, check __float_as_uint(x) after an arithmetic op and look for the exponent field being all zero with non-zero mantissa — that is a subnormal.
[A12.1.3]
ULP — The Currency of Error
error analysis
One unit in the last place (ULP) is the gap between two adjacent representable floats. For FP32 at magnitude 1.0, 1 ULP ≈ 1.19e−7. A correctly rounded operation has error ≤ 0.5 ULP. NVIDIA documents the max ULP error of every intrinsic in the CUDA Math API; e.g. __expf is 2 ULPs while expf is < 1 ULP. When you read "tolerance of 1e-5" in a unit test, translate it: at magnitude 1, that's ~84 ULPs of slack. At magnitude 10⁶, the same absolute tolerance accepts ~8 ULPs.
12.2FMA Semantics & Why Multiply-Then-Add ≠ FMA
A single rounding step changes more than you'd think
[A12.2.1]
Fused Multiply-Add
FMA
fma(a,b,c) computes a*b + c with a single rounding step at the end. Plain a*b + c in C++ rounds twice. The difference can be 1 ULP per operation, which is everywhere in GEMM (millions of FMAs). The reason your CUDA result differs from your CPU reference is often that nvcc fused multiply-adds while gcc didn't.
Force FMA on/off when reproducing bug reports:
nvcc -fmad=false — disable contraction. Useful to match a CPU reference compiled with -ffp-contract=off.
__fmul_rn(a,b) + c — explicit unfused multiply, then add.
12.3Summation Algorithms — When Floats Stop Associating
Naive, pairwise, Kahan, and Neumaier compared
[A12.3.1]
Why Order Matters
numerical stability
FP addition is non-associative: (a+b)+c ≠ a+(b+c) in general. The relative error of a naive serial sum of N positive FP32 numbers is bounded by N · ε where ε = 2⁻²⁴. With N = 2²⁴ ≈ 16M, you can lose all precision. Better algorithms cap or shrink this dependence on N.
Algorithm
Forward error
Cost
GPU fit
Naive serial
O(Nε)
N adds
Bad — also slow
Pairwise (tree)
O(log N · ε)
N adds
Natural for warp/block reduce
Kahan
O(ε)
4N ops
Possible, register pressure
Neumaier
O(ε)
3N ops
Like Kahan, handles mixed signs
Higher precision accumulator
O(Nε²)
2× regs
Use FP64 acc for FP32 sum
// Warp-level Kahan reduce. 32 threads, each holds val; output = sum across warp.
__device__ float warp_kahan_sum(float val) {
float sum = val;
float c = 0.0f; // running compensation
for (int offset = 16; offset > 0; offset >>= 1) {
float other_sum = __shfl_down_sync(0xffffffff, sum, offset);
float other_c = __shfl_down_sync(0xffffffff, c, offset);
float y = other_sum - (c + other_c);
float t = sum + y;
c = (t - sum) - y; // bits lost going into t
sum = t;
}
return sum; // lane 0 holds the answer
}
Tensor Cores accumulate in FP32 — be aware
An FP16×FP16 → FP32 Tensor Core operation multiplies in FP16 (3 decimal digits of precision) but accumulates in FP32. The accumulation chain is hardware-pairwise across the 8/16/32 K-axis steps, so a single mma.sync is well-behaved. The problem comes in the K loop: how many mma.sync calls feed the same FP32 accumulator? After ~10⁴ calls you may lose accuracy in the low bits.
12.4Conditioning & Stability
When the algorithm is the problem, not the precision
[A12.4.1]
Condition Number
linear algebra
For a problem y = f(x), the condition number measures how much a small change in x can move y. For matrix multiply y = Ax, it is κ(A) = σ_max(A) / σ_min(A). If κ ≈ 10⁶, you lose ~6 decimal digits when solving with A. FP32 has ~7 digits — you have 1 left. Reducing to FP16 (3 digits) on an ill-conditioned matrix produces nonsense.
κ ≥ 10⁵ → keep FP32 throughout, or rescale the problem.
[A12.4.2]
Catastrophic Cancellation
subtraction
Subtracting two nearly equal numbers leaves only their (small) difference, with the precision of the difference. Example: (1 + 1e-8) - 1 in FP32 returns 0 because 1e-8 is below the FP32 ULP at magnitude 1. Common offenders:
Mean-centering large tensors (x - mean(x)) before computing variance.
Softmax numerator/denominator with poorly chosen max-subtraction.
Naive variance formula E[X²] − E[X]² instead of Welford.
Fix by algebraic rearrangement or higher precision intermediates.
12.5Mixed Precision & Loss Scaling
Half the bits, twice the throughput, none of the divergence — if you do it right
[A12.5.1]
Automatic Mixed Precision (AMP) Recipe
training
Standard AMP for training:
Store weights as FP32 master copies, cast to FP16/BF16 for forward and backward passes.
Compute matmuls and convolutions in FP16/BF16 with FP32 accumulators (Tensor Cores).
Keep softmax, layernorm, loss, and optimizer steps in FP32.
Loss scaling (only for FP16, not BF16): multiply loss by S (typically 2¹⁰–2¹⁶) before backward so gradient magnitudes stay above FP16's subnormal threshold; unscale before applying to optimizer.
BF16 has the FP32 exponent range, so loss scaling is unnecessary — at the cost of fewer mantissa bits.
Loss scaling exists to push small gradients into the visible range of FP16 (the labeled FP16 interval). BF16 covers the same range as FP32, so the trick is unnecessary.
12.6Determinism on the GPU
Same input, same kernel, same hardware — different answer
[A12.6.1]
Sources of Non-Determinism
determinism
The same GEMM kernel can return bit-different results across runs because of three independent sources:
Atomic operations — order of atomicAdd across blocks depends on scheduler. Solution: use deterministic reduction (segmented or tree).
Algorithm selection — cuBLAS and cuDNN heuristically pick different kernels based on cache state. Disable with CUBLAS_PEDANTIC_MATH_MODE, CUBLASLT_ALGO_CONFIG pinning, or torch.use_deterministic_algorithms(True).
Reduction order — split-K and stream-K change the order of K-axis additions; FP non-associativity makes the result bit-different.
If you need byte-identical reproducibility, accept the typical 10–30% performance cost and lock all three.
State the max ULP error of __sinf vs sinf and decide which one your kernel needs.
Compute the worst-case forward error of a naive vs pairwise vs Kahan sum of 10⁶ FP32 values.
Explain when BF16 is preferable to FP16 in 30 seconds.
Identify the three sources of non-determinism in a multi-block reduction.
Estimate the condition number of a near-singular matrix and pick a precision strategy.
13
Chapter 13
Quantization & Sparsity: Shrinking the Operands Without Breaking the Math
Learning goal. Tensor Cores double their throughput every time you halve the operand width. INT8 is 2× FP16; INT4 is 4×; sparse-INT8 is 8×. But each step trades precision for speed. This chapter teaches you the four quantization schemes you'll meet (per-tensor, per-channel, per-token, group-wise), the FP8 formats and when each one is right, how 2:4 structured sparsity is enforced at the hardware level, and how to fuse dequant + GEMM + bias + activation into a single kernel.
13.1The Quantization Spectrum
From FP32 down to 1-bit, what each tier actually costs
[A13.1.1]
Five Quantization Granularities
quantization
Per-tensor — one (scale, zero_point) for the whole tensor. Cheapest, lowest accuracy.
Per-channel — one per output channel. Standard for weights.
Per-token / per-row — one per activation row. Standard for transformers.
Group-wise — split a tensor into groups of e.g. 64 consecutive values, one scale per group. AWQ, GPTQ use 128-group.
Sub-channel — multiple scales per channel, used by FP4 schemes (NVFP4 has two-level scale).
The finer the granularity, the more accuracy you preserve, but the more metadata bandwidth you spend.
[A13.1.2]
Symmetric vs Affine Quantization
scheme
Symmetric:q = round(x / scale). Zero in the float domain maps to 0 in the int domain. Cheaper kernels (no zero-point arithmetic), but wastes the bottom half of the int range when x is non-negative (e.g. after ReLU).
Affine:q = round(x / scale + zero_point). Uses the full int range, at the cost of one extra add per multiply (which can be folded into the bias).
Modern LLM inference is largely weight-only symmetric (W4A16, W8A16) with affine activations only where necessary.
13.2INT8 GEMM Kernels
The first Tensor-Core integer pipeline
[A13.2.1]
IMMA — Integer Matrix-Multiply-Accumulate
tensor cores
Available since Turing. Sample shape on Ampere: m16n8k32 s8s8s32 — A and B are INT8 tiles, accumulator is INT32. Throughput: 2× the FP16 Tensor-Core rate. PTX form:
The s8.s8.s32 means: A is signed INT8, B is signed INT8, accumulator is signed INT32. The INT32 accumulator never overflows for K ≤ 2³¹/256² ≈ 32K.
// Per-channel symmetric quant for weights, per-token affine for activations.
struct Quant {
int8_t* q_data; // quantized values
float* scale; // scale per channel or per row
int32_t* zero; // zero point (0 if symmetric)
};
void gemm_int8(const Quant& A, const Quant& B, float* C,
int M, int N, int K, cudaStream_t s) {
// 1) Call the IMMA kernel that produces an INT32 partial sum.
int32_t* C_int;
cudaMallocAsync(&C_int, M * N * sizeof(int32_t), s);
imma_gemm_kernel<<<grid, block, 0, s>>>(A.q_data, B.q_data, C_int, M, N, K);
// 2) Dequant + bias + activation in a fused epilogue:
dequant_epilogue<<<..., s>>>(C_int, A.scale, B.scale, C, M, N);
cudaFreeAsync(C_int, s);
}
13.3FP8 — E4M3 vs E5M2
Two competing 8-bit floats — when to use each
[A13.3.1]
The Two FP8 Formats
FP8 · hopper
Hopper introduces two FP8 formats following the OCP FP8 spec:
E4M3 — 1 sign, 4 exponent, 3 mantissa. Range ±448, ~3 ULP precision. Used for activations and weights in forward pass.
E5M2 — 1 sign, 5 exponent, 2 mantissa. Range ±57344, ~7 ULP precision. Used for backward gradients (wider range, less precision).
Hopper Tensor Cores accept any mix: fp8_e4m3 × fp8_e4m3 → fp32, fp8_e5m2 × fp8_e4m3 → fp16, etc. The Transformer Engine library auto-selects format per tensor based on histogram statistics.
FP8 inference of an LLM can match FP16 within 0.1 perplexity if (a) weights and activations use per-tensor scales updated every forward, (b) attention logits stay in FP16, and (c) layer-norm runs in FP32. Skipping any of these makes the model diverge within a few hundred tokens.
13.4Sub-Byte Weights — INT4 & FP4
When the GEMM is memory-bound, every bit you save is throughput
[A13.4.1]
Packing & Decoding INT4
int4
Two INT4 values share one byte. The kernel decodes them on load with shifts and masks, multiplies the FP16 activations, accumulates in INT32 (or FP32 after dequant). The 2× memory savings over INT8 plus the unchanged Tensor-Core throughput means INT4 weight-only quantization is the workhorse of consumer LLM inference. Marlin, AWQ, and ExLlamaV2 are all INT4 weight kernels with different tile/layout choices.
[A13.4.2]
NVFP4 — Blackwell's 4-bit Float
blackwell
Blackwell adds an FP4 format (E2M1) and Tensor-Core instructions that consume it directly. Two-level scaling: each block of 16 FP4 values has an FP8 scale, and each block of 16 of those has an FP32 scale. The hardware decodes and rescales on the fly. Total memory cost: ~4.5 bits/value. Theoretical 2× over FP8 throughput on Blackwell Tensor Cores.
13.52:4 Structured Sparsity
Free 2× from the hardware if your weights cooperate
[A13.5.1]
The 2:4 Pattern
sparsity
In every group of 4 consecutive weights, exactly 2 must be zero. The hardware stores only the 2 non-zeros plus a 2-bit index (0b00–0b11) telling it which positions are non-zero. A sparse Tensor Core multiplies a sparse 16×K weight tile by a dense K×N activation tile in the same cycle count as a dense 16×(K/2) tile — i.e., 2× throughput.
Restrictions:
2:4 along the K-axis of the weight tile (not the M-axis).
K must be a multiple of 4 (16 for FP16/BF16, 32 for INT8).
Activations stay dense; only the weight side is sparse.
Practical approach: train dense, prune to 2:4 with the ASP (Automatic Sparsity) workflow, fine-tune for ~10% of original training cost, deploy. Accuracy loss on most LLMs is < 0.5%.
13.6Dequant Fusion & Epilogues
Why a separate dequant kernel is always wrong
[A13.6.1]
The Epilogue Belongs in the GEMM
fusion
An INT8 GEMM produces an INT32 partial sum that you need to dequantize, add a bias to, then apply an activation (GeLU, SiLU). If you write three separate kernels, you re-read and re-write the M×N tile to/from global memory twice. Fusing the dequant + bias + activation inside the GEMM epilogue — the code that runs after the K loop — keeps the tile in registers until the final store. Savings: typically 30–50% end-to-end latency on small-M LLM decode.
CUTLASS exposes this via the EpilogueOp template parameter. Triton fuses it automatically when you write tl.store(c_ptr, activation(c_int32 * scale + bias)). Raw CUDA: you write the epilogue yourself, after the final mma.sync and before the global stmatrix.
Pick a granularity (per-tensor / per-channel / per-token / group-wise) for weights and activations of a transformer linear layer.
Write the symmetric quantize/dequantize formula.
Explain the difference between FP8 E4M3 and E5M2 in one sentence each.
Describe the 2:4 sparsity layout and the constraints it imposes.
Sketch a fused INT8 GEMM + bias + GeLU epilogue.
14
Chapter 14
Flash Attention & IO-Aware Algorithms
Learning goal. FlashAttention is the canonical example of an algorithm that beat the textbook math by being honest about the memory hierarchy. Understanding it teaches you a generalizable design pattern — tile so the inner loop stays in shared memory, recompute instead of storing, and online-update the dependent statistics — that you can apply to softmax, layer norm, scan-based loss functions, and any kernel that touches a large intermediate.
14.1Why Attention Is Memory-Bound
The N² intermediate that doesn't fit anywhere
[A14.1.1]
Standard Attention's IO Cost
attention
Standard scaled-dot-product attention on a sequence of length N with head dimension d:
S = Q · Kᵀ // (N × d) · (d × N) → N × N
P = softmax(S / √d) // N × N
O = P · V // (N × N) · (N × d) → N × d
Compute cost: O(N²·d) FLOPs. Memory cost: the N×N matrix S (or P) must be written to global memory and read back — 2·N² FP16 reads/writes. For N = 8192, that's 256 MB per attention head, on a chip whose L2 is 50 MB. The kernel becomes memory-bound long before it becomes compute-bound.
Arithmetic intensity:
AI ≈ N²·d / (N² + N·d) ≈ d FLOPs/byte
For d = 64, AI ≈ 64. The A100 ridge point is around 290. So we are 4.5× below the roofline ridge — memory-bound by construction.
Update the normalizer as new blocks arrive, without storing the unnormalized scores
[A14.2.1]
Streaming Maximum & Streaming Sum-Exp
softmax
Naive softmax requires three passes: find max, subtract max and exp, divide by sum. The flash idea: process the input in blocks of size B, and after each block update the running (max, sum, output) tuple such that the final answer is exact. For two blocks with statistics (mᵢ, ℓᵢ) and (mⱼ, ℓⱼ):
// Inputs: Q (N x d), K (N x d), V (N x d)
// Outputs: O (N x d)
// Block sizes: Br rows of Q, Bc rows of K/V
for (i = 0; i < N; i += Br) {
// Load a Br × d block of Q into shared memory.
Q_i = load_tile(Q, i, Br);
// Running statistics for this Q-block.
m_i = -inf; // running max
l_i = 0; // running sum-exp
O_i = zeros(Br, d); // running output
for (j = 0; j < N; j += Bc) {
// Load a Bc × d block of K and V.
K_j = load_tile(K, j, Bc);
V_j = load_tile(V, j, Bc);
// Compute S_ij = Q_i · K_jᵀ (Br × Bc) — stays in shared mem.
S_ij = mma(Q_i, transpose(K_j)); // Tensor Core GEMM
// Apply causal mask if needed.
if (j > i) S_ij = mask(S_ij);
// Online softmax update.
m_ij = rowmax(S_ij);
m_i_new = max(m_i, m_ij);
P_ij = exp(S_ij - m_i_new);
l_ij = rowsum(P_ij);
l_i_new = exp(m_i - m_i_new) * l_i + l_ij;
// Update output: rescale prior, add new contribution.
O_i = (exp(m_i - m_i_new) * l_i / l_i_new) * O_i
+ (1.0 / l_i_new) * mma(P_ij, V_j);
m_i = m_i_new;
l_i = l_i_new;
}
store_tile(O, i, O_i);
}
Why this is faster
The N×N matrix S is never written to global memory — it lives in shared memory as a Br×Bc block, then disappears. HBM traffic drops from O(N²) to O(N·d) (the four input/output tensors). For N = 8K, d = 64, that's a 60× reduction in memory traffic, which on an A100 translates to a 4–7× speedup over a fused-but-non-IO-aware implementation.
14.4FlashAttention-2 & 3
What changed when Tri Dao revisited the design
[A14.4.1]
FA-2 — Work Partitioning
fa2
FA-1 split the grid along (head, batch). FA-2 adds a third axis: sequence. Multiple thread blocks now collaborate on different Q-blocks of the same head, increasing parallelism for the short-context, large-batch case. Other tweaks:
Reduce the rescaling chain by deferring the 1/ℓ division to the end.
Refactor inner loops so the producer-consumer pipeline interleaves load and MMA more tightly.
Avoid the implicit transpose of K by storing K already transposed.
Net result: ~2× throughput vs FA-1 on A100, ~70% of theoretical Tensor-Core peak.
[A14.4.2]
FA-3 — Hopper-Native
fa3 · hopper
FlashAttention-3 targets Hopper's TMA, wgmma, and warp specialization. It splits the warps inside a block into a producer warp group that issues TMA loads and a consumer warp group that runs wgmma on the loaded tiles. The two communicate via an mbarrier, so loads and math overlap at fine granularity. Reaches ~75% of H100 Tensor-Core peak FP16.
Block to fit shared memory — any intermediate larger than SMEM should be regenerated, not stored.
Stream-update dependent statistics — running max, running sum, running mean/variance (Welford). These let you avoid the multi-pass version.
Recompute < store on backward pass. The FA backward recomputes the attention matrix from saved (max, sum) statistics instead of storing it.
Producer/consumer specialization on Hopper — partition warps by role so load and math overlap without scheduler luck.
Pick block sizes so the next block fits in L2 — by the time a Q-block finishes its K-loop, the next K-block is already there.
Apply these to softmax, layer norm, RMSNorm, cross-entropy with logit shifts, RoPE, and any "compute a big intermediate, immediately reduce it" pattern.
Checkpoint 14
Apply the pattern, not the formula
State the arithmetic intensity of standard attention and explain why it's memory-bound.
Derive the online softmax update formula on a whiteboard.
Identify one operator in your own code that would benefit from the FA design pattern.
Compare FA-1, FA-2, FA-3 in one sentence each.
15
Chapter 15
Convolution Kernels: From im2col to Winograd
Learning goal. Convolution is the second pillar of deep-learning compute. It looks like a different problem from GEMM, but every fast GPU implementation either reduces it to a GEMM or trades multiplies for additions via Winograd transforms. By the end you can implement each strategy, predict when each one wins, and read a cuDNN log to know which algorithm the heuristic picked.
15.1What Convolution Is — One More Time
2-D, batched, multi-channel — the shape that matters
[A15.1.1]
The 7-D Convolution
convolution
An ML 2-D convolution has shape parameters (N, C, H, W, K, R, S, U, V, pad):
N — batch.
C — input channels.
H, W — input spatial.
K — output channels.
R, S — filter spatial.
U, V — stride.
P, Q — output spatial = ((H + 2·pad − R)/U) + 1.
FLOPs: 2 · N · K · C · R · S · P · Q. For ResNet-50's 3×3 layer at 28×28 with 256 channels and batch 64, that's ~6 GFLOP — small individually, but a network has hundreds of such ops.
15.2im2col + GEMM
The straightforward, memory-hungry reduction to matrix multiply
[A15.2.1]
The Unfolding Trick
im2col
For each output pixel, list the C·R·S input values that contribute to it as a column of a giant matrix X_unf of shape (C·R·S) × (N·P·Q). Then convolution is just
Y = W_flat · X_unf
where W_flat is the filter reshaped to K × (C·R·S). This turns convolution into one giant GEMM. Caltech's Caffe popularized the technique; every modern stack still keeps it as a fallback. Downside: X_unf uses R·S× more memory than X. For 3×3 that's 9× — manageable. For 7×7 it is 49×.
Implicit GEMM is the standard cuDNN algorithm. The kernel acts as if it is doing the GEMM Y = W_flat · X_unf, but each GEMM tile load does the im2col index calculation inline, reading directly from the original X tensor. The result: same arithmetic and bandwidth as a dense GEMM of the same logical size, no R·S memory overhead. Trade-off: more address-generation pressure, which Hopper's TMA largely mitigates.
15.4Winograd Minimal Filtering
Trade multiplies for additions in 3×3 kernels
[A15.4.1]
F(2,3) — 2-output Winograd
winograd
The "minimal filtering" form due to Winograd computes a 2×2 output tile from a 4×4 input tile using only 16 element-wise multiplies after a fixed linear transform — versus 36 for the direct 3×3 conv. The 2.25× reduction in multiplies maps directly to a 2.25× peak speedup on FP32, but in practice you get 1.4–1.7× because:
The four transform matrices (A, B, G) add memory traffic.
Precision degrades — Winograd has higher rounding error than direct conv, so FP16 with Winograd can break.
F(4,3) (4-output Winograd) is even more aggressive but loses accuracy faster. Most production stacks default to F(2,3) for FP32 and skip Winograd entirely for FP16/BF16, using implicit GEMM there instead.
// F(2,3) algorithm:
G·g·Gᵀ ⊙ Bᵀ·d·B → Aᵀ · (·) · A = 2×2 output
where g is 3×3 filter, d is 4×4 input tile.
15.5FFT and Direct Convolution
The other two paths, and when each wins
[A15.5.1]
FFT Convolution
fft
For large filter sizes (R, S ≥ 11), FFT-based conv (cuFFT + element-wise multiply + inverse FFT) is asymptotically O((H·W)·log(H·W)) versus direct O(H·W·R·S). Wins decisively for non-strided conv with very large kernels. ML rarely has those, so FFT-conv is uncommon in deep nets but standard in scientific/image processing.
[A15.5.2]
Direct Convolution
direct
Skip the GEMM mapping entirely; have each thread block compute a small output tile by sliding the filter directly. Wins when: tiny channels (C, K < 16, so GEMM tiles waste rows), tiny H/W (mobile), or depthwise convs where each output channel reads only one input channel.
15.6Depthwise & Group Convolution
The shape that breaks every GEMM-based plan
[A15.6.1]
Why Depthwise Doesn't im2col
depthwise
Depthwise conv applies one filter per input channel. The "GEMM" you'd build is K=1 wide — degenerate. cuDNN's depthwise kernels are direct: each thread block owns one channel, slides the filter through the output. MobileNet's bottleneck is depthwise conv precisely because the GEMM trick stops paying. Same story for grouped conv with small group size.
Filter / Layer Shape
Best Algorithm
Why
3×3, FP16/BF16, batched
Implicit GEMM (HMMA)
Tensor Cores dominate.
3×3, FP32, batched
Winograd F(2,3)
Saves 2.25× multiplies, FP32 has room.
1×1
Plain GEMM
No im2col needed; pure matmul.
7×7 first layer
Implicit GEMM
Large filter but only a few channels.
Depthwise 3×3
Direct kernel
K=1 — GEMM degenerate.
Large kernel image processing (15+)
FFT
O(log N) per pixel wins.
Stride > 1
Implicit GEMM (no Winograd)
Winograd designed for stride-1.
Checkpoint 15
Pick the right algorithm without thinking
Derive the FLOP count of a 2-D conv given (N, C, H, W, K, R, S).
Compute the memory blow-up of im2col for a 5×5 conv.
Explain why depthwise conv breaks the GEMM mapping.
Decide between Winograd F(2,3) and implicit GEMM for FP32 vs FP16 inputs.
16
Chapter 16
Triton & CUTLASS: The Two Abstractions Above Raw CUDA
Learning goal. Most production kernels are no longer written in raw CUDA C++. Triton (Python-embedded tile-IR JIT) and CUTLASS (header-only C++ template library with CuTe layouts) cover ~90% of the kernel design space at a fraction of the engineering cost. By the end you can read a Triton kernel, walk a CUTLASS GEMM template, and decide which abstraction to reach for given a new problem.
16.1The Kernel-DSL Landscape
Why "raw CUDA" is rarely the answer in 2026
[A16.1.1]
Where Each Abstraction Lives
DSL
Layer
Examples
Best for
Tax
SASS (machine code)
hand-tuned ASM
Final 5% on a single hot kernel
Weeks per kernel, brittle
PTX (virtual ISA)
inline asm in CUDA
Specific instructions you can't get otherwise
Manual register management
CUDA C++
this book's Ch 2–5
Full control, mature tooling
~1000s LOC per kernel family
CUTLASS templates
cutlass::gemm::device
GEMM variants, full perf
Steep template syntax
CuTe layouts
cute::Layout
New algorithms with non-standard tiles
Layout algebra is its own language
Triton
@triton.jit
~80% of perf for ~20% of effort
Less control over scheduling
torch.compile / Inductor
auto-generated Triton
Fusing many small ops
You don't write the kernel
16.2Triton in Anger
A complete tiled GEMM in 35 lines of Python
import triton
import triton.language as tl
@triton.jit
def gemm_kernel(
A, B, C, M, N, K,
stride_am, stride_ak, stride_bk, stride_bn, stride_cm, stride_cn,
BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr,
):
pid_m = tl.program_id(0)
pid_n = tl.program_id(1)
offs_m = pid_m * BM + tl.arange(0, BM)
offs_n = pid_n * BN + tl.arange(0, BN)
offs_k = tl.arange(0, BK)
a_ptrs = A + offs_m[:, None] * stride_am + offs_k[None, :] * stride_ak
b_ptrs = B + offs_k[:, None] * stride_bk + offs_n[None, :] * stride_bn
acc = tl.zeros((BM, BN), dtype=tl.float32)
for k in range(0, K, BK):
a = tl.load(a_ptrs, mask=offs_k[None, :] < K - k, other=0.0)
b = tl.load(b_ptrs, mask=offs_k[:, None] < K - k, other=0.0)
acc += tl.dot(a, b) # Tensor Core mma
a_ptrs += BK * stride_ak
b_ptrs += BK * stride_bk
c_ptrs = C + offs_m[:, None] * stride_cm + offs_n[None, :] * stride_cn
tl.store(c_ptrs, acc, mask=(offs_m[:, None] < M) & (offs_n[None, :] < N))
[A16.2.1]
What Triton Does for You
triton
Lowers tl.dot directly to mma.sync on Tensor Cores.
Coalesces global loads automatically based on the layout of your tile.
Picks the shared-memory swizzle that avoids bank conflicts for your tile shape.
Pipelines load/MMA stages with double-buffered shared memory.
Runs an autotune search over (BM, BN, BK, num_warps, num_stages) when you use @triton.autotune.
What you give up: fine control over per-instruction scheduling, advanced Hopper features (cluster, TMA descriptors before 2024), and the ability to read the exact SASS without compiling and disassembling.
16.3CUTLASS Architecture
The five-level hierarchy that builds every GEMM kernel
[A16.3.1]
Device → Kernel → Threadblock → Warp → MMA Atom
cutlass
Device API — what you call from host code; chooses defaults.
Threadblock — owns one output tile, runs the K-loop with shared-memory tiles.
Warp — owns a fraction of the threadblock tile; issues mma.sync.
MMA Atom — one Tensor-Core instruction (m16n8k16 etc.), defined by a cute::MMA_Atom.
Each level is a template specialization. You configure them from the outside; the compiler stitches a kernel that is essentially identical to one a hand-tuner would write — but in 30 lines instead of 1500.
Layouts compose: layout1 ∘ layout2 is functional composition. Tiling, partitioning, swizzling, and gather/scatter are all just layout transformations. The whole CUTLASS 3 codebase is built on this algebra — once you grok it, you can express any access pattern your kernel needs without writing index math by hand.
Learning resource
The CuTe documentation has a 50-page tutorial that is the best single resource on GPU tensor algebra in existence. Reading it makes every other CUDA paper easier to follow.
16.5Choosing Your Abstraction
A decision tree
Figure 16.5
Pick the right tool
Checkpoint 16
Abstraction selection
Read the Triton GEMM listing and identify every line that picks Tensor Cores.
Name the five layers of the CUTLASS template hierarchy.
Write a CuTe Layout<Shape, Stride> for a 32×32 column-major tile.
Pick the right abstraction for: a new fused norm-bias-act kernel; a one-off research experiment; a permanent inference path.
17
Chapter 17
Debugging & Correctness: The Tools That Find What Profilers Can't
Learning goal. A fast wrong kernel is worse than a slow right one. This chapter equips you with every diagnostic the CUDA toolkit ships: compute-sanitizer (memcheck, racecheck, initcheck, synccheck), cuda-gdb, kernel asserts, device-side printf, and the numerical validation harness you should keep on every kernel from day one.
17.1The compute-sanitizer Suite
Four tools, run them all on every new kernel
[A17.1.1]
memcheck — Out-of-Bounds & Misaligned
memcheck
Reports any global, shared, or local memory access that goes past an allocation or violates alignment. Each launch is slower (5–50×) but the report is exact: PC, thread, address, allocation that "owns" the area.
compute-sanitizer --tool memcheck ./my_program
If your kernel passes memcheck in debug builds, ship it. If it fails, fix it before anything else — performance work on a UB'd kernel is wasted.
[A17.1.2]
racecheck — Shared-Memory Races
racecheck
Catches a thread writing a shared-memory location while another thread reads/writes the same location without an intervening barrier. Most common cause: forgot a __syncthreads() between the smem load and the smem read for a tiled GEMM.
[A17.1.3]
initcheck — Reading Uninitialized Memory
initcheck
Reports reads of memory the kernel never wrote. Common cause: forgot to zero an accumulator before the K-loop. Also catches the failing edge of an early-return when masking is incomplete.
[A17.1.4]
synccheck — Divergent Barriers
synccheck
Catches __syncthreads() reached by a non-uniform subset of the warp — undefined behavior since Volta's independent thread scheduling. Especially insidious because the bug may only manifest under specific scheduling.
CI workflow
Run all four sanitizers on a small test suite as part of CI. Slow, yes, but it catches the entire class of bugs that profilers will never surface. Set --check-cache-control yes for additional load/store policy checks.
17.2cuda-gdb Workflow
Set a breakpoint inside a kernel and inspect every thread
# Compile with debug info (-G) — disables optimization.
nvcc -G -g -arch=sm_80 kernel.cu -o kernel
# Start the debugger.
cuda-gdb ./kernel
(cuda-gdb) break gemm_kernel
(cuda-gdb) run
# Hit the breakpoint. List threads:
(cuda-gdb) info cuda threads
# Switch focus:
(cuda-gdb) cuda block (0,0) thread (3,2)
# Inspect registers and locals:
(cuda-gdb) print row
(cuda-gdb) print As[3][7]
# Step through:
(cuda-gdb) next
(cuda-gdb) continue
Trade-off
-G generates unoptimized device code — usually 3–10× slower. It's diagnostic only. For profiling, use -lineinfo which keeps optimization but preserves the source-line mapping.
17.3Race Conditions & Memory Ordering
When the bug only appears under load
[A17.3.1]
Atomic Doesn't Mean Ordered
atomics · ordering
atomicAdd on a global address is atomic w.r.t. other atomics on the same address, but offers no ordering relative to other reads/writes. To enforce a "I wrote X, now signal flag" pattern across blocks, you need __threadfence_system() (or PTX fence.sc.gpu) between the write and the flag set. Forgetting this produces a race only visible under high load when the scheduler interleaves blocks aggressively.
// Compute relative and absolute error vs a reference (CPU or higher precision).
double validate(const float* test, const float* ref, int N,
double rtol = 1e-3, double atol = 1e-5) {
double max_rel = 0, max_abs = 0;
int n_fail = 0;
for (int i = 0; i < N; ++i) {
double a = std::abs((double)test[i] - (double)ref[i]);
double r = a / (std::abs((double)ref[i]) + 1e-30);
max_abs = std::max(max_abs, a);
max_rel = std::max(max_rel, r);
if (a > atol && r > rtol) ++n_fail;
}
printf("max_abs=%e max_rel=%e fails=%d/%d\n", max_abs, max_rel, n_fail, N);
return max_rel;
}
Set tolerances honestly
For an FP16 Tensor-Core GEMM with FP32 accumulator, expect rtol ≈ 1e-3. For FP32 throughout, rtol ≈ 1e-5. For BF16, rtol ≈ 1e-2. If your test passes only at rtol = 1e-1, you have a bug, not a precision limit.
17.5Printf, Asserts, & Trap
The lo-fi diagnostics that still work
[A17.5.1]
Device-Side printf
printf
Device printf writes into a per-context circular buffer and flushes at kernel exit or on cudaDeviceSynchronize. Each call from each thread serializes onto a hardware FIFO — printing from all 32 lanes of a warp will reorder and may drop messages if the buffer overflows. Use the gating pattern:
Grow the buffer with cudaDeviceSetLimit(cudaLimitPrintfFifoSize, 16 << 20) if you're losing output.
[A17.5.2]
assert() in Device Code
assert
Standard C assert() works on the device. On failure it prints the failed expression with the block/thread index and traps the launch — the next cudaDeviceSynchronize returns cudaErrorAssert. Cheap insurance for invariants like "K is a multiple of 16" deep inside a kernel.
Checkpoint 17
Correctness habits
Name and describe each compute-sanitizer tool.
Sketch the cuda-gdb commands to focus on a specific (block, thread) pair.
Explain why atomic ≠ ordered.
Pick realistic rtol/atol for FP16/BF16/FP32 kernels.
Show the gating pattern for device-side printf.
18
Chapter 18
Performance Methodology: The Discipline Behind the Win
Learning goal. Beating cuBLAS is not about knowing one trick; it is about applying a disciplined loop of measurement, hypothesis, intervention, and re-measurement. This chapter codifies that loop so you can apply it to any kernel, not just GEMM. You will learn the SOL (speed-of-light) analysis Nsight Compute exposes, how to bound expected performance from first principles, how to set up an autotuner, and how to recognize and avoid the dead-ends every new kernel engineer falls into.
18.1The Optimization Loop
Five steps, in this order, always
[A18.1.1]
Measure → Bound → Hypothesize → Change One Thing → Measure Again
methodology
Measure — collect Nsight Compute counters with --set full. Read SOL %, achieved occupancy, memory throughput.
Bound — compute the theoretical best for this shape (roofline) and the realistic best (SOL minus known taxes).
Hypothesize — name the single bottleneck (memory BW, MMA throughput, occupancy, launch overhead, branch divergence).
Change one thing — adjust tile size or swizzle or pipeline depth. Never two at once.
Re-measure — if the bottleneck moved, repeat; if it didn't, your hypothesis was wrong.
18.2SOL & OAE Analysis
Two numbers Nsight Compute computes for you
[A18.2.1]
Speed-of-Light Percentages
sol
Nsight Compute reports SOL for compute, memory, and L2 throughput. They are percentages of the architectural peak achieved by your kernel over the time it actually ran. Interpretation:
SOL Memory > 80% → kernel is memory-bound at near-peak. Move math closer to the data or change algorithm.
SOL Compute > 80% → kernel is compute-bound at near-peak. Pick a better instruction (Tensor Core, FMA, sparse).
Both < 40% → you are stalled on something else (latency, scheduler, occupancy). Look at warp-state statistics.
[A18.2.2]
OAE — Occupancy-Adjusted Efficiency
oae
A kernel at 25% occupancy can still hit 80% SOL if it issues enough instruction-level parallelism per thread. OAE = SOL / (theoretical occupancy / 100). High OAE despite low occupancy means your kernel is doing ILP well; you don't need more threads. Low OAE despite high occupancy means each thread is stalled and adding more threads is the wrong answer.
18.3Autotuning Frameworks
Let the search find the tile size
[A18.3.1]
Search Spaces You Will Define
autotuning
Almost every GPU kernel has 4–10 knobs that interact non-linearly. Hand-picking the right combination is impractical. Express them as a Cartesian product, prune known-bad combos, evaluate the rest:
Threadblock tile (BM, BN, BK) — typically 8–24 valid combos.
Warp tile (WM, WN) — 2–6 valid sub-divisions.
Pipeline stages — 2, 3, 4.
Vectorization (128-bit vs 64-bit loads).
Split-K factor (1, 2, 4, 8).
Tools: Triton's @triton.autotune, CUTLASS Profiler, NVIDIA Kernel Generator, OpenAI's kbench. All produce a JSON or YAML pick-list keyed by problem size.
Pick a best-known config. For each knob, perturb by ±1 step and re-measure. The knobs whose perturbations change runtime by > 5% are your load-bearing knobs; the rest are noise. Future tuning effort should concentrate on the load-bearing ones.
This protects you from over-tuning a flat region of the search space and helps explain to teammates which choices matter.
18.5Recording & Reproducing Wins
Lab notebook discipline
[A18.5.1]
The Per-Experiment Card
documentation
Every experiment leaves a card with:
Date, git SHA, driver version, GPU model.
Exact kernel parameters and tile sizes.
Compile flags (nvcc -V, --ptxas-options).
Locked clocks (nvidia-smi -lgc) and locked power.
Median + 95% CI over ≥ 100 launches, with warmup discarded.
Nsight Compute report file (.ncu-rep).
This is how you defend a published "I beat cuBLAS by 12%" claim against the inevitable skeptic.
Sketch a Triton autotune config and a sensitivity-analysis plan.
List every field on a "good" experiment card.
19
Chapter 19
Hopper & Blackwell: The Next Two Architectures Demystified
Learning goal. Ampere is the focus of this book, but every concept you've learned has a Hopper analogue that delivers 2–3× more throughput when wielded correctly. This chapter is the reference layer for H100 and H200 (Hopper) and the early-look layer for B100/B200 (Blackwell): TMA descriptors, wgmma warp-group MMA, thread-block clusters with DSMEM, the Transformer Engine, and the FP4 instructions that change everything for low-precision inference.
19.1The Hopper SM — What Changed from Ampere
Every relevant per-SM number, side-by-side
Per-SM resource
A100 (sm_80)
H100 (sm_90)
Δ
FP32 cores
64
128
2×
FP64 cores
32
64
2×
Tensor Cores
4 (Gen 3)
4 (Gen 4)
~2× throughput
Register file
64K × 32-bit
64K × 32-bit
—
Shared memory + L1
192 KB
256 KB
+33%
Max shared memory
164 KB
228 KB
+39%
Max threads
2048
2048
—
Warps / SM
64
64
—
L2 cache (chip)
40 MB
50 MB
+25%
TMA engines
0
1 per SM
new
Cluster support
no
yes
new
DSMEM
no
yes
new
FP8 Tensor Cores
no
yes (E4M3, E5M2)
new
19.2TMA in Detail
The async-bulk-copy instruction that replaces a warp of cp.asyncs
[A19.2.1]
The Tensor Map Descriptor
tma
A TMA descriptor is a 128-byte opaque struct (CUtensorMap) created on the host with cuTensorMapEncodeTiled and passed to the kernel as a kernel param (which the driver staged into constant memory). It encodes:
Global base, per-dimension extents and strides.
Box size per dimension (the tile shape).
Element type (FP16/BF16/FP8/INT8/…).
Interleave mode (NONE, 32B, 64B, 128B — for image data).
Swizzle pattern (NONE / 32B / 64B / 128B).
L2 promotion policy and OOB fill behavior (zero, constant, copy).
A single PTX cp.async.bulk.tensor.{1d,2d,3d,4d,5d}.shared::cluster.global instruction, issued by one thread, kicks off the entire tile copy and signals an mbarrier on completion.
Hopper's new instruction that operates on 4 warps at once
[A19.3.1]
128 Threads, One MMA
wgmma · hopper
Ampere's mma.sync issues 1 instruction per warp (32 threads). Hopper introduces wgmma.mma_async which issues 1 instruction per warp group (4 warps = 128 threads), with the operands implicitly distributed across the warps. Sample shape: m64n128k16 fp16fp16fp32.
Asynchronous semantics: the wgmma fires off, the warps continue, and later commit/wait instructions stall until results are ready. This enables tighter overlap with the TMA loads above.
// Producer warp issues TMA copy and arrives on mbarrier.
cp.async.bulk.tensor.2d.shared::cluster.global [smem], [desc, coords], [mbar];
mbarrier.arrive.expect_tx.b64 [mbar], bytes;
// Consumer warp group waits, then issues wgmma.
mbarrier.try_wait.parity.b64 P0, [mbar], phase;
@P0 bra wait;
wgmma.fence.sync.aligned;
wgmma.mma_async.sync.aligned.m64n128k16.f32.f16.f16.f32 {d…}, descA, descB, scaleD, scaleC;
wgmma.commit_group.sync.aligned;
wgmma.wait_group.sync.aligned 0;
19.4Thread-Block Clusters & DSMEM
A new level above the threadblock
[A19.4.1]
Clusters: 16 Blocks That Talk Directly
cluster
A Hopper cluster is a group of up to 16 thread blocks (8 portably) that are guaranteed to be co-scheduled on adjacent SMs and can directly read/write each other's shared memory via DSMEM (Distributed Shared Memory). New launch syntax:
Why it matters: a 256×256 output tile that was too big for one block's SMEM can now span 4 blocks × 64×64 SMEM each, with one-hop DSMEM access. Used heavily in FlashAttention-3 and Hopper CUTLASS GEMMs.
5th-gen NVLink — 1.8 TB/s per GPU, 18-link NVSwitch fabric scaling to 576-GPU domains.
2-die "chiplet" GPU — first NVIDIA GPU built as two reticle-limit dies stitched with a 10 TB/s NV-HBI link, presented to software as a single device.
What stays the same: the SIMT execution model, the shared-memory bank layout, the CUDA C++ surface. Everything you learned in chapters 1–17 still applies — Blackwell mostly adds more dimensions to the same Tensor-Core / TMA / cluster axes Hopper opened.
Checkpoint 19
Forward compatibility
List the four new features Hopper added over Ampere.
Outline the TMA descriptor's fields.
Explain why wgmma is async and how that helps overlap.
Predict the kernel-design changes Blackwell's FP4 will require.
20
Chapter 20
Appendix: C++, Tooling, Statistics, & the Final Self-Test
Learning goal. A working reference: the modern-C++ features your kernels rely on, how to set up a clean CUDA toolkit and lock the GPU for benchmarking, the statistical method to defend a benchmark claim, a master cheat sheet of every number in the book, and a 50-question self-test that you should be able to answer without notes if you've worked through every chapter.
20.1C++ for CUDA Kernel Writers
The subset you actually need
[A20.1.1]
Templates, constexpr, and Why CUTLASS Looks Like That
c++
The C++ features every CUDA kernel author should know:
Function templates — let one kernel cover multiple tile sizes. template <int BM, int BN, int BK> __global__ void gemm(...).
constexpr — compile-time computation; the compiler folds BM * BK into an immediate.
auto + decltype — concise return types; useful for cooperative-groups / cute lambdas.
std::integer_sequence / index_sequence — unrolled loops at compile time without macros.
if constexpr — pick code paths based on template params with no branch in the binary.
CRTP (Curiously Recurring Template Pattern) — static polymorphism for epilogues without virtual cost.
SFINAE / concepts — overload resolution that respects device constraints.
Keep away from: exceptions (forbidden on device), RTTI, virtual functions across host/device, anything that allocates with global new in a kernel.
template <int BM, int BN, int BK, int TM, int TN>
__global__ void gemm(const float* A, const float* B, float* C, int M, int N, int K) {
float acc[TM][TN] = {};
#pragma unroll
for (int k = 0; k < BK; ++k) {
#pragma unroll
for (int i = 0; i < TM; ++i) {
#pragma unroll
for (int j = 0; j < TN; ++j) {
acc[i][j] = __fmaf_rn(/* loads */, /* loads */, acc[i][j]);
}
}
}
// ...store acc to C
}
20.2Driver, Toolkit, Install
How to set up a benchmark-ready box
# 1. Match driver to toolkit. CUDA 12.4 needs >= 550.54.
sudo apt-get install -y nvidia-driver-555
sudo reboot
# 2. Install the toolkit, not the bundled driver.
wget https://developer.download.nvidia.com/compute/cuda/12.4.1/local_installers/cuda_12.4.1_550.54.15_linux.run
sudo sh cuda_12.4.1_550.54.15_linux.run --toolkit --silent
# 3. Path setup.
echo 'export PATH=/usr/local/cuda-12.4/bin:$PATH' >> ~/.bashrc
echo 'export LD_LIBRARY_PATH=/usr/local/cuda-12.4/lib64:$LD_LIBRARY_PATH' >> ~/.bashrc
source ~/.bashrc
# 4. Verify.
nvidia-smi
nvcc -V
nsight-compute --version
# 5. (Benchmark prep) Lock the clocks.
sudo nvidia-smi -pm 1
sudo nvidia-smi --lock-gpu-clocks=1410,1410 # set to the boost clock you want
sudo nvidia-smi --lock-memory-clocks=1593,1593
# 6. (Optional) Enable persistence and disable autoboost.
sudo nvidia-smi --auto-boost-default=0
20.3Statistical Benchmarking
How to defend "12% faster than cuBLAS" against a skeptical reviewer
[A20.3.1]
Median, CI, and Coefficient of Variation
statistics
Warm up for 50 launches; discard those samples.
Sample N ≥ 200 launches.
Report the median, not the mean — kernel launches have a heavy right tail.
Coefficient of variation (CV = stdev/mean) should be < 2%. Higher means your measurement is contaminated by another process, thermal throttling, or driver scheduling. Stop and fix the rig before publishing.
95% confidence interval via percentile or bootstrap. "Median 38.4 µs (95% CI: 38.1–38.7)" is a real claim. "Mean 41 µs" is not.
Paired test when comparing two kernels — alternate them launch-by-launch to absorb shared environmental noise. Then use the per-pair difference for the CI.
Describe the data flow of FlashAttention-1 in 5 sentences.
Why does FlashAttention save memory, not compute?
Outline implicit-GEMM convolution and contrast it with im2col.
When is Winograd F(2,3) the wrong choice?
Name the five levels of the CUTLASS template hierarchy.
What does a CuTe Layout<Shape, Stride> express?
How does Triton choose a tile size?
What does compute-sanitizer --tool synccheck catch that memcheck doesn't?
List the four Nsight Compute views and what each one is for.
Define SOL and OAE.
State the speed-of-light ridge of an A100 in FLOPs/byte.
Why is the median preferred over the mean when reporting kernel times?
What is the CV of a well-conditioned benchmark, and why does it matter?
Explain how cudaMallocAsync differs from cudaMalloc.
Configure an L2 persistent carveout for a 32 MB tensor.
Describe what TMA descriptors encode.
Compare mma.sync and wgmma.mma_async.
What is DSMEM and why does it matter for big tiles?
Outline what the Transformer Engine library does each forward pass.
Name the four collectives in NCCL and one use case for each.
Why is tensor parallelism communication-heavy but pipeline parallelism communication-light?
Describe split-K vs stream-K dispatch.
Sketch a warp reduction using __shfl_down_sync.
Implement a block reduction in 10 lines of pseudocode.
What is decoupled lookback in a single-pass prefix scan?
Why are histograms a privatization-friendly workload?
Outline the persistent-kernel pattern and one workload that benefits.
Give the four-step optimization-loop discipline from §18.1, and apply it to a 35% SOL Memory kernel.
Closing
The chapters before this one give you the answers. If a question stumped you, return to the relevant chapter — the atomic-note IDs throughout the book mean every concept has a single landing page you can re-read in five minutes.