The CUDA programming model: threads, warps, blocks, launches, occupancy

How you tell a GPU what to run: a complete CUDA program and its two timelines, how each thread finds its data, warps and warp-level cooperation, synchronisation from a warp to the whole GPU, occupancy and waves, the error model, the memory API and launch cost. Real compiler output for four NVIDIA targets; measurements on an Apple M1 Pro GPU, labelled. Child of Topic: cuda-and-gpu-programming. Data as of October 2026. Reading: 36 min, plus 16 in closed details.

The idea in one screen

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:

  1. The grid: 4,096 blocks. The launch asks for a grid of 4,096 blocks of 256 threads, one thread per element (4,096 × 256 = 1,048,576). Blocks 0 to 31 are drawn. Blocks run in any order on any SM, so they never wait for each other.
  2. Block 9: 256 threads in 8 warps. One block always runs on one SM, never split. The hardware cuts it into warps by linear thread id: warp w holds threads 32w to 32w + 31, so 256 threads = 8 warps.
  3. Warp 1: 32 lanes. Threads 32 to 63 of the block issue as one: each instruction runs for all 32 lanes at once.
  4. Lane 5 is thread 37. The thread highlighted is 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.
  5. Each level talks its own way. Under each plate: how its threads cooperate, and where it runs. The grid: atomics, or end the kernel, spread over all SMs in waves. The block: shared memory and __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.

Host, device
the CPU with its memory; the GPU with its own memory.
Kernel
a __global__ function: runs on the device, launched from the host.
Grid, block, thread
a launch is a grid of blocks; a block (up to 1,024 threads) runs on one SM and its threads can share memory and wait for each other.
Warp, lane
32 consecutive threads of a block, issued as one instruction; a lane is a thread's position (0 to 31) in its warp.
SM
streaming multiprocessor, the GPU's core: 108 on an A100, 132 on an H100.
Occupancy
warps resident on an SM divided by the most it can hold.
Wave
one round of blocks filling every SM; a grid needs ceil(blocks / (SMs × blocks per SM)) of them.

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.

The page in one table (reference)
IdeaIn one lineHow to check itSection
Kernel, launchA __global__ function; k<<<grid, block>>>(args) starts grid × block threads and returns at once.cudaGetLastError() after the launch1
Thread, block, gridEach thread reads blockIdx, blockDim, threadIdx to compute which element is its job.a bounds check on every index2
Warp32 threads with consecutive ids, issued together; they can swap registers (shuffles) and vote.SASS: SHFL, VOTE3
SynchronisationWarp: __syncwarp. Block: __syncthreads + shared memory. Cluster: cluster.sync(). Whole grid: end the kernel (or a cooperative launch). Any thread: atomics.compute-sanitizer --tool racecheck4
Launch configurationBlock 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 planner5
ErrorsReturn codes, not exceptions; kernel errors appear at a later call; some poison the whole process.a CUDA_CHECK macro, CUDA_LAUNCH_BLOCKING=16
Memory APIcudaMalloc, cudaMemcpy, pinned and managed memory, the stream-ordered allocator.torch.cuda.memory_allocated() vs memory_reserved()7
Launch costMicroseconds of CPU work per launch; tiny kernels leave the GPU idle between them.a profiler timeline (gaps between kernels)8

1. Host and device: a complete program

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);
}
CPU workCPU blocked (hatched)copykernelerror

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:

  1. Start. The host arrays hx and hy (1,048,576 floats, 4 MiB each) are in CPU memory. Nothing is on the GPU yet.
  2. 1 cudaMalloc, twice. 4 MiB each in GPU memory (1,048,576 × 4 B). dx and dy are device addresses: the CPU holds them but cannot dereference them.
  3. 2 cudaMemcpy, host to device. Synchronous: the CPU waits until the 4 MiB have crossed to the GPU.
  4. 3 and 4 The launch. scale<<<4096, 256>>>: the CPU writes a launch command into the stream's queue and returns at once. Nothing has run yet.
  5. The kernel runs; the CPU runs on. 4,096 blocks spread over the SMs. Meanwhile the CPU executes the next line, cudaGetLastError(): cudaSuccess, the launch was valid. It could do any other work here.
  6. 5 cudaMemcpy, device to host. Queued behind the kernel on the same stream, so it starts only when the kernel ends; the CPU is blocked from the call until the copy is done.
  7. 6 and 7 Check and free. Compare 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).

Predict: n = 1,000,000 and block = 256. How many threads does the launch start, and how many do no work?
What the GPU actually runs: the real SASS of 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.

2. How each thread finds its data: indexing

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-inMeaningLimit vendor doc
threadIdx.{x,y,z}this thread's position inside its blockblock x, y ≤ 1,024; z ≤ 64; x·y·z ≤ 1,024
blockDim.{x,y,z}the block's shape, as launchedsame
blockIdx.{x,y,z}this block's position in the gridgrid x ≤ 231−1; y, z ≤ 65,535
gridDim.{x,y,z}the grid's shapesame
warpSizethreads per warp32 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.

Three patterns cover almost every kernel

// 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.

Which threads form a warp

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.

Predict: a 16 × 16 block. Which threads are in warp 1?

The block's shape decides which elements one warp loads together

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).

3. Warps from the programmer's side

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):

  1. A block, cut into warps. With blockDim.x = 256, warp w holds threads 32w to 32w + 31: eight warps.
  2. One instruction, 32 lanes. Warp 1 issues 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.
  3. Path A, half the lanes masked. At 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.
  4. Path B, the other half masked. Then path B for lanes 16 to 31, with lanes 0 to 15 masked. Each path ran with half the warp idle.
  5. Reconverged: the branch cost both paths. After the branch all 32 lanes run together again. A divergent branch costs the sum of its paths, which is why kernels keep branches uniform within a warp where they can.

One warp's sum: five shuffles against shared memory and barriers

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.

A warp's row sum: shuffles

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:

  1. Start: lane i holds i + 1. Each lane has one value in a register. Sum = 528.
  2. Shuffle 1 of 5: add the value 16 lanes away. 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.
  3. Shuffle 2: 8 lanes away. Lanes 0 to 7 now carry the partial sums.
  4. Shuffle 3: 4 lanes away. Lanes 0 to 3.
  5. Shuffle 4: 2 lanes away. Lanes 0 and 1.
  6. Shuffle 5: 1 lane away. Lane 0 now holds 528: five instructions, no memory, no barrier.
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.

The warp-level functions, the Volta change in NVIDIA's words, and the compiler's warp-aggregated atomics (depth)
Warp-level functionWhat it doesSASS seen here
__shfl_sync(m, v, src), _up, _down, _xorEach 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_syncWhich 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.

4. Synchronisation, from a warp to the whole GPU

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.

ScopeToolWhat it costs or requiresReal SASS (sm_90a) compiled here
Warp (32 threads)shuffles, votes, __syncwarp (section 3)registers only; no memorySHFL, VOTE, REDUX
Block (up to 1,024)__syncthreads() + __shared__ memorya hardware barrier per SM; every thread of the block must reach the same barrierBAR.SYNC, STS/LDS
Cluster (up to 8 blocks portably; sm_90 and later)cluster.sync(), another block's shared memory via cluster.map_shared_rankthe blocks of a cluster are scheduled together on neighbouring SMsUCGABAR_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 oncebarrier, MEMBAR.ALL.GPU, ATOM.E.ADD on a counter, a spin loop
Any threads, no waitingatomics (atomicAdd, atomicCAS, ...), fences __threadfence_block/()/_systemcontention on one address serialises; fences order memory, they do not wait for anyoneREDG, 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 tree sum in shared memory: the barrier is what makes it right

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 barrier, and what happens without it

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:

  1. Start. Both warps issue their load of x from global memory. Shared memory s[0..15] is empty.
  2. Warp 0 stores and waits. Warp 0's load arrived: s[0..7] written. It reaches __syncthreads() and waits: 8 of 16 threads have arrived.
  3. Warp 1 stores; the barrier opens. Warp 1's load arrives late, s[8..15] written, it reaches the barrier: 16 of 16 arrived, everyone continues.
  4. Level k = 8. Threads 0 to 7 add s[t + 8] into s[t], then all 16 meet at __syncthreads() again.
  5. Level k = 4. Threads 0 to 3 add s[t + 4], then the barrier.
  6. Level k = 2. Threads 0 and 1 add s[t + 2], then the barrier.
  7. Level k = 1. Thread 0 adds s[1], then the barrier.
  8. Result: 80. Thread 0 writes s[0] = 80, the correct sum.

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.

The rules of __syncthreads()
It is "permitted in conditional code, but only if the condition evaluates uniformly across the entire thread block. Otherwise, execution may hang or produce unintended side effects" (language extensions): 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.

Atomics: combining without waiting

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.

Contention fixes, and why float atomics are not bit-reproducible (depth)

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).

Wider than a block: grid sync and clusters

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 grid-sync kernel, its SASS, and clusters compiled for four targets (depth)

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.

5. Choosing a launch: block size, occupancy, waves

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: the resource that runs out first

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.

  1. One SM, two budgets. An H100 SM holds at most 64 warps (left) and 65,536 registers (right), allocated per warp in units of 256; each cell on the right is 1,024 registers, one warp's worth at 32 per thread. A block is placed only if all of it fits. Shared memory and the block-slot cap are budgets too; these kernels use no shared memory.
  2. 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.
  3. __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.
  4. __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.

Any register count

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.

Registers per thread decide how many blocks share an SM: drag to try any count

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.

Two real compiler and runtime details (depth)

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.

How the suggestion is computed, and how this page checks its own occupancy numbers (depth)

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).

Waves and the tail

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:

  1. N = 1,536: 108 tiles, one wave. M = 2,304 gives ceil(2,304 / 256) = 9 tile rows and N = 1,536 gives ceil(1,536 / 128) = 12 columns: 108 tiles, one block each, one per SM. Every SM runs exactly one tile; the GPU is full the whole time.
  2. N = 1,544: 117 tiles. A thirteenth column of tiles: 9 × 13 = 117. The first wave takes 108 of them; 9 wait in the queue.
  3. Wave 2: 9 busy, 99 idle. The second wave runs 9 tiles on 9 SMs while 99 sit idle, and it takes as long as the first. 0.5% more work, twice the time: SM utilisation 54.2% derived: tiles = ceil(M/256) × ceil(N/128); waves = ceil(tiles / 108); every tile assumed to take the same time. NVIDIA reports that "GFLOPS roughly halve and duration roughly doubles from N=1536 to N=1544".
  4. The running example's row sum on an H100. One 256-thread block per row: 4,096 blocks. 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.
  5. The fourth wave is 87.9% full. 928 blocks are left: 4 waves in all, the last nearly full derived. Fine: the tail costs at most one wave in four, and with hundreds of thousands of small blocks it is a rounding error.

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.

Time rises in steps of 16 threadgroups: one wave per step

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.

6. When things go wrong: CUDA's error model

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:

  1. API errors, returned by the call itself: a bad argument to cudaMemcpy, out of memory in cudaMalloc. Wrap every call in a check macro.
  2. Launch errors: an impossible configuration (more than 1,024 threads per block, too much shared memory: 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").
  3. Execution errors, raised while the kernel runs: an out-of-bounds or misaligned access, a device-side 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.

The error surfaces two calls after the launch that caused it

CPU workCPU blocked (hatched)copykernelerror

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:

  1. Start. The same program as section 1: the host arrays are in CPU memory.
  2. 1 cudaMalloc, twice. As before.
  3. 2 cudaMemcpy, host to device. As before: the CPU waits for the copy.
  4. 3 and 4 The launch. The CPU queues the kernel and returns at once.
  5. The kernel faults; the CPU does not know. One thread reads past the end of x: an illegal address, and the kernel stops. The CPU had already called cudaGetLastError(), which returned cudaSuccess: the launch itself was valid.
  6. 5 cudaMemcpy reports the error. The copy waits for the kernel, which has failed, and returns code 700, cudaErrorIllegalAddress, "an illegal memory access was encountered". This is the line the error macro blames, two calls after the guilty launch.
  7. Sticky: every later call fails. Every CUDA call in this process now returns 700, 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
The real output of an error-handling program run without a GPU, and the runtime's own error messages (depth)

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:

Sticky errors: some errors end the process's use of the GPU
For an illegal address (700) and an unspecified launch failure (719) the header says: "This leaves the process in an inconsistent state and any further CUDA work will return the same error. To continue using CUDA, the process must be terminated and relaunched." In a training job this is the familiar 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.
  • A device-side 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.

Where "device-side assert triggered" comes from in PyTorch (depth)

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.

7. The host-side memory API, the basics

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:

CallWhat it doesWatch out forPyTorch's version
cudaMalloc / cudaFreeallocate and free device memoryslow calls; "cudaFree operations synchronize the entire device"the caching allocator: freed tensors keep their memory for reuse
cudaMemcpycopy host to device, device to host, or device to device"synchronous": it returns when the copy is done, after earlier work on the streamt.to("cuda"), t.cpu(), .item()
cudaMallocHost (pinned)page-locked host memory the GPU can read directlya copy from ordinary (pageable) memory is staged through a pinned buffer by the driver; too much pinned memory starves the OSpin_memory=True in a DataLoader; t.to("cuda", non_blocking=True)
cudaMemcpyAsynca copy queued on a stream, returning at onceoverlaps with other work only from pinned memorynon_blocking=True
cudaMallocManagedone pointer valid on host and device; pages move on demandconvenient, but page faults on first touch can be slowrarely used in training
cudaMallocAsync / cudaFreeAsyncstream-ordered allocation (CUDA 11.2): no device-wide synchronisationmemory is reused in stream orderPYTORCH_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.

The sources for the table, and shared memory limits (depth)

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.

8. What a launch costs

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, and the argument-size limit (depth)

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.

Queue many launches, wait once: about 31 times less per kernel

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).

9. The same model from Python, and in Metal

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):

RouteLaunchIndexBlock barrierHow far it got here
CUDA C++k<<<grid, block>>>(args)blockIdx.x * blockDim.x + threadIdx.x__syncthreads()compiled for four targets
Numba CUDAk[grid, block](args)cuda.grid(1)cuda.syncthreads()ran in the simulator; PTX compiled
CuPy RawKernelk((grid,), (block,), (args))CUDA C++ in a string__syncthreads()needs a driver even to compile
torch.utils.cpp_extension<<<>>> inside a C++ functionCUDA C++__syncthreads()needs a CUDA build of PyTorch
Tritonk[grid](args), grid of programstl.program_id(0): blocks, not threadsnone: the compiler decidessee Triton and Gluon
Metal (MLX)grid=, threadgroup= (grid counts threads)thread_position_in_gridthreadgroup_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.

Numba, CuPy and PyTorch extension code with what each run printed; the CUDA to Metal dictionary (depth)

Numba CUDA: Python syntax, CUDA semantics

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.

CuPy RawKernel: CUDA C++ in a string

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

torch.utils.cpp_extension: a CUDA kernel as a PyTorch function

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 to Metal

CUDAMetal (MSL)Note
warp (32 threads)SIMD-group32 threads on the M1 Pro (threads_per_simdgroup, measured by the root's simulator agent)
block, __shared__threadgroup, threadgroup memoryup to 1,024 threads and 32 KB per threadgroup on Apple7 (M1), Apple's Metal feature set tables
threadIdx, blockIdx, global indexthread_position_in_threadgroup, threadgroup_position_in_grid, thread_position_in_gridthe global index is built in
lane, warp idthread_index_in_simdgroup, simdgroup_index_in_threadgroupused in the atomics kernels here
__syncthreads()threadgroup_barrier(mem_flags::mem_threadgroup)the race measurement of section 4
warp shuffle reductionsimd_sum (also simd_shuffle_down, simd_ballot)simd_sum used here
atomicAddatomic_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
streamcommand queue and command buffersMLX 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.

Depth: mistakes, a first-kernel checklist, interview rehearsal

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.

Three more mistakes (depth)

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).

Checklist for a first kernel (depth)
  1. Index with blockIdx.x * blockDim.x + threadIdx.x and the ceiling-division grid; always bounds-check; 64-bit indices for very large tensors.
  2. Block size a multiple of 32, start at 128 or 256; tune by measurement.
  3. Wrap every runtime call in CUDA_CHECK; cudaGetLastError() after each launch while developing.
  4. Compile for your GPU: -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.
  5. Check results against a CPU or PyTorch reference before timing anything; run once under compute-sanitizer.
Interview rehearsal: four design questions (optional)

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.

Corrections to the old version of this page
"Current toolkit: 13.3": the current release is 13.4.2 (Docker Hub tag 2026-09-29; Programming Guide v13.4.2). "Compile for your GPU: RTX 5090": no NVIDIA GPU is used for this knowledge base; the checklist now names targets. "Matmul and attention deliberately run at 25 to 50% occupancy": the principle is kept (section 5 shows a real 25%-occupancy kernel), the range is unconfirmed and dropped. "64 warps per SM on recent architectures": true for A100, H100 and B200, but consumer GPUs (sm_86, sm_89, sm_120, including the RTX 5090) hold 48 (Programming Guide, Table 31). "A laptop GPU with 20 SMs": unconfirmed, dropped. "Launch overhead is a few microseconds": kept with NVIDIA's measured numbers. The old saxpy example is replaced by kernels compiled here. Everything else on the old page is carried and now sourced; see src/coverage.json.