The idea in one sentence. A GPU runs one function, the kernel, on tens of thousands of threads in lockstep groups of 32, and almost every kernel is limited by the bytes it moves through a ladder of memories, so GPU programming is keeping every thread busy while moving fewer bytes per useful operation; each child page of this topic is one way to do that, or to check that you did.
p = torch.softmax(s, dim=-1) then o = p @ v: the running example, the heart of attention. On the CPU, PyTorch's dispatcher picks a CUDA kernel; nothing has run on the GPU yet. This page, section 1: dispatch, launch, and the three regimes every slow operation falls into.p @ v is a matmul: one matrix instruction per generation, mma, wgmma, tcgen05, at about 15 times an H100's float32 rate (section 7). Owner: Libraries and tensor cores (sections 5, 6), whose Fig. 2 draws one MMA instruction per generation to scale and Fig. 3 feeds one tile a K slice at a time.A map, not a mechanism: each step lights the part one child page owns, and links that child's own figure. Numbers are this page's runs on the Apple M1 Pro GPU and the H100 SXM specification it cites; the counts drawn (11 SMs, six HBM stacks, four warps, two GPUs) are illustrative.
You need (only if new to you): the roofline and arithmetic intensity, on Performance math; what an SM physically holds, on GPU architecture. Everything else is defined here. Neighbours: the chip itself (HBM, interconnects) is Topic: hardware; the CPU underneath (caches, SIMD) is C++: the machine underneath; the driver and the path from a launch to the device is Virtualization and the GPU driver stack.
nvcc, ptxas, Triton 3.8.0) produced in a container without a GPU; compiling needs no device, running does. vendor spec: datasheets and NVIDIA documentation, fetched 2026-10-05. published: papers and blog posts, kept apart from vendor claims. derived: computed from the formula shown. illustrative: an input chosen for the example. unconfirmed: a claim from the old page that could not be traced to a source. The current toolkit is CUDA 13.4.2 and Triton 3.8.0 (GitHub release, August 28, 2026) checked 2026-10-05; the old page's "13.3 latest, 13.4 in preview" and "3.7 is current" are out of date.The same two lines cost two trips through memory eagerly and one when fused
t = s * scale then p = torch.softmax(t, dim=-1), on the 8,192 by 8,192 float32 s. Top lane: the CPU; bottom lane: the GPU; arrows: traffic to and from GPU memory. illustrative timeline, not to scale in time
Traffic counts each full read or write of a 256 MiB matrix. Time at H100 bandwidth = bytes / 3.35 TB/s derived; the M1 Pro column uses the softmax bandwidth measured below. Whether Inductor fuses a given pair is visible in its generated code (TORCH_LOGS=output_code); a pointwise op feeding a reduction is the textbook case it fuses. Inductor's own log of this example, node by node, is stepped on The compiler stack, section 1.
Suppose s is an 8,192 by 8,192 matrix of float32 scores on the GPU (256 MiB) and you write p = torch.softmax(s, dim=-1). Four things happen, and only the last one runs on the GPU. Dispatch: the dispatcher reads the tensor's device and picks the CUDA implementation from the registry, native_functions.yaml (softmax_cuda_out, against softmax_cpu_out and softmax_mps_out). Choose a kernel: PyTorch's SoftMax.cu picks by row length; rows of at most 2,048 elements (and 8 KB) get one warp per row, longer rows like ours one thread block per row (8,192 blocks) read from PyTorch main, 2026-10-05. Launch: the CPU queues "run this kernel with this many blocks of this many threads" on a stream and returns immediately, so a Python timer around a GPU call measures almost nothing. Execute: the GPU hands blocks to its SMs; the CPU waits only when it needs a value (p.item(), .cpu()), a synchronisation. Which code runs depends on the operator: torch.matmul calls cuBLAS or cuBLASLt, F.scaled_dot_product_attention picks among FlashAttention, memory-efficient, cuDNN and a "math" fallback, and under torch.compile none of them may run, because TorchInductor "translates PyTorch programs into OpenAI's Triton for GPUs" (PyTorch 2 paper, ASPLOS 2024) and fuses the softmax with its neighbours.
Predict how many full reads and writes of the 256 MiB matrix each version makes, then follow the steps (the buttons on the figure switch versions).
Eager PyTorch: two kernels
t = s * scale. PyTorch's dispatcher sees a CUDA tensor and picks the CUDA multiply kernel. Nothing has run on the GPU yet.s (256 MiB) and writes t (256 MiB); meanwhile Python has already moved to the next line.t back from memory and writes p. Two kernels, four full passes over memory, for two lines of code.p.item(): the CPU waits. Only now does the CPU block, until the GPU has finished both kernels. Without this synchronisation a Python timer would have measured only the launches.torch.compile: one fused kernel
s once, multiplies by scale in registers, computes the row maximum and sum, and writes p. The intermediate t never exists in memory.p.item(): the CPU waits. The CPU blocks until the single kernel finishes.Measured on the M1 Pro GPU measured on Apple M1 Pro GPU: MLX's softmax over the same matrix took 3.2 ms (median of 3 runs, as every M1 number on this page), 166 GB/s counting one read and one write, which equals the M1 Pro's measured copy bandwidth (about 165 GB/s on Topic: hardware's Roofline lab). Softmax does a few operations per byte, so its speed is the speed of memory and the only way to make it faster is to move fewer bytes. The first of the three runs, taken while other jobs loaded the laptop, gave 43 GB/s (12.36, 3.23, 3.21 ms; load average 6.0): a median of 7 trials inside one disturbed run did not protect it, repeating runs did. The output matched a NumPy float32 reference to 3.7e-09.
Three regimes. Horace He's "Making Deep Learning Go Brrrr" names them: memory-bound (softmax, every elementwise and normalisation kernel), compute-bound (large matmuls, once tiling keeps the reuse on chip) and overhead-bound (kernels so small that the GPU idles between launches). On overhead: NVIDIA measured a 2.9 µs kernel at 9.6 µs per kernel when the CPU waited after each launch and 3.4 µs with a CUDA graph (NVIDIA blog, 2019, V100) published; the synchronisation, not the launch, costs most of the gap. Streams, CUDA graphs and multi-GPU programming, section 3, takes the numbers apart. On the M1 Pro, one tiny MLX operation launched and waited for took about 235 µs (runs 674, 197, 235), MLX's bookkeeping included, so not comparable to a bare CUDA launch; the lesson transfers: when kernels are small, use fewer, larger kernels or graphs. Section 2 maps every lever to the regime it attacks.
Kernel optimisation is a ladder: write the obvious version, find out what limits it, remove that limit, repeat until the limit is the hardware's. The levers below are the whole topic in one table. Read it by the first column: a lever only helps when its limit is the one that binds, which is why section 8's profiler comes before any of them.
| Lever | Limit it attacks | What it buys (evidence) | What it costs, or when it does not help | Owner |
|---|---|---|---|---|
Coalesced access: threadIdx.x walks the contiguous dimension | memory: wasted sectors | 8 times fewer sectors per warp than a stride of 32 floats derived; on the M1 Pro, stride 32 was 6.0 times slower measured; a naive matmul 4.8 times faster from swapping one index measured | layout work; sometimes a transpose staged in shared memory | GPU memory hierarchy, section 1 |
| Shared-memory tiles | memory: each value fetched once per thread that needs it | global loads fall by the tile width | shared memory per block lowers blocks per SM: on the M1 Pro 32 × 32 tiles ran slower than 8 × 8 (478 against 677 GFLOP/s) measured | GPU memory hierarchy, section 3 |
| Register tiles: each thread computes a small block of outputs | shared-memory bandwidth and instruction issue | 5.4 times across Boehm's kernels 3 to 5 published | registers per thread, so fewer warps; spills past the limit | Writing kernels, section 1 |
| Padding or swizzling shared memory | bank conflicts | M1 Pro: lane stride 32 at 113 billion reads/s against 394 at stride 33 measured | only matters when shared memory is the bottleneck | GPU memory hierarchy, section 4 |
| Enough warps and blocks (occupancy, waves) | latency | M1 Pro streaming: 11 GB/s with 256 threads in flight, 138 to 151 with 8,192 or more measured | a means, not a goal: fast matmul and attention kernels run at low occupancy on purpose | The CUDA programming model, section 5; GPU simulator |
| Warp-uniform branches | issue slots lost to divergence | M1 Pro, two equal branches split inside every warp: 1.86 times slower measured | rarely matters in matmuls and norms; often in masking, ragged inputs, MoE routing | The CUDA programming model, section 3; GPU simulator |
| Fusion | memory: intermediates written and read back | k memory-bound operations cost close to one; eager softmax took 4.0 times the single kernel on the M1 Pro measured | rarely pays between two compute-bound matmuls; torch.compile already fuses elementwise chains | Writing kernels, section 5; section 5 here |
| Online softmax, FlashAttention | memory: the N × N scores | whole attention at N = 8,192 on the M1 Pro: 1,056 MiB to 32 MiB measured | recomputes scores in the backward pass | Writing kernels, section 7 |
| Tensor cores (mma, wgmma, tcgen05) | compute | H100: about 15 times its float32 rate (989.5 against 67 TFLOP/s dense) vendor spec | code tied to one generation; low-precision formats | Libraries and tensor cores, section 5 |
| Asynchronous copies, TMA, warp specialisation | load latency stalling the math | the next tile loads while this one is multiplied | shared memory per pipeline stage; complexity | GPU memory hierarchy, section 7; Libraries and tensor cores, section 6 |
| Split-K, Stream-K, tile choice | too few tiles to fill the SMs (the last wave) | idle SMs get work | an extra reduction | Libraries and tensor cores, section 3 |
| Fewer launches: CUDA graphs, larger kernels | overhead | 9.6 to 3.4 µs per kernel (section 1) published | captured shapes and addresses are fixed | Streams, CUDA graphs and multi-GPU programming, sections 3 and 4 |
| Overlap on streams (copies, NCCL) | idle time between dependent work | data-parallel training hides its all-reduce behind backward compute | ordering bugs, hangs | Streams, CUDA graphs and multi-GPU programming, sections 1, 6, 7 |
Number formats themselves (BF16, FP8, FP4, scaling) are owned by Quantization and Precision; their library paths by Libraries and tensor cores, section 8. The roofline that tells you which limit binds is Performance math's.
The problem. A GPU has tens of thousands of arithmetic lanes and wants hundreds of thousands of independent pieces of work in flight. So you write one function, the kernel, and launch it on many threads; each thread works out from its own index which piece of data is its job. Four nested words describe how the threads are grouped:
__syncthreads(). Blocks must not depend on each other: the GPU runs them in any order on any SM, which is why the same program runs on a GPU with 20 SMs or 170.SIMT (single instruction, multiple threads): you write scalar code for one thread, the hardware issues each instruction once for a whole warp. It is SIMD without writing the vectors, and its catch is the branch: if the 32 threads of a warp disagree on an if, the warp runs both paths one after the other with the other lanes masked (warp divergence). On the M1 Pro, two equally heavy branches split inside every warp ran 1.86 times slower (2.82 against 1.52 ms) measured on Apple M1 Pro GPU: the sum of the two paths, not 32 times, because lanes are masked, not serialised one by one. A branch that is the same for a whole warp costs nothing.
Latency hiding. A read from GPU memory takes hundreds of cycles. A GPU hides it by switching warps: every resident warp keeps its registers on the SM, so when one waits the scheduler issues from another at no cost. Occupancy, resident warps over the maximum (64 per SM on an H100), is limited by whichever runs out first: registers per thread, shared memory per block, threads per block or the cap on blocks. A kernel launched with fewer blocks than the GPU has SMs leaves most of the chip idle. The GPU simulator steps all three (divergence; occupancy, whose calculator agrees with NVIDIA's own cuda_occupancy.h on all 1,988 tested cases; and latency hiding) with the M1 Pro measurements beside each.
The problem. An H100 SXM can do 989.5 trillion BF16 operations per second on its tensor cores (dense) but fetch only 3.35 TB per second from its memory vendor spec: about 295 operations for every byte it reads derived: 989.5e12 / 3.35e12. A float32 softmax does about five operations per element, under one per byte moved derived: 5 / 8 bytes read and written. Almost every kernel would starve if each operand came from main memory, so the chip has a ladder of smaller, faster memories: registers (one thread, about one cycle), shared memory and L1 (one block or SM, tens of cycles), L2 (the whole GPU, 50 MB on an H100) and HBM (every tensor, hundreds of cycles away). Much of kernel writing is deciding which rung each piece of data lives on.
Three rules follow, each owned and drawn by GPU memory hierarchy: make neighbouring threads touch neighbouring addresses, because a warp's 32 loads are served in 32-byte sectors (coalescing, its section 1); stage a tile in shared memory once and let every thread of the block reuse it, so global loads fall by the tile width (tiling, section 3); and lay the tile out so a warp's reads hit 32 different banks (banks and swizzles, section 4). Registers are the scarcest rung: a kernel that needs more than 255 per thread spills to "local memory", which lives in DRAM behind the caches; the Compiler explorer's register-pressure ladder ends in 1760 bytes spill stores, 1184 bytes spill loads on sm_90a compiled here.
The N × N matrices are almost all the traffic, and fusion removes them
Bars in HBM are drawn to scale in bytes (BF16, 2 bytes). Traffic counts each tensor read or written once per kernel; the fused count is the ideal (in FlashAttention each block of Q re-reads K and V, which for one head is a few MB and is mostly served from the 50 MB L2). Times at H100 SXM rates: memory = bytes / 3.35 TB/s, compute = 4N²d × heads / 989.5 TFLOP/s derived; the slower of the two bounds the kernel.
When several operations run as separate kernels, each writes its result to HBM and the next reads it back. Fusion runs them in one kernel so the intermediate stays in registers or shared memory. Attention is the example that changed the field: S = QKT, P = softmax(S), O = PV, where the two N × N matrices dwarf the inputs (with head size d = 128, S is N / 128 times the size of Q). FlashAttention (Dao et al., 2022) never forms them in memory: it streams blocks of K and V past a block of Q on chip and folds each block of scores into the output with the online softmax, a running maximum and sum that rescale when a larger value arrives (Milakov and Gimelshein, 2018). Predict how the bytes of the two versions grow as you double N, then follow the steps (the buttons on the figure switch versions; the selectors change the sizes).
Unfused: three kernels, S and P in HBM
Fused (FlashAttention-style): one kernel
Measured on the M1 Pro GPU measured on Apple M1 Pro GPU: 8 heads, d = 64, float16, three separately evaluated steps (so S and P really go to memory) against MLX's fused scaled_dot_product_attention; outputs agree to within 0.00024 at N = 4,096, inside float16 rounding.
| N | Unfused, ms | Fused, ms | Speedup | runs (unfused / fused) |
|---|
The Kernel lab built both steps as its own Metal kernels: softmax then a matmul at N = 8,192, unfused 7.00 ms with 520 MiB in memory, fused with the online softmax 4.38 ms with 260 MiB; whole attention, 53.5 ms and 1,056 MiB against 30.2 ms and 32 MiB.
Why only about 1.3 to 1.4 times here, when the bytes fall by far more? On this laptop the unfused version is roughly balanced: at N = 4,096 it moves 1.09 GB, 6.6 ms at 165 GB/s, against 6.9 ms of arithmetic at the M1 Pro's 5 TFLOP/s derived. Its ridge point (peak operations per byte of bandwidth) is about 30; an H100's is about 295, so the same unfused attention there spends 4.8 times longer moving bytes than computing (the default above), and fusion pays far more. What transfers: the byte arithmetic, and the memory column (at long context the unfused version does not fit). What does not: the size of the win, which grows with the chip's ratio of compute to bandwidth, and that ratio has grown every generation.
The same softmax can reach the GPU five ways. They differ in what you write and what someone else decides for you; most of the time you should not write the kernel at all.
| Way | You write | Decided for you | Reaches tensor cores through | When it is the answer | Owner |
|---|---|---|---|---|---|
| torch.compile | ordinary PyTorch | which operations fuse; the Triton code; matmuls go to cuBLAS by default | cuBLAS, or Triton templates under mode="max-autotune" | first, always: it already writes Triton for you | The compiler stack, section 8 |
| A library: cuBLAS, cuBLASLt, cuDNN, CUTLASS, CCCL (Thrust, CUB), NCCL | a call | the kernel, picked by a heuristic; epilogues (bias, GELU, scaling) in cuBLASLt | built in | any standard GEMM, convolution, attention, reduction, scan or collective | Libraries and tensor cores, sections 1 to 4 |
| Triton | what one program does to whole blocks | threads, vector loads, shared memory, synchronisation, the instruction per target | tl.dot | an algorithm the compiler cannot express or schedule well: attention variants, quantised or mixed-format matmuls, fused MoE routing | Triton and Gluon |
| Gluon, CuTe DSL | layouts, async copies, warp specialisation, in Python | less: you take back what Triton hides | wgmma, tcgen05 explicitly | peak kernels without C++ templates; FlashAttention-4 is written in CuTe DSL | Triton and Gluon, section 10; Libraries and tensor cores, section 7 |
| CUDA C++, CUTLASS | what one thread does, and all the cooperation | only register allocation and instruction scheduling | mma.sync, wgmma, tcgen05, or CUTLASS/CuTe | control Triton hides, or the last few percent on a kernel that dominates the profile | Writing kernels; Libraries and tensor cores, section 7 |
The same row softmax by hand in CUDA and in Triton, both as compiled in the Compiler explorer, shows the difference in one screen:
for (int j = threadIdx.x; j < ncols; j += 256) m = fmaxf(m, xr[j]); // pass 1: max m = warp_max(m); if (lane == 0) red[warp] = m; __syncthreads(); m = (lane < 8) ? red[lane] : -INFINITY; m = warp_max(m); __syncthreads(); for (int j = threadIdx.x; j < ncols; j += 256) s += __expf(xr[j] - m); // pass 2: sum // ... same two-level reduction for s ... for (int j = threadIdx.x; j < ncols; j += 256) yr[j] = __expf(xr[j] - m) * inv; // pass 3
@triton.jit
def softmax(x_ptr, y_ptr, ncols, stride, BLOCK: tl.constexpr):
row = tl.program_id(0) # one program per row
offs = tl.arange(0, BLOCK)
mask = offs < ncols
x = tl.load(x_ptr + row * stride + offs,
mask=mask, other=-float("inf"))
x = x - tl.max(x, axis=0) # reduction: compiler's job
e = tl.exp(x)
tl.store(y_ptr + row * stride + offs,
e / tl.sum(e, axis=0), mask=mask)tl.program_id replaces blockIdx; tl.arange with a mask replaces per-thread indexing and bounds checks; tl.max and tl.sum emit the shuffles written by hand on the left. One Triton matmul source, compiled here without a GPU, picks HMMA on sm_80 and sm_120, HGMMA on sm_90a and UTCHMMA on sm_100a compiled here. The often-quoted "within 0 to 20% of expert CUDA in a tenth of the code" is a rule of thumb from the old page unconfirmed as a general figure; the line counts above are one data point.
A tensor core multiplies small matrix tiles in one instruction. You reach it, from most to least abstract, through a library, Triton's tl.dot, CUTLASS/CuTe, or PTX directly, and the instruction changed shape every generation, which is what makes peak kernel code generation-specific:
| Generation | Instruction (PTX, then SASS) | Issued by; accumulators in | Fed by |
|---|---|---|---|
| Ampere sm_80 (and consumer sm_86, sm_89, sm_120) | mma.sync → HMMA | one warp; registers | cp.async |
| Hopper sm_90a | wgmma → HGMMA | a warpgroup of 4 warps, asynchronously; registers, operands from shared memory | TMA: one thread starts a bulk tile copy |
| Datacenter Blackwell sm_100a | tcgen05.mma → UTCHMMA | one thread for the block; TMEM, tensor memory beside the SM | TMA |
The trap compiled here: wgmma assembles only for sm_90a and tcgen05 only for sm_100a, while TMA and clusters compile for sm_90a, sm_100a and sm_120. So an RTX 5090 (sm_120) has TMA and clusters but no wgmma, tcgen05 or TMEM, and a Hopper tutorial does not run on it as written; the a suffix marks features that do not carry forward. A modern Hopper or Blackwell kernel is warp-specialised: producer warps only issue TMA copies, consumer warps only issue matrix instructions, linked by barriers in shared memory with several tiles in flight. Once you can name those four parts, FlashAttention-3 or a CUTLASS mainloop becomes readable.
Two instruction sets. PTX is NVIDIA's virtual instruction set, stable text that belongs to no chip; SASS is one architecture's machine code and changes every generation. nvcc compiles a .cu file's GPU part to PTX, ptxas turns PTX into SASS for each target named (-arch=sm_90a), and both go into a fat binary; a binary with PTX but no SASS for the GPU it lands on is compiled by the driver just in time, which is how old binaries run on new GPUs. Each generation has a compute capability (8.0 for A100, 9.0 for H100, 10.0 for B200, 12.0 for the RTX 5090); build for the one you run on (-arch=sm_120 or -arch=native), and note that sm_100 and sm_120 need CUDA 12.8 or newer (CUDA 12.8 release notes). nvcc -Xptxas -v reports registers, shared memory and spill bytes per kernel: the numbers that set occupancy. Reading SASS is where you confirm that a load is vectorised (LDG.E.128), shared memory is used (LDS), tensor cores are used (HMMA, HGMMA, UTCHMMA) and nothing spills (STL, LDL). The vector-add kernel compiles to 12 registers per thread on sm_90a compiled here; its PTX and SASS line by line open the Compiler explorer.
Profile before optimising. The two NVIDIA tools answer different questions:
Nsight Systems (nsys) | Nsight Compute (ncu) | |
|---|---|---|
| Answers | where does the wall-clock time go? | why is this one kernel slow? |
| Shows | a timeline: CPU threads, API calls, launches, copies, NCCL, gaps | counters: Speed of Light (compute and memory as a share of peak), occupancy, warp stalls, sectors per request |
| Cost | cheap, so always first | replays the kernel many times; point it only at kernels the timeline convicted |
Speed of Light places a kernel at once: memory high and compute low means memory-bound (move fewer bytes, fuse); compute high means compute-bound (tensor cores, lower precision); both low means latency-bound (too few warps, divergence, a tail of idle SMs, or a tiny kernel). Then time honestly: synchronise (a launch returns at once), warm up, mind the L2, report a median with its spread over repeated runs, and compare against torch.compile and cuBLAS, not eager. And check the answer against a higher-precision reference with a tolerance for the data type, at sizes that are not multiples of the tile: the Kernel lab records a synchronisation bug in its fused kernel that passed every small test and corrupted 1 to 5 random rows per run at 4,096 rows, fixed with a full threadgroup barrier; on NVIDIA, compute-sanitizer --tool racecheck is built for this class of bug.
ncu locks clocks to base by default. The Nsight Compute CLI documentation (v2026.3.1) lists --clock-control default boost (base, force-boost and none are options) and --cache-control default all (caches flushed between replays): check the version you run. Triton's do_bench has no flush_l2 argument; it always clears the L2 by zeroing a 256 MB buffer before each timed run (testing.py, read 2026-10-05).Everything above is a few ideas (many threads in lockstep groups, a memory ladder, tiles, fusion) under different names. The mapping lets you read code for any GPU:
| CUDA | AMD HIP / ROCm | Apple Metal | Triton |
|---|---|---|---|
| thread | thread (work-item) | thread | (hidden) |
| warp, 32 threads | wavefront: 64 on CDNA 3 and 4 (Instinct up to MI355X), 32 on RDNA (Radeon); the MI455X advertises Wave32 | SIMD-group, 32 on Apple GPUs | num_warps |
| thread block | block (workgroup) | threadgroup | program instance |
shared memory, __syncthreads() | LDS (local data share), __syncthreads() | threadgroup memory, threadgroup_barrier() | (compiler-managed) |
| global memory | global memory | device memory (shared with the CPU) | pointers |
| warp shuffle | wavefront shuffle (same intrinsics) | simd_shuffle, simd_sum | tl.sum, tl.max |
tensor core (mma, wgmma, tcgen05) | matrix core (MFMA) | simdgroup_matrix 8 × 8 | tl.dot |
Wavefront sizes: HIP programming model and AMD Instinct MI400 ("Wave32 execution"), read 2026-10-05 vendor doc. Apple's SIMD-group width of 32 was read from the M1 Pro's own Metal device by the GPU simulator.
AMD. HIP is AMD's CUDA-like C++ ("the Runtime API serves the same role within ROCm as the CUDA Runtime API does in NVIDIA's stack"); most PyTorch kernels reach Instinct parts through Triton's AMD backend. The wavefront of 64 is the porting trap: warp-sized assumptions (a 32-bit lane mask, 32-way reductions) silently break, so check the target before assuming 32 or 64. Apple. The M1 Pro is a real SIMT GPU, which is why this page could measure divergence, latency hiding and fusion on it. Its memory is unified: CPU and GPU share one DRAM (about 165 GB/s measured, against 3.35 TB/s of HBM on an H100), so there are no host-to-device copies and much less bandwidth; kernels are Metal Shading Language, or from Python MLX's mx.fast.metal_kernel, which is how this page's labs ran them; PyTorch's mps device runs on Metal too.
Reading times are each page's header (2026-11-12): core minutes, plus closed details.
A path from PyTorch user to kernel author, written for a laptop plus rented GPUs (times are reading or working estimates): the model and the memory ladder (children 1 and 2, about 4 h with PMPP chapters 1 to 6, and Horace He's "Brrrr", 25 min); first kernels on the Mac (a weekend: vector add, softmax and a tiled matmul as Metal kernels through MLX, predicting each step of child 3's ladders before you time it); Triton (about 3 h: official tutorials 01, 02, 03 and 06 under TRITON_INTERPRET=1, then Sasha Rush's Triton-Puzzles); read compiler output (2 h, compiling for sm_90a and sm_120 without a GPU as the Compiler explorer does); rent a GPU for a day (an H100 at about $3.99 per GPU-hour on demand at Lambda, fetched 2026-10-05) to run Boehm's kernels 1 to 6 and your Triton kernels under Nsight, timed honestly (child 7); a real fusion project (a fused RMSNorm with a matmul epilogue, a dequantise-and-multiply kernel, or a FlashAttention variant, in Triton first and CUDA second, against torch.compile and cuBLAS, written up as a worklog); then read production kernels (FlashAttention-2 in CUDA, FlashAttention-4 in CuTe DSL, CUTLASS examples, ggml-cuda, vLLM's attention kernels). The GPU MODE lectures follow roughly this order, and its Discord and kernel leaderboard supply graded practice. Resources with times are in Further reading.
What is a warp, and why does it matter for performance? 32 threads that execute one instruction at a time together. Branch divergence, memory coalescing and shuffles are all defined per warp; a warp is the unit the scheduler switches between to hide latency.
Why is softmax memory-bound and matmul compute-bound? Softmax does a handful of operations per element read, under one per byte, far below the roughly 295 operations per byte an H100 needs to be compute-bound. An N × N matmul does 2N³ operations on 3N² values, so its intensity grows with N, provided tiling keeps the reuse on chip.
What does shared memory buy you in a matmul? Each tile of A and B is fetched from global memory once and reused by every thread in the block, cutting global traffic by the tile width; register tiling repeats the trick one level down.
Explain FlashAttention in three sentences. Standard attention writes the N × N score and probability matrices to HBM. FlashAttention tiles Q, K and V so each block of scores is computed and consumed on chip, using the online-softmax rescaling to combine blocks, and recomputes scores in the backward pass instead of storing them. It does the same FLOPs with far fewer HBM bytes and O(N) extra memory.
High occupancy is good, right? Only as a means. It helps memory-bound kernels hide latency; fast matmul and attention kernels run at low occupancy on purpose because registers per thread buy reuse. Measure achieved bandwidth or FLOPs, not occupancy.
Your custom kernel is 2 times faster than PyTorch. What do you check before believing it? Correctness against a reference at several sizes; synchronisation and warmup in the timing; L2 effects (data larger than the cache, or flushed); the baseline (compiled, right dtype and layout); clocks and load; spread over repeated runs.
What is the difference between PTX and SASS? PTX is a stable virtual instruction set; SASS is the real machine code of one GPU generation, produced from PTX by ptxas (or by the driver at load time). You read SASS to see what really runs: vector loads, tensor-core instructions, spills.
Why does a Hopper kernel not run on an RTX 5090? sm_120 has TMA and clusters but not wgmma, tcgen05 or TMEM; a Hopper kernel built on wgmma will not even assemble for it. Consumer Blackwell kernels look like Ampere ones (mma.sync, register accumulators) plus TMA.
Nsight Systems or Nsight Compute first? Systems: it shows where the time goes across the whole program (gaps, overlap, launch overhead) at little cost. Then Compute on the kernels the timeline convicts, to see why each is slow.
When would you write Triton, CUDA, or neither? Neither if torch.compile or a library already does it. Triton for a new fusion or algorithm. CUDA or CUTLASS when you need control Triton hides (warp specialisation, exotic layouts) or the last few percent on a kernel that dominates the profile.
Three small machines that show how an SM runs the code you write: how a warp runs a branch, how many warps fit on an SM, and how warps hide memory latency. Coalescing, shared-memory banks, the 32 by 32 transpose and tiling, with their M1 Pro measurements, are taught where they are owned: GPU memory hierarchy, sections 1, 3 and 4. Each runs in your browser, step by step, on one input you can change; each opens on its finished run, and you can replay it one step at a time. The ideas themselves are drawn on The CUDA programming model: Fig. 2 (a branch in a warp) and Fig. 3 (occupancy on one SM); what this tab adds is any input you choose, an occupancy calculator checked against NVIDIA's own, and the M1 Pro measurements. Where the Apple M1 Pro GPU this page was built on can show the same effect for real, the measured number sits next to the simulation.
cuda_occupancy.h from CUDA 13.4.2) and cross-checked against real ptxas output from the Compiler explorer. The Apple M1 Pro GPU is a real SIMT GPU of the same family of ideas: it runs threads in SIMD-groups of 32 (read from the GPU itself with threads_per_simdgroup), groups them into threadgroups that share a fast on-chip threadgroup memory, and streams from DRAM. So the same effects show up, but its sizes and rules are Apple's, mostly undocumented. Each measured card says what transfers to an NVIDIA GPU and what does not.threadIdx and its own registers.__syncthreads(). Apple: threadgroup.The problem. You write a kernel as if each thread were on its own, with ordinary if statements. But the hardware fetches and issues one instruction for a whole warp of 32 threads. When the threads of one warp disagree about a branch, the warp cannot go both ways at once: in NVIDIA's words, "the warp executes each branch path taken, disabling threads that are not on that path" (CUDA Programming Guide 3.2.2.1, SIMT execution model). The disabled lanes sit idle. Different warps never slow each other this way: "branch divergence occurs only within a warp".
How to read the picture. Each row is one instruction issued for the warp; each of the 32 squares is a lane. A filled square did useful work; an empty one was switched off by the active mask, the 32-bit mask of lanes that take part. Two warps (64 threads) run the same code below. Count rows: rows are time.
threadIdx.x % 2 splits every warp 16 / 16, both branches 4 instructions long. How many more issue slots than the version that branches per warp?
__syncwarp() or the *_sync warp intrinsics (Programming Guide 3.2.2.1.1).Dense matmuls and elementwise kernels have no data-dependent branches, so divergence rarely matters there. It does in masked attention, variable-length (packed) sequences, mixture-of-experts routing and sampling. The fix is to make the decision per warp or per block instead of per thread. FlashAttention-2 does exactly this for the causal mask: it skips whole blocks that are fully masked, "approximately half of the blocks for large sequence length", for a 1.7 to 1.8x speedup, and applies the per-element mask only on the diagonal blocks (Dao, 2023, section 3.1.1).
Check in Nsight Compute: the Source Counters section reports branch efficiency per line; derived__avg_thread_executed (thread instructions per warp instruction) is 32 when no lane is ever idle (Nsight Compute Profiling Guide, last updated 2026-08-27).
The problem. An SM runs many warps at once so that while some wait for memory, others compute (section 3 shows why that matters). How many fit is decided when the block is placed: every warp gets its registers and every block its shared memory for its whole life, out of fixed per-SM budgets. Occupancy is the number of resident warps divided by the maximum the SM can hold. Four limits apply, and the smallest wins:
Per-SM limits: CUDA Programming Guide, Compute Capabilities, Tables 30 and 31 (last updated 2026-09-10). Allocation rules: NVIDIA's occupancy calculator header cuda_occupancy.h, CUDA 13.4.2, which this calculator ports line by line.
The Compiler explorer's register ladder compiles a kernel in which each thread keeps 128 running sums, the way a register-tiled matmul keeps its piece of the output; ptxas gives it 168 registers per thread. The animation fills one SM's register file warp by warp, blocks of 128 threads, until the next block no longer fits, then does the same with the kernel capped at 128 registers (what __launch_bounds__(128, 4) or -maxrregcount=128 asks for). The register file is drawn to scale: 4 sub-partitions of 16,384 registers, one cell per 256.
ptxas would have to spill some to "local memory", which lives in DRAM behind the caches; the register ladder in the Compiler explorer shows the spill bytes appear past 255. Fewer warps that each keep more data in registers often win: Volkov's "Better performance at lower occupancy" showed matmul and FFT kernels running fastest at low occupancy by giving each thread more independent work (GTC 2010), and today's FlashAttention and CUTLASS kernels often run only one or two large blocks per SM on purpose. Occupancy matters when a kernel is waiting on memory and has nothing else to do, which is the next section.You meet occupancy when a custom kernel (Triton or CUDA) is slower than expected: Triton's num_warps and num_stages and a block size that uses too much shared memory change it directly. A Triton autotune sweep is in effect a search over this calculator's inputs.
Check: compile with -Xptxas -v (or read the Compiler explorer) for registers and shared memory; Nsight Compute's Occupancy section reports Theoretical Occupancy (sm__maximum_warps_per_active_cycle_pct, what this calculator computes) against achieved occupancy; "large discrepancies between the theoretical and the achieved occupancy during execution typically indicates highly imbalanced workloads" (Profiling Guide). At run time, cudaOccupancyMaxActiveBlocksPerMultiprocessor gives the same answer.
The problem. A load from DRAM takes hundreds of cycles to come back. Microbenchmarks measured average global-memory latencies of 466 cycles on an A100, 479 on an H800 (a Hopper H100 variant) and 542 on an RTX 4090, against about 29 to 30 cycles for shared memory and 262 to 273 for the L2 cache (Luo et al., 2024, Table IV; independent measurements, not NVIDIA figures). A GPU does not hide this with big caches or out-of-order execution like a CPU. It hides it with other warps: each SM sub-partition has a warp scheduler that, every cycle, picks one warp whose next instruction is ready and issues it. Nsight Compute's words: active warps that are not stalled are eligible; the scheduler issues from one of them; "on cycles with no eligible warp, the issue slot is skipped" (Profiling Guide, Scheduler Statistics).
The model. One scheduler, W warps, each running the same loop: issue k independent loads, wait L cycles for them, then k x c instructions that use the data. The scheduler issues one instruction per cycle and keeps issuing from the same warp until it stalls, then switches to the warp that has been ready longest ("greedy then oldest"). Little's law gives the answer the simulation lands on: the scheduler is kept busy when W x k(c + 1) ≥ k(c + 1) + L, so utilisation = min(1, W·k(c+1) / (k(c+1) + L)).
cp.async, TMA) with double buffering do.It explains why small kernels are slow: a softmax over a few rows, a decode step at batch 1, or a launch with fewer blocks than the GPU has SMs leaves schedulers idle. It is the reason behind "fuse small kernels", CUDA graphs, and split-K or persistent kernels that keep every SM busy. The Kernel lab shows it on real attention kernels; the softmax ladder is in Writing kernels, section 4.
Check in Nsight Compute: Scheduler Statistics (eligible warps per cycle, and the share of cycles with no eligible warp) and Warp State Statistics, where a large "stall long scoreboard" means warps are waiting on L1TEX (global or local memory) operations (Profiling Guide).
if (threadIdx.x < 16) with two branches of equal length. What does it cost?threadIdx.x / 32 instead costs nothing extra, because divergence only happens inside a warp.When you call torch.matmul or launch a kernel you wrote, the GPU does not execute your C++ or Python. It executes SASS, the machine code of one specific GPU generation. This tab follows real kernels through the real NVIDIA compiler, from source to PTX (a portable assembly language) to SASS, for four generations: sm_80 (A100, Ampere), sm_90a (H100 and H200, Hopper), sm_100a (B200 and GB200, datacenter Blackwell) and sm_120 (RTX 5090, consumer Blackwell). You learn to read what the compiler tells you: how many registers each thread needs, how much shared memory a block uses, whether anything spilled, which instructions do the arithmetic, and how many threads can therefore run at once.
Every PTX listing, SASS listing, register count, spill count and error message below was produced by NVIDIA's own compiler (nvcc, in the Linux arm64 build of the CUDA toolkit, run in a Docker container on a laptop) and, for the Triton kernels, by Triton's own compiler (Triton) asked for each GPU target explicitly. No NVIDIA GPU was used: compiling needs no GPU, running does. So nothing here is a timing; real timings of kernels like these, on the Apple M1 Pro's GPU, are in the Kernel lab and the Kernel bench tab of Writing kernels. Occupancy figures are derived: computed from the compiler's resource numbers and NVIDIA's documented per-SM limits, and checked against NVIDIA's own occupancy calculator code. Scripts and every raw output are in the page's src/compile/ folder (run_all.sh reproduces them).
A compiler works in stages, each turning one language into a lower one. Follow the single line that adds two numbers in a vector-add kernel through every stage. Then switch to Triton and watch the same addition take a different road to the same kind of machine code. Click a stage, or step through: the figure opens on the last stage, the SASS that runs.
The compiler stages themselves are taught, one form at a time, by The compiler stack, whose Fig. 4 takes the row softmax down the nvcc road, and by Triton and Gluon, whose Fig. 3 takes one operation down Triton's compiler. This widget keeps what they do not show side by side: this toolchain's real output for one line on both roads.
Pick a kernel from the ladder (each step adds one idea) and a GPU target. Click any line of source: the PTX and SASS lines the compiler produced from it light up (the mapping comes from the compiler's own line tables, .loc in PTX and nvdisasm -g for SASS). Click a SASS line for a plain-words meaning of its instruction, taken from NVIDIA's instruction-set table. Above the listings, the compiler's resource report and what it implies.
The naive matmul reads both operands of every multiply-add from global memory. The tiled version first copies a 32 by 32 tile of A and of B into shared memory, then does 32 multiply-adds per element from there. In C++ the two inner loops look almost the same. In SASS the difference is plain: count the loads that go to global memory (LDG) against the loads from shared memory (LDS) for every fused multiply-add (FFMA). The animation steps through the real inner loop the compiler produced, one instruction at a time, with running counters.
The figure opens on the whole inner loop; switch kernels or targets, or replay it one instruction at a time.
Each thread loads one element of A and one of B per tile (8 bytes) and then does 32 multiply-adds with values from shared memory, so global traffic per multiply-add falls from 8 bytes to 8/32 = 0.25 bytes. (Caches soften the naive kernel's real traffic: neighbouring threads read the same row of A, which the L1 cache can serve. The instruction count does not lie, though: the naive loop still issues two global loads per FFMA.)
An FFMA does one multiply-add per thread, so 32 per warp instruction. A tensor core is a unit on the SM that multiplies small matrices in one instruction. Each generation made that instruction bigger and moved more of the work off the threads: the warp-level mma.sync (SASS HMMA, the form every generation since Volta has) is issued by one warp with operands in registers; Hopper's wgmma (SASS HGMMA) is issued by a warpgroup of four warps and reads its operands straight from shared memory; datacenter Blackwell's tcgen05.mma (SASS UTCHMMA and relatives) is issued by a single thread, reads shared memory and accumulates into Tensor Memory (TMEM), a separate on-chip store of 256 KB per block (512 columns x 128 lanes x 4 bytes, PTX ISA), so the accumulator no longer occupies registers at all. The chart counts multiply-adds per issued instruction, from the instruction shapes in this tab's kernels; the table under it shows which target accepted which instruction, from the real compiles.
Each instruction drawn to one scale, as tiles, is Libraries and tensor cores' Fig. 2; what this section adds is which of them compiled for which target, here.
Keeping more partial results per thread in registers means each value loaded from memory is reused more (that is how fast matmuls work: each thread owns a small tile of the output). The price is registers. A thread can use at most 255, and every register a thread uses is taken from the SM's fixed pool of 65,536, so fewer threads fit. Past the limit, the compiler spills: it parks values in local memory, which despite the name is per-thread space in global memory (behind the L1 and L2 caches), and reloads them later with STL and LDL instructions. Slide N, the number of running sums each thread keeps.
Register allocation is decided per thread at compile time. A bigger block only changes how many blocks fit on an SM. The exception: __launch_bounds__ (or -maxrregcount) tells ptxas the block size up front, and it may then cap registers per thread so that the block fits, which can cause spills. The ladder above uses __launch_bounds__(128).
PTX is portable forward: PTX written for compute_80 can be compiled for any later GPU. Machine code is not: a cubin (compiled GPU binary) runs only on GPUs of the same major version with an equal or higher minor version, so sm_80 SASS runs on an RTX 3090 (8.6) but not on an H100 (9.0) (CUDA Programming Guide 1.3.4). Since Hopper there is a third kind of target: the "a" suffix (sm_90a, sm_100a, sm_120a) unlocks architecture-specific instructions that only the exact chip runs, which is where the newest tensor-core instructions live (Programming Guide 5.1.2). Each cell below is a real compile; click a red one for the compiler's own words.
Occupancy is how many warps an SM holds at once, as a fraction of its maximum. Warps waiting for memory are parked while others compute, so more resident warps hide more latency, up to a point. Four limits apply at once, and the smallest wins: registers (65,536 per SM, allocated per warp in chunks of 256), shared memory (per block, plus 1 KB that CUDA reserves per block, per the Ampere tuning guide), the maximum warps per SM and the maximum blocks per SM. All four come from the compiler's report and the documented per-SM limits. Change the block size and watch which limit binds.
In Triton you write what a whole block computes (load a tile, tl.dot two tiles, store a tile) and the compiler decides which thread holds which element, whether to stage data through shared memory, how many pipeline stages to use, and which tensor-core instruction to emit. The table shows what Triton chose for each target, read from the PTX and SASS it produced. Correctness was checked separately by running the same kernels in Triton's CPU interpreter (TRITON_INTERPRET=1) against PyTorch.
Everything on this tab came from a handful of commands. All of them work without a GPU.
# resource report: registers, shared memory, spills, per kernel nvcc -arch=sm_90a -cubin -Xptxas -v -lineinfo kernel.cu # keep every intermediate file (.ptx, .cubin, ...) next to the source nvcc -arch=sm_90a --keep -c kernel.cu # PTX only (the virtual ISA), with .loc source-line directives nvcc -arch=compute_90a -ptx -lineinfo kernel.cu # SASS, and SASS interleaved with source file and line cuobjdump -sass kernel.cubin nvdisasm -g -c kernel.cubin # resource usage of every kernel already inside a binary or library cuobjdump -res-usage my_binary # list which SASS targets and PTX versions a binary carries cuobjdump -lelf -lptx my_binary # Triton: every stage of a compiled kernel (handle returned by the launch) k = my_kernel[grid](x, y, n, BLOCK=1024) print(k.asm["ttgir"]); print(k.asm["ptx"]); print(k.n_regs, k.n_spills) # Triton without a GPU: run on the CPU for correctness TRITON_INTERPRET=1 python my_kernel_test.py # torch.compile: print the Triton kernels Inductor generated TORCH_LOGS="output_code" python train.py
On the web, Compiler Explorer (godbolt.org) compiles CUDA C++ and shows PTX and SASS in the browser. NVRTC is the library form of the CUDA C++ compiler: a program can compile a kernel from a string at run time and get PTX or a cubin back (NVRTC User Guide).
PTX is NVIDIA's virtual instruction set: a portable assembly with unlimited virtual registers, stable across GPU generations. SASS is the real machine code of one generation, produced from PTX by ptxas (ahead of time) or by the driver (just in time). SASS is what runs, and what Nsight Compute shows you; register allocation, instruction scheduling and spilling happen only at the PTX to SASS step.
-arch=sm_80. Does it run on an H100?Yes, but not from the sm_80 machine code: cubins are compatible only within a major version. nvcc's shorthand -arch=sm_80 also embeds compute_80 PTX, and the driver compiles that PTX for 9.0 the first time it loads (slower start, then cached). It cannot use Hopper-only features such as wgmma or TMA. Built with -gencode arch=compute_80,code=sm_80 (no PTX), it fails with "no kernel image is available for execution on the device".
"a" selects the architecture-specific feature set: instructions such as wgmma that exist only on that exact compute capability and are not promised to later chips. Code compiled for an "a" target runs only on that compute capability, so sm_90a code needs a 9.0 GPU. Blackwell has its own (tcgen05); a Hopper kernel must be rewritten or recompiled from a portable source, which is one reason libraries such as CUTLASS and Triton keep per-architecture code paths.
Each warp needs 128 x 32 = 4,096 registers; the SM has 65,536, so 16 warps fit. A block is 8 warps, so 2 blocks, 16 of the 64 warp slots: 25%. Whether 25% is too low depends on the kernel: a matmul with lots of independent work per thread can run at full speed at low occupancy; a memory-bound elementwise kernel usually cannot.
When a thread needs more live values than its register budget, ptxas stores some to local memory (per-thread space in global memory, cached in L1 and L2) and reloads them later. -Xptxas -v prints "bytes spill stores / spill loads"; in SASS they are STL and LDL. A few bytes that hit L1 are cheap; spills inside a hot loop add memory traffic and latency where you wanted pure arithmetic.
FA3 is written around Hopper's wgmma and TMA, and wgmma exists only on sm_90a. The RTX 5090 is compute capability 12.0: it has no wgmma and no tcgen05 (this tab's compiles show both rejected for sm_120), so its tensor cores are reached through warp-level mma.sync instructions. A kernel written for it uses a different instruction mix, which is why kernel libraries ship separate sm_120 code.
HMMA in a profiler's SASS view for a matmul on an H100. Is something wrong?Probably, for a large matmul: HMMA is the warp-level mma.sync instruction that every generation since Volta has. On an H100 the fastest GEMMs use HGMMA (wgmma). Seeing HMMA means the kernel was compiled for a portable target (sm_80 or sm_90 without "a"), or written with WMMA or mma.sync. It still uses the tensor cores, at a lower peak in practice; the exact gap is a measurement this tab cannot make (no GPU).
Follow the running example down to the kernel: softmax over each row followed by a matrix multiply, first as two kernels, then fused into one, then as whole attention the way FlashAttention does it. Every step below was written twice: as a Metal kernel timed on this laptop's GPU, and as a Triton kernel checked on the CPU and compiled for NVIDIA GPUs. Each number says where it came from.
This page was built on an Apple M1 Pro laptop. Its GPU is a real SIMT machine with the same building blocks as an NVIDIA GPU: groups of 32 threads that execute one instruction together, groups of threads that share a small fast on-chip memory, and a big slow memory everyone can reach. So the shape of every optimisation below transfers to CUDA, and the numbers are honest measurements of that shape. The sizes do not transfer: an H100 has about 20 times the memory bandwidth and, with tensor cores, about 200 times the matrix throughput of this GPU (section 3 does the arithmetic). The same names, side by side:
Measured ceilings of this GPU, from the hardware root's Roofline lab (same machine, same day): . Metal limits from Apple's Metal Feature Set Tables (Apple7 family, M1; fetched 2026-10-05): up to 1,024 threads and 32 KB of threadgroup memory per threadgroup; SIMD-scoped matrix multiply from Apple7 on.
This lab's first two experiments, the softmax ladder (one thread per row against one threadgroup per row, 50 times apart, then every later rung within a few percent of a copy) and the matmul ladder (229.20 ms naive and uncoalesced down to the 8 × 8 matrix-instruction kernel), are taught where the kernels are owned: the hero stepper and section 1 of Writing kernels for matmul, its section 4 for softmax. Their runs are still recorded here (src/lab/out/data.json) and that page quotes them.
Before and after on the same S and V measured derived bytes
In attention, softmax is followed by a matmul: O = softmax(S) V, where S holds one score per (query, key) pair and V holds one 64-number vector per key. Done the obvious way, softmax writes its whole N × N output P to device memory and the matmul reads it back. Fusing means one kernel does both, so P lives only in fast on-chip memory, a tile at a time. There is a catch: to normalise a row you need its maximum and sum, which you only know after seeing the whole row. Two ways out: read S twice (once for the statistics, once to multiply), or use the online softmax trick: keep a running maximum and, whenever it grows, rescale everything accumulated so far.
Pick a design on the figure and follow its steps; the bars under it are the measured times of every design at three sizes.
Unfused: softmax, then matmul
Fused, two passes over S
Fused, one pass (online)
One query row, 8 tiles of 4 keys: naive against online computed in your browser
Scores and the 1-number values are seeded pseudo-random; the last step checks that both methods give the same output to 12 digits. Python reference: src/lab/code/recompute.py.
The real kernels as sequence length grows measured
Attention for one head is O = softmax(Q KT / √d) V. The naive way runs three library calls and puts N × N matrices (scores S, then probabilities P) in device memory: memory grows with the square of the sequence length. The FlashAttention way is section 1's online kernel with one more step inside the loop: compute the 64 × 32 tile of scores from a tile of Q and a tile of K on chip. Nothing of size N × N ever exists. The figure checks the bookkeeping on one query row and opens on its last step, where both methods agree; the kernel block by block, step by step, is Writing kernels' Fig. 6.
Now the real kernels as sequence length grows, 4 heads of dimension 64, fp32: measured
The ladder's logic carries over unchanged; the constants do not. Per step, what this GPU measured and what an H100 SXM brings, keeping vendor peaks, independent measurements and our own arithmetic apart. Nothing in this table was run on an H100.
H100 SXM figures from NVIDIA's H100 page (fetched 2026-10-05; tensor figures there are with sparsity, halved here to dense). Shared memory per block from the CUDA Programming Guide v13.4.2 compute capability tables. Independent GEMM figure: SemiAnalysis, 22 December 2024. FlashAttention figures: FlashAttention-2 (July 2023) and FlashAttention-3 (July 2024), abstracts. The chip-level comparison lives in the hardware root (Topic: hardware).
In Triton you write what one program does to a block of data (a whole row, a 64 × 64 tile); the compiler decides which of its threads holds which element, how wide each load is, what goes through shared memory and which tensor-core instructions to use. Each kernel below was run with TRITON_INTERPRET=1 on the CPU against PyTorch in float64, then compiled for an A100 (sm_80) and an H100 (sm_90a) without a GPU, and its resources read from the binary. For the full PTX and SASS of these kinds of kernel, line by line, see the Compiler explorer.
Instruction counts are static: how many times the instruction appears in the binary, not how many times it runs. HMMA is the Ampere tensor-core instruction (from PTX mma.sync), HGMMA the Hopper warpgroup one (from wgmma), MUFU.EX2 the hardware 2x unit that tl.exp becomes, LDGSTS an asynchronous copy from global to shared memory (cp.async).
Every link opens in a new tab; times are reading or watching estimates. Links checked 2026-10-05.
Divergence, occupancy (validated against NVIDIA's cuda_occupancy.h) and latency hiding, step by step, with the M1 Pro measurements beside each.
Real PTX, SASS and ptxas -v for CUDA and Triton kernels on sm_80, sm_90a, sm_100a and sm_120, compiled without a GPU.
The running example measured: softmax fused into the matmul, and attention naive against online softmax, as Metal kernels on the M1 Pro and as Triton in the interpreter; what changes on an H100.
The sibling root: what the chip is made of, memory technology, numeric formats, interconnects, roofline and MFU, choosing and costing hardware.
CPU caches, SIMD and a measured roofline of this laptop's CPU. 33 min, plus 21
One token through llama.cpp's code, down to the quantised kernels. 37 min, plus 39
One CUDA call down through the driver; MIG and GPU virtualisation. Child of Topic: operating-systems.
Floating point, precision formats and the stable softmax, the arithmetic behind the stable softmax and the tolerances of section 8.
The algorithm, its IO proof and a runnable kernel; the depth behind section 5.
Where kernels meet training: parallelism and NCCL, clusters and throughput, low-precision formats.
inference-and-serving (serving kernels, megakernels; 34 min, plus 3), pytorch-ecosystem (torch.compile), jax-and-tpu (the TPU programming side).
Host and device in a complete program, indexing, warps, synchronisation from a warp to the grid, occupancy and waves, the error model, what a launch costs. Tab: Launch planner.
What one warp's load fetches, the caches and launch order, tiling, banks and swizzles, registers and spills, constant memory, async copies, pinned and managed memory. Tab: Memory instructions.
The matmul ladder, reductions, scans, softmax and the norms, fusion, decode with 4-bit weights, FlashAttention step by step, testing against a reference. Tabs: Kernel bench (M1); Compiled for NVIDIA.
Vector add to FlashAttention in Triton, num_warps and num_stages, autotuning, the compiler stage by stage, layouts, Gluon, which tool when. Tabs: Compiler stages; Config explorer.
cuBLAS and cuBLASLt, tiles, waves and Stream-K, attention libraries, one tensor-core instruction per generation, TMA and warp specialisation, CUTLASS and CuTe, FP8 and FP4. Tabs: Layout lab; Instruction atlas.
What each compiler decides, nvcc as a driver, PTX, reading SASS, which binary runs where, NVRTC and inline PTX, LLVM and MLIR, torch.compile as one road. Tab: Inside torch.compile.
Why a stopwatch lies, honest benchmarking, timelines with Nsight Systems and torch.profiler, Nsight Compute, tolerances, order and atomics. Tab: Report reader.
Streams and events, pinned copies and managed memory, launch overhead and CUDA graphs, several GPUs from one process, NCCL as an API, hangs and timeouts, symmetric memory.
Compute-bound, memory-bound, overhead-bound: the frame for every section here (section 1).
Short, accurate definitions of every term on this page, with diagrams.
December 2022; the canonical worked example of the matmul ladder, ten kernels with numbers (Writing kernels, section 1).
Hwu, Kirk and El Hajj; the standard textbook. Elsevier's page gives February 27, 2026 in its header and June 3, 2026 in its product details.
The model, memory, and the compute-capability tables quoted here.
Coalescing, timing with events, effective bandwidth.
Ground truth for mma, wgmma, tcgen05 and TMEM.
The profilers of section 8.
AMD's version of section 3.
Vector add, fused softmax, matmul, fused attention.
Why blocks instead of threads.
Layouts, TMA, wgmma, tcgen05, warp specialisation, from Python.
Learn the indexing by solving.
The classic seven-step reduction ladder.
The sequel to Boehm: vectorisation, double buffering, autotuning.
C++ templates and the CuTe DSL; release 4.8.0.
CuTe layouts, Hopper pipelines, FlashAttention-3-style kernels explained in writing.
And the flash-attention repository for FlashAttention-4 in CuTe DSL.
The rescaling trick of section 5.
TorchDynamo and TorchInductor, the compiler of section 8.
Independent microbenchmarks: the latencies quoted by GPU memory hierarchy and this page's GPU simulator.
Follows PMPP, then Triton, CUTLASS and guest kernel authors. Resource stream (20 min) indexes the rest.
September 8, 2026: cuda-oxide and cutile-rs (section 9).
September 8, 2026: a whole decode step in one kernel (section 9).
August 27, 2026: ROCm CLI, Hyperloom, AMD Skills.
2019; launch overhead measured (section 1).