Phase 02/Where the bytes live/Memory coalescing and bandwidth
PHASE 02 · Where the bytes live

Memory coalescing and bandwidth

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

A GPU fetches memory the way a delivery van picks up parcels. The van only stops at a depot once per trip and takes a whole crate, not a single parcel. If 32 workers each need one parcel and the parcels sit side by side in one crate, a single trip serves everyone. If the parcels are scattered across 32 crates, the van makes 32 trips and almost everyone waits. Arranging data so that neighbouring threads read neighbouring addresses is called coalescing, and it can make the same code ten times faster. The second idea in this topic, the roofline, is a simple chart that tells you whether your kernel is limited by how fast vans can drive or by how fast the workers can work.

Why it matters

Decode-phase LLM inference is almost entirely bandwidth-bound, so tokens per second is roughly bandwidth divided by model bytes. Being able to compute the bandwidth ceiling and check whether a kernel reaches it is the core skill of inference performance work.

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

  • Explain how a warp's 32 loads become one or many memory transactions.
  • Measure achieved bandwidth and compare it to the device peak.
  • Compute arithmetic intensity and place a kernel on a roofline plot.
  • Diagnose strided and misaligned access patterns and restructure them.

Key concepts

Coalesced access
Consecutive threads in a warp reading consecutive addresses so the loads merge into the minimum number of 32-byte sectors.
Memory transaction / sector
The unit (32 bytes on modern NVIDIA GPUs) in which the memory system moves data.
Strided access
Threads reading addresses spaced by a stride greater than one element; wastes most of each fetched sector.
Effective bandwidth
Useful bytes moved divided by kernel time; compare it to the theoretical peak from the spec sheet.
Arithmetic intensity
FLOPs performed per byte moved from memory; the x-axis of the roofline model.
Roofline model
A plot with peak compute as a flat ceiling and peak bandwidth as a sloped ceiling; a kernel's attainable performance is the minimum of the two.
Ridge point
The arithmetic intensity where the bandwidth roof meets the compute roof; below it kernels are memory-bound.

Subtopics

  1. 1. How warps access global memory

    32-byte sectors, 128-byte cache lines, alignment, and how the number of transactions per request is counted.

  2. 2. Access patterns that break coalescing

    Strided loops, array-of-structs layouts, column-wise access of row-major matrices, and the structure-of-arrays fix.

  3. 3. Measuring bandwidth

    Copy and SAXPY kernels as bandwidth tests; counting bytes correctly; why 70-85 percent of peak is typically the best achievable.

  4. 4. The roofline model

    Deriving the ridge point from peak FLOPS and bandwidth; placing matmul, softmax and attention on the chart.

  5. 5. Bandwidth and LLM decode

    Tokens per second upper bound as bandwidth / bytes of weights; why batching raises arithmetic intensity.

Resources

article
paper

Hands-on lessons

L1

Roofline numbers by hand from spec sheets

CPU · your Macdesign60 minrequired

Goal · A hand-drawn or matplotlib roofline for the T4 and A100 with four kernels placed on it, including Llama-2-7B decode at batch 1.

  1. 1From the datasheets, record peak FP16 tensor TFLOPS and memory bandwidth for T4 and A100-80GB; compute the ridge point in FLOPs per byte.
  2. 2Compute arithmetic intensity for float32 vector add (n=1e7), float16 square matmul with N=4096, and float16 softmax over a 4096 x 4096 matrix.
  3. 3For Llama-2-7B decode at batch 1 in FP16, estimate bytes moved per token (about 13.5 GB) and FLOPs per token (about 2 x 7e9), and compute intensity.
  4. 4Plot both rooflines on log-log axes in matplotlib and mark the four points.
  5. 5For each point write whether it is memory- or compute-bound and the attainable GFLOP/s.
  6. 6Compute the theoretical maximum tokens per second for batch-1 decode on each GPU.
Deliverable
roofline.png plus a short table of intensities and bounds.
Check
Vector add, softmax and batch-1 decode land left of the ridge point on both GPUs; matmul at N=4096 lands right of it; T4 decode ceiling is roughly 320 GB/s / 13.5 GB, about 24 tokens per second.
L2

Reproduce the strided-access bandwidth cliff

Colab T4 · freenotebook75 minrequired

Goal · A plot of effective bandwidth versus stride for a copy kernel on a T4, plus a measured peak-copy bandwidth figure.

  1. 1Write a numba.cuda copy kernel out[i] = in[i * stride] over a large float32 array, with a bounds check.
  2. 2Time it for stride 1, 2, 4, 8, 16, 32 using cuda.synchronize(); compute effective GB/s counting only useful bytes.
  3. 3Write an offset variant in[i + offset] for offsets 0 to 32 and plot the misalignment penalty.
  4. 4Compare your stride-1 bandwidth to the T4 peak of 320 GB/s and report the percentage achieved.
  5. 5Rewrite a column-wise read of a 4096 x 4096 row-major matrix as a row-wise read and show the speedup.
Deliverable
Notebook with the two plots and the percentage-of-peak figure.
Check
Stride-1 copy achieves at least 60 percent of peak; bandwidth at stride 32 is less than 15 percent of stride 1.
Fallback
Kaggle T4/P100, or analyse the published plot in the NVIDIA blog post and predict the cliff shape from sector size.

Build your own

Build your own bandwidth benchmark

CUDA C++Colab T4 · free~6 h

A CLI that measures copy, strided, misaligned and transpose kernels on a T4, with and without coalescing and shared-memory tiling, and plots every result on a roofline next to the 320 GB/s spec line.

The real thing: github.com/NVIDIA/cuda-samples/tree/master/cpp/6_Performance/transpose ↗

How you know a stage passes

bw.cu builds a CLI `./bw <kernel> <bytes> [stride|offset|tile]` that runs the kernel with CUDA events (median of 20 after 3 warm-ups), verifies the output against a host or device reference, and prints one CSV line (kernel, bytes, param, ms, GB/s). tests/test_bw.py, written first, calls the CLI via subprocess and asserts the correctness flag and the bandwidth relationships below; `python plot_roofline.py results.csv` writes roofline.png. Run `pytest -q` on a Colab T4.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01device-to-device copy and your measured peak
    A copy kernel over 256 MB of floats with a grid-stride loop; GB/s counts bytes read plus written; cudaMemcpy device-to-device is measured as the reference.
    test · Output equals input byte for byte; GB/s is at least 65 percent of the T4 spec of 320 (about 210 GB/s) and within 15 percent of cudaMemcpy D2D.
  2. 02strided and misaligned reads
    Stride and offset parameters on the read side; a sweep script runs stride 1..32 and offset 0..32 and appends to results.csv.
    test · Bandwidth at stride 32 is below 15 percent of stride 1; offset 1 is measurably below offset 0 and offset 32 is within 5 percent of offset 0.
  3. 03naive transpose
    A 4096 x 4096 float transpose with one thread per element that reads rows and writes columns (uncoalesced writes).
    test · Output matches the input transposed exactly; GB/s is below 40 percent of your s1 copy bandwidth.
  4. 04shared-memory tiled transpose
    32 x 32 tiles staged through __shared__ so both global reads and writes are coalesced.
    test · Output still exact; at least 2x faster than s3.
  5. 05pad the tile to remove bank conflicts
    Declare the tile as [32][33] so column reads of the tile hit distinct banks; confirm with the ncu shared-memory bank-conflict metric when the profiler is permitted.
    test · At least 1.2x faster than s4 and within 80 percent of your copy bandwidth; the l1tex shared bank-conflict count from ncu is reported, or the ERR_NVGPUCTRPERM block is documented and the timing alone is used.
  6. 06float4 loads and the roofline plot
    A float4 copy variant and plot_roofline.py, which draws the T4 roofline (8.1 TFLOPS FP32, 320 GB/s) and places every kernel in results.csv plus SAXPY and the matmuls from earlier lessons by their measured FLOP/s and arithmetic intensity.
    test · float4 copy is not slower than the float copy; `python plot_roofline.py results.csv` exits 0 and the png shows every bandwidth kernel within 30 percent below the memory roof and labelled.

Knowledge check

QA warp reads 32 consecutive float32 values starting at a 128-byte-aligned address. How many 32-byte sectors are fetched?

Four: 32 x 4 bytes = 128 bytes, which is exactly four sectors with no waste.

QWhy is batch-1 LLM decode memory-bound?

Every weight must be read once per token but is used for only about two FLOPs per batch element, giving an intensity far below the ridge point.

QWhat does doubling the batch size do to the arithmetic intensity of decode?

It roughly doubles it, since the same weight bytes now serve twice the FLOPs; this is why batching raises throughput almost for free until the ridge point.

QName one layout change that fixes uncoalesced access to an array of structs.

Convert to a structure of arrays so that consecutive threads read consecutive elements of the same field.

Completion

  • All 5 subtopics marked done
  • All 2 required lessons done
  • All five subtopics marked completed.
  • roofline.png and the stride notebook saved with checks passing.
  • Can compute a ridge point and a decode tokens-per-second ceiling from spec numbers in under five minutes.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →