Maps to: Stanford CS 217 Hardware Accelerators for Machine Learning (Winter 2026), Lecture 7 · Tue 01/27/2026 · Memory Systems. Lab 3 is out: a global buffer with a near-memory processor — the block of §6. Reading: the schedule lists no reading for this session. These notes draw on:
- Hennessy & Patterson, Computer Architecture: A Quantitative Approach, memory-hierarchy chapters;
- B. Jacob, S. Ng, D. Wang, Memory Systems: Cache, DRAM, Disk (DRAM organization, timing, refresh, address mapping);
- S. Rixner et al., Memory access scheduling, ISCA 2000 (FR-FCFS);
- J.-W. Hong and H. T. Kung, I/O complexity: the red-blue pebble game, STOC 1981, and T. Smith et al., A tight I/O lower bound for matrix multiplication, 2019;
- V. Sze et al., Efficient Processing of Deep Neural Networks, chapters on memory hierarchies and dataflows;
- the public JEDEC description of HBM (channels, pseudo-channels, banks, refresh).
Basis: The slides are not public. This lecture follows the session title, the schedule’s description of Lab 3, and the sources above. The experiments use models written for these notes (
memory.py,tiling.py,global_buffer.py):
- a banked-SRAM model;
- a request-level DRAM timing model with HBM2-like parameters that are typical orders of magnitude, not a datasheet;
- exact traffic counting for tiled loops;
- a cycle-level global buffer with real values, checked against numpy.
The experiments do not reflect what was said in class. Code:
code/lecture07/(4 scripts + 3 modules; three run in about a second, the DRAM script in ~18 s) Reading time: 3–4 hours including running the code
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Describe an accelerator’s memory hierarchy — registers, PE buffers, global buffer, L2, HBM/DRAM — with the capacity, bandwidth and energy of each level, and explain why accelerators prefer software-managed scratchpads to caches.
- Explain bank conflicts in a banked SRAM, predict them for strided accesses (gcd rule), and remove them with mappings (XOR, prime) and padding. Compare banks with ports.
- Explain how DRAM works: channels, banks, rows, the row buffer, activate/read/precharge/refresh. Predict the bandwidth of sequential, random and strided streams. Apply Little’s law to the number of outstanding requests.
- Explain why address mapping, page policy, the scheduler (FR-FCFS) and the data layout (row-major vs blocked) change delivered bandwidth by large factors.
- Count the DRAM traffic of a tiled GEMM for any loop order. State the √S law (traffic ≥ 2MNK/√S) and size a buffer so that a layer becomes compute-bound.
- Explain when double buffering hides memory completely, and what it costs in capacity.
- Explain what near-memory processing in the global buffer saves (split-K reductions, element-wise operations), and the placement it requires.
0.2 Prerequisites and scope
| Assumed | Introduced here | Developed later |
|---|---|---|
| Lecture 1: energy per access, roofline, compulsory traffic, the √S teaser | banks, mappings, padding; DRAM timing; Little’s law | networks between buffers and PEs (L8) |
| Lecture 3: Eyeriss energy accounting | tiling and loop orders, the I/O lower bound | the full mapping search (L9) |
| Lecture 5: tile pipelining, double-buffered weights | double buffering of DRAM transfers | FlashAttention’s tiling (L10) |
| Lecture 6: the reference core, vector units | a global buffer with near-memory processing (Lab 3) | processing in/near DRAM (L14–15) |
0.3 Map
§1 the memory hierarchy of an accelerator; scratchpads vs caches
§2 SRAM banks: conflicts, mappings, padding, gathers, banks vs ports ← code 01
§3 DRAM and HBM: rows and banks, Little's law, patterns, scheduling, ← code 02
address mapping, refresh, layouts
§4 reuse and tiling: loop orders, the sqrt(S) law, transformers, convolution ← code 03 (Parts 1-3, 5)
§5 double buffering ← code 03 (Part 4)
§6 the global buffer: placement, near-memory processing (Lab 3) ← code 04
§7 summary §8 pitfalls §9 exercises §10 further reading §11 next lecture
0.4 Notation
| Symbol | Meaning |
|---|---|
| number of SRAM banks; : lanes (words requested per cycle) | |
| word | the unit one bank delivers per access |
| pitch | stored length of a matrix row (≥ its number of columns) |
| channel, bank, row, column | DRAM organization; a row is 1 KB here (the “page”) |
| ACT, RD, PRE, REF | activate a row, read a column, precharge (close) the row, refresh |
| tRCD, tCL, tRP, tRAS, tRRD, tFAW | DRAM timing constraints (§3.2) |
| on-chip buffer size; : GEMM tile sizes | |
| ridge | peak FLOP/s ÷ memory bytes/s (Lecture 1) |
1. The memory hierarchy of an accelerator
1.1 Intuition: a kitchen’s pantry
A cook works from what is on the counter (registers), reaches for the shelf above (PE buffers), walks to the pantry (global buffer), and sends someone to the warehouse across town (DRAM) for anything else. A good cook plans the meal so that each warehouse trip brings back a crate that serves many dishes, and so that the next crate is on its way while this one is used. Accelerator memory design is exactly that plan, with energy and bandwidth instead of walking time.
1.2 The levels
| Level | Typical size | Energy per byte (45 nm, Lecture 1) | Who manages it | Examples |
|---|---|---|---|---|
| registers / PE register files | bytes – 1 KB per PE | ~0.1 pJ | hardware / compiler | systolic PE registers, vector registers (L5, L6) |
| PE / array buffers | 8–256 KB | 1.25 pJ at 8 KB | compiler | weight FIFOs, accumulators |
| global buffer (scratchpad) | 1–200 MB | 12.5 pJ at 1 MB (more for larger banks, plus wires) | compiler / runtime (DMA) | TPU v1: 24 MiB unified buffer + 4 MiB accumulators; TPU v4: 128 MiB CMEM + 32 MiB VMEM per chip |
| last-level cache | 40–50 MB | similar | hardware | A100 40 MB L2, H100 50 MB L2 |
| HBM / DRAM | 8–192 GB | ~160 pJ (Horowitz’s DDR, low end) | hardware controller | TPU v1: 34 GB/s DDR3; H100: 3.35 TB/s HBM3 |
On-chip sizes and bandwidths are from Lecture 1’s hw_specs.py, with sources there. Two facts drive everything else:
- Energy rises ~10× per level, from 0.1 pJ in registers to ~1 pJ in a small SRAM, ~10 pJ in a large one and ~100+ pJ off chip. Lecture 3’s Eyeriss accounting (RF 1, array 2, buffer 6, DRAM 200 per access, relative to a MAC) is the same ladder.
- Bandwidth falls per level. The arithmetic needs operands at hundreds of TB/s; HBM delivers a few TB/s. Only reuse in the upper levels closes the gap.
1.3 Scratchpads, not caches
A cache decides by itself what to keep, using tags, comparators and a replacement policy. A scratchpad is plain addressable SRAM that software fills explicitly with a DMA engine. Accelerators favor scratchpads because:
- ML access patterns are known at compile time: loop nests over tensors, with no data-dependent pointers. The compiler can plan every transfer.
- Tags and misses cost energy and predictability. A miss stalls the whole array at an unknown time, while a planned DMA transfer can be issued early (§5).
- Capacity is used fully: no conflict misses, no unneeded lines.
The cost is software complexity. The compiler must tile, place and schedule every transfer, which is the topic of §4–§6 and Lectures 9–10. GPUs keep both: caches for generality, and shared memory (a scratchpad) plus asynchronous copies (TMA) for performance-critical kernels (Lecture 11).
2. SRAM banks
2.1 Why banks
One SRAM array delivers one word per port per cycle. A vector unit with 16 lanes, or a systolic array edge with 128 inputs, needs many words per cycle. Adding ports to every cell is expensive: each port adds a word line and bit lines to every cell. So the buffer is split into B banks, each a small single-port SRAM, and different words can be read from different banks in the same cycle. The catch: two requests for different words in the same bank conflict, and one of them waits.
2.2 Strides and mappings
The mapping from word address to bank decides which access patterns conflict. Script 01, Part 1 measures 16 lanes reading a strided vector, in cycles per access:
| Mapping | s = 1 | 2 | 3 | 4 | 8 | 16 | 17 | 32 | Average, s = 1..33 |
|---|---|---|---|---|---|---|---|---|---|
| 16 banks, low-order (bank = word mod 16) | 1 | 2 | 1 | 4 | 8 | 16 | 1 | 16 | 2.94 |
| 16 banks, XOR hash | 1 | 1 | 3 | 1 | 1 | 1 | 16 | 2 | 3.36 |
| 17 banks (prime) | 1 | 1 | 1 | 1 | 1 | 1 | 16 | 1 | 1.45 |
| 32 banks, low-order | 1 | 1 | 1 | 2 | 4 | 8 | 1 | 16 | 1.97 |
The gcd rule: with low-order interleaving over B banks, stride visits distinct banks, so an access costs cycles. Every odd stride is free, and stride 16 serializes everything. An XOR hash (bank = (word ⊕ word/16) mod 16) fixes power-of-two strides but creates new bad strides (17 → 16 cycles). A prime number of banks makes only multiples of 17 conflict, at the price of a modulo-17 in the address path. Every fixed mapping has bad strides; the question is how common they are in the workload.
2.3 Columns, transposes and padding
A row-major matrix with 64 columns in 16 banks puts element at word . Since 64 is a multiple of 16, a whole column lives in one bank. Script 01, Part 2:
| Layout | Row read (16 el.) | Column read (16 el.) | 16 × 16 transpose | Wasted capacity |
|---|---|---|---|---|
| pitch 64 | 1 | 16 | 272 cycles | 0% |
| pitch 65 (padded by one word) | 1 | 1 | 32 cycles | 1.5% |
| pitch 72 | 1 | 8 | 144 cycles | 11.1% |
Padding each row by one word shifts every row by one bank, so a column covers all 16 banks: conflict-free column reads and an 8.5× faster transpose for 1.5% of the capacity. (Pitch 72 shifts by 8 banks and only halves the damage — the gcd rule again: gcd(72, 16) = 8.) This is the same trick CUDA programmers use to pad shared-memory arrays.
2.4 Random gathers
Embedding lookups, sparse indices and some attention variants read words at random addresses. Script 01, Part 3 (16 lanes, 4,000 random gathers):
| Banks | 16 | 32 | 64 | 128 | 256 |
|---|---|---|---|---|---|
| Mean cycles per gather | 3.07 | 2.39 | 1.99 | 1.66 | 1.39 |
The time of a gather is the maximum load over banks: a balls-into-bins game. Even 16× more banks than lanes leave 39% overhead. Gather-heavy units need many banks, request queues that reorder conflicting requests, or a layout that turns gathers into streams.
2.5 Banks or ports?
Script 01, Part 4 asks how a 1 MiB buffer should deliver 16 words per cycle (45 nm area model of Lecture 2):
| Organization | Area | pJ per 4-byte access | Unit stride | Random gather |
|---|---|---|---|---|
| 1 bank, 16 ports | 49.9 mm² | 50.0 | 1 cycle | 1.00 |
| 16 banks, 1 port | 5.91 mm² | 13.8 | 1 | 3.07 |
| 64 banks, 1 port | 6.03 mm² | 7.07 | 1 | 1.99 |
| 16 banks, 2 ports | 8.87 mm² | 13.8 | 1 | 1.84 |
The area model even flatters multi-porting: real 16-port cells are impractical. Banking wins on area and energy (smaller banks have shorter wires, so each access is cheaper). Its cost — conflicts — falls on the address mapping and the compiler.
3. DRAM and HBM
3.1 How DRAM works
A DRAM chip stores bits as charge in capacitors, organized as channels (independent interfaces, each with its own data bus) of banks (independent arrays) of rows (1–8 KB each). Reading data takes three steps:
- ACT (activate): copy a whole row into the bank’s row buffer (sense amplifiers). This takes tRCD ≈ 14 ns before any column can be read.
- RD (read): transfer a burst (64 B here) from the row buffer; the data appears tCL ≈ 14 ns later and occupies the channel’s data bus for 2 ns (32 GB/s per channel).
- PRE (precharge): close the row (tRP ≈ 14 ns) before another row of the same bank can be activated; a row must stay open at least tRAS ≈ 33 ns.
A row hit (the row is already open) costs only tCL. A row miss costs PRE + ACT + RD. Two more limits protect the power supply: at most one ACT per tRRD = 4 ns per channel, and four per tFAW = 16 ns. And because capacitors leak, every tREFI = 3.9 µs each channel stops for tRFC = 350 ns to refresh its rows.
Our model, memory.HBM2_LIKE, is a stack of 8 channels × 32 GB/s = 256 GB/s peak, with 16 banks of 1 KB rows per channel. These are typical HBM2 orders of magnitude; real HBM adds pseudo-channels, bank groups, write turnarounds and more.
3.2 Little’s law
A memory system with latency delivering bandwidth must have bytes in flight. Script 02, Part 1 (sequential 1 MiB read, refresh off):
| Outstanding requests | 1 | 4 | 16 | 64 | 128 | 256 | 1,024 |
|---|---|---|---|---|---|---|---|
| GB/s | 3.8 | 15 | 58 | 178 | 254 | 254 | 254 |
| mean latency (ns) | 17 | 17 | 18 | 23 | 32 | 64 | 249 |
With one request at a time, a 256 GB/s stack delivers 1.5%. About 128 requests (8 KB) must be in flight to cover the ~30 ns latency. Beyond that, extra requests only wait in queues. A DMA engine — or a GPU, with its thousands of threads (Lecture 11) — exists largely to keep enough requests in flight.
3.3 Access patterns, page policy, scheduling
Script 02, Part 2 (hashed address mapping, refresh off; GB/s and row-hit rate):
| Pattern | Open page, FR-FCFS | Open page, FCFS | Closed page, FR-FCFS | Closed page, FCFS |
|---|---|---|---|---|
| sequential | 254 (94%) | 254 (94%) | 32 (0%) | 12 (0%) |
| random 64 B | 83 (0%) | 40 (0%) | 83 (0%) | 40 (0%) |
| random 1 KB blocks | 161 (50%) | 88 (50%) | 81 (0%) | 19 (0%) |
| 8 interleaved streams | 248 (94%) | 253 (94%) | 90 (0%) | 76 (0%) |
- Sequential streams hit 15 of every 16 accesses: one activate per 1 KB row.
- Random 64-byte reads open a row for one burst. Activations become the bottleneck — tRRD/tFAW (one per 4 ns per channel) and the bank cycle (tRAS + tRP = 47 ns) — and only a third of the peak remains.
- Closed page (precharge after every access) suits random traffic and destroys streams.
- FR-FCFS (Rixner et al.), the standard controller policy, serves ready row hits first and otherwise the oldest request. It doubles the bandwidth of random blocks compared with first-come-first-served.
3.4 Address mapping
Which address bits select the channel and the bank? Script 02, Part 3 (64-byte requests, stride bytes apart):
| Stride | 64 B | 256 B | 1 KB | 4 KB | 8 KB | 64 KB |
|---|---|---|---|---|---|---|
| interleaved (burst | channel | column | bank | row) | 253 | 64 | 32 | 32 | 16 | 3 |
| row-major (burst | column | bank | channel | row) | 60 | 95 | 127 | 44 | 22 | 3 |
| hashed (interleaved + XOR of higher bits) | 253 | 253 | 226 | 213 | 121 | 126 |
- Plain channel interleaving is perfect for sequential streams but funnels power-of-two strides into a few channels.
- A row-major mapping (a whole row per channel before moving on) fails even on sequential streams. With 256 outstanding requests, the DMA’s window (16 KB) covers one channel at a time, and the full per-channel queue stalls everything behind it.
- XOR-hashing the channel and bank indices with higher address bits — as GPU and server memory controllers do — keeps every stride between 121 and 253 GB/s.
Bandwidth is a property of the whole stack — device, controller, mapping and access pattern — not of the DRAM datasheet.
3.5 Refresh
Script 02, Part 4 (sequential 4 MiB): refresh costs 8.4% of the bandwidth at tREFI = 3.9 µs, and 18.7% when the DRAM is hot and must refresh twice as often (tREFI = 1.95 µs above 85 °C). Every DRAM-bound kernel — LLM decode above all — pays this tax. It is also why HBM’s thermal design matters.
3.6 Layouts: tiles of a matrix
A GEMM reads its weights tile by tile. In a row-major 4096 × 4096 bf16 matrix (8 KB per row), a 128 × 16 tile is 128 pieces of 32 B, 8 KB apart. Script 02, Part 5 fetches 1 MiB of such tiles (useful GB/s):
| Tile | Row-major, interleaved | Row-major, hashed | Blocked, interleaved | Blocked, hashed |
|---|---|---|---|---|
| 128 × 16 (4 KiB) | 8 | 61 | 91 | 254 |
| 128 × 64 (16 KiB) | 32 | 122 | 254 | 254 |
| 128 × 256 (64 KiB) | 128 | 128 | 254 | 254 |
Narrow tiles waste half of every burst and stride across rows. A blocked layout stores the matrix tile by tile, so each tile is one contiguous stream. Accelerator compilers lay out weights that way, ahead of time. A blocked layout still needs a good mapping: without hashing, the 1 MiB-apart tiles all start in the same bank of every channel.
4. Reuse and tiling
4.1 The problem
A 4096 × 4096 × 4096 bf16 GEMM touches 101 MB of compulsory data but performs 137 GFLOP: 1,365 FLOP per byte if each matrix moves once. That needs the whole problem on chip. With a buffer of bytes, the compiler cuts the loops into tiles: an tile of A, of B and of C, ordered by three tile loops (m, n, k).
4.2 The reuse rule and loop orders
The buffer holds one tile of each operand. An operand stays resident while the loops it does not depend on run inside its innermost dependent loop, and is fetched again otherwise. A depends on (m, k), B on (k, n), C on (m, n). With the k loop innermost (order mnk), A and B are re-fetched every step, but C stays: the partial sums never leave (output-stationary). With n innermost (mkn), A stays, but C’s partial sums are written out and read back once per k tile, in fp32. Script 03, Part 2 (256³ tiles):
| Order | What stays | A | B | C | Total |
|---|---|---|---|---|---|
| mnk, nmk | C (output-stationary) | 537 MB | 537 MB | 33.6 MB | 1.11 GB |
| mkn, kmn | A | 33.6 MB | 537 MB | 2.08 GB | 2.65 GB |
| nkm, knm | B (weight-stationary) | 537 MB | 33.6 MB | 2.08 GB | 2.65 GB |
The same lesson as Lecture 5’s dataflows, one level up: keeping the accumulators stationary avoids spilling wide partial sums.
4.3 The √S law
How much traffic is unavoidable? Hong and Kung’s red-blue pebble game (1981) gives the answer. Divide the computation into segments that each move words between the buffer and DRAM. Within one segment, at most ~ entries of A, B and C are available. By the Loomis–Whitney inequality, they support at most ~ multiply-adds. So the multiply-adds need at least segments, i.e. traffic of
Script 03, Part 1 searches all power-of-two tilings (edges ≥ 32 elements) and loop orders for the 4096³ GEMM:
| Buffer | Best tiling | Traffic | Lower bound | FLOP/byte | Bound on the reference core |
|---|---|---|---|---|---|
| 16 KiB | 32×64×32 mnk | 6.48 GB | 3.04 GB | 21 | memory |
| 256 KiB | 128×256×32 mnk | 1.64 GB | 759 MB | 84 | memory |
| 1 MiB | 256×512×32 mnk | 839 MB | 380 MB | 164 | memory |
| 4 MiB | 512×1024×32 mnk | 436 MB | 190 MB | 315 | compute |
| 16 MiB | 32×1024×4096 nkm | 201 MB | 101 MB | 683 | compute |
| 64 MiB | 32×4096×4096 nkm | 101 MB | 101 MB | 1,365 | compute |
16× more buffer cuts traffic ~4×: the square-root law. The best tilings stay within 1.0–2.3× of the bound. They lose ~√2 by keeping the C tile in fp32, and up to another ~√2 because power-of-two tiles cannot fill the buffer exactly. On the reference core of Lecture 6 (137.6 TFLOPS, 600 GB/s, ridge 229 FLOP/byte), the GEMM becomes compute-bound with 4 MiB of buffer. At 64 MiB a whole weight matrix stays on chip, and only compulsory traffic remains.
4.4 What a buffer cannot fix
Script 03, Part 3 (FLOP per DRAM byte of the best tiling; “if each matrix moved once” is the ceiling):
| GEMM (Llama 3 8B) | Ceiling | 64 KiB | 1 MiB | 16 MiB |
|---|---|---|---|---|
| MLP up, prefill 2,048 tokens | 1,247 | 42 | 164 | 775 |
| q_proj, prefill 2,048 | 1,024 | 42 | 164 | 683 |
| attention QKᵀ, one head, 2,048 | 114 | 62 | 114 | 114 |
| MLP up, decode batch 64 | 63 | 42 | 63 | 63 |
| MLP up, decode batch 1 | 1 | 1 | 1 | 1 |
Prefill GEMMs reward buffer capacity. Decode does not. Its weights must be read once per step, and with batch 64 that is only 63 FLOP per byte whatever the buffer — the memory wall of LLM inference (Lectures 1, 14). Attention’s QKᵀ is capped too: it writes a 2,048 × 2,048 score matrix per head, compulsory output traffic. The only escape is not to write the scores at all — keep them on chip, apply softmax and multiply by V inside the tile loop. That is FlashAttention, Lecture 10.
4.5 Convolutions: halos vs im2col
A convolution tile of output pixels needs a input tile: neighbouring tiles re-read a halo. The alternative, lowering to a GEMM with im2col, copies every input pixel times. Script 03, Part 5 (256 KiB buffer):
| Convolution | Compulsory | Direct, tiled | Input re-reads | im2col + GEMM |
|---|---|---|---|---|
| ResNet-50 3×3, 56×56×64→64 | 877 kB | 1.23 MB | 1.33× | 8.1 MB |
| ResNet-50 3×3, 14×14×256→256 | 1.38 MB | 1.41 MB | 1.31× | 3.19 MB |
| 7×7, 112×112×64→64 | 3.61 MB | 9.07 MB | 2.90× | 171 MB |
Halos cost little once tiles are a few dozen pixels wide. Lowering through memory costs 2–19× more traffic. Accelerators convolve directly from tiles, or build the im2col view on the fly inside the buffer.
5. Double buffering
5.1 The pipeline
Each tile step loads its operands, computes, and stores results. With one buffer the three happen in sequence, and every step also pays the memory latency. With two buffers, the next tile is loaded while the current one is computed:
Double buffering hides memory completely when : when the step’s arithmetic intensity (FLOPs per byte transferred) is at least the machine’s ridge. It also hides latency, as long as one step of prefetch covers it. Otherwise prefetch two or more tiles ahead — which needs more buffers. The price: each copy gets half the buffer, so tiles shrink and traffic grows by ~√2.
5.2 The numbers
Script 03, Part 4 (4096³ GEMM on the reference core, output-stationary, 100 ns per transfer):
| Buffer | Single-buffered tiles | Time | Of peak | Double-buffered tiles | Time | Of peak | Step FLOP/byte |
|---|---|---|---|---|---|---|---|
| 256 KiB | 128×256×32 | 10.3 ms | 10% | 128×128×32 | 3.64 ms | 27% | 64 |
| 1 MiB | 256×512×32 | 4.04 ms | 25% | 256×256×32 | 1.85 ms | 54% | 128 |
| 4 MiB | 512×1024×32 | 2.14 ms | 47% | 512×512×32 | 999 µs | 100% | 256 |
| 64 MiB | 2048×4096×32 | 1.25 ms | 80% | 2048×2048×32 | 999 µs | 100% | 1,024 |
Double buffering wins at every size even though its tiles are half as large. From 4 MiB on, each step’s intensity (256) exceeds the ridge (229), and the GEMM runs at peak. Single buffering never gets there: it serializes transfer and compute.
6. The global buffer as a shared resource (Lab 3)
6.1 Clients and placement
The global buffer serves several clients at once:
- the DMA engine filling the next tiles;
- the matrix unit reading operands and writing results;
- the vector unit;
- in Lab 3, a near-memory processor.
global_buffer.py arbitrates each bank cycle by cycle (round-robin among the clients that want it). Script 04, Part 1 runs one double-buffered GEMM step:
- the matrix unit reads the current A and B tiles (1 word/cycle each);
- the DMA writes the next A and B (0.5 word/cycle each);
- the C tile drains (0.25 word/cycle).
| Placement | MXU operands done (cycle) | Step done | Stalls |
|---|---|---|---|
| all regions interleaved from bank 0 | 8,164 | 8,194 | 8,275 |
| interleaved, regions offset by 3 banks | 6,256 | 8,323 | 4,686 |
| partitioned (each region in its own banks) | 4,096 | 8,192 | 0 |
The interleaved layouts show a convoy. When a fast stream (the matrix unit’s reads) catches up with a slow one (the DMA’s half-rate writes) in some bank, one wins. After that both want the next bank in the same cycle again, so the fast stream is dragged to the slow one’s pace and the matrix unit’s reads take twice as long. A partitioned placement gives every region its own banks, and the streams never meet. Placement must be planned together with double buffering, by the compiler or a buffer manager.
6.2 Near-memory processing: split-K reductions
When a GEMM’s reduction dimension K is split across P cores, each core produces a partial C tile and the partials must be summed. Two ways:
- compute path: write the P partials to the buffer, then one compute unit reads them all, adds, and writes the result;
- near-memory path: each core sends its partial as accumulate-writes; a small adder next to each bank reads the old value, adds, and writes back (a read-modify-write, RMW).
Script 04, Part 2 (2,048-word = 64 KiB fp32 partial tiles; energies in MAC units per element, from Eyeriss’s costs):
| P | Compute unit: cycles | NMP, 2-cycle RMW | NMP, 1-cycle RMW | Buffer used | NMP buffer | Energy | NMP energy |
|---|---|---|---|---|---|---|---|
| 2 | 6,147 | 2,051 | 2,049 | 192 KiB | 64 KiB | 43 | 30 |
| 4 | 10,247 | 2,055 | 2,051 | 320 KiB | 64 KiB | 79 | 60 |
| 8 | 18,447 | 2,063 | 2,055 | 576 KiB | 64 KiB | 151 | 120 |
All three paths produce numpy’s sum. Near-memory accumulation is faster because all producers stream into all banks at once, while the compute unit funnels every partial through its port. A compute unit with 16 ports would close the time gap, but not the others. It is smaller: one copy of the tile instead of P + 1. And it uses less energy, because it skips the store-then-reload of every partial.
6.3 Element-wise operations near memory
A residual add on 512 KiB that already sits in the buffer (script 04, Part 3):
| Where | Cycles | Words over the network | Energy per element |
|---|---|---|---|
| compute unit (one read + one write port) | 32,770 | 49,152 | 27 |
| near-memory, x and r in the same bank | 3,072 | 0 | 19 |
| near-memory, r shifted by one bank | 3,072 | 16,384 | 21 |
All three are simulated with values and equal numpy’s sum. The near-memory units work in all 16 banks at once and never use the chip’s network. But they need both operands of an element in the same bank: the compiler must place and at bases that are equal modulo the bank interleaving. Shifted by one bank, the time stays the same (the 16 units stay in lockstep on different banks). However, every must now cross from its bank to the neighbouring bank’s unit, through an inter-bank path the hardware has to provide and pay for. Near-memory processing is a placement contract between hardware and compiler. Lectures 14–15 take the same idea into the DRAM itself.
7. Summary
- An accelerator’s memory hierarchy spans ~10× in energy and bandwidth per level. Accelerators use scratchpads filled by DMA because ML access patterns are known at compile time.
- Banks are cheaper than ports, but conflict. With low-order interleaving, stride costs cycles. XOR hashes and prime bank counts shift the bad strides; padding rows by one word makes columns conflict-free. Random gathers obey balls-into-bins (3.07 cycles for 16 lanes on 16 banks).
- DRAM rewards locality. Sequential streams reach 99% of peak (with refresh off); random 64 B reads about a third, limited by row activations. Closed pages destroy streams, and FR-FCFS doubles random-block bandwidth.
- Little’s law: ~128 requests in flight are needed to reach an HBM stack’s bandwidth.
- Address mapping changes strided bandwidth from 3 to 253 GB/s; hashing makes it robust.
- Refresh costs 8–19%, and narrow row-major tiles waste bursts — blocked layouts stream at peak.
- Tiling: an operand is re-fetched unless the loops it ignores run inside its residency. Output-stationary orders avoid partial-sum spills (1.11 vs 2.65 GB).
- The √S law: traffic ≥ 2MNK/√S. 16× more buffer gives ~4× less traffic, and a 4096³ GEMM becomes compute-bound on the reference core at 4 MiB. Buffers cannot fix decode (63 FLOP/B at batch 64) or QKᵀ’s score matrix (114 FLOP/B).
- Double buffering hides memory completely once each step’s intensity exceeds the ridge: 100% of peak from 4 MiB.
- The global buffer is a shared resource. Bad placement makes streams convoy (2× slower operand reads). Near-memory accumulation sums 8 split-K partials 9× faster than a one-port compute unit, with one copy instead of P + 1. Element-wise operations near memory are 11× faster and avoid the network — if operands share banks.
8. Common pitfalls
- “Peak bandwidth is the bandwidth.” Only for sequential, well-mapped, deep-queued streams. Random access gets a third, and badly mapped strides 1% (§3).
- “More outstanding requests always help.” Past Little’s-law saturation they only add latency (§3.2).
- “A bigger buffer always helps.” Traffic falls only as 1/√S, and not at all for decode or for compulsory outputs (§4.3–4.4).
- “Loop order is a detail.” It decides whether fp32 partial sums spill (2.4× traffic, §4.2).
- “Double buffering halves the buffer, so it hurts.” It hides the transfers; that matters more than the √2 extra traffic (§5).
- “Banks are independent, so streams don’t interact.” Streams of different speeds convoy (§6.1).
- “Near-memory processing is free.” Its operands must be co-located in banks, and its adders and control cost area in every bank (§6.3).
9. Exercises
Exercise 1 (gcd rule). An 8-bank SRAM with low-order interleaving serves 8 lanes. How many cycles do strides 2, 3, 4, 6 and 8 cost? Which strides are free?
Answer
Cycles = gcd(s, 8): stride 2 → 2, 3 → 1, 4 → 4, 6 → 2, 8 → 8. All odd strides are free (gcd = 1). With 7 banks (prime), every stride that is not a multiple of 7 would be free.
Exercise 2 (padding). A 32 × 32 fp32 matrix is stored in 32 banks with pitch P. For which P are column reads conflict-free? Which P would you pick, and what does it cost?
Answer
Column element is at , bank ; the 32 elements hit distinct banks iff gcd(P, 32) = 1, i.e. P odd. Pick P = 33: 1 extra word per row, 3% of the capacity. P = 34 gives 2-way conflicts (gcd 2: 2 cycles), P = 48 16-way conflicts (gcd 16: 16 cycles).
Exercise 3 (balls into bins). Why does a 16-lane random gather still need 1.39 cycles on 256 banks? Estimate the probability that all 16 requests hit distinct banks.
Answer
P(all distinct) = ∏_{i=0}^{15} (1 − i/256) ≈ exp(−Σ i/256) = exp(−120/256) ≈ 0.63. So ~37% of gathers have at least one conflict and take ≥ 2 cycles: mean ≈ 0.63 × 1 + 0.37 × 2 ≈ 1.37, close to the measured 1.39. Conflict-free gathers need B ≫ L² (birthday paradox).
Exercise 4 (Little’s law for an H100). An H100’s HBM3 delivers 3.35 TB/s. If the loaded latency is ~600 ns, how many bytes must be in flight? How many 64-byte requests is that, and why does a GPU need tens of thousands of threads?
Answer
3.35e12 × 600e-9 ≈ 2.0 MB in flight = ~31,000 requests of 64 B. Spread over 132 SMs, that is ~240 outstanding requests per SM. A thread typically has a few loads in flight, so thousands of threads per GPU are needed just to keep memory busy — one reason for GPU multithreading (Lecture 11).
Exercise 5 (row buffers). With 1 KB rows and 64 B bursts, what is the row-hit rate of a sequential stream? With 2 KB rows? Why do random 64 B reads reach only ~83 GB/s in script 02, and what is the activate-rate limit of the model?
Answer
Sequential: 15/16 = 94% (1 KB), 31/32 = 97% (2 KB). Random 64 B: every access needs an activate. tRRD = 4 ns and tFAW = 16 ns per 4 activates both allow one activate per 4 ns per channel → 64 B / 4 ns = 16 GB/s per channel = 128 GB/s for 8 channels. The measured 83 GB/s is lower because banks also collide: a bank reused within its row cycle tRAS + tRP = 47 ns stalls, and with 16 banks random reuse happens often.
Exercise 6 (mapping). With the “interleaved” mapping (burst | channel(3 bits) | column(4 bits) | bank(4 bits) | row), which channels does a 1 KB-stride stream use? Why does it get 32 GB/s?
Answer
Address / 64 = 16j. Channel = 16j mod 8 = 0 for every j: one channel of 32 GB/s. (Within it, column = 2j mod 16 and bank = j/8 mod 16, so it even gets row hits — but one channel is the limit.) Hashing the channel with column and row bits spreads the stream over all 8 channels (226 GB/s).
Exercise 7 (refresh). At tRFC = 350 ns and tREFI = 3.9 µs, what fraction of time is a channel unavailable? How does that change a memory-bound decode step’s time? What happens when the stack runs hot?
Answer
350 / 3900 = 9.0% (measured bandwidth loss 8.4%). A decode step that is purely memory-bound gets ~9% slower than the peak bandwidth predicts. Hot (tREFI halved): 18% of the time, 18.7% measured. This is one reason datasheet bandwidth is never reached, and why HBM cooling matters.
Exercise 8 (the √S law by hand). For order mnk with square tiles and the C tile in a buffer of S words, derive the traffic and the best T. Compare with the lower bound.
Answer
A is read N/T times, B M/T times, C once: (plus MN). The C tile dominates the buffer: , so and — exactly the lower bound’s leading term. With fp32 partial sums and bf16 inputs, bytes, so and the traffic in bf16 elements is √2 above the bound — part of the 2.1–2.3× in script 03.
Exercise 9 (loop order). For the 4096³ GEMM with 256³ tiles and order mkn, compute the C traffic. Why is it 62× the compulsory output?
Answer
C leaves the buffer after every k tile: K/T_k = 16 visits. Each writes fp32 partial sums (16 × 4 B) and all but the first read them back (15 × 4 B): 124 B per output element vs 2 B for a single bf16 write — 62×. Over 16.8 M elements: 2.08 GB, as in script 03.
Exercise 10 (double buffering). A pipeline has 100 steps, each with a 1.0 µs load, 0.8 µs compute and 0.1 µs latency. Compute the single- and double-buffered times. What does double buffering hide here?
Answer
Single: 100 × (0.1 + 1.0 + 0.8) = 190 µs. Double: 0.1 + 1.0 + 99 × max(0.8, 1.0) + 0.8 = 100.9 µs. The step is memory-bound (load > compute), so double buffering hides the computation and the latency behind the loads; memory time remains. It hides memory only when compute ≥ load.
Exercise 11 (programming: sizing a buffer for H100). Using tiling.best_gemm_tiling with min_tile=32, find the smallest power-of-two buffer at which the 2048 × 4096 × 4096 q-projection of a Llama 3 8B prefill becomes compute-bound at an H100-like ridge (989.4 TFLOPS / 3.35 TB/s = 295 FLOP/byte), with and without double buffering.
Answer
The author’s run: 4 MiB single-buffered (512×1024×32, order mnk, 315 FLOP/byte) and 8 MiB double-buffered (the same tiles in each half). An H100 SM has 228 KB of shared memory: one SM’s buffer is far too small, which is why GPU GEMMs rely on the 50 MB L2 cache and on many SMs sharing tiles — and why Hopper added thread-block clusters and distributed shared memory (Lecture 11).
Exercise 12 (programming: near-memory residual add). Model the near-memory residual add of §6.3 with global_buffer.simulate: one client per bank that reads , reads and writes for the words of its bank. Check the 3,072-cycle estimate and the result against numpy. What happens if ‘s base is shifted by one word?
Answer
With x at word 0 and r at word 16,384 (a multiple of 16), bank b owns words b, b + 16, … of both; each client issues 3 requests per word for 1,024 words: 3,072 cycles, no conflicts, y = x + r exactly. (Script 04, Part 3 does exactly this.) With r shifted by one word, element i of r lives in bank (i + 1) mod 16. In the author’s run the time is still 3,072 cycles with no stalls: at any cycle the 16 units touch 16 different banks, because they stay in lockstep. What changes is the hardware: unit b must read from bank b + 1, so every bank needs a path to its neighbour (or a crossbar), and every crosses it. The simulator lets any client reach any bank, so it shows the cost as traffic, not time. Co-location is the contract.
10. Further reading
- B. Jacob, S. W. Ng, D. T. Wang, Memory Systems: Cache, DRAM, Disk, Morgan Kaufmann 2008.
- S. Rixner, W. Dally, U. Kapasi, P. Mattson, J. Owens, “Memory access scheduling”, ISCA 2000.
- J.-W. Hong, H. T. Kung, “I/O complexity: the red-blue pebble game”, STOC 1981; T. M. Smith et al., “A tight I/O lower bound for matrix multiplication”, 2019.
- D. Irony, S. Toledo, A. Tiskin, “Communication lower bounds for distributed-memory matrix multiplication”, JPDC 2004.
- V. Sze, Y.-H. Chen, T.-J. Yang, J. Emer, Efficient Processing of Deep Neural Networks, chapters 5–6.
- JEDEC, High Bandwidth Memory (HBM) DRAM standard (JESD235 family), for channel, bank and refresh organization.
- N. Jouppi et al., TPU v1 (ISCA 2017) and TPU v4 (ISCA 2023) papers — unified buffer, CMEM and VMEM.
11. Next lecture
Lecture 8, Interconnects and networks-on-chip, connects the pieces. The global buffer, PE arrays and vector units of Lectures 5–7 talk over an on-chip network, and chips talk over off-chip links. We will build a cycle-level mesh NoC with credit-based flow control and watch latency explode near saturation. We will compare buses, crossbars, trees and Benes networks for the broadcast and reduction patterns of ML, build SIGMA’s flexible distribution and reduction network for sparse GEMMs, and assemble the course’s toy accelerator (Lab 4): PEs, a vector unit, a global buffer and a NoC running a layer end to end.