Topic: cuda-and-gpu-programming

Reading: 28 min, plus 4 in closed details. The map of GPU programming: one kernel's life drawn in 3D, from a PyTorch call down to the instructions, with the page that owns each part, every optimisation lever on one screen with the limit it attacks and the child page that owns it, the five ways to get a kernel compared, tensor cores by generation, and the same ideas on AMD and Apple GPUs. Tabs: GPU simulator, Compiler explorer, Kernel lab (measured on an Apple M1 Pro GPU; no NVIDIA GPU was used). Data as of October 2026.

The idea

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.

  1. One call: the running example. 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.
  2. Where the kernel comes from. Four sources (section 6 compares them). torch.compile: Inductor fuses the graph and writes Triton for you (The compiler stack, sections 1 and 8). A library: cuBLAS, cuBLASLt, cuDNN, CUTLASS, CUB, NCCL (Libraries and tensor cores, sections 1 to 4, 7). Triton or Gluon: you write blocks; the compiler places threads (Triton and Gluon, whose Fig. 1 draws one program on one tile). CUDA C++ by hand: reductions, softmax, the matmul ladder, fusion, FlashAttention (Writing kernels, whose Fig. 1 climbs the matmul ladder).
  3. Compiled: PTX, then SASS. Source to PTX (virtual) to SASS (one chip's machine code), packed in a fat binary with one image per target; the vector add needs 12 registers a thread on sm_90a compiled here. Owner: The compiler stack, whose Fig. 4 takes the row softmax down and Fig. 5 shows which image each GPU runs; real output for four generations in this page's Compiler explorer.
  4. Launched on a stream. A grid of blocks of threads, queued asynchronously: the CPU returns at once. Streams, events and CUDA graphs order and batch launches (a graph took NVIDIA's 2.9 µs kernel from 9.6 to 3.4 µs per kernel, section 1). Owners: The CUDA programming model (sections 1, 5, 8); Streams, CUDA graphs and multi-GPU programming (sections 1 to 4), whose Fig. 2 launches 20 kernels three ways.
  5. The grid lands on the SMs. This softmax launches 8,192 blocks, one per row; the GPU hands them to its SMs (132 on an H100 SXM; 11 drawn) in any order, which is why blocks must not depend on each other. Owner: The CUDA programming model, whose Fig. 1 unpacks one launch and Fig. 4 fills the SMs in waves.
  6. SMs running warps of 32. SIMT, divergence, occupancy, latency hiding (section 3): each instruction is issued once for 32 lanes, and a branch that splits a warp runs both sides, 1.86 times slower on the M1 Pro. Owner: The CUDA programming model (sections 3 to 5; Fig. 2 a branch in a warp, Fig. 3 occupancy on one SM); this page's GPU simulator.
  7. The memory ladder. Registers, shared memory and L1, L2, HBM: where the bytes are (section 4). The softmax reads its 256 MiB once from HBM and writes 256 MiB back, so its speed is memory's: 166 GB/s on the M1 Pro, against 3.35 TB/s of HBM on an H100. Owner: GPU memory hierarchy, whose Fig. 1 is the ladder on an H100 and Fig. 3 one tile fetched once and reused.
  8. Tensor cores. 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.
  9. Several GPUs. Peer access, NCCL, overlap of communication with compute. Owner: Streams, CUDA graphs and multi-GPU programming (sections 5 to 8), whose Fig. 3 runs one DDP step on 8 of 64 GPUs.
  10. Checked. Checked by: a timeline first, then counters for the one kernel it convicts, honest timing, and a comparison against a reference (section 8). Here the softmax took 3.2 ms as a median, and its first run under load 12.36 ms. Owner: Profiling, benchmarking and correctness, whose Fig. 1 times one matmul four ways and Fig. 2 reads one report top-down. This page's Kernel lab measures the running example unfused and fused on a real GPU.

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.

New terms
Kernel: a function that runs on the GPU, executed by many threads at once.
Thread, warp, block, grid: one execution; 32 that issue together; up to 1,024 on one SM; all blocks of one launch.
SM: streaming multiprocessor, the GPU's core; an H100 SXM has 132.
Stream: a queue of GPU work; a launch returns at once.
Shared memory: on-chip scratchpad one block fills and reads.
Coalesced: a warp's 32 loads served by as few 32-byte sectors as possible.
Occupancy: resident warps per SM over the maximum.
Fusion: several operations in one kernel, intermediates kept on chip.
Tensor core: a unit that multiplies small matrix tiles in one instruction.
PTX, SASS: NVIDIA's virtual instruction set; one chip's real machine code.
How evidence is labelled (no NVIDIA GPU was used to build this page)
measured on Apple M1 Pro GPU: the laptop this page was built on has a real SIMT GPU (16 cores, SIMD-groups of 32 threads, threadgroup memory), programmed here through Apple's MLX and Metal; the same ideas apply to NVIDIA, the absolute numbers do not, and each case says what transfers. compiled here: real NVIDIA compiler output (CUDA toolkit 13.4.2, 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.

1. One call, from PyTorch to the GPU

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

  1. Python reaches t = s * scale. PyTorch's dispatcher sees a CUDA tensor and picks the CUDA multiply kernel. Nothing has run on the GPU yet.
  2. Launch 1: the multiply. The CPU enqueues the kernel on the stream and returns at once. The GPU reads s (256 MiB) and writes t (256 MiB); meanwhile Python has already moved to the next line.
  3. Launch 2: the softmax. The softmax waits in the queue behind the multiply, then reads t back from memory and writes p. Two kernels, four full passes over memory, for two lines of code.
  4. 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

  1. First call: compile. TorchDynamo captures the two lines as a graph; Inductor writes one Triton kernel that scales and normalises in a single pass, and compiles it (once; later calls reuse it).
  2. Launch: one fused kernel. One launch. The kernel reads s once, multiplies by scale in registers, computes the row maximum and sum, and writes p. The intermediate t never exists in memory.
  3. p.item(): the CPU waits. The CPU blocks until the single kernel finishes.
  4. Half the traffic. Two passes over memory instead of four. For a memory-bound operation, half the bytes is close to half the time; the compute was never the bottleneck.

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.

2. Every lever, the limit it attacks, and who owns it

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.

LeverLimit it attacksWhat it buys (evidence)What it costs, or when it does not helpOwner
Coalesced access: threadIdx.x walks the contiguous dimensionmemory: wasted sectors8 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 measuredlayout work; sometimes a transpose staged in shared memoryGPU memory hierarchy, section 1
Shared-memory tilesmemory: each value fetched once per thread that needs itglobal loads fall by the tile widthshared memory per block lowers blocks per SM: on the M1 Pro 32 × 32 tiles ran slower than 8 × 8 (478 against 677 GFLOP/s) measuredGPU memory hierarchy, section 3
Register tiles: each thread computes a small block of outputsshared-memory bandwidth and instruction issue5.4 times across Boehm's kernels 3 to 5 publishedregisters per thread, so fewer warps; spills past the limitWriting kernels, section 1
Padding or swizzling shared memorybank conflictsM1 Pro: lane stride 32 at 113 billion reads/s against 394 at stride 33 measuredonly matters when shared memory is the bottleneckGPU memory hierarchy, section 4
Enough warps and blocks (occupancy, waves)latencyM1 Pro streaming: 11 GB/s with 256 threads in flight, 138 to 151 with 8,192 or more measureda means, not a goal: fast matmul and attention kernels run at low occupancy on purposeThe CUDA programming model, section 5; GPU simulator
Warp-uniform branchesissue slots lost to divergenceM1 Pro, two equal branches split inside every warp: 1.86 times slower measuredrarely matters in matmuls and norms; often in masking, ragged inputs, MoE routingThe CUDA programming model, section 3; GPU simulator
Fusionmemory: intermediates written and read backk memory-bound operations cost close to one; eager softmax took 4.0 times the single kernel on the M1 Pro measuredrarely pays between two compute-bound matmuls; torch.compile already fuses elementwise chainsWriting kernels, section 5; section 5 here
Online softmax, FlashAttentionmemory: the N × N scoreswhole attention at N = 8,192 on the M1 Pro: 1,056 MiB to 32 MiB measuredrecomputes scores in the backward passWriting kernels, section 7
Tensor cores (mma, wgmma, tcgen05)computeH100: about 15 times its float32 rate (989.5 against 67 TFLOP/s dense) vendor speccode tied to one generation; low-precision formatsLibraries and tensor cores, section 5
Asynchronous copies, TMA, warp specialisationload latency stalling the maththe next tile loads while this one is multipliedshared memory per pipeline stage; complexityGPU memory hierarchy, section 7; Libraries and tensor cores, section 6
Split-K, Stream-K, tile choicetoo few tiles to fill the SMs (the last wave)idle SMs get workan extra reductionLibraries and tensor cores, section 3
Fewer launches: CUDA graphs, larger kernelsoverhead9.6 to 3.4 µs per kernel (section 1) publishedcaptured shapes and addresses are fixedStreams, CUDA graphs and multi-GPU programming, sections 3 and 4
Overlap on streams (copies, NCCL)idle time between dependent workdata-parallel training hides its all-reduce behind backward computeordering bugs, hangsStreams, 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.

3. Threads, warps, blocks: the model every child assumes

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:

ThreadOne execution of the kernel, with its own private registers (the fastest storage there is). You launch millions.
Warp32 consecutive threads that the hardware runs together, one instruction at a time for all 32. Not part of the language, but the unit everything performs in.
BlockUp to 1,024 threads that run on one SM and stay there. They share shared memory and can wait for each other with __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.
GridAll the blocks of one launch; the end of the kernel is the only cheap global barrier. Since Hopper (compute capability 9.0) an optional cluster sits between block and grid: a few blocks on neighbouring SMs that can read each other's shared memory.

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.

Go deeper: The CUDA programming model owns this section: a complete program, indexing, warp cooperation, synchronisation from a warp to the whole GPU, occupancy and waves (its Launch planner tab), the error model and what a launch costs; what an SM physically contains is on GPU architecture.

4. The memory ladder: why bytes decide

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.

Go deeper: GPU memory hierarchy has the ladder with H100 sizes and H800 latencies as its hero, what one warp's load fetches, cache hints and launch order, tiling animated at real size, banks and swizzles, registers and spills, asynchronous copies, and pinned and managed memory, with its Memory instructions tab of real SASS; what HBM and SRAM are physically is on Topic: hardware, section 3.

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.

5. Fusion: the running example, unfused and fused

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

  1. Kernel 1: S = QKT. Read Q and K, write the full N × N score matrix S to HBM. The scores exist in memory only to be read straight back.
  2. Kernel 2: P = softmax(S). Read S, write P, another N × N matrix. This kernel is pure memory traffic: a few operations per element.
  3. Kernel 3: O = PV. Read P and V, write O. Two N × N matrices were written and read; the output is only N × d.
  4. Total. Four N × N passes plus the inputs and output. S and P also need their own memory, which is what limited sequence length before FlashAttention.

Fused (FlashAttention-style): one kernel

  1. Load a block of Q rows on chip. One thread block takes, say, 128 rows of Q into shared memory and registers and keeps them there for the whole kernel.
  2. Stream K blocks: scores on chip. For each block of K, that block of S = QKT is computed with tensor cores, in registers, and the running row maximum m and sum d are updated (online softmax). Nothing is written.
  3. Stream V blocks: accumulate O. The block of probabilities times the matching block of V is added into the output accumulator, first rescaled by emold − mnew whenever the maximum moved.
  4. Write O once. Divide by the final sum d and write O; keep m and d (N numbers) so the backward pass can recompute S block by block instead of storing P. The kernel itself, block by block, is Writing kernels' Fig. 6; what this figure adds is the bytes, to scale, at any size.

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.

NUnfused, msFused, msSpeedupruns (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.

Go deeper: Writing kernels owns the kernels: the softmax ladder (section 4), fusion and when it does not pay (section 5), and FlashAttention step by step, FA-1 to FA-4 with split-KV decode (section 7); the paper page FlashAttention has the algorithm and its proof; the Kernel lab has these kernels, their Triton twins and the H100 arithmetic; serving kernels (paged attention, decode) belong to inference-and-serving.

6. Five ways to get a kernel, compared

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.

WayYou writeDecided for youReaches tensor cores throughWhen it is the answerOwner
torch.compileordinary PyTorchwhich operations fuse; the Triton code; matmuls go to cuBLAS by defaultcuBLAS, or Triton templates under mode="max-autotune"first, always: it already writes Triton for youThe compiler stack, section 8
A library: cuBLAS, cuBLASLt, cuDNN, CUTLASS, CCCL (Thrust, CUB), NCCLa callthe kernel, picked by a heuristic; epilogues (bias, GELU, scaling) in cuBLASLtbuilt inany standard GEMM, convolution, attention, reduction, scan or collectiveLibraries and tensor cores, sections 1 to 4
Tritonwhat one program does to whole blocksthreads, vector loads, shared memory, synchronisation, the instruction per targettl.dotan algorithm the compiler cannot express or schedule well: attention variants, quantised or mixed-format matmuls, fused MoE routingTriton and Gluon
Gluon, CuTe DSLlayouts, async copies, warp specialisation, in Pythonless: you take back what Triton hideswgmma, tcgen05 explicitlypeak kernels without C++ templates; FlashAttention-4 is written in CuTe DSLTriton and Gluon, section 10; Libraries and tensor cores, section 7
CUDA C++, CUTLASSwhat one thread does, and all the cooperationonly register allocation and instruction schedulingmma.sync, wgmma, tcgen05, or CUTLASS/CuTecontrol Triton hides, or the last few percent on a kernel that dominates the profileWriting 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:

CUDA C++: 29 lines without comments; three passes, warp shuffles and a shared-memory step written by hand (core loop shown)
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: 9 lines; the whole row is one block of values
@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.

7. Tensor cores: one instruction per generation

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:

GenerationInstruction (PTX, then SASS)Issued by; accumulators inFed by
Ampere sm_80 (and consumer sm_86, sm_89, sm_120)mma.sync → HMMAone warp; registerscp.async
Hopper sm_90awgmma → HGMMAa warpgroup of 4 warps, asynchronously; registers, operands from shared memoryTMA: one thread starts a bulk tile copy
Datacenter Blackwell sm_100atcgen05.mma → UTCHMMAone thread for the block; TMEM, tensor memory beside the SMTMA

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.

Go deeper: Libraries and tensor cores owns the instructions: tile shapes drawn to one scale, fragment maps, TMA and warp specialisation, what fits on one SM, FP8 and FP4, and its Instruction atlas tab of 20 one-instruction kernels on 8 targets; the Compiler explorer, sections 4 and 6, shows one multiply-add per thread against one tensor-core instruction, and what compiled on which of four generations; tensor cores physically are on GPU architecture.

8. Compile, profile, check: how you know what ran

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)
Answerswhere does the wall-clock time go?why is this one kernel slow?
Showsa timeline: CPU threads, API calls, launches, copies, NCCL, gapscounters: Speed of Light (compute and memory as a share of peak), occupancy, warp stalls, sectors per request
Costcheap, so always firstreplays 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.

Corrections to the old page (profiling)
The old page said 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).
Go deeper: The compiler stack owns the compilers: what each decides, nvcc as a driver, PTX, reading SASS and its control bits, which binary runs on which GPU, NVRTC and inline PTX, LLVM and MLIR, and torch.compile from Dynamo to Inductor (its Inside torch.compile tab); Profiling, benchmarking and correctness owns the checking loop: why a stopwatch lies, honest benchmarks, timelines, Nsight Compute (its Report reader tab reads NVIDIA's own reports), tolerances, summation order and atomics; MFU and training throughput are on Performance math.

9. Other GPUs: the same ideas under other names

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:

CUDAAMD HIP / ROCmApple MetalTriton
threadthread (work-item)thread(hidden)
warp, 32 threadswavefront: 64 on CDNA 3 and 4 (Instinct up to MI355X), 32 on RDNA (Radeon); the MI455X advertises Wave32SIMD-group, 32 on Apple GPUsnum_warps
thread blockblock (workgroup)threadgroupprogram instance
shared memory, __syncthreads()LDS (local data share), __syncthreads()threadgroup memory, threadgroup_barrier()(compiler-managed)
global memoryglobal memorydevice memory (shared with the CPU)pointers
warp shufflewavefront shuffle (same intrinsics)simd_shuffle, simd_sumtl.sum, tl.max
tensor core (mma, wgmma, tcgen05)matrix core (MFMA)simdgroup_matrix 8 × 8tl.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.

Dated: ROCm 10, and CUDA in Rust (news, kept in tech news)
ROCm 10.0 (August 27, 2026; AMD ROCm blog, Phoronix) jumped from 7.14 and added the ROCm CLI, Hyperloom and AMD Skills; details in the 2026-09-14 tech news. The old page's "3.3 times inference and 2.4 times training over ROCm 7" appears in neither source unconfirmed. CUDA in Rust (NVIDIA, September 8, 2026): cuda-oxide, a thread-level rustc backend down to PTX, and cutile-rs, a tile-level track through CUDA Tile IR; details in the 2026-09-21 tech news. A megakernel (a whole decode step in one persistent kernel) is the far end of fusion; Cohere's figures are in the 2026-09-14 issue.

10. The child pages, in reading order

Reading times are each page's header (2026-11-12): core minutes, plus closed details.

1. The CUDA programming model: threads, warps, blocks, launches, occupancyChild page, about 36 min, plus 16 in closed details. Host and device, indexing, warps, synchronisation scopes, occupancy and waves, the error model, launch cost; Launch planner tab.
2. GPU memory hierarchy: coalescing, shared memory, bank conflicts, registers and spillsChild page, about 31 min, plus 11 in closed details. Sectors, caches and launch order, tiling, banks and swizzles, registers and spills, constant memory, async copies, host memory.
3. Writing kernels: reductions, softmax, tiled matmul, fusion, FlashAttentionChild page, about 34 min, plus 15 in closed details. The matmul ladder, reductions, scans, row norms, fusion, 4-bit decode, FlashAttention step by step, testing.
4. Triton and Gluon: block-level kernels, autotuning, what the compiler doesChild page, about 37 min, plus 9 in closed details. Blocks not threads, softmax to attention, num_warps and num_stages, autotuning, compiler stages, layouts, Gluon.
5. Libraries and tensor cores: cuBLAS, cuDNN, CUTLASS and CuTe, mma, wgmma, TMA, tcgen05Child page, about 35 min, plus 9 in closed details. What libraries ship and pick, waves and Stream-K, one tensor-core instruction per generation, TMA, CuTe, FP8 and FP4.
6. The compiler stack: PTX, SASS, NVRTC, torch.compile and InductorChild page, about 37 min, plus 22 in closed details. What each compiler decides, nvcc, PTX, reading SASS, which binary runs where, NVRTC, torch.compile as one road.
7. Profiling, benchmarking and correctness: Nsight, honest timing, numerical checksChild page, about 28 min, plus 8 in closed details. Why a stopwatch lies, honest benchmarks, timelines, Nsight Compute, tolerances, order and atomics.
8. Streams, CUDA graphs and multi-GPU programming: overlap, launch overhead, NCCLChild page, about 33 min, plus 15 in closed details. Streams and events, copies and managed memory, CUDA graphs, peer access, NCCL overlap, hangs, symmetric memory.

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.

Interview rehearsal: ten questions with short answers

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.