You write the code of one thread; a launch runs it on a grid of blocks, each block split into warps of 32 threads that issue together. Each thread computes its own index to find its data; threads cooperate only inside a warp or a block; and the GPU places as many blocks on each SM as registers and shared memory allow (occupancy), running the rest in waves.
Fig. 1 unpacks the running example's launch, scale<<<4096, 256>>> (section 1), one level per step derived:
blockIdx.x 9, threadIdx.x 37 (warp 1, lane 5), so its element is i = 9 × 256 + 37 = 2,341: the only thing that makes it different from its neighbours is that index.__syncthreads(), on one SM. The warp: shuffles, votes and __syncwarp(). The thread: only its own registers.You need: nothing beyond C or Python and the idea of a matrix in memory. What an SM physically contains and why a GPU needs thousands of threads to hide latency are on GPU architecture (sections 2 and 3); this page is how you program it.
__global__ function: runs on the device, launched from the host.The running example. Attention scores s, a 4,096 by 4,096 float32 matrix, need an elementwise step (scale every score, e = a * s) and a reduction (the sum of each row) on the way to a softmax. The elementwise step teaches launches and indexing; the reduction forces threads to cooperate, which teaches warps, shared memory, barriers and atomics. The parent, Topic: cuda-and-gpu-programming, follows the whole softmax and attention from PyTorch down to the instructions; this page owns the model underneath.
Evidence (no NVIDIA GPU was used): compiled here is real output of NVIDIA's toolkit (release 13.4, V13.4.92) in a Linux container with no GPU, for sm_80 (A100), sm_90a (H100), sm_100a (B200) and sm_120 (RTX 5090): ptxas -v reports, SASS (the GPU's machine code), and host programs actually run, so their error output is real. measured on Apple M1 Pro GPU is the same idea as a Metal kernel (Apple's SIMD-groups are 32 threads wide, like warps) timed through MLX 0.32.3, three runs on a shared laptop, load average 5.0 to 6.3. vendor doc is NVIDIA documentation fetched 2026-10-05; published papers and blogs; derived by the formula shown; illustrative an input chosen for drawing. Nearby owners: coalescing, banks and spills on GPU memory hierarchy; HBM and SRAM as hardware on Memory technology; roofline on Performance math; divergence and per-generation SM limits on GPU architecture; streams and graphs on Streams, CUDA graphs and multi-GPU programming; PTX and SASS on The compiler stack.
| Idea | In one line | How to check it | Section |
|---|---|---|---|
| Kernel, launch | A __global__ function; k<<<grid, block>>>(args) starts grid × block threads and returns at once. | cudaGetLastError() after the launch | 1 |
| Thread, block, grid | Each thread reads blockIdx, blockDim, threadIdx to compute which element is its job. | a bounds check on every index | 2 |
| Warp | 32 threads with consecutive ids, issued together; they can swap registers (shuffles) and vote. | SASS: SHFL, VOTE | 3 |
| Synchronisation | Warp: __syncwarp. Block: __syncthreads + shared memory. Cluster: cluster.sync(). Whole grid: end the kernel (or a cooperative launch). Any thread: atomics. | compute-sanitizer --tool racecheck | 4 |
| Launch configuration | Block size (a multiple of 32, usually 128 to 256), grid size, shared memory; with registers they set occupancy, and grid / (SMs × blocks per SM) sets the waves. | ptxas -v, the occupancy API, the Launch planner | 5 |
| Errors | Return codes, not exceptions; kernel errors appear at a later call; some poison the whole process. | a CUDA_CHECK macro, CUDA_LAUNCH_BLOCKING=1 | 6 |
| Memory API | cudaMalloc, cudaMemcpy, pinned and managed memory, the stream-ordered allocator. | torch.cuda.memory_allocated() vs memory_reserved() | 7 |
| Launch cost | Microseconds of CPU work per launch; tiny kernels leave the GPU idle between them. | a profiler timeline (gaps between kernels) | 8 |
The CPU (host) and the GPU (device) have separate memories and run separate code. A CUDA program is ordinary C++ for the host plus functions marked to run on the device; it allocates device memory, copies data in, launches, and copies results back. Here is the whole of it for the elementwise step, y = a * x on 1,048,576 floats, a real file compiled here with nvcc for sm_90a (H100) compiled here:
__global__ void scale(const float* x, float* y, float a, int n) { // runs on the GPU int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) y[i] = a * x[i]; } int main() { const int n = 1 << 20; // 1,048,576 elements std::vector<float> hx(n), hy(n); // host arrays float *dx, *dy; // device pointers: not usable on the CPU CUDA_CHECK(cudaMalloc(&dx, n * sizeof(float))); // 1 allocate GPU memory CUDA_CHECK(cudaMalloc(&dy, n * sizeof(float))); CUDA_CHECK(cudaMemcpy(dx, hx.data(), n * sizeof(float), cudaMemcpyHostToDevice)); // 2 copy in int block = 256, grid = (n + block - 1) / block; // 3 choose the launch: 4,096 blocks of 256 scale<<<grid, block>>>(dx, dy, 2.0f, n); // 4 launch (returns at once) CUDA_CHECK(cudaGetLastError()); // was the launch itself valid? CUDA_CHECK(cudaMemcpy(hy.data(), dy, n * sizeof(float), cudaMemcpyDeviceToHost)); // 5 copy out (waits) // 6 compare hy with 2 * hx on the CPU; 7 cudaFree(dx); cudaFree(dy); }
Bar lengths are schematic, not measured: a launch is microseconds (section 8), the copies and the kernel depend on size. Hatched = the CPU is blocked waiting for the GPU illustrative timing.
The launch is asynchronous. scale<<<grid, block>>>(...), the execution configuration, starts grid blocks of block threads (4,096 × 256 = 1,048,576, one per element) and returns before the kernel runs: "Kernel launches are asynchronous with respect to the host thread" (Programming Guide, 2.1.4). The program waits at step 5, because "the cudaMemcpy API is synchronous. That is, it does not return until the copy has completed" (2.1.3.2), and a copy queued after the kernel on the same stream starts only when the kernel ends. The stepper walks through it, both timelines at once:
hx and hy (1,048,576 floats, 4 MiB each) are in CPU memory. Nothing is on the GPU yet.dx and dy are device addresses: the CPU holds them but cannot dereference them.scale<<<4096, 256>>>: the CPU writes a launch command into the stream's queue and returns at once. Nothing has run yet.cudaGetLastError(): cudaSuccess, the launch was valid. It could do any other work here.hy with 2 × hx on the CPU, then cudaFree. The CPU waited only at the two copies; the launch itself cost microseconds (section 8).Two more launch arguments are optional: bytes of dynamic shared memory per block and the stream to queue on, <<<grid, block, smemBytes, stream>>>. Three function markers: __global__ is a kernel (returns void; results go through pointers); __device__ a helper callable only from device code; __host__ __device__ compiles for both sides, the usual way to share small maths (CUDA Programming Guide, section 2.1 vendor doc). nvcc splits the file: host code to the normal C++ compiler, device code to NVIDIA's, and the device machine code is embedded in the executable (The compiler stack). The "thread index" costs almost nothing: in the real SASS it is two special-register reads and one multiply-add (listing below).
i < n and exit at once. Without that check they would read and write past the end of the arrays, and sometimes nothing visible happens, which is worse: the classic first-kernel bug (compute-sanitizer's memcheck finds it, section 6).scale, and the run without a GPU (depth)S2R R0, SR_TID.X and S2UR UR4, SR_CTAID.X read threadIdx.x and blockIdx.x from special registers; LDC R7, c[0x0][RZ] loads blockDim.x from the constant bank where the launch put it; IMAD is the index; ISETP and @P0 EXIT are the bounds check (threads past n simply exit); c[0x0][0x210] and up are the kernel's arguments, also delivered in the constant bank; LDG, FMUL, STG are the load, multiply and store. Each instruction is issued once per warp of 32 threads. compiled here
Full source with the CUDA_CHECK macro and the CPU check: src/cuda/host/first_program.cu. Compiled with exit code 0; run in the container, which has no GPU or driver, it stopped at its first CUDA call (line 19, the first cudaMalloc) with CUDA driver version is insufficient for CUDA runtime version, exactly as the error check is meant to. Compiling needs no GPU; running does. The same vadd kernel compiled for four generations, PTX and SASS side by side, is in the root's Compiler explorer tab; how a launch reaches the device through the driver is on Virtualization and the GPU driver stack.
All threads run the same code; the only thing that makes thread 77,000 different from thread 3 is a handful of read-only built-in variables, and turning them into "my element" is the first thing every kernel does.
| Built-in | Meaning | Limit vendor doc |
|---|---|---|
threadIdx.{x,y,z} | this thread's position inside its block | block x, y ≤ 1,024; z ≤ 64; x·y·z ≤ 1,024 |
blockDim.{x,y,z} | the block's shape, as launched | same |
blockIdx.{x,y,z} | this block's position in the grid | grid x ≤ 231−1; y, z ≤ 65,535 |
gridDim.{x,y,z} | the grid's shape | same |
warpSize | threads per warp | 32 on every GPU so far |
Limits from the CUDA Programming Guide, Table 30 (v13.4.2, updated Sep 10, 2026), identical for every compute capability it lists. Shapes are dim3 values: dim3 block(32, 8) is 32 × 8 = 256 threads.
// 1 one thread per element (the host launches ceil(n / block) blocks) int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) y[i] = a * x[i]; // 2 grid-stride loop: any grid size covers any n for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x) y[i] = a * x[i]; // 3 a 2D grid over a matrix: x walks columns, so neighbouring threads touch neighbouring addresses int c = blockIdx.x * blockDim.x + threadIdx.x, r = blockIdx.y * blockDim.y + threadIdx.y; if (r < rows && c < cols) y[r * cols + c] = a * x[r * cols + c]; // host: dim3 block(32, 8); dim3 grid((cols + 31) / 32, (rows + 7) / 8);
All three are in src/cuda/kernels/p1_index.cu and compile for all four targets; on sm_90a, ptxas gives the one-per-element and 2D kernels 10 registers per thread and the grid-stride kernel 14 (it carries the loop) compiled here. For the running example, the 4,096 × 4,096 scores take pattern 3 with a 128 by 512 grid of 32 × 8 blocks, or pattern 1 on the flattened 16,777,216 elements: for an elementwise step the shape does not matter as long as consecutive threads touch consecutive addresses.
Why the grid-stride loop is worth knowing. The grid no longer depends on n: launch exactly as many blocks as fit on the GPU at once (a persistent grid) and let each thread do several elements, run one block of one thread to debug serially, and do per-thread setup once instead of once per element (Mark Harris, "CUDA Pro Tip: Write Flexible Kernels with Grid-Stride Loops", NVIDIA, 2013 published). It does not remove the tail effect of section 5: the last iteration is still uneven.
Integer overflow. int stops at 231−1 = 2,147,483,647. A tensor of 16 × 32 × 4,096 × 4,096 attention scores has 8,589,934,592 elements, so blockIdx.x * blockDim.x + threadIdx.x computed in int wraps around silently derived. Use 64-bit arithmetic ((long long)blockIdx.x * blockDim.x, or size_t) whenever an index can pass two billion.
The hardware groups a block's threads into warps by a single linear thread id, x + y·Dx + z·Dx·Dy ("the first index x moves the fastest, followed by y and then z"), and warp w holds linear ids 32w to 32w+31, "the first warp containing thread 0" (Programming Guide 2.3.2; 3.2, Hardware Implementation). So the block's shape decides which matrix elements one warp touches together. Pick a 256-thread shape over a row-major float32 matrix in the widget on the right:
32 × 8, 16 × 16 and 8 × 32 all touch 4 sectors per warp load, every byte used; narrower than 8 columns, sectors are half empty and the same load costs 8, then 32 sectors. Why sectors are the unit, and what it costs, is the subject of GPU memory hierarchy (coalescing). The rule to keep: make threadIdx.x walk the contiguous dimension.
x + 16y for y = 2 and 3, so rows 2 and 3 of the block, all 16 columns each. Warp 0 is rows 0 and 1. Try the 16 × 16 button in the widget and click any cell of rows 2 to 3.Each cell is one thread of the block placed on the matrix element it handles (columns across, rows down), coloured by warp. Click a cell to see that thread's numbers. Sectors: the 32-byte pieces of memory one warp's load touches, if the rows start 32-byte aligned and are more than a block wide derived: rows touched × ceil(columns per row × 4 B / 32 B).
The hardware issues one instruction for 32 threads at a time, the warp; if a warp's threads disagree on a branch, both paths run in turn with the inactive lanes masked off (divergence: the parent's GPU simulator, section 1, steps it; GPU architecture section 5 measures its cost). What the warp lets you do: its 32 lanes can read each other's registers and vote, with no shared memory and no barrier. In a one-dimensional block a thread's lane is threadIdx.x % 32 (& 31) and its warp threadIdx.x / 32 (>> 5).
Fig. 2 takes one 256-thread block apart and runs a branch in one of its warps (the branch is illustrative; the rule is the hardware's):
blockDim.x = 256, warp w holds threads 32w to 32w + 31: eight warps.y = a * x once and all 32 lanes execute it: one issue slot. The rows behind are the warp's issue slots in time order.if (lane < 16) the lanes disagree. The warp issues path A for lanes 0 to 15; lanes 16 to 31 are masked off and wait.One warp, lane i starting with the value i + 1 (sum 528) illustrative input. Shuffles: 5 SHFL, no memory, no barrier. Shared memory: 10 loads, 6 stores and 6 barriers. Instruction counts per step come from the real SASS of warp_sum (5 SHFL) and block_sum (per level: 2 LDS, 1 STS, 1 BAR) on sm_90a compiled here.
The row sum of the running example adds 4,096 numbers into one. Inside a warp, five shuffles do it: add the value 16 lanes away, then 8, 4, 2, 1, and lane 0 holds the sum of all 32. Predict how many shared-memory loads and barriers the same sum costs without shuffles, then switch the card on the right to compare:
v += __shfl_down_sync(0xffffffff, v, 16). Lanes 16 to 31 have no lane 16 above them and get their own value back; their results are never used. Lanes 0 to 15 carry the partial sums.STS), then the block waits at __syncthreads() (1 BAR) so every store is visible.__syncthreads() so the next level reads finished values.extern "C" __global__ void warp_sum(const float* x, float* out) { float v = x[blockIdx.x * blockDim.x + threadIdx.x]; for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xffffffffu, v, off); if ((threadIdx.x & 31) == 0) atomicAdd(out, v); // one atomic per warp, not per thread }
ptxas unrolls the loop into 5 SHFL instructions and one REDG (a reduction in global memory: the atomic add whose result nobody reads), using 12 registers and no shared memory compiled here. The cooperative-groups version, cg::reduce(tile, v, cg::plus<float>()), compiles to the same five shuffles in the butterfly (xor) pattern, after which every lane, not just lane 0, holds the sum. The other warp-level functions (votes, __reduce_add_sync, __syncwarp) are in the closed table below.
Why every warp function takes a mask and ends in _sync. Before Volta (2017) a warp had one program counter, so code could assume its 32 lanes ran in lockstep ("warp-synchronous" code). Since Volta each thread has its own program counter and lanes can be at different instructions, so warp-level code must name the lanes taking part (the mask, usually 0xffffffff) and synchronise explicitly with __syncwarp(). Old kernels (pre-2017 tutorials, some ggml or Caffe-era code) that use warp tricks without _sync are no longer guaranteed to work. Atomics are aggregated for you: for the naive if (x[i] > 0.f) atomicAdd(out, 1); ptxas already emits one atomic per warp instead of one per thread (closed block below), so write the simple atomic first, read the SASS, and measure before hand-optimising.
| Warp-level function | What it does | SASS seen here |
|---|---|---|
__shfl_sync(m, v, src), _up, _down, _xor | Each lane receives v from another lane: a fixed one, lane − d, lane + d ("shifting value down the warp by delta lanes") or lane xor d. | SHFL.DOWN, SHFL.BFLY |
__all_sync, __any_sync, __ballot_sync(m, p) | Votes: is p true in every lane, in any lane; or a 32-bit word whose bit N is lane N's p. | VOTE |
__reduce_add_sync(m, v) (and min, max, and, or, xor) | Sum of an integer over the warp in one instruction; compute capability 8.x or higher. | REDUX.SUM.S32 |
__syncwarp(m) | The lanes in m wait for each other and their memory accesses are ordered. | WARPSYNC (in the grid-sync kernel of section 4; a full-mask __syncwarp right after __reduce_add_sync compiled to nothing) |
__activemask(), __match_any_sync | Which lanes are executing here; which lanes hold the same value. |
Descriptions from the CUDA C++ language extensions appendix vendor doc. Every lane named in the mask m must reach the same call.
Independent thread scheduling, in the sources. Since Volta "threads can now diverge and reconverge at sub-warp granularity"; NVIDIA's instruction is that "developers should explicitly synchronize such code using __syncwarp() to ensure correct behavior across all GPU generations" (Programming Guide 3.2) vendor doc. "The legacy warp-level primitives are deprecated starting in CUDA 9.0" and "implicit warp-synchronous programming is unsafe" (Lin and Grover, "Using CUDA Warp-Level Primitives", NVIDIA, Jan 15, 2018) published. Old reduction kernels relied on lockstep with volatile shared memory instead.
The compiler already aggregates your atomics. Thousands of threads hitting one address with atomicAdd(out, 1) should serialise. The real SASS ptxas emits for it on sm_90a compiled here:
VOTEU.ANY collects which lanes are active, UFLO picks the first of them, POPC counts them, and only that lane issues REDG.E.ADD with the count: one atomic per warp instead of up to 32. This is warp-aggregated atomics, the same thing the explicit __ballot_sync + __popc kernel does by hand (its SASS: one VOTE.ANY, one POPC, one REDG); __reduce_add_sync is a third spelling, a single REDUX.SUM.S32. On the M1 Pro the three versions of a 16 Mi-element count (one atomic per positive thread, one per SIMD-group after simd_sum, one per threadgroup) took 1.18, 1.08 and 1.10 ms (medians of 3 runs; runs of the first varied from 1.095 to 1.49) measured on Apple M1 Pro GPU: no reliable difference, all close to the time to read 64 MiB. Whether Apple's compiler aggregates the same way is not documented; the result is consistent with it.
Full reductions (tree, shuffles, CUB's BlockReduce), scans and the softmax built from them are on Writing kernels; the divergence simulation with measurements is in the root's GPU simulator tab.
A row sum needs threads to combine partial results, and a thread may read another thread's result only after it has been written. Each scope has its own tool and its own price: the wider the scope, the more expensive (or restricted) waiting becomes, so choosing the narrowest scope that works is most of the design of a reduction, a softmax or an attention kernel.
| Scope | Tool | What it costs or requires | Real SASS (sm_90a) compiled here |
|---|---|---|---|
| Warp (32 threads) | shuffles, votes, __syncwarp (section 3) | registers only; no memory | SHFL, VOTE, REDUX |
| Block (up to 1,024) | __syncthreads() + __shared__ memory | a hardware barrier per SM; every thread of the block must reach the same barrier | BAR.SYNC, STS/LDS |
| Cluster (up to 8 blocks portably; sm_90 and later) | cluster.sync(), another block's shared memory via cluster.map_shared_rank | the blocks of a cluster are scheduled together on neighbouring SMs | UCGABAR_ARV, UCGABAR_WAIT; remote read is a generic LD |
| Grid (all blocks) | end the kernel; or a cooperative launch with grid.sync() | kernel boundary: a launch; grid.sync(): every block must be resident at once | barrier, MEMBAR.ALL.GPU, ATOM.E.ADD on a counter, a spin loop |
| Any threads, no waiting | atomics (atomicAdd, atomicCAS, ...), fences __threadfence_block/()/_system | contention on one address serialises; fences order memory, they do not wait for anyone | REDG, ATOM, ATOMS, MEMBAR |
Portable cluster size 8 and "hardware-supported synchronization across the cluster": Programming Guide 2.1.10; fence scopes (block, device, system): language extensions vendor doc. Host-side ordering (streams, events) is on Streams, CUDA graphs and multi-GPU programming.
A toy block of 16 threads drawn as two warps of 8 so it fits (real warps have 32); warp 1's load from global memory arrives one step late, as a slow memory access would. Shared memory starts empty (drawn as · and read as 0; real uninitialised shared memory holds whatever was there before) illustrative input: 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3, sum 80.
The block-wide row sum puts each thread's value in shared memory, then halves the active threads level by level: at level k, thread t < k adds s[t + k] into s[t]. Between levels every thread must wait until all the writes of the previous level have landed; that is __syncthreads(), which makes threads "wait until all non-exited threads in the thread block simultaneously reach the same __syncthreads()" (language extensions). Leave it out and the code still compiles, still runs, and is wrong whenever one warp falls behind another. The card on the right runs both versions:
x from global memory. Shared memory s[0..15] is empty.__syncthreads() and waits: 8 of 16 threads have arrived.__syncthreads() again.x from global memory. Shared memory s[0..15] is empty.On real hardware. The same 256-thread tree sum over 65,536 blocks of small integers, as a Metal kernel with and without threadgroup_barrier (Metal's __syncthreads): with the barrier, 0 wrong blocks in 15 repetitions; without it, 10.4% to 80.4% of the blocks were wrong in each repetition (median 47.4%), a different set every time measured on Apple M1 Pro GPU. A race is not "usually fine": it is wrong at a rate that depends on timing, which is why it survives small tests.
The compiler makes it worse. Without a barrier, nothing tells the compiler that another thread may have changed s[t], so it may keep its own copy in a register. The real SASS shows it did: the correct block_sum reads shared memory 17 times (two loads per level, eight levels, plus the result) with 9 BAR.SYNC; the barrier-free version reads it only 9 times, because s[t] never gets re-read compiled here. The barrier is also a compiler fence: it is what makes the write of another thread visible at all.
if (t < k) { ...; __syncthreads(); } is a bug, so put the barrier outside the if; threads that exit early are fine. Races and bad barriers are found by compute-sanitizer --tool racecheck ("shared memory data access hazards") and --tool synccheck ("invalid usages of synchronization primitives") vendor doc, v2026.3.0.An atomic is a read-modify-write no other thread can interleave with: atomicAdd(&h[bin], 1) is correct even when thousands of threads hit the same bin. Atomics wait for no one, so they are how blocks combine results without a grid barrier: each block reduces its part with shuffles and shared memory, then issues one atomicAdd to the global total. The cost is contention: atomics to one address are processed one after another.
The two fixes, both in p2_sync.cu: aggregate first (one atomic per warp, which the compiler did by itself in section 3) and privatise (a histogram in shared memory per block, ATOMS in SASS, merged into global memory once per block). Floating-point atomics add in arrival order, so a float sum by atomics can differ in the last bits from run to run; for bit-identical results reduce in a fixed order (Profiling, benchmarking and correctness covers tolerances).
A grid barrier. Cooperative groups (#include <cooperative_groups.h>) turn each scope into an object with sync(): this_thread_block(), tiled_partition<32>(block) for a warp, this_cluster(), this_grid(). grid.sync() is built from the narrower tools: every block meets at its block barrier, one thread per block adds to a counter in global memory and spins until every block has arrived. A spinning block occupies its SM, so blocks not yet scheduled could never start and the grid would hang; that is why grid.sync() needs a cooperative launch that refuses grids larger than what fits at once (here, on an H100 with 256-thread blocks: 8 blocks per SM × 132 SMs = 1,056 blocks at most derived with NVIDIA's occupancy rules). Most code takes the cheaper route: end the kernel and launch a second one.
Clusters (compute capability 9.0 and later) sit between block and grid: up to 8 blocks, portably, scheduled together on neighbouring SMs, each able to read the others' shared memory (distributed shared memory) and to meet at a hardware barrier, cluster.sync(). Hopper and Blackwell kernels use them to share tiles between SMs (TMA multicast, FlashAttention-3), which is on Libraries and tensor cores; how DSMEM is wired is on GPU architecture.
The kernel below normalises an array by its own total: phase 1 sums, a grid-wide barrier, phase 2 divides.
cg::grid_group grid = cg::this_grid();
float v = 0.f;
for (int i = grid.thread_rank(); i < n; i += grid.size()) v += x[i];
v = cg::reduce(cg::tiled_partition<32>(cg::this_thread_block()), v, cg::plus<float>());
if ((threadIdx.x & 31) == 0) atomicAdd(&partial[0], v);
grid.sync(); // every block has added before anyone reads
float total = partial[0];
for (int i = grid.thread_rank(); i < n; i += grid.size()) x[i] /= total;
How grid.sync() is implemented, from the real SASS (the relevant instructions in order) compiled here:
The barrier, then MEMBAR.ALL.GPU, then ATOM.E.ADD on the counter, then a spin (LD.E.STRONG.GPU in a loop with YIELD) until the counter shows every block has arrived; then the block barrier releases the rest. Launched with cudaLaunchCooperativeKernel, a grid that is too large fails with cudaErrorCooperativeLaunchTooLarge, which the runtime's own header defines as more blocks than "cudaOccupancyMaxActiveBlocksPerMultiprocessor ... times the number of multiprocessors" (driver_types.h, CUDA 13.4.2).
Clusters, compiled. __cluster_dims__(2, 1, 1) pairs blocks; cluster.map_shared_rank(s, other) returns a pointer into the partner block's shared memory, and cluster.sync() compiles to the hardware cluster barrier UCGABAR_ARV / UCGABAR_WAIT, the same on sm_90a, sm_100a and sm_120. For sm_80 the compiler refuses: __cluster_dims__ is not supported for this GPU architecture compiled here. The second cluster.sync() in p4_cluster.cu matters: a block must not exit while its partner may still read its shared memory.
The same kernel can be launched in thousands of ways, and the launch decides how much of the GPU works. You choose the block size, the grid size and the dynamic shared memory; the compiler chooses registers per thread, which you can steer. Two consequences follow: how many blocks fit on one SM at once (occupancy), and how many rounds the grid needs to get through the SMs (waves).
Occupancy is resident warps per SM divided by the most the SM can hold (64 on A100, H100 and B200; 48 on the RTX 5090). A block is placed on an SM only if all of it fits: its warps, its registers (registers per thread × threads), its shared memory and a free block slot. Why resident warps hide latency, and the per-generation limits, are on GPU architecture (sections 3 and 4).
Steering registers trades occupancy for spills. One kernel with many live values per thread (96 accumulators), compiled three ways:
__global__ void heavy_plain(...) // the compiler picks registers freely __global__ void __launch_bounds__(1024) heavy_lb1024(...) // "I will launch up to 1,024 threads per block" __global__ void __launch_bounds__(256, 8) heavy_lb256x8(...) // "256 threads, and I want 8 blocks per SM"
Fig. 3 fills one H100 SM with 256-thread blocks of these three kernels, compiled for sm_90a: registers per thread are the real ptxas -v counts compiled here; blocks per SM follow NVIDIA's rules from cuda_occupancy.h derived.
heavy_plain: 128 registers, 2 blocks. A warp needs 128 × 32 = 4,096 registers, a block 32,768: two blocks fill the register file while 48 of the 64 warp slots stay empty. 16 of 64 warps, 25% occupancy, limited by registers; a third block waits.__launch_bounds__(1024): 64 registers, 4 blocks. The promise of 1,024-thread blocks makes ptxas cap the kernel at 65,536 / 1,024 = 64 registers: 4 blocks fit, 32 warps, 50%. The values that no longer fit are spilled to local memory: 2,328 bytes of spill stores.__launch_bounds__(256, 8): 32 registers, 8 blocks. 8 blocks of 256 leave 32 registers per thread: all 64 warps resident, 100%, registers and warp slots running out together. Spill stores grow to 3,004 bytes.The same SM as a widget: 256-thread blocks, and the only thing that changes is how many registers each thread needs. The presets are the three kernels of Fig. 3; drag between them to see where each extra block stops fitting.
H100 (sm_90a): 64 warp slots drawn as 8 rows of 8, one row per 256-thread block; 65,536 registers per SM, allocated per warp in units of 256. Blocks per SM from the page's port of NVIDIA's cuda_occupancy.h, checked against the header on 1,155 values (Launch planner tab) derived.
The same three kernels compiled for all four targets:
Registers and spills: ptxas -v, CUDA 13.4.2 compiled here. Occupancy at 256 threads per block: NVIDIA's rules from cuda_occupancy.h derived. On A100, H100 and B200 the three kernels reach 25%, 50% and 100% occupancy, and both capped kernels spill (2,328 to 4,260 bytes of spill stores in the ptxas reports). "Spill" bytes are values that did not fit in registers and went to local memory, which lives in the GPU's main memory behind the caches (GPU memory hierarchy).
__launch_bounds__(maxThreadsPerBlock, minBlocksPerMultiprocessor) tells ptxas the launch you promise, so it caps registers to make it fit (and a launch above the promised size fails): 1,024 threads in 65,536 registers leaves 64 per thread, 8 blocks of 256 leaves 32 (-maxrregcount=N caps every kernel in the file). Occupancy goes up; so do spills. Which wins is a measurement, not a rule: for matmul and attention kernels, which reuse values held in registers, it is usually fewer warps and no spills. What a register cap does to one kernel step by step (a 128-accumulator kernel needs 160 registers on sm_90a; capped at 128 it spills 84 bytes, capped at 32 it spills 1,240) is section 4 of GPU memory hierarchy and its Memory instructions tab.
On sm_120 ptxas printed Value of threads per SM for entry heavy_lb256x8 is out of range. .minnctapersm will be ignored (8 × 256 = 2,048 threads, but an sm_120 SM holds 1,536) and kept 128 registers. And heavy_plain launched with 1,024 threads would need 128 × 1,024 = 131,072 registers, twice an SM's 65,536, so the launch fails with cudaErrorLaunchOutOfResources, "too many resources requested for launch", which the runtime header explains as "the kernel launch specifies too many threads for the kernel's register count".
Letting CUDA suggest a block size. cudaOccupancyMaxPotentialBlockSize(&minGrid, &block, kernel) returns the block size with the highest occupancy and the smallest grid that fills the GPU; for the simple scale kernel it answers 1,024 threads on H100 and 768 on the RTX 5090. That maximises occupancy, not speed: a starting point.
The API searches from the largest block size down and keeps the first that reaches the highest occupancy. NVIDIA ships the same logic as a host-only header, cuda_occupancy.h, which runs without a GPU: compiled and run here for this page's kernels on four GPUs and checked against this page's JavaScript port, the two agree on 1,155 of 1,155 values (0 mismatches) compiled and run here.
Block size in practice. Always a multiple of 32 (a partial warp wastes lanes); 128 to 256 is the usual default. Too small hits the block-slot cap: 32-thread blocks on an H100 give at most 32 blocks of one warp, 50% occupancy derived. Too large makes each block a big unit to schedule and synchronise. On the M1 Pro a memory-bound y = 2x over 64 Mi floats ran at 156.9 to 161.5 GB/s for every threadgroup size from 32 to 1,024 measured on Apple M1 Pro GPU: once enough threads are in flight, a simple kernel does not care. Kernels that use shared memory per block or synchronise inside the block do care, and are tuned by measurement (the autotuning in Triton and Gluon is exactly this search).
Blocks are handed to SMs as slots free up. If a grid has B blocks and the GPU holds S SMs × k blocks per SM at once, the grid runs in ceil(B / (S·k)) waves, and the last wave may be nearly empty while it costs nearly a full wave of time. NVIDIA's own example is a matrix multiply on an A100 (108 SMs) with 256 × 128 output tiles, one tile per block, one block per SM, M = 2,304, K = 4,096 (NVIDIA Matrix Multiplication Background guide, "Wave quantization") vendor doc. Growing N from 1,536 to 1,544 adds 0.5% more work; predict the cost before Fig. 4 steps it:
block_sum's registers and shared memory let 8 blocks share an SM, so the 132 SMs hold 1,056 blocks at once (each box is one SM's 8); the first three waves run 3,168.Measured on a real GPU. A compute-only Metal kernel with 1,024-thread threadgroups, each doing the same work, launched with 1 to 72 threadgroups on the M1 Pro's 16 GPU cores measured on Apple M1 Pro GPU, in the chart on the right.
When it matters. Waves matter when each block is long: matmul tiles and attention. A GEMM whose tile count is just over a multiple of the SM count wastes most of its last wave, and cuBLAS heuristics choose tile shapes (and split-K and Stream-K) partly to avoid it (Libraries and tensor cores). The Launch planner tab computes occupancy, the limiting resource and waves for this page's real kernels on four GPUs.
Median of 3 runs (dots: each run); time rises in steps at 17, 33, 49 and 65 threadgroups, about 1.31 ms per extra wave: 16 threadgroups of this size run at once, one per core. 17 threadgroups take as long as 32. The scattered points at the left are the first launches of runs 1 and 3, slowed by warm-up and by other jobs on the laptop.
CUDA functions return an error code (cudaError_t) instead of throwing, a kernel launch returns nothing at all, and a kernel that crashes is noticed only by some later call. Without a habit of checking, a bad launch looks like garbage output three functions later. There are three kinds of error and three places to catch them:
cudaMemcpy, out of memory in cudaMalloc. Wrap every call in a check macro.cudaErrorInvalidConfiguration; too many registers for the block: cudaErrorLaunchOutOfResources). The launch statement cannot return them, so ask right after it: cudaGetLastError() "returns current error state and then resets it to cudaSuccess" (cudaPeekAtLastError() returns it "without resetting it").assert, a timeout. They surface at the next call that waits for the GPU, and are "returned by every CUDA runtime API until the error state has been cleared" (Programming Guide 2.1.7) vendor doc.It opens at the launch (step 4); step back for the start. Same program and schematic timing as section 1 illustrative timing. The error is reported by cudaMemcpy, two calls after the guilty launch; cudaGetLastError() right after the launch returned success. Code 700 is cudaErrorIllegalAddress, a sticky error (below).
The program of section 1 again, with a kernel that reads out of bounds. Predict which line reports the error, then follow the stepper:
x: an illegal address, and the kernel stops. The CPU had already called cudaGetLastError(), which returned cudaSuccess: the launch itself was valid.cudaErrorIllegalAddress, "an illegal memory access was encountered". This is the line the error macro blames, two calls after the guilty launch.cudaFree included. The process must be restarted; no retry inside it can recover.#define CUDA_CHECK(call) do { cudaError_t e_ = (call); if (e_ != cudaSuccess) \
printf("%s:%d %s failed: %s (%s, code %d)\n", __FILE__, __LINE__, #call, \
cudaGetErrorName(e_), cudaGetErrorString(e_), (int)e_); } while (0)
CUDA_CHECK(cudaGetDeviceCount(&n));
CUDA_CHECK(cudaMalloc(&d, 1024));
k<<<1, 256>>>(d);
CUDA_CHECK(cudaGetLastError()); // launch-time errors
CUDA_CHECK(cudaDeviceSynchronize()); // errors raised while the kernel ran
This program (src/cuda/host/errors.cu) was compiled and run in the container, which has the CUDA runtime but no GPU and no driver; its real output run here:
Without a driver, every call fails with code 35, not with "no CUDA-capable device" (code 100): the runtime cannot even ask. The same program printed the runtime's own name and message for the errors a kernel author meets most, with the comment that explains each in driver_types.h (CUDA 13.4.2) where it is quoted here:
CUDA error: an illegal memory access was encountered that no try/except can recover from: the worker must restart, which is why elastic training restarts processes rather than retrying the step (Distributed Training).Finding the line that failed. Because errors surface late, the reported location is often wrong. Three tools fix that:
CUDA_LAUNCH_BLOCKING=1 makes every launch synchronous, so the error appears at the guilty launch. PyTorch's CUDA semantics notes: set it "to debug GPU errors or force synchronous behavior", for "more accurate" stack traces. Slow; for debugging only.compute-sanitizer (default tool memcheck: "out of bounds and misaligned memory access errors"; also racecheck, initcheck for reads of uninitialised global memory, synccheck) names the kernel, thread, block and address of the first bad access (Compute Sanitizer docs v2026.3.0). It runs much more slowly; use it on a small input.assert(i < n) stops the kernel with error 710, device-side assert triggered, another sticky error; in training it usually means a label outside the number of classes (closed block).In training: an illegal-address crash mid-run is almost always an out-of-range index (embedding ids, labels, gather indices) or a custom kernel's bounds check. Re-run the failing step with CUDA_LAUNCH_BLOCKING=1, then under compute-sanitizer if it is your kernel.
Error 710's runtime message is exactly device-side assert triggered (printed by the program above), and its header comment reads "The device cannot be used again. All existing allocations are invalid". PyTorch's kernels assert on their inputs: its loss kernels check CUDA_KERNEL_ASSERT(INDEX >= 0 && INDEX < N_CLASSES) in Loss.cu (read 2026-10-05), which is where this message comes from in training.
A device pointer is an address in GPU memory: the CPU cannot dereference it, and a kernel cannot dereference an ordinary CPU pointer, so every byte a kernel touches is allocated on the device and brought there. A handful of calls cover nearly everything, and PyTorch makes the same calls for you:
| Call | What it does | Watch out for | PyTorch's version |
|---|---|---|---|
cudaMalloc / cudaFree | allocate and free device memory | slow calls; "cudaFree operations synchronize the entire device" | the caching allocator: freed tensors keep their memory for reuse |
cudaMemcpy | copy host to device, device to host, or device to device | "synchronous": it returns when the copy is done, after earlier work on the stream | t.to("cuda"), t.cpu(), .item() |
cudaMallocHost (pinned) | page-locked host memory the GPU can read directly | a copy from ordinary (pageable) memory is staged through a pinned buffer by the driver; too much pinned memory starves the OS | pin_memory=True in a DataLoader; t.to("cuda", non_blocking=True) |
cudaMemcpyAsync | a copy queued on a stream, returning at once | overlaps with other work only from pinned memory | non_blocking=True |
cudaMallocManaged | one pointer valid on host and device; pages move on demand | convenient, but page faults on first touch can be slow | rarely used in training |
cudaMallocAsync / cudaFreeAsync | stream-ordered allocation (CUDA 11.2): no device-wide synchronisation | memory is reused in stream order | PYTORCH_ALLOC_CONF=backend:cudaMallocAsync (CUDA 11.4 or newer) |
Why nvidia-smi shows your memory as used. PyTorch never calls cudaFree when a tensor dies: its caching allocator keeps the block for the next tensor, because cudaMalloc and cudaFree are slow and synchronising. The PyTorch notes: unused cached memory "still appears occupied in nvidia-smi"; torch.cuda.memory_allocated() counts live tensors and memory_reserved() counts everything the allocator holds; empty_cache() returns the unused part. When a run reports out-of-memory with plenty "reserved but unallocated", the cause is fragmentation, not a leak.
Shared memory is not allocated with this API. It is declared in the kernel, __shared__ float s[256]; (static) or extern __shared__ float s[]; sized by the third launch argument (dynamic); above 48 KB per block needs an explicit opt-in (closed block). Using it well (banks, tiling) is on GPU memory hierarchy.
Sources: Programming Guide 2.1.3 (cudaMemcpy "is synchronous") and the stream-ordered allocator post (NVIDIA blog, Jul 27, 2021: introduced in CUDA 11.2; "cudaFree ... synchronize[s] the entire device") vendor doc; pageable copies "must first allocate a temporary page-locked, or pinned, host array" and "you should not over-allocate pinned memory" (Mark Harris, "How to Optimize Data Transfers in CUDA C/C++", 2012) published; PyTorch behaviour from its CUDA semantics notes (2.14).
Shared memory limits. It is declared in the kernel: __shared__ float s[256]; (static, size known at compile time; ptxas reports "1024 bytes smem" for block_sum) or extern __shared__ float s[]; with the size given as the third launch argument (dynamic). Static shared memory "remain[s] limited to 48 KB", and "an explicit opt-in is also required to enable dynamic allocations above this limit" (cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, bytes)); "the H100 GPU enables a single thread block to address up to 227 KB of shared memory" (Hopper tuning guide) vendor doc. Everything about using it well (banks, tiling) is on GPU memory hierarchy.
Every launch is CPU work: the runtime and driver check the configuration, copy the arguments and write a command for the GPU into a queue. If kernels are short, the GPU finishes each one before the CPU has queued the next, and sits idle. Eager PyTorch launches at least one kernel per operation, so a model made of many small operations can be limited by launches rather than by the GPU, the regime Horace He calls overhead-bound ("Making Deep Learning Go Brrrr").
What travels with a launch. The grid and block shapes, the shared memory size, the stream, and the arguments by value. Arguments were limited to 4,096 bytes; CUDA 12.1 raised the limit to 32,764 bytes on Volta and later (NVIDIA blog, Jun 5, 2023) vendor doc. Checked here with a pointer plus a struct argument: 8 + 32,756 = 32,764 bytes compiles; 8 + 32,760 fails with compiled here. In SASS the arguments are read from a constant bank (the c[0x0][0x210] loads of section 1).
How long. NVIDIA's CUDA Graphs post measured a 2.9 µs kernel taking 9.6 µs per kernel when the CPU waited after each launch, 3.4 µs with CUDA Graphs (NVIDIA blog, 2019, V100) published. The asynchronous launch is what lets the CPU run ahead: queue many kernels, wait once. On the M1 Pro, through MLX, the same tiny Metal kernel (1,024 threads), charted on the right measured on Apple M1 Pro GPU.
Median of 3 runs (each the median of 7 trials). Launch and wait each time: 179.5 µs per kernel (runs 192.7, 179.5, 146.5). 200 launches queued, each reading the previous one's output, then one wait: 5.8 µs per kernel, about 31 times less. Both include MLX's Python and graph bookkeeping, so they are not CUDA numbers; the ratio is the lesson.
Three consequences for training code. Never synchronise in the hot loop without need (.item(), print(loss), a .cpu() every step: each one drains the queue). Fewer, larger kernels win when kernels are small: fusion, by hand or by torch.compile (Writing kernels, The compiler stack). And when the sequence of kernels repeats exactly, as in LLM decoding, record it once and replay it as a CUDA graph (Streams, CUDA graphs and multi-GPU programming). How to check: a profiler timeline shows gaps between kernels on the GPU row; if the gaps are as long as the kernels, you are overhead-bound (Profiling, benchmarking and correctness).
You will rarely write a main(). The model is the same from Python; only the spelling changes. Each route was tried here for real, in the container with the CUDA toolkit and no GPU, so each says how far it got (closed block):
| Route | Launch | Index | Block barrier | How far it got here |
|---|---|---|---|---|
| CUDA C++ | k<<<grid, block>>>(args) | blockIdx.x * blockDim.x + threadIdx.x | __syncthreads() | compiled for four targets |
| Numba CUDA | k[grid, block](args) | cuda.grid(1) | cuda.syncthreads() | ran in the simulator; PTX compiled |
CuPy RawKernel | k((grid,), (block,), (args)) | CUDA C++ in a string | __syncthreads() | needs a driver even to compile |
torch.utils.cpp_extension | <<<>>> inside a C++ function | CUDA C++ | __syncthreads() | needs a CUDA build of PyTorch |
| Triton | k[grid](args), grid of programs | tl.program_id(0): blocks, not threads | none: the compiler decides | see Triton and Gluon |
| Metal (MLX) | grid=, threadgroup= (grid counts threads) | thread_position_in_grid | threadgroup_barrier(...) | every M1 measurement on this page |
Triton changes the model itself: you write the program of one block on whole tiles (tl.load of 1,024 elements at once), and the compiler decides threads, warps, shared memory and synchronisation; everything on this page still happens, Triton does it for you, the rung the parent page's ladder puts right after calling a library. Metal: every measurement on this page ran as a Metal kernel through mx.fast.metal_kernel in MLX. Apple's GPU is a SIMT GPU with the same structure under different names (SIMD-group for warp, threadgroup for block), which is why the ideas transfer and the numbers do not.
What transfers and what does not. Warp-sized SIMD groups, barriers, races, the cost of launch-and-wait, and waves on a fixed number of cores all behaved as the CUDA model predicts. Absolute numbers do not transfer: the M1 Pro has 16 cores where an H100 has 132 SMs, about 160 GB/s where an H100 has 3.35 TB/s, and its compiler and driver are Apple's, so occupancy limits, atomic throughput and launch overheads differ.
from numba import cuda, float32
@cuda.jit
def scale(x, y, a):
i = cuda.grid(1) # = blockIdx.x * blockDim.x + threadIdx.x
if i < x.size:
y[i] = a * x[i]
@cuda.jit
def block_sum(x, out):
s = cuda.shared.array(256, dtype=float32) # __shared__ float s[256]
t = cuda.threadIdx.x
s[t] = x[cuda.blockIdx.x * 256 + t]
cuda.syncthreads() # __syncthreads()
k = 128
while k > 0:
if t < k:
s[t] += s[t + k]
cuda.syncthreads()
k //= 2
if t == 0:
out[cuda.blockIdx.x] = s[0]
scale[grid, block](x, y, 2.0) # the launch: [grid, block] instead of <<<>>>
Numba-CUDA is now a separate package maintained by NVIDIA (numba-cuda docs). Its simulator executes kernels "one block at a time. One thread is spawned for each thread in the block, and scheduling of the execution of these threads is left up to the operating system", and it "does not implement warp-level operations" (simulator docs): good for checking indexing and barriers, useless for timing.
import cupy as cp
k = cp.RawKernel(r'''
extern "C" __global__ void scale(const float* x, float* y, float a, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) y[i] = a * x[i];
}''', "scale")
k((grid,), (block,), (x, y, cp.float32(2.0), cp.int32(n))) # grid, block, arguments
from torch.utils.cpp_extension import load_inline
cuda_src = r'''
#include <torch/extension.h>
__global__ void scale_kernel(const float* x, float* y, float a, int n) { ... }
torch::Tensor scale(torch::Tensor x, double a) {
auto y = torch::empty_like(x);
int n = x.numel(), block = 256, grid = (n + block - 1) / block;
scale_kernel<<<grid, block>>>(x.data_ptr<float>(), y.data_ptr<float>(), (float)a, n);
return y;
}'''
m = load_inline("pm_scale", cpp_sources="torch::Tensor scale(torch::Tensor x, double a);",
cuda_sources=cuda_src, functions=["scale"]) # nvcc + ninja, then import
On a CUDA build of PyTorch with a GPU, load_inline writes the sources to a build directory, compiles them with nvcc and ninja, and imports the result as a Python module (PyTorch C++ extension docs). A production version also launches on PyTorch's current stream, checks devices and dtypes, and registers the function with torch.library so torch.compile can see it; that is pytorch-ecosystem territory.
| CUDA | Metal (MSL) | Note |
|---|---|---|
| warp (32 threads) | SIMD-group | 32 threads on the M1 Pro (threads_per_simdgroup, measured by the root's simulator agent) |
block, __shared__ | threadgroup, threadgroup memory | up to 1,024 threads and 32 KB per threadgroup on Apple7 (M1), Apple's Metal feature set tables |
threadIdx, blockIdx, global index | thread_position_in_threadgroup, threadgroup_position_in_grid, thread_position_in_grid | the global index is built in |
| lane, warp id | thread_index_in_simdgroup, simdgroup_index_in_threadgroup | used in the atomics kernels here |
__syncthreads() | threadgroup_barrier(mem_flags::mem_threadgroup) | the race measurement of section 4 |
| warp shuffle reduction | simd_sum (also simd_shuffle_down, simd_ballot) | simd_sum used here |
atomicAdd | atomic_fetch_add_explicit(..., memory_order_relaxed) | used here |
k<<<grid, block>>> (grid counts blocks) | dispatch with grid=, threadgroup= (MLX's grid counts threads) | an easy off-by-a-factor mistake when porting |
| stream | command queue and command buffers | MLX batches launches into command buffers |
Names from the Metal Shading Language Specification; those marked "used here" compiled and ran in src/m1/measure.py (MLX 0.32.3) measured on Apple M1 Pro GPU. MLX's grid convention is from its custom Metal kernels guide.
The mistakes the sections above already show (no bounds check, __syncthreads() in a branch, lockstep warps, chasing occupancy, 32-bit indices, sticky errors) are not repeated here.
Timing or error-checking the launch line. The launch returns before the kernel runs. A CPU timer around it measures the launch; an error check right after it sees only configuration errors. Synchronise (or use events) to time, and check after the next synchronising call for execution errors.
Expecting blocks to run in some order, or to wait for each other. "No ordering guarantees are made by the scheduler" (Programming Guide 2.3.7). A block that spins waiting for a later block can deadlock if that block is never scheduled; only a cooperative launch guarantees co-residency.
Block size not a multiple of 32, or threadIdx.x on the wrong dimension. A 100-thread block wastes 28 lanes of its fourth warp. Making threadIdx.y walk the contiguous dimension spreads each warp's load over 32 rows (32 sectors instead of 4: the 1 × 256 case in section 2).
blockIdx.x * blockDim.x + threadIdx.x and the ceiling-division grid; always bounds-check; 64-bit indices for very large tensors.CUDA_CHECK; cudaGetLastError() after each launch while developing.-arch=sm_90a for H100 features, -arch=sm_120 for an RTX 5090 (CUDA 12.8 or later), or -arch=native; current toolkit 13.4.2. Look at -Xptxas -v for registers and spills.compute-sanitizer.Why must blocks be independent? So the hardware can run them in any order on any number of SMs: the same binary scales from a laptop GPU to a 170-SM card. Cross-block cooperation goes through atomics, a second kernel, a cooperative launch or (sm_90+) clusters.
How do you sum 4,096 numbers in one block? Each thread sums its share (grid-stride), each warp reduces with 5 shuffles, warp leaders write to shared memory, __syncthreads(), one warp reduces the partials. One barrier instead of eight.
What limits occupancy, and is higher always better? Registers per thread, shared memory per block, threads per block and the block-slot cap, whichever runs out first. No: matmul-like kernels trade warps for registers and reuse; spills to reach high occupancy usually lose.
An illegal memory access error appears at a cudaMemcpy. Is the copy wrong? Probably not: execution errors surface at the next synchronising call. Re-run with CUDA_LAUNCH_BLOCKING=1 or under compute-sanitizer to find the kernel; the process must restart.
saxpy example is replaced by kernels compiled here. Everything else on the old page is carried and now sourced; see src/coverage.json.Pick a GPU and a kernel, then a block size and a problem size: the planner shows how many blocks fit on one SM and which resource stops more from fitting, the occupancy for every block size, the block size CUDA's occupancy API would suggest, and how many waves the grid needs. The presets are this page's kernels with their real ptxas -v reports (CUDA 13.4.2) compiled here; "Custom" lets you type your own.
cuda_occupancy.h (CUDA 13.4.2), ported line by line: registers are allocated per warp in units of 256 and split over 4 SM sub-partitions; each block uses its shared memory plus 1 KB reserved by the system, rounded up to 128 bytes, against the SM's maximum carveout; plus the warp limit, the block-slot limit and the barrier limit; per-SM limits from the CUDA Programming Guide, Tables 30 and 31. The suggested block size follows cudaOccMaxPotentialOccupancyBlockSize: from 1,024 down, the first block size reaching the highest number of resident threads. For the presets, the header itself was compiled and run without a GPU: it agrees with this page on . Waves = ceil(grid / (SMs × blocks per SM)) derived; they assume every block takes the same time. SM counts: A100 108, H100 SXM 132 (NVIDIA architecture blogs), B200 148 (independent measurement paper, arXiv 2512.02189), RTX 5090 170 (NVIDIA whitepaper). Occupancy is not speed: see section 5 of the Reading tab.Every link opens in a new tab; times are reading or watching estimates. Links checked 2026-10-05.
Occupancy, the limiting resource, the suggested block size and waves for this page's real kernels on A100, H100, B200 and RTX 5090, checked against NVIDIA's occupancy header.
The root: the map of the topic, every optimisation lever with the page that owns it, and the five ways to get a kernel compared. Tabs: GPU simulator (divergence, occupancy, latency hiding), Compiler explorer (real PTX and SASS for four generations), Kernel lab (the running example unfused and fused, measured on the M1 Pro).
Coalescing and sectors, shared memory and bank conflicts, registers and spills, async copies, pinned and unified memory.
Reductions, scans, softmax, the matmul ladder, fusion, FlashAttention.
Block-level kernels, autotuning, what the Triton compiler does.
cuBLAS, cuDNN, CUTLASS and CuTe; mma, wgmma, TMA, tcgen05; clusters in use.
Nsight Systems and Compute, honest timing, numerical checks.
nvcc phases, PTX, SASS, NVRTC, torch.compile and Inductor.
Streams and events, overlap, CUDA graphs, NCCL as an API.
The SM from zero, latency hiding and Little's law, occupancy limits per generation, divergence measured, tensor cores, Ampere to Rubin.
Chips, memory technology, interconnects, roofline and MFU, costing hardware.
What a launch does below the runtime: the driver, the kernel module, the device queues.
CPU caches and SIMD (section 6), the CPU side of SIMT. 33 min, plus 21
llama.cpp and its backends, CUDA among them. 37 min, plus 39
Where sticky errors and restarts meet elastic training; NCCL streams overlapping backward.
Custom ops, torch.library, the caching allocator in depth. 30 min
NVIDIA's reference, reorganised in CUDA 13: introduction, writing kernels, thread hierarchy; appendices for limits and language extensions.
The optimisation checklist NVIDIA maintains.
Hwu, Kirk and El Hajj. Threads, blocks and scheduling; the best teaching treatment.
Lecture 2 covers PMPP chapters 1 to 3; Christian Mills's notes (30 min).
Short, precise definitions of SIMT, warp, occupancy and the rest.
Lin and Grover, 2018: the _sync functions, masks, independent thread scheduling.
NVIDIA's introduction to groups as objects, tiles and grid synchronisation.
Mark Harris, 2013.
Tiles, waves and why GEMM shapes matter, with NVIDIA's measured curves.
memcheck, racecheck, initcheck, synccheck.
Launch overhead measured, and the fix.
Horace He: compute-, memory- and overhead-bound.
Why the 4 KB argument limit went, and what it saved.
cudaMallocAsync and why cudaFree synchronises.
The three Python routes of section 9.
For running the same experiments on a Mac.