Phase 02/Where the bytes live/GPU memory hierarchy
PHASE 02 · Where the bytes live

GPU memory hierarchy

0%
6 h5 subtopics2 lessons · 1 required
In plain English

Think of a cook working in a huge kitchen. Ingredients in their hands (registers) are instant to use. The counter next to them (shared memory) is a quick reach away and the whole team at that station can use it. The walk-in pantry at the back of the building (global memory) holds everything but every trip takes a long time. A GPU has exactly these three tiers, and the entire art of fast kernels is deciding what to fetch from the pantry once, put on the counter, and reuse many times. Get this wrong and your thousands of cooks spend all day walking to the pantry instead of cooking.

Why it matters

LLM inference at small batch sizes is dominated by moving weights from GPU memory, not by arithmetic. Shared memory tiling is the trick behind fast matmul and FlashAttention, and register pressure decides how many warps fit on an SM.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Rank registers, shared memory, L1/L2 cache and global memory by latency and capacity.
  • Explain what shared memory is for and how __syncthreads() coordinates its use.
  • Describe shared memory bank conflicts and one way to avoid them.
  • Predict how register and shared memory usage limits occupancy.

Key concepts

Global memory (HBM/GDDR)
The large off-chip DRAM holding all tensors; hundreds of cycles of latency.
Shared memory
Programmer-managed on-chip scratchpad per block, tens of KB per SM, roughly 20-30x lower latency than global memory.
Registers
Per-thread storage inside the SM; fastest level, but using many per thread reduces how many threads fit.
L2 cache
A chip-wide cache (tens of MB on modern GPUs) that sits in front of global memory and is not programmer-controlled.
Bank conflict
Two threads in a warp hitting different addresses in the same shared memory bank, forcing serialised access.
Register spilling
When a kernel needs more registers than available and the compiler moves values to slow local memory.
Memory-bound kernel
A kernel whose runtime is set by bytes moved rather than arithmetic performed.

Subtopics

  1. 1. The tiers and their numbers

    Capacity, latency and bandwidth of registers, shared memory, L1, L2 and HBM on a T4 and an A100; where each is physically located.

  2. 2. Global memory and the host-device boundary

    cudaMalloc, cudaMemcpy, pinned memory, PCIe versus HBM bandwidth, and why copying is often the real bottleneck.

  3. 3. Shared memory and __syncthreads

    Declaring __shared__ arrays, the load-sync-compute-sync pattern, and bank layout.

  4. 4. Registers, local memory and occupancy

    Reading register count from the compiler, how 255 registers per thread caps resident warps, and what spilling looks like.

  5. 5. Caches you do not control

    L1/texture cache and L2; why reuse within a block should go through shared memory rather than hoping for cache hits.

Resources

article
paper

Hands-on lessons

L1

Measure the latency of each memory tier on a T4

Colab T4 · freenotebook90 minrequired

Goal · A bar chart of measured cycles-per-access for registers, shared memory, L2-resident global memory and DRAM-resident global memory.

  1. 1On Colab, use %%writefile to create pchase.cu, a pointer-chasing kernel that follows a linked list of indices and reads clock64() before and after.
  2. 2Compile with !nvcc -arch=sm_75 -o pchase pchase.cu and run with array sizes 4 KB (L1), 1 MB (L2) and 256 MB (DRAM).
  3. 3Add a variant that chases through a __shared__ array and one that only does register arithmetic in a loop.
  4. 4Divide elapsed clocks by the number of accesses and plot one bar per tier.
  5. 5Compare with Table 3 of the Volta microbenchmarking paper and note which numbers moved for Turing.
Deliverable
Notebook with pchase.cu, the raw clock numbers and the bar chart.
Check
Shared memory is at least 10x faster per access than DRAM-resident global memory; the three global-memory sizes show clearly increasing latency.
Fallback
Run on Kaggle, or read the Volta paper tables and reproduce the chart from their numbers.
L2

Shared-memory tiling for a 1D stencil

Colab T4 · freenotebook75 minoptional

Goal · A numba.cuda 1D stencil kernel that loads a tile plus halo into shared memory and runs faster than the naive global-memory version.

  1. 1Write a naive 7-point moving-average kernel where each thread reads its 7 neighbours from global memory.
  2. 2Write a tiled version that loads blockDim.x + 6 elements into cuda.shared.array, calls cuda.syncthreads(), then computes from shared memory.
  3. 3Verify both against numpy.convolve on a 1e7-element array.
  4. 4Time both for block sizes 128 and 256 and compute effective bandwidth as bytes_read / time.
  5. 5Deliberately remove the syncthreads call and show that results become nondeterministic across runs.
Deliverable
Notebook with both kernels, timings and the broken-without-sync demonstration.
Check
Both kernels match numpy within 1e-5; the tiled kernel is faster or at least equal, and the no-sync version produces at least one wrong element.

Build your own

Build your own shared-memory reduction

CUDA C++Colab T4 · free~5 h

A sum reduction over 16 million floats that climbs from one atomicAdd per element to a shared-memory tree, warp shuffles and a grid-stride kernel that runs at memory bandwidth, each step measured.

The real thing: github.com/NVIDIA/cccl/tree/main/cub ↗

How you know a stage passes

reduce.cu holds every version behind a `-k N` flag. A driver fills 1<<24 random floats, runs the chosen kernel, compares with a float64 CPU sum (relative error must be below 1e-5), and prints one CSV line with ms and GB/s from CUDA events. tests/test_reduce.py (written first) runs the binary via subprocess for each stage and asserts the error bound and the speed relationships below. Run `pytest -q` on a Colab T4.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01every thread does one atomicAdd
    A correct but contended baseline where each thread atomically adds its element into a single device float.
    test · Relative error below 1e-4 against the float64 sum; the printed ms is recorded as the baseline that later stages are compared to.
  2. 02shared-memory tree per block
    Each block loads a tile into __shared__, halves the stride with __syncthreads between steps, and thread 0 does one atomicAdd per block.
    test · Relative error below 1e-5; at least 10x faster than s1; with the __syncthreads calls removed, at least one of five runs returns a wrong sum.
  3. 03sequential addressing and first add on load
    Replace interleaved addressing (which leaves half of every warp idle and causes bank conflicts) with stride halving from blockDim/2, and have each thread add two elements while loading.
    test · At least 1.5x faster than s2 at the same block size and the achieved GB/s is printed.
  4. 04warp shuffles for the last five levels
    The final 32-value reduction uses __shfl_down_sync instead of shared memory, leaving one __syncthreads in the kernel.
    test · Relative error below 1e-5; not slower than s3; the register count from `nvcc --ptxas-options=-v` is recorded in the README.
  5. 05grid-stride accumulation to reach bandwidth
    A fixed grid (about 8 blocks per SM, 320 on a T4) where each thread accumulates many elements in a register over a grid-stride loop before the block tree, so the kernel is bound by reading the input once.
    test · Effective bandwidth (n x 4 bytes / time) is at least 70 percent of your measured device copy bandwidth (Colab T4s sustain about 220-250 GB/s of the 320 GB/s spec); relative error below 1e-5.
  6. 06race CUB and torch.sum
    A benchmark driver times your best kernel against cub::DeviceReduce::Sum and torch.sum on the same array and writes results.csv plus a GB/s-per-stage plot.
    test · Your kernel is within 1.3x of CUB at n = 1<<24; results.csv has one row per stage plus CUB and torch; the plot is in the README.

Knowledge check

QOrder these from fastest to slowest - global memory, registers, shared memory, L2 cache.

Registers, shared memory, L2 cache, global memory.

QWhat does __syncthreads() guarantee and what is its scope?

Every thread in the block has reached that point and all their shared/global writes are visible to the block; it does not synchronise across blocks.

QWhy can using 200 registers per thread make a kernel slower even if no spilling occurs?

The register file is finite, so fewer warps fit on the SM, occupancy drops and there are not enough warps to hide memory latency.

QWhat is the pointer-chasing trick measuring?

True dependent-load latency, because each address depends on the previous load so the hardware cannot overlap requests.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All five subtopics marked completed.
  • Lesson l1 latency chart saved with numbers in the expected ratios.
  • Can draw the memory tiers with rough latency numbers for a T4.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →