Maps to: Stanford CS 217 Hardware Accelerators for Machine Learning (Winter 2026), Lecture 1 · Tue 01/06/2026 · Introduction (Thierry Tambe, Kunle Olukotun). Lab 0 (overview of HLS and AWS FPGA prototyping) is released. Reading (from the schedule):
- M. Horowitz, Computing’s energy problem (and what we can do about it), ISSCC 2014;
- S. Williams, A. Waterman, D. Patterson, Roofline: an insightful visual performance model for multicore architectures, CACM 2009;
- M. Verhelst, L. Benini, N. Verma, How to keep pushing ML accelerator performance? Know your rooflines!, IEEE JSSC 2025;
- A. Vaswani et al., Attention is all you need, NeurIPS 2017.
Basis: The slides are not public. This lecture follows the official topic and the four readings, with background from Hennessy & Patterson’s chapter on domain-specific architectures and from Sze et al., Efficient Processing of Deep Neural Networks. Numbers quoted from papers and datasheets are labelled as such. Everything else — the energy models, the rooflines of real kernels, the toy accelerator, the LLM analysis and the measurements — comes from five experiments designed for these notes, which do not reflect what was said in class. Code:
code/lecture01/(5 scripts + 6 modules; Python standard library + numpy, matplotlib optional; scripts 01–04 run in about a second each, script 05 measures your machine in ~30 s) Reading time: 4–5 hours including running the code
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Explain why ML hardware became specialized: the growth of ML compute on one side, the end of Dennard scaling and the power wall on the other, and the conclusion performance = power × operations per joule.
- Use Horowitz’s energy table to estimate the energy of arithmetic, on-chip memory and off-chip memory, and explain why data movement and instruction overhead — not arithmetic — dominate a general-purpose processor’s energy.
- Decompose the energy of a multiply-accumulate (MAC) into arithmetic, instruction overhead and data movement for different architectures, and explain how SIMD units, matrix engines and systolic arrays reduce each term.
- Define and use the performance metrics of accelerators (FLOP vs MAC, peak vs attained throughput, utilization, TOPS/W, TOPS/mm²) and recognize how they can mislead.
- Draw and read a roofline: compute the arithmetic intensity of a kernel and the ridge point of a machine, decide which roof binds, and predict an upper bound on performance.
- Explain why on-chip memory raises intensity (tiling: intensity ∝ √buffer size), and why energy follows a different roofline than time.
- Name the levers of accelerator performance — more processing elements, more bandwidth, more on-chip memory, lower precision, batching, fusion, utilization — and predict which lever helps which workload.
- Apply Amdahl’s law to an accelerator whose matrix unit keeps growing.
- Write down the attention mechanism, explain its parts (scaling, softmax, heads, causal mask), and list the operators of a transformer layer with their FLOPs and bytes.
- Explain why LLM prefill is compute-bound and decode is memory-bound, what batching does to decode, and why the KV cache makes memory capacity a first-class constraint.
0.2 Prerequisites and scope
The official prerequisite is CS 149 (parallel computing) or EE 180 (digital systems architecture); CS 229 is recommended. This lecture needs much less:
| Assumed | Introduced here | Developed later |
|---|---|---|
| what a processor, a cache and DRAM are | energy per operation and per access; instruction overhead | PEs (L3), systolic arrays (L5), vector units (L6), memory systems (L7) |
| matrix multiplication; big-O notation | FLOPs, bytes, arithmetic intensity, the roofline | dataflows and mapping (L9), fusion (L10) |
| what a neural network layer computes | GEMMs, convolution as GEMM, attention, transformer layers | quantization (L4), FlashAttention and PagedAttention (L10) |
| a little Python | analytical models of hardware, numpy timing | cycle-level simulators of every block (L2–L8) |
If “a matrix multiplication of size costs FLOPs” is new to you, read §4.1 slowly; everything else builds on that kind of counting.
0.3 Map
§1 why accelerators: demand, the end of Dennard scaling, the specialization spectrum ← code 01 (Part 5), 05 (Part 4)
§2 computing's energy problem: Horowitz's table, instruction overhead ← code 01 (Parts 1-2)
§3 where the energy goes: four designs, one GEMM; Eyeriss's hierarchy ← code 01 (Parts 3-4)
§4 metrics: FLOPs, MACs, peak vs attained, utilization, TOPS/W, TOPS/mm²
§5 the roofline model: intensity, ridge, kernels, tiling, energy, precision, your machine ← code 02, 05
§6 how to keep pushing performance: the levers, Amdahl, area budgets, array shape ← code 03
§7 what ML asks of hardware: GEMMs, attention, transformer layers, prefill vs decode ← code 04 (Parts 1-6)
§8 training vs inference ← code 04 (Part 7)
§9 the map of the course and Lab 0
§10 summary §11 common pitfalls §12 exercises §13 further reading §14 next lecture
Suggested order: §1 → §2 → run 01 (Parts 1–2) → §3 → run 01 (Parts 3–5) → §4 → §5 → run 02 → run 05 → §6 → run 03 → §7–§8 → run 04 → §9.
0.4 Notation and units
| Symbol | Meaning |
|---|---|
| FLOP, op | one arithmetic operation (FLOP for floating point, op for integers) |
| MAC | one multiply-accumulate = 2 operations |
| peak compute throughput of a machine (FLOP/s or op/s), the compute roof | |
| memory bandwidth (bytes/s), the bandwidth roof | |
| , | work (FLOPs) and memory traffic (bytes) of a kernel |
| arithmetic intensity (FLOP/byte) | |
| ridge point of a machine | |
| bytes per element (4 for fp32, 2 for bf16/fp16, 1 for int8/fp8) | |
| GEMM dimensions: | |
| pJ | picojoule = J; a 1 W chip spends pJ per second |
Rates and data sizes use powers of ten (1 TB/s = B/s, 1 TFLOP/s = FLOP/s), like datasheets; memory capacities use binary units (KiB, MiB, GiB) where the difference matters. Peak throughputs are dense (vendors often quote “with sparsity” figures that are twice as large).
0.5 About CS 217
- Staff (Winter 2026): Thierry Tambe and Kunle Olukotun (instructors); Pullabhatla Smriti, Peijing Li, Vyom Garg and Jake Cheng (TAs). Guest lectures by Raghu Prabhakar (SambaNova), Nafea Bshara (AWS) and Ronny Krashinsky (NVIDIA).
- What the course covers (from the course page): the design, programming and performance of modern AI accelerators — architectural techniques, dataflow, tensor processing, memory hierarchies, compilation for accelerators — for CNNs and transformers/LLMs, in training and inference, and the impact of batch size, precision, sparsity and compression.
- Hands-on work: five labs in which students implement block-level designs in C++/SystemC, synthesize them with high-level synthesis (HLS) and evaluate the result on cloud FPGAs — a SIMD processing element, a vector unit, a global buffer with a near-memory processor, and a top level with an interconnect fabric. Three homeworks (analytical modeling of LLM arithmetic performance; the cost of MX-format scaling; kernel fusion) and a project.
- Arc of the course: foundations (energy, rooflines, HLS, metrics) → numerics (quantization) → compute units (systolic arrays, vector and scalar units) → memory and interconnect → the software stack (dataflows, mapping, fusion, FlashAttention, PagedAttention) → architectures (GPUs, reconfigurable dataflow, memory-centric computing) → industry perspectives (SambaNova, AWS, NVIDIA).
0.6 The code of this course: model the hardware yourself
The labs need HLS tools and FPGAs; these notes cannot. Instead, the course builds a hardware-modeling stack in Python, one lecture at a time (SYLLABUS.md, §3):
- analytical models (time, traffic, energy, area as formulas) for design-space sweeps — this lecture;
- cycle-level simulators of each block (PE, systolic array, vector unit, global buffer, network-on-chip) — Lectures 2–8, mirroring the labs;
- numpy references that every simulator is checked against.
This lecture lays the foundation that every later lecture imports:
| Module | What it holds |
|---|---|
hw_specs.py | datasheet numbers of seven reference machines (a Xeon CPU, V100, A100, H100, B200, TPU v1, TPU v4), each with its source |
energy_model.py | Horowitz’s 45 nm energy/area table, Eyeriss’s normalized storage costs, scaling fits, an EnergyBreakdown |
roofline.py | attainable performance, ridge points, hierarchical and energy rooflines, terminal and matplotlib plots |
workloads.py | FLOPs and bytes of element-wise ops, GEMM/GEMV, convolution, attention, transformer layers and whole LLMs |
1. Why hardware accelerators for machine learning?
1.1 A thought experiment: one dot product, nearly four orders of magnitude
Start with something you can run. Script 05 (Part 4) computes the same dot product three ways on a laptop:
| How | Time per multiply-add | Rate |
|---|---|---|
a Python for loop | ~34 ns | ~58 MFLOP/s |
one call to numpy.dot | ~0.03 ns | ~66 GFLOP/s (1,100× faster) |
| inside a 512 × 512 matrix multiplication | ~0.005 ns | ~420 GFLOP/s (7,200× faster) |
(One run on an Apple M4 Pro laptop that was busy with other jobs at the time; your numbers will differ.)
The arithmetic is identical. What changes is how much machinery runs per useful multiply-add. The Python interpreter fetches, decodes and dispatches dozens of machine instructions — type checks, reference counting, a dictionary lookup — for every MAC. numpy.dot makes that decision once for 200,000 MACs and then runs a tight compiled loop with SIMD instructions. The matrix multiplication additionally reuses every number it loads many times and runs on all cores and on a dedicated matrix unit.
Hold on to this picture: the cost of a computation is mostly the cost of deciding what to do and of moving data to where it is done. An accelerator is what you get when you push that idea all the way down into silicon.
1.2 The demand side: ML wants ever more operations
Two facts drive the field:
- Training compute grows exponentially. Sevilla et al. (Compute trends across three eras of machine learning, 2022) estimate that the compute used to train notable ML models doubled roughly every six months from about 2010 on — far faster than Moore’s law. Script 04 (Part 7) computes one data point: Llama 3 8B, trained on 15 trillion tokens, needs about FLOPs.
- Inference is a mass market. A trained model is run billions of times. For LLMs the cost per generated token decides whether a product is viable at all — and, as §7 shows, generating tokens stresses memory bandwidth and capacity more than arithmetic.
1.3 The supply side: transistors keep coming, free speed does not
For decades two scaling laws delivered faster computers automatically:
- Moore’s law: the number of transistors per chip doubles about every two years.
- Dennard scaling (Dennard et al., 1974): when every dimension of a transistor shrinks by a factor , its capacitance and supply voltage shrink by and it can switch times faster. Dynamic power per transistor is
and since more transistors fit per mm², power density stays constant. Each generation brought twice the transistors, running faster, at the same watts per mm².
Around 2005 Dennard scaling ended: the supply voltage could no longer drop (lower threshold voltages make transistors leak exponentially more current), and clock frequencies stopped rising. With and roughly fixed, power per transistor only falls like , so power density grows by per generation. Script 01 (Part 5) tabulates this simple model:
| Generation | Transistors / mm² | Power density, Dennard | Power density, post-Dennard | Share of the chip usable at fixed power |
|---|---|---|---|---|
| 0 | 1.0× | 1.00× | 1.00× | 100% |
| 2 | 4.2× | 1.00× | 2.04× | 49% |
| 4 | 17.3× | 1.00× | 4.16× | 24% |
| 6 | 72.2× | 1.00× | 8.50× | 12% |
| 8 | 300.9× | 1.00× | 17.35× | 6% |
Chips have a fixed power budget (set by cooling and power delivery), so only a shrinking fraction of their transistors can switch at full speed — the rest must stay idle, a situation Esmaeilzadeh et al. (ISCA 2011) called dark silicon. The model is the extreme case (voltages did keep falling, slowly), but its direction is what happened.
1.4 The conclusion: efficiency is performance
When the power budget is fixed,
The only way left to go faster is to spend fewer joules per operation. Making a general-purpose core more clever (deeper pipelines, wider out-of-order windows, bigger caches) costs more energy per instruction. The alternative is to build hardware that does one class of computations — here, the tensor algebra of ML — with almost no overhead: domain-specific architectures, which Hennessy and Patterson’s 2018 Turing lecture called the start of “a new golden age for computer architecture”. Google’s first TPU is the canonical example: its authors report it ran their production inference workloads 15–30× faster than contemporary CPUs and GPUs, with 30–80× higher TOPS/W (Jouppi et al., ISCA 2017).
Why does ML lend itself to specialization so well?
- A few kernels dominate. Almost all of the arithmetic is matrix multiplication (§7.1), plus a short list of element-wise functions.
- Massive, regular parallelism. Millions of independent multiply-adds with static, predictable data access: no need for branch prediction, speculation or caches that guess.
- Tolerance to low precision. Networks work with 8-bit or even 4-bit numbers (Lecture 4), and narrow arithmetic is dramatically cheaper (§2).
- Reuse. Every weight is applied to many inputs, every input meets many weights: data, once on chip, can be used hundreds of times (§3.4, §5.5).
1.5 The specialization spectrum
The CS 217 course page shows four kinds of machines; the course studies all of them.
| Kind (course page) | Example | What is specialized | What generality remains | Lectures |
|---|---|---|---|---|
| Generic | multicore CPU | SIMD units; recently small matrix extensions (Intel AMX, Apple’s matrix unit) | everything: any program | baseline throughout |
| Repurposed and augmented | GPU with tensor cores | massive multithreading built for graphics, augmented with matrix units and low-precision formats | any data-parallel program (CUDA) | 11, 17 |
| Bespoke and customized | Google TPU | a large systolic matrix unit, a software-managed memory hierarchy, a narrow instruction set | only tensor programs compiled by XLA | 5, 6 |
| Flexible and reconfigurable | SambaNova RDU (dataflow), FPGAs, CGRAs | the datapath itself is configured per program | any program expressible as a dataflow graph | 12, 13 |
Moving down the table trades flexibility for efficiency. Moving between rows is not a ranking: each design point is the right answer for some workloads, budgets and software ecosystems. The course gives you the tools — energy accounting, rooflines, utilization analysis — to decide.
2. Computing’s energy problem
2.1 Horowitz’s table
In his 2014 ISSCC keynote, Mark Horowitz summarized the energy and area of basic operations in a 45 nm process at 0.9 V. Script 01 (Part 1) reprints the table (these are Horowitz’s numbers, not measurements of these notes):
| Operation | Energy (pJ) | × an 8-bit add | Area (µm²) |
|---|---|---|---|
| 8-bit integer add | 0.03 | 1 | 36 |
| 32-bit integer add | 0.1 | 3 | 137 |
| 8-bit integer multiply | 0.2 | 7 | 282 |
| 32-bit integer multiply | 3.1 | 103 | 3,495 |
| 16-bit float add | 0.4 | 13 | 1,360 |
| 32-bit float add | 0.9 | 30 | 4,184 |
| 16-bit float multiply | 1.1 | 37 | 1,640 |
| 32-bit float multiply | 3.7 | 123 | 7,700 |
| SRAM read, 8 KB (64 bits) | 10 | 333 | |
| SRAM read, 32 KB (64 bits) | 20 | 667 | |
| SRAM read, 1 MB (64 bits) | 100 | 3,333 | |
| DRAM read (64 bits) | 1,300–2,600 | 43,333–86,667 |
On a logarithmic bar chart (script 01 prints one), each step down the table is a visible jump: arithmetic sits at the bottom, small SRAMs a decade or two above, DRAM at the top.
Caveat on technology. 45 nm is old. Modern processes make logic several times more efficient, but wires — and therefore data movement — improved less. The ratios in this table, not its absolute values, are the lasting lesson. The code uses the low end of the DRAM range (1.3 nJ per 64 bits = 162.5 pJ/B), so every conclusion of the form “DRAM dominates” is conservative.
2.2 Three lessons from one table
Lesson 1: moving data costs far more than computing on it. One 64-bit DRAM read costs as much as 43,000 8-bit additions or 350 32-bit float multiplications. Even reading a 1 MB on-chip SRAM costs 27× a 32-bit float multiply. An architecture that fetches operands from far away for every operation spends almost all its energy on the fetch.
Lesson 2: narrow arithmetic is much cheaper — quadratically for multipliers. Fitting a power law through the narrowest and widest entries of each unit (script 01, Part 1):
| Unit | Energy grows like | Area grows like |
|---|---|---|
| integer add | bits^0.87 | bits^0.96 |
| integer multiply | bits^1.98 | bits^1.82 |
An integer multiplier is essentially a grid of partial products, hence ; an adder is a chain of cells, hence . Halving the width of a multiplier cuts its energy and area about 4× — the hardware root of low-precision formats (Lecture 4). Floating point adds its own cost: a 16-bit float add costs 8× a 16-bit integer add and takes 20× the area, because exponents must be aligned and results normalized by shifters. Floating point buys dynamic range with energy and area.
Lesson 3: small memories are cheap, big memories are expensive — per access. Interpolating between Horowitz’s three SRAM sizes, the energy per read grows with a local exponent of 0.50 (8 → 32 KB) and 0.46 (32 KB → 1 MB): roughly energy ∝ √capacity. The reason is geometric: a memory of capacity laid out as a square has sides , and every access drives word lines and bit lines across it. This is why every accelerator has a hierarchy: tiny register files next to each arithmetic unit, a larger buffer shared by many units, DRAM far away — and why the computation must be organized so that most operand fetches hit the small, near memories.
2.3 The cost of being general: instruction overhead
Horowitz also estimates that executing one 32-bit add instruction on a simple in-order processor costs about 70 pJ — instruction fetch from the instruction cache, decoding, reading and writing the register file, pipeline control. The add itself is 0.1 pJ, 0.14% of the total. An out-of-order core spends far more.
This is the price of programmability: every operation carries the cost of deciding which operation it is. The way out is to make each instruction do more work. Script 01 (Part 2) asks how many MACs an instruction must perform before its 70 pJ overhead is no larger than the arithmetic:
| MAC format | MAC energy (pJ) | MACs per instruction to break even |
|---|---|---|
| fp32 (fp32 mul + fp32 add) | 4.6 | 15 |
| fp16 (fp16 mul + fp32 accumulate) | 2.0 | 35 |
| int8 (int8 mul + int32 accumulate) | 0.3 | 233 |
and compares real instructions:
| Instruction | MACs per instruction | Overhead per MAC | Overhead / arithmetic |
|---|---|---|---|
| scalar FMA (any CPU) | 1 | 70 pJ | 15 |
| AVX-512 FMA, fp32 (16 lanes) | 16 | 4.4 pJ | 0.95 |
| AVX-512 VNNI, int8 | 64 | 1.1 pJ | 3.6 |
Intel AMX TDPBF16PS (16×16×32) | 8,192 | 0.009 pJ | 0.004 |
NVIDIA mma.sync m16n8k16 (one warp) | 2,048 | 0.034 pJ | 0.017 |
NVIDIA wgmma m64n256k16 (Hopper) | 262,144 | 0.0003 pJ | 0.0001 |
| TPU v1 MatrixMultiply, 256 rows | 16,777,216 | ~0 | ~0 |
(The 70 pJ is Horowitz’s number for a simple core; wide SIMD and matrix instructions cost more to issue, so treat the right-hand columns as orders of magnitude.)
Two observations shape the whole course:
- Each generation of ML hardware made instructions bigger. SIMD (16 operations per instruction), then matrix instructions (thousands), then a matrix engine that a single instruction keeps busy for millions of MACs. Tensor cores (Lecture 11) and systolic arrays (Lecture 5) are, first of all, ways to amortize control.
- Low precision and coarse-grained control go together. The cheaper the arithmetic, the more of it each instruction must carry: an int8 MAC needs ~230 MACs per instruction just to break even. An int8 SIMD instruction with 64 MACs still spends 3.6× more on overhead than on arithmetic.
2.4 Horowitz’s prescription
Put together, the table says what can be done about the energy problem:
- Amortize control: make each instruction (or each configuration of a reconfigurable fabric) cover as much work as possible.
- Exploit locality: arrange the computation so that operands come from small, nearby memories, and each value fetched from far away is reused many times.
- Use the narrowest arithmetic that works: multipliers shrink quadratically with width.
- Use parallelism, not frequency: many slow, simple units beat one fast, complex one at a fixed power budget.
These four points are the agenda of CS 217. Every architecture in the course — systolic arrays, vector units, global buffers, dataflow machines, in-memory computing — is a particular way of combining them.
3. Where does the energy go? Four designs, one matrix multiplication
3.1 An energy model for one MAC
To compare architectures we need a model, even a crude one. Script 01 (Part 3) charges each MAC of a 1024 × 1024 × 1024 matrix multiplication with four terms:
The last term is the important one: if each value fetched from level (energy per byte) is used by MACs, then each MAC pays only of the fetch. Reuse is the only way to make expensive memories affordable. DRAM traffic is set to the compulsory minimum (each of the three matrices read or written once), so the comparison isolates the effects of control and on-chip reuse.
3.2 The four designs
| Design | Format | How it runs the GEMM |
|---|---|---|
| scalar core | fp32 | per MAC: load a, load b, FMA = 3 instructions; both operands from the 32 KB L1 cache every time |
| SIMD core (AVX-512-like) | fp32 | register-blocked micro-kernel: 9 instructions per 64 MACs, 80 bytes from L1 per 64 MACs |
| GPU-style matrix engine | fp16 in, fp32 accumulate | a warp tile of 64×64×16 = 65,536 MACs uses 40 instructions and 4 KB from shared memory; a block tile reuses L2 data |
| TPU-style 256 × 256 systolic array | int8 in, int32 accumulate | one instruction streams the whole matrix; each activation is used by 256 MACs as it flows across the array |
Result (script 01, Part 3):
| Design | Arithmetic | Instruction overhead | On-chip SRAM | DRAM (compulsory) | Total pJ/MAC |
|---|---|---|---|---|---|
| scalar core, fp32 | 4.6 (2%) | 210 (89%) | 20 (8%) | 1.9 (1%) | 237 |
| SIMD core, fp32 | 4.6 (24%) | 9.84 (51%) | 3.12 (16%) | 1.9 (10%) | 19.5 |
| matrix engine, fp16 | 2.0 (56%) | 0.04 (1%) | 0.55 (15%) | 0.95 (27%) | 3.54 |
| systolic array, int8 | 0.3 (25%) | ~0 (0%) | 0.44 (36%) | 0.48 (39%) | 1.22 |

Read the table from top to bottom:
- The scalar core spends 89% of its energy deciding what to do and 2% doing it.
- The SIMD core cuts the total 12×, but instruction overhead is still half of what remains.
- The matrix engine makes control negligible. Now the arithmetic dominates — so the format matters — followed by data movement.
- The systolic array uses int8 arithmetic (7× cheaper than fp16) and reuses each operand 256× on chip. What is left is split roughly evenly among arithmetic, on-chip buffers and DRAM: from here on, every further gain must come from data movement — the subject of Lectures 5, 7, 9 and 10.
The model ignores register-file and pipeline-register energy (Horowitz’s 70 pJ includes it for the CPUs; for the others it is left out), which flatters the designs with a lot of local movement. Lecture 3 adds it with Eyeriss’s ratios.
3.3 Energy-limited throughput
At a fixed power budget, energy per operation converts directly into throughput:
| Design (300 W budget) | Energy-limited throughput | vs scalar |
|---|---|---|
| scalar core, fp32 | 2.5 Top/s | 1× |
| SIMD core, fp32 | 31 Top/s | 12× |
| matrix engine, fp16 | 169 Top/s | 67× |
| systolic array, int8 | 494 Top/s | 195× |
All four designs use the same 45 nm technology: specialization, not transistors, buys the factor of ~200. For scale, script 01 also prints the datasheet peak divided by the thermal design power (TDP) of real chips — an upper bound on their efficiency, everything included:
| Chip | Format | Peak / TDP | pJ per MAC at TDP |
|---|---|---|---|
| TPU v1 (28 nm) | int8 | 1.23 Top/s per W | 1.63 |
| A100 (7 nm) | bf16 | 0.78 Top/s per W | 2.56 |
| H100 (4 nm) | bf16 | 1.41 Top/s per W | 1.41 |
| H100 (4 nm) | fp8 | 2.83 Top/s per W | 0.71 |
The 2015 TPU, in 28 nm, lands at the same order of magnitude as our 45 nm systolic estimate. GPUs got there a few years later by adding matrix units and narrower formats to a programmable machine.
3.4 Inside an accelerator: Eyeriss’s storage hierarchy
Eyeriss (Chen, Krishna, Emer, Sze; a CS 217 reading for Lecture 3) measured, in a 65 nm chip, the energy of fetching one 16-bit operand from each storage level, normalized to one 16-bit MAC:
| Storage level | Energy relative to a MAC |
|---|---|
| ALU (one MAC) | 1× |
| register file inside the PE (0.5–1 kB) | 1× |
| network between PEs (200–1000 PEs) | 2× |
| global buffer (100–500 kB SRAM) | 6× |
| DRAM | 200× |
A MAC reads three values (two operands and a partial sum) and writes one. If all four accesses went to a single level (script 01, Part 4):
| All accesses at | Energy per MAC | Share spent moving data |
|---|---|---|
| register file | 5× | 80% |
| PE network | 9× | 89% |
| global buffer | 25× | 96% |
| DRAM | 801× | 99.9% |
So each level must provide reuse proportional to its cost: every value brought from DRAM should be used ~200 times before it is evicted, every value read from the global buffer ~6 times. Choosing the order of the loops and the placement of data so that this happens is called choosing a dataflow — weight-stationary, output-stationary, row-stationary and so on (Lectures 3, 5, 9). It is no exaggeration to say that most of accelerator design is the engineering of reuse.
4. Measuring performance: metrics that matter (and how they mislead)
4.1 Counting operations
- A MAC computes and is counted as 2 operations (one multiply, one add).
- A matrix multiplication performs MACs FLOPs. A matrix-vector product () performs .
- Peak throughput = number of MAC units × 2 × clock frequency. TPU v1: MACs × 2 × 0.7 GHz = 92 Tera-ops/s, exactly its datasheet figure.
- Vendors quote peaks per format (fp32, tf32, bf16, fp8, int8, fp4) and often “with sparsity” (2:4 structured sparsity doubles the nominal number). These notes always use dense numbers.
4.2 Peak vs attained: utilization
What a workload actually gets is
and utilization is lost in many places: arrays larger than the matrices they process (edge tiles, §6.5), pipeline fill and drain, waiting for memory (the roofline, §5), synchronization, operators that do not run on the matrix unit at all (Amdahl, §6.3). A chip with 2× the peak can be slower on a real network if its utilization is lower. MLPerf-style benchmarks exist precisely because peak numbers do not predict application performance.
4.3 Efficiency metrics
| Metric | What it measures | Watch out for |
|---|---|---|
| TOPS (or FLOP/s) | peak throughput | which format, dense or sparse, at which clock |
| TOPS/W | operations per joule (energy efficiency) | measured on which workload, at which utilization, including DRAM or not, in which process |
| TOPS/mm² | throughput per silicon area (cost) | which process node; chip area or only the MAC array |
| energy per inference (J/token, J/image) | the end-to-end quantity that matters for a deployment | depends on the model, batch size and accuracy target |
| latency vs throughput | time for one request vs requests per second | batching raises throughput and latency together |
A peak TOPS/W figure computed from “MACs × 2 × frequency / core power” excludes memory, I/O and idle time, and can differ by 10× from the energy per inference of a real model. Lecture 3 treats fair comparison in detail. For this lecture, keep one rule: a metric is meaningful only together with the workload, format and utilization it was measured at.
5. The roofline model
5.1 Intuition: a kitchen with a narrow door
Picture a kitchen with ten cooks (the arithmetic units) and one door through which ingredients arrive (the memory bus). If each dish needs a lot of ingredients and little cooking — a salad — the cooks stand idle waiting at the door: the door limits output. If each dish needs a lot of cooking per ingredient — a slow stew — the door is idle and the cooks limit output. What decides which case you are in is not the kitchen alone and not the recipe alone, but the ratio cooking per ingredient compared to the kitchen’s ratio cooks per door.
5.2 The model
A kernel performs operations and moves bytes between memory and the chip. The machine performs at most operations per second and moves at most bytes per second. If computation and transfers overlap perfectly, the time is
is the kernel’s arithmetic intensity (Williams et al. call it operational intensity), in FLOPs per byte. On log-log axes, is a line of slope 1 (the bandwidth roof) that meets a horizontal line (the compute roof) at the ridge point
- : memory-bound. The kernel runs at ; adding arithmetic units does nothing; only more bandwidth or more intensity helps.
- : compute-bound. The kernel can run at ; more bandwidth does nothing.
Why is the roofline so useful? Because it reduces a kernel to one number () and a machine to two (, ), and it says which kind of optimization is worth doing before you do any. It is an upper bound: real kernels also lose time to latency, launch overheads, imperfect overlap and low utilization (§5.8).
Where does come from? In these notes is, unless stated otherwise, the compulsory traffic: each input read from DRAM once and each output written once (workloads.py explains the convention). This is the best case; a kernel that cannot keep its working set on chip moves more (§5.5).
5.3 The roofs of real machines, and the memory wall
Script 02 (Part 1), from datasheet numbers:
| Machine | Kind | Year | 16-bit peak | Ridge | Best-format peak (Top/s) | Ridge | Memory | Bandwidth |
|---|---|---|---|---|---|---|---|---|
| Xeon 8380 | generic | 2021 | fp32: 5.89 TFLOP/s | 29 | int8: 23.6 | 115 | DDR4 × 8 | 205 GB/s |
| V100 | repurposed | 2017 | fp16: 125 TFLOP/s | 139 | fp16: 125 | 139 | HBM2 | 900 GB/s |
| A100 | repurposed | 2020 | bf16: 312 TFLOP/s | 153 | int8: 624 | 306 | HBM2e | 2.04 TB/s |
| H100 | repurposed | 2022 | bf16: 989 TFLOP/s | 295 | fp8: 1,979 | 591 | HBM3 | 3.35 TB/s |
| B200 | repurposed | 2024 | bf16: 2.25 PFLOP/s | 281 | fp4: 9,000 | 1,125 | HBM3e | 8 TB/s |
| TPU v1 | bespoke | 2015 | int8: 92 Top/s | 2,706 | int8: 92 | 2,706 | DDR3 | 34 GB/s |
| TPU v4 | bespoke | 2020 | bf16: 275 TFLOP/s | 229 | bf16: 275 | 229 | HBM2 | 1.2 TB/s |
(The Xeon has no 16-bit matrix math, so its “16-bit” column shows fp32; its peak is computed from cores × clock × AVX-512 width.)
Two facts stand out:
- Every accelerator needs hundreds of operations per byte fetched from DRAM to be compute-bound. Few kernels naturally have that much reuse; §5.4 shows which do.
- Compute outruns bandwidth. From V100 to B200 the 16-bit peak grew 18× while bandwidth grew 8.9×; counting the narrower formats each generation added, peak grew 72×. The ridge point keeps moving right, so more kernels fall on the memory-bound side every generation. This is the memory wall, and it is one of the threads of the course: HBM (Lecture 7), on-chip SRAM capacity (Lectures 7, 13), fusion (Lecture 10) and memory-centric computing (Lectures 14–15) are all responses to it.

5.4 ML kernels on the H100 roofline
Script 02 (Parts 2–3) places fourteen kernels on the H100’s bf16 roofline (989 TFLOP/s, 3.35 TB/s, ridge 295 FLOP/B):
| Kernel | Intensity (FLOP/B) | Bound | % of peak attainable |
|---|---|---|---|
| vector add ( elements) | 0.167 | memory | 0.06% |
| RMSNorm (8192 × 4096) | 1 | memory | 0.34% |
| GEMV 4096 × 4096 (batch 1) | 1 | memory | 0.34% |
| “skinny” GEMM, batch 16 | 15.9 | memory | 5.4% |
| GEMM 128³ | 42.7 | memory | 14% |
| GEMM 512³ | 171 | memory | 58% |
| GEMM 2048³ | 683 | compute | 100% |
| GEMM 8192³ | 2,731 | compute | 100% |
| ResNet-50 3×3 conv (batch 32, 64→64 channels, 56×56) | 287 | memory | 97% |
| 1×1 conv 256→64 (batch 32) | 51 | memory | 17% |
| attention, decode (Llama 3 8B, 4096 context) | 4.0 | memory | 1.4% |
| attention QK^T, prefill 4096 (unfused) | 62 | memory | 21% |
| softmax, prefill 4096 (unfused) | 0.63 | memory | 0.2% |
| attention fused, prefill 4096 | 1,655 | compute | 100% |
How to derive these intensities by hand:
- Element-wise operations read and write each element once and do one or a few operations on it: a vector add in bf16 does 1 FLOP per 6 bytes. Always memory-bound, on every machine in this course.
- GEMM with in bf16: . Intensity grows linearly with the matrix size, so big GEMMs are compute-bound and small ones are not.
- GEMV (): every weight is read once and used for one MAC: FLOP/B in bf16. This is LLM decoding at batch 1 (§7.5). More generally, a linear layer with tokens and a square weight has for : the batch size is the intensity.
- Convolution reuses each input pixel for output positions and each filter for every position, so a 3×3 convolution has ~9× the intensity of a 1×1 convolution with the same channels.
- Decode attention reads the KV cache once per generated token: each 2-byte key or value element serves the query heads of its group with 2 FLOPs each, so — independent of the batch size, because every sequence has its own cache.
- Unfused prefill attention writes the score matrix of each of 32 heads to HBM and reads it back (2.15 GB for the softmax alone). The three unfused steps together reach 32 FLOP/B; fused (FlashAttention, Lecture 10), the same FLOPs reach 1,655 FLOP/B, 52× higher, and become compute-bound. Same math, different data movement.
Do the verdicts depend on the machine? Script 02 (Part 4) recomputes the table for six machines. The extremes agree everywhere (element-wise, GEMV, decode attention: memory-bound; large GEMMs and fused attention: compute-bound). The middle kernels flip with the ridge: the 512³ GEMM (171 FLOP/B) is compute-bound on the Xeon (fp32, ridge 29), V100 (139) and A100 (153), but memory-bound on TPU v4 (229), B200 (281) and H100 (295). A faster machine does not speed up a memory-bound kernel unless its bandwidth grew too.
5.5 Why on-chip memory matters: tiling raises intensity
The compulsory-traffic intensities above assume the chip can hold whatever it needs. It cannot: an 8192³ GEMM touches 400 MB. Suppose the chip has an on-chip buffer of bytes. The classic blocked algorithm computes in tiles: for each tile, it streams the matching row panel of and column panel of through the buffer, which holds about three tiles (). Each element of and is then read times:
Script 02 (Part 5) evaluates this for an 8192³ bf16 GEMM on the H100:
| Buffer | Tile | Intensity (FLOP/B) | Bound | % of peak | DRAM energy per MAC (45 nm) |
|---|---|---|---|---|---|
| 16 KiB | 52 | 26 | memory | 9% | 12.5 pJ |
| 256 KiB | 209 | 103 | memory | 35% | 3.2 pJ |
| 1 MiB | 418 | 204 | memory | 69% | 1.6 pJ |
| 4 MiB | 836 | 398 | compute | 100% | 0.82 pJ |
| 64 MiB | 3,344 | 1,389 | compute | 100% | 0.23 pJ |
To reach the ridge (295 FLOP/B) the tile must be , i.e. a buffer of about 2 MiB. Three lessons:
- Intensity grows only like the square root of the buffer: 4× the SRAM for 2× the intensity. Hong and Kung (1981) proved this is optimal: no schedule of matrix multiplication can move fewer than words.
- Even the most compute-heavy kernel in existence is memory-bound on an H100 without megabytes of on-chip memory. On-chip SRAM is not a convenience; it is what makes the compute roof reachable. (A real H100 GEMM kernel spreads its tiles over the 228 KB of shared memory per SM and the 50 MB L2 cache — a two-level version of this calculation.)
- DRAM energy per MAC falls with the same law. Reuse saves time and joules at once.
This is also the first glimpse of a hierarchical roofline: every level of the memory hierarchy (DRAM, L2, shared memory, registers) has its own bandwidth and its own traffic, hence its own roof, and the slowest one binds (roofline.multilevel_time).
5.6 The energy roofline
Time takes the maximum of compute and memory time, because they overlap. Energy adds:
With Horowitz’s numbers ( pJ for half an fp16 MAC, pJ for DRAM), FLOP/B. Script 02 (Part 6):
| Kernel | Intensity | pJ per FLOP | Share spent on DRAM |
|---|---|---|---|
| vector add | 0.167 | 976 | 100% |
| GEMV, batch 1 | 1 | 164 | 99% |
| skinny GEMM, batch 16 | 15.9 | 11.2 | 91% |
| GEMM 512³ | 171 | 1.95 | 49% |
| GEMM 2048³ | 683 | 1.24 | 19% |
| GEMM 8192³ | 2,731 | 1.06 | 6% |
| attention fused, prefill 4096 | 1,655 | 1.10 | 9% |
A kernel exactly at the energy ridge spends half its energy on DRAM, even though in time it may already be compute-bound. In time, transfers above the ridge are “free” (hidden behind compute); in energy, nothing is free. This is a central point of Verhelst, Benini and Verma’s survey: accelerator efficiency depends on how compute and memory technologies interact, so reuse keeps paying off long after a kernel has become compute-bound — and techniques such as quantization, sparsity and the memory hierarchy should be judged on both rooflines.
5.7 Ceilings, precision, and your own machine
A machine has several compute roofs, one per execution path and format — Williams et al. call the lower ones ceilings. On the H100 (script 02, Part 7):
| Format | Unit | Peak | Ridge (FLOP/B) |
|---|---|---|---|
| fp32 | CUDA cores (no tensor cores) | 67 TFLOP/s | 20 |
| tf32 | tensor cores | 495 TFLOP/s | 148 |
| bf16 | tensor cores | 989 TFLOP/s | 295 |
| fp8 | tensor cores | 1,979 TFLOP/s | 591 |
Code that misses the tensor cores sees a roof 15× lower. And precision moves both the roof and the kernel:
| Kernel | Format | Intensity | Bound | Time |
|---|---|---|---|---|
| GEMV 4096×4096 | fp32 / bf16 / fp8 | 0.5 / 1.0 / 2.0 | memory | 20 / 10 / 5.0 µs |
| GEMM 512³ | fp32 / bf16 / fp8 | 85 / 171 / 341 | compute / memory / memory | 4.0 µs / 470 ns / 235 ns |
| GEMM 8192³ | fp32 / bf16 / fp8 | 1,365 / 2,731 / 5,461 | compute | 16.4 / 1.11 / 0.56 ms |
Fewer bits per element mean fewer bytes for the same FLOPs (higher intensity) and more MACs per mm² and per joule (higher roof). Memory-bound kernels speed up by the byte ratio, compute-bound ones by the peak ratio: halving the bits helps on both sides of the ridge. That is why precision is a whole lecture (Lecture 4).
Measuring a roofline. Datasheet roofs are promises; measured roofs are facts. Script 05 builds the roofline of the computer you run it on: it measures the bandwidth of c = a + b on one core for working sets from 24 KiB to 1.5 GiB, the throughput of matrix multiplications from 32 to 4096, and then compares the roofline’s prediction with measured kernels. One run on an Apple M4 Pro laptop, while other jobs kept it busy (load average ~40 on 12 cores), so the numbers scatter; yours will differ:
- Bandwidth (one core): up to ~130 GB/s for working sets that fit in the caches, ~87 GB/s for arrays streamed from DRAM (1.5× less). On a quiet machine the curve falls in clearer steps at the cache sizes — the memory hierarchy, measured. The same large vector add measured again a few seconds later in Part 3 gave 72 GB/s: on a shared machine even a roof is a noisy quantity.
- Compute: fp32 matrix multiplication reaches ~1.8 TFLOP/s at n = 4096 (fp64: ~0.49 TFLOP/s, 3.7× less). On Apple-silicon Macs, numpy’s BLAS (Accelerate) runs large matrix multiplications on a dedicated matrix unit next to the CPU cores — even a “generic” CPU now carries a small accelerator for this one kernel.
- Prediction vs measurement (roofs 1.81 TFLOP/s and 72 GB/s, ridge 25 FLOP/B): the vector add defines the bandwidth roof (100% by construction); small matmuls reach 45% (n = 64) and 60% (n = 256) of their bound — their compulsory traffic is tiny, so the model calls them compute-bound, but fixed overheads and imperfect parallelism dominate. The n = 1024 matmul came out at 32%, slower than the n = 256 one, and the n = 4096 one at 109% (faster than its own best in Part 2): scatter from the other jobs. The matrix-vector product lands above the single-core roof (160%), because BLAS runs it on several cores, which together draw more bandwidth than the one core that measured the roof. A roof must describe the resources the kernel actually uses.

5.8 What the roofline leaves out
The roofline is a bound under ideal conditions. It ignores:
- latency: a small kernel never reaches either roof (launch overhead, pipeline fill);
- overlap: without double buffering (Lecture 7), time is closer to the sum of compute and transfer time (at most 2× the roofline);
- extra traffic: cache misses, poor tiling, writes that are not compulsory;
- utilization of the arithmetic units: shapes that do not fill the array (§6.5), operators that run elsewhere (§6.3);
- contention: other kernels or other users sharing bandwidth.
Each later lecture adds one of these effects back with a more detailed model. The roofline remains the first sanity check: if a kernel runs at 5% of its roofline bound, something other than the hardware is wrong.
6. How to keep pushing accelerator performance: the levers
6.1 The lever map
The roofline names every way to make a kernel faster. Either raise a roof, move the kernel right (raise its intensity), or get closer to the roof:
| Lever | Raises | Cost | Course |
|---|---|---|---|
| more processing elements, higher clock | compute roof | area, power | L3, L5 |
| lower precision (int8, fp8, fp4) | compute roof and intensity | accuracy risk, scaling logic | L4 |
| sparsity (skip zeros) | effective compute roof | irregularity, metadata, interconnect | L4, L8 |
| more DRAM bandwidth (HBM, more channels) | bandwidth roof | cost, power, package | L7, L17 |
| more on-chip memory, better tiling | intensity (reuse) | area | L7, L9 |
| batching | intensity of weight-bound layers | latency, KV-cache capacity | L1 §7.5, L10 |
| operator fusion | intensity (no DRAM round trips between operators) | compiler complexity | L10 |
| better mapping, matching array shapes | utilization (distance to the roof) | compiler / hardware flexibility | L5, L9 |
| balanced vector units | Amdahl fraction | area | L6 |
Verhelst, Benini and Verma organize their survey of accelerator trends in the same spirit: each technique is understood by which roof it moves, and by how much, on time and energy.
6.2 One lever at a time on a toy accelerator
Script 03 models a small accelerator — a 32 × 32 array of 16-bit MACs at 1 GHz (2.05 Top/s), a 32-lane vector unit, 2 MiB of SRAM, 64 GB/s of DRAM; ridge 32 ops/B — running Llama 3.2 1B (1.24 billion parameters, 2.47 GB of 16-bit weights). The model is analytical: operators run one after another; inside an operator compute and DRAM transfers overlap; GEMMs run on the array with a tiling-dependent DRAM traffic and an array utilization that loses edge tiles and pipeline fill/drain; everything else runs on the vector unit; every operator goes through DRAM (no fusion).
Baseline. Prefill of a 512-token prompt takes 574 ms (time to first token, TTFT), 91% of it array-bound. Decoding one token with 512 tokens of context takes 39 ms (time per output token, TPOT), 100% DRAM-bound: 2.47 GB of weights / 64 GB/s = 38.6 ms. Same model, same chip, two different roofs.
One lever at a time (script 03, Part 2):
| Lever | TTFT | Speedup | Prefill bound | TPOT | Speedup | Decode bound |
|---|---|---|---|---|---|---|
| baseline | 574 ms | 1.00× | array (91%) | 39 ms | 1.00× | DRAM (100%) |
| 2× MACs (32 × 64) | 317 ms | 1.81× | array | 39 ms | 1.00× | DRAM |
| 2× DRAM bandwidth | 568 ms | 1.01× | array | 19.5 ms | 2.00× | DRAM |
| 4× SRAM (8 MiB) | 574 ms | 1.00× | array | 39 ms | 1.00× | DRAM |
| 1/64 SRAM (32 KiB) | 815 ms | 0.70× | DRAM | 39.6 ms | 0.98× | DRAM |
| int8 weights + activations (2× MACs/cycle) | 306 ms | 1.88× | array | 19.5 ms | 2.00× | DRAM |
| weight-only int8 (16-bit math) | 570 ms | 1.01× | array | 19.7 ms | 1.98× | DRAM |
| 4× vector lanes | 555 ms | 1.03× | array | 39 ms | 1.00× | DRAM |
- Prefill is a compute problem: more MACs and int8 math help (not quite 2×, because the vector operators do not speed up); bandwidth and SRAM do not — unless the SRAM becomes so small (32 KiB) that the GEMM tiles shrink and prefill turns DRAM-bound.
- Decode is a bandwidth problem: more bandwidth or fewer bytes per weight help 2×; more MACs help nothing. Weight-only quantization is the decode lever that needs no new arithmetic: weights are stored in int8 (or int4) and expanded to 16 bits on chip.
Batching decode (same hardware, 16-bit):
| Batch | Time per step | Tokens/s | Throughput vs batch 1 | Bound |
|---|---|---|---|---|
| 1 | 39.0 ms | 25.6 | 1.0× | DRAM |
| 4 | 40.2 ms | 99.6 | 3.9× | DRAM |
| 16 | 44.8 ms | 357 | 13.9× | DRAM |
| 32 | 51.3 ms | 624 | 24.4× | array (61%) |
| 64 | 102 ms | 626 | 24.4× | array |
Batching is the strongest decode lever: the weights are read once per step, not per sequence, so throughput rises almost linearly while the time per step barely grows (39 → 51 ms). Batching moves decode to the right along the intensity axis until it reaches the ridge (§5.4: the intensity of a linear layer is ≈ the batch size); beyond that, the array is the limit and throughput stops at ~625 tokens/s.

6.3 Amdahl’s law
If a fraction of the time can be sped up by a factor , the overall speedup is
Script 03 (Part 3) grows the MAC array of the toy accelerator from 32 × 32 up to 64× more MACs while keeping the vector unit and the DRAM bandwidth fixed:
| Array | Peak | TTFT | Speedup | Linear layers | of which DRAM-bound | Attention GEMMs | Vector ops |
|---|---|---|---|---|---|---|---|
| 1× (32 × 32) | 2.05 Top/s | 574 ms | 1.00× | 88% | 2% | 5% | 7% |
| 2× (45 × 45) | 4.05 Top/s | 319 ms | 1.80× | 82% | 3% | 5% | 13% |
| 4× (64 × 64) | 8.19 Top/s | 188 ms | 3.06× | 72% | 6% | 6% | 22% |
| 8× (90 × 90) | 16.2 Top/s | 126 ms | 4.55× | 60% | 77% | 8% | 32% |
| 64× (256 × 256) | 131 Top/s | 126 ms | 4.56× | 60% | 100% | 8% | 32% |
Sixty-four times the peak buys 4.6× the speed. Two things stop it: the linear layers become DRAM-bound (with 2 MiB of SRAM their intensity is capped, §5.5), and the vector operators — norms, softmax, SiLU, residual adds — do not shrink at all, growing from 7% to 32% of the time. The part you did not accelerate decides the speed. The cure is balance: grow the vector unit (Lecture 6), the bandwidth and the buffer with the array, and stop sending element-wise results through DRAM by fusing them (Lecture 10).
6.4 Co-design under an area budget
Silicon area is the currency of chip design. Script 03 (Part 4) splits a fixed 40 mm² (45 nm) between MACs and SRAM, with an area model built on Horowitz’s table — a 16-bit MAC = fp16 multiplier + fp32 adder × 2 for registers and control ≈ 11,600 µm²; SRAM ≈ 5.9 mm² per MiB (an assumed 0.7 µm² per bit) — and measures prefill time at two DRAM bandwidths:
| Area to MACs | Array | SRAM | TTFT @ 32 GB/s | Bound | TTFT @ 128 GB/s | Bound |
|---|---|---|---|---|---|---|
| 10% | 18 × 18 | 6.1 MiB | 1.69 s | array | 1.67 s | array |
| 55% | 43 × 43 | 3.1 MiB | 363 ms | array | 338 ms | array |
| 80% | 52 × 52 | 1.4 MiB | 276 ms | array | 247 ms | array |
| 90% | 55 × 55 | 698 KiB | 341 ms | DRAM | 226 ms | array |
| 98% | 58 × 58 | 140 KiB | 593 ms | DRAM | 209 ms | array |
| 99.5% | 58 × 58 | 35 KiB | 1.6 s | DRAM | 426 ms | DRAM |
Too few MACs and prefill is compute-bound on a small array; too little SRAM and the GEMM tiles shrink until the traffic makes it DRAM-bound. The best split balances the two roofs — and it depends on the memory system around the chip: with 32 GB/s the optimum keeps 1.4 MiB of SRAM, with 128 GB/s only 140 KiB. On-chip memory substitutes for bandwidth by raising reuse. (Decode is not shown: at batch 1 its 2.47 GB of weights never fit on chip, so every split gives the same DRAM-bound time; a decode-only chip would spend its money on bandwidth.)
This is the spirit of the whole course: there is no best accelerator, only a best accelerator for a workload, a budget and a memory system.
6.5 Array shape and utilization
The same 16,384 MACs can be one 128 × 128 array or sixty-four 16 × 16 arrays. Script 03 (Part 5) uses a simple utilization model — edge tiles, plus a fill/drain cost of about rows + cols cycles per output tile while it streams steps:
| GEMM | M × N × K | 1 × 128² | 4 × 64² | 16 × 32² | 64 × 16² |
|---|---|---|---|---|---|
| qkv_proj, prefill | 512 × 3072 × 2048 | 89% | 94% | 97% | 98% |
| QK^T per KV head, prefill | 2048 × 512 × 64 | 20% | 33% | 50% | 67% |
| qkv_proj, decode batch 1 | 1 × 3072 × 2048 | 17% | 18% | 18% | 18% |
| qkv_proj, decode batch 16 | 16 × 3072 × 2048 | 89% | 94% | 97% | 98% |
Big GEMMs use any shape well. A short reduction dimension (the head dimension, 64) wastes a big array, because filling and draining it takes as long as the useful work; a tiny GEMM (3,072 outputs) cannot fill 16,384 MACs however they are arranged. Smaller arrays keep utilization up at the cost of more control and data distribution — one reason TPU v4 uses four 128 × 128 arrays per core instead of one 256 × 256 (Lecture 5).
7. What ML asks of hardware: from matrix multiplication to attention
7.1 Everything is a GEMM (almost)
- A fully connected (linear) layer with of shape (tokens × ) and of shape () is a GEMM with = tokens, , .
- A convolution with images, input channels, filters of size and output size is a GEMM with , , (“implicit GEMM”), but with more reuse than that GEMM because neighboring outputs share input pixels.
- Attention is two batched GEMMs with a softmax between them (§7.2).
- What is not a GEMM — normalization, activation functions, residual adds, softmax, rotary embeddings — is element-wise or a reduction along one axis: little arithmetic, all memory traffic.
This is why a matrix engine plus a vector unit covers almost all of ML, and why the two must be balanced (§6.3).
7.2 The attention mechanism
Motivation. Before 2017, sequence models were recurrent: a hidden state was updated token by token. That made training inherently sequential (token needs token ) and squeezed all past information through one fixed-size vector. Vaswani et al. replaced recurrence entirely with attention: every token directly looks at every other token and takes what it needs. For hardware this was decisive: all tokens of a sequence can be processed in parallel, as matrix multiplications.
The computation. Each token’s vector is projected into a query (“what am I looking for?”), a key (“what do I contain?”) and a value (“what do I pass on?”). Token ‘s output is a weighted average of all values, weighted by query-key similarity:
Why each piece is there:
- Dot products as similarity: cheap, and exactly what a matrix engine computes ( is one GEMM for all pairs).
- Division by : if the entries of and have unit variance, their dot product has variance . Large scores push the softmax toward a one-hot distribution with vanishing gradients; dividing by keeps the variance at 1 (the paper’s own justification).
- Softmax: turns scores into non-negative weights that sum to 1 — a differentiable “soft lookup”.
- Multiple heads: independent attentions on -dimensional slices, concatenated. Different heads can attend to different things; for hardware they are one batched GEMM.
- Causal mask: in a decoder, token may only attend to tokens (add to the scores above the diagonal). This is what lets a model generate text one token at a time — and lets it cache the keys and values of the past.
- Positional information: attention by itself treats its input as a set; word order is injected separately (sinusoidal encodings in the original paper, rotary embeddings in Llama).
Script 04 (Part 1) builds attention in numpy on six tokens and checks these properties numerically: rows of the probability matrix sum to 1 (max deviation ); permuting the tokens permutes the outputs (); with a causal mask, perturbing the last token changes earlier outputs by exactly 0 while changing its own output by 2.3; and two heads computed in a loop equal the batched-GEMM form exactly.
The hardware view. Attention has a cost that grows with the square of the sequence length: the score matrix has entries per head. With 32 heads and 4096 tokens that is 1 GB in bf16 — far more than the inputs. Whether that matrix ever leaves the chip decides whether attention is memory-bound (unfused, 32 FLOP/B) or compute-bound (fused, 1,655 FLOP/B) (§5.4, Lecture 10).
7.3 A first look at numerics
Two numerical facts from script 04 (Part 2) explain design choices you will meet again:
- Softmax overflows in fp16. The largest fp16 number is 65,504, so overflows for . Logits give
nanwith a naive softmax in fp16. Subtracting the row maximum first is exact in real arithmetic and keeps every exponent ≤ 0; the stable fp16 result is within of fp64. Every softmax kernel does this, and it is why FlashAttention must carry a running maximum when it processes a row in pieces (Lecture 10). - Accumulators must be wide. A dot product of fp16 numbers accumulated sequentially in fp16 drifts: with the fp16 sum is 112.4 instead of 114.4. Accumulated in fp32 it is exact to 7 digits. Hence every MAC unit multiplies narrow inputs but accumulates wide: fp16/bf16 × fp16/bf16 → fp32, int8 × int8 → int32 (Lecture 4). This is also why the MAC energies of §2.3 pair a narrow multiplier with a 32-bit adder.
7.4 One transformer layer, operator by operator
A Llama-style decoder layer applies, to tokens: RMSNorm → a fused Q/K/V projection → rotary embeddings → append K, V to the cache → attention → output projection → residual add → RMSNorm → a fused gate/up projection → SiLU(gate) × up → down projection → residual add. Script 04 (Part 3) lists every operator of one layer of Llama 3 8B (d_model 4096, 32 layers, 32 query heads / 8 KV heads of width 128, FFN 14,336; 8.03 B parameters) on an H100 in bf16:
Prefill, 2048-token prompt (unfused attention) — 928 GFLOP, 2.24 GB, 1.36 ms per layer:
| Operator | Intensity | Bound | Share of time | Share of FLOPs |
|---|---|---|---|---|
| qkv_proj | 1,120 | compute | 7.7% | 11.1% |
| QK^T (scores) | 59 | memory | 6.4% | 1.9% |
| softmax | 0.63 | memory | 11.8% | 0.0% |
| PV | 59 | memory | 6.4% | 1.9% |
| o_proj | 1,020 | compute | 5.1% | 7.4% |
| gate_up_proj | 1,300 | compute | 35.9% | 51.8% |
| down_proj | 1,250 | compute | 17.9% | 25.9% |
| norms, RoPE, residuals, SiLU×up, cache append | ≤ 1 | memory | 8.8% | < 0.1% |
The four linear layers do 96% of the FLOPs but take 67% of the time; unfused attention takes ~25% of the time with 4% of the FLOPs, because the score matrices (268 MB per layer) travel to HBM and back.
Decode, one token, 2048 tokens of context — 470 MFLOP, 445 MB, 133 µs per layer: every operator is memory-bound; the linear layers take 98% of the time, simply by being the biggest reads (218 M weights per layer, 2 FLOPs each).
7.5 Prefill vs decode, the KV cache, and batching
An LLM serves a request in two phases:
- Prefill: process the whole prompt at once. Linear layers are GEMMs with = prompt length — compute-bound for prompts of more than a few hundred tokens.
- Decode: generate tokens one at a time. Each step processes one new token per sequence, so linear layers are GEMVs ( = batch size) and every weight byte is used for ~2 FLOPs per sequence. The keys and values of all previous tokens are kept in the KV cache so that they are not recomputed; each step reads the whole cache.
Decode on one H100 (Llama 3 8B, script 04, Part 4):
| Batch | Step time (2k context) | Tokens/s | Intensity | Weights’ share of traffic | KV cache | Fits in 80 GB? |
|---|---|---|---|---|---|---|
| 1 | 4.56 ms | 219 | 1.1 | 98% | 256 MiB | yes |
| 4 | 4.81 ms | 831 | 4.0 | 93% | 1 GiB | yes |
| 16 | 5.82 ms | 2,750 | 13.2 | 77% | 4 GiB | yes |
| 64 | 9.83 ms | 6,511 | 31.3 | 46% | 16 GiB | yes |
| 128 | 15.2 ms | 8,433 | 40.5 | 30% | 32 GiB | yes |
| 256 | 25.9 ms | 9,893 | 47.5 | 17% | 64 GiB | no |
At 8k context the same batches give 208, 692, 1,656, 2,538 (does not fit), … tokens/s, saturating near 2,900.
- At batch 1, a step reads 15 GB of weights to produce one token: the lower bound is 15 GB / 3.35 TB/s = 4.48 ms, ~220 tokens/s, using about 0.4% of the H100’s arithmetic.
- Batching shares the weight read: 4 sequences give 3.8× the throughput for 5% more time per step.
- The KV cache does not share: its traffic grows with batch × context and overtakes the weights (17% of the traffic at batch 256). The step’s intensity stops rising — about 47 FLOP/B at 2k context, 17 at 8k, far below the ridge of 295 — because decode attention’s own intensity is 4 regardless of batch (§5.4).
- Capacity runs out first. At 8k context, 64 sequences need 64 GiB of KV cache, which with 16 GB of weights no longer fits in 80 GB. Memory capacity, not FLOPs, caps the batch. Responses later in the course: PagedAttention to waste none of it (Lecture 10), KV-cache quantization (Lecture 4), memory-centric architectures and high-capacity memory tiers (Lectures 13–15).

Prefill vs prompt length (script 04, Part 5; fused attention):
| Prompt tokens | GFLOP per token | Attention share of FLOPs | Intensity | TTFT |
|---|---|---|---|---|
| 128 | 14.0 | 0% | 109 | 4.9 ms |
| 2,048 | 14.5 | 4% | 774 | 34 ms |
| 32,768 | 22.6 | 38% | 1,906 | 812 ms |
| 131,072 | 48.7 | 71% | 4,219 | 6.7 s |
Linear layers cost a fixed ~14 GFLOP per token (2 FLOPs per layer weight); attention grows with the context because every token attends to all earlier ones — 4% of the FLOPs at 2k tokens, 71% at 128k. A 128-token prompt is still memory-bound (intensity 109 < 295): the weights are read once for only 128 tokens.
Capacity across models (script 04, Part 6; bf16):
| Model | Weights | KV per token | Saved by GQA | Max sequences on H100 @ 8k / 32k / 128k | on B200 |
|---|---|---|---|---|---|
| Llama 3.2 1B | 2.47 GB | 32 KiB | 4× | 288 / 72 / 18 | 706 / 176 / 44 |
| Llama 3 8B | 16.1 GB | 128 KiB | 4× | 59 / 14 / 3 | 163 / 40 / 10 |
| Llama 3 70B | 141 GB | 320 KiB | 8× | weights don’t fit | 18 / 4 / 1 |
Grouped-query attention (GQA: 8 KV heads shared by 32 or 64 query heads) shrinks the cache 4–8× — an architectural choice made for the hardware. Llama 3 70B in bf16 does not fit on one H100 at all.
8. Training vs inference
Training runs the forward pass, a backward pass (about twice the forward cost) and an optimizer update on huge batches. Two numbers summarize its demands (script 04, Part 7):
- Compute: FLOPs for parameters and training tokens (2N per token forward, 4N backward). Llama 3 8B on 15 T tokens: FLOPs, i.e. 0.51 M H100 GPU-hours at 40% model-FLOPs utilization (MFU). Meta’s Llama 3 model card reports 1.3 M H100-80GB GPU-hours for the 8B model, which corresponds to about 16% of dense bf16 peak at — reported totals include much more than the ideal FLOPs.
- Memory: with mixed precision and Adam, each parameter carries bf16 weights (2 B), bf16 gradients (2 B), fp32 master weights (4 B) and two fp32 Adam moments (8 B): 16 bytes per parameter, 128 GB for an 8B model before any activations — 1.6× one H100. Training state must be sharded across many chips, so the interconnect becomes part of the machine (Lectures 8, 16, 17).
| Training | Inference: prefill | Inference: decode | |
|---|---|---|---|
| Typical bound | compute (large batches) + interconnect | compute | memory bandwidth and capacity |
| Precision | bf16/fp8 with fp32 master copies; stochastic rounding | int8/fp8 | weight-only int4/int8, fp8/fp4 |
| What a chip is judged on | FLOP/s, memory capacity, scale-out bandwidth | FLOP/s, TTFT | bytes/s per token, capacity, latency |
9. The map of the course, and Lab 0
Every lecture of CS 217 picks up one part of the picture drawn here:
workload: CNNs, transformers, LLMs (L1, L4, L10)
│
numerics: formats, block scaling, quantization (L4)
│
┌──────────────── compute ───────────────┼──────────── memory & interconnect ────────────┐
│ PE / SIMD (L3) systolic arrays (L5) │ memory systems, global buffer (L7) │
│ vector & scalar units (L6) │ networks-on-chip, chip-to-chip (L8) │
└────────────────────────────────────────┴───────────────────────────────────────────────┘
│
software: dataflows & mapping (L9), fusion, FlashAttention, PagedAttention (L10)
│
architectures: GPUs (L11, L17) · reconfigurable dataflow (L12, L13) · memory-centric (L14, L15) · AWS (L16)
│
methodology: HLS, FPGA prototyping, metrics (L2, L3)
Lab 0 introduces the methodology of the labs: writing hardware blocks in C++/SystemC, turning them into register-transfer-level (RTL) hardware with a high-level synthesis tool, and prototyping the result on an AWS FPGA instance. Lecture 2 explains what an HLS tool does — scheduling, binding, pipelining — and builds a toy one in Python. Labs 1–4 then build one accelerator block by block (a SIMD PE, a vector unit, a global buffer with near-memory compute, a top level with an interconnect fabric), which these notes mirror with cycle-level Python models in Lectures 3, 6, 7 and 8.
10. Summary
- Since Dennard scaling ended (~2005), chips are limited by power, so throughput = power budget / energy per operation. Specialization is the remaining lever; ML suits it because a few kernels dominate, parallelism is massive and regular, low precision works, and data can be reused.
- Horowitz’s table: a DRAM read costs ~43,000 8-bit adds; SRAM energy grows ~√capacity; integer multipliers grow ~bits²; a simple core spends ~70 pJ per instruction on a 0.1 pJ add.
- Energy per MAC falls from 237 pJ (scalar core) to 19.5 (SIMD), 3.5 (matrix engine) and 1.2 pJ (int8 systolic array) in the same 45 nm model — by amortizing control, reusing data and narrowing arithmetic. What remains is data movement, the main subject of the course.
- The roofline: , ridge . Accelerators need hundreds of FLOPs per DRAM byte; the ridge rises every generation (the memory wall).
- Element-wise ops, GEMV and decode attention are memory-bound everywhere; large GEMMs and fused attention are compute-bound everywhere; the middle depends on the machine. On-chip memory raises intensity only like ; energy adds where time overlaps; lower precision raises both the roof and the intensity.
- The levers act on different roofs: MACs and int8 math help compute-bound prefill; bandwidth, weight-only quantization and batching help memory-bound decode. Amdahl’s law caps a growing matrix unit by the operators it does not run; area budgets must balance MACs and SRAM, and the balance depends on the bandwidth.
- Attention = softmax(): parallel over tokens, quadratic in sequence length; its intermediate score matrix decides its intensity. Softmax needs max-subtraction in fp16; accumulators must be wide.
- Prefill is compute-bound, decode is memory-bound; batching raises decode throughput until the per-sequence KV cache dominates traffic and exhausts capacity. Training needs ~ FLOPs and ~16 bytes of state per parameter.
11. Common pitfalls
- Counting a MAC as one FLOP. It is two. Datasheets count 2; mixing conventions loses a factor of 2.
- Comparing peak numbers across formats or with/without sparsity. “1,979 TFLOP/s” for H100 is fp8 dense (or bf16 with sparsity); bf16 dense is 989.
- Treating the roofline as a prediction. It is an upper bound; small kernels sit far below it (script 05).
- Using the wrong roof. A single-core bandwidth roof underestimates multi-core kernels (script 05’s matrix-vector product reached 160% of it); a DRAM roof says nothing about a kernel that lives in L2.
- Assuming more compute helps a memory-bound kernel. Decode on the toy accelerator: 2× MACs → 1.00×.
- Forgetting that intensity depends on the memory level and on fusion. The same attention has 32 FLOP/B unfused and 1,655 fused.
- Ignoring Amdahl. A 64× bigger matrix unit gave 4.6× on prefill.
- Thinking batching is free. It raises throughput, but each sequence brings its own KV cache: capacity and per-sequence latency set the limit.
- Reading Horowitz’s numbers as modern absolute values. They are 45 nm; use them for ratios.
- Equating time-bound and energy-bound. A compute-bound kernel at the energy ridge still spends half its energy on DRAM.
12. Exercises
Exercise 1 (energy of a GEMV). A 4096 × 4096 fp16 matrix-vector product reads its weights from DRAM (162.5 pJ/B) and computes with fp16 MACs (2.0 pJ). (a) What share of the energy is DRAM traffic? (b) If 64 input vectors are processed together (batch 64), what is the share?
Answer
(a) Each 2-byte weight is used by one MAC: 325 pJ of DRAM energy per MAC vs 2.0 pJ arithmetic → 325 / 327 = 99.4%. (b) Each weight now serves 64 MACs: 325/64 = 5.1 pJ per MAC → 5.1 / 7.1 = 72%. Batching is reuse; even batch 64 does not reach Eyeriss’s ”≥ 200 uses per DRAM fetch”.
Exercise 2 (roofline by hand). An A100 has 312 TFLOP/s (bf16) and 2.039 TB/s. (a) What is its ridge point? (b) Is a 1024³ bf16 GEMM compute- or memory-bound with compulsory traffic, and how long does it take at best? (c) And a 1024 × 1024 GEMV?
Answer
(a) 312e12 / 2.039e12 = 153 FLOP/B. (b) > 153 → compute-bound; = 6.9 µs. (c) → memory-bound; traffic ≈ 1024² × 2 B = 2.1 MB → 1.03 µs, achieving ~2 TFLOP/s (0.7% of peak).
Exercise 3 (how big a batch?). A linear layer has a square bf16 weight and processes tokens. (a) Show that . (b) For on an H100 (ridge 295), how many tokens per step make it compute-bound? (c) What does this mean for decode?
Answer
(a) FLOPs ; bytes ; ratio . (b) 345 tokens. (c) A decode step must batch ~345 sequences before its linear layers become compute-bound — more than the KV-cache capacity usually allows at long contexts (script 04, Part 4). For , : the batch size is the intensity.
Exercise 4 (KV cache). Compute the KV-cache size per token of Llama 3 70B (80 layers, 8 KV heads of width 128, bf16) and the cache of one 32k-token conversation. How much would it be without GQA (64 KV heads)?
Answer
B = 327,680 B = 320 KiB per token; × 32,768 tokens = 10 GiB per conversation. With 64 KV heads: 8× more, 2.5 MiB per token and 80 GiB per conversation — a whole H100 for one user.
Exercise 5 (Amdahl). In a prefill workload, 10% of the time is spent in vector operators that the matrix unit cannot run. (a) What is the overall speedup if the matrix unit becomes 10× faster? (b) The limit for an infinitely fast matrix unit? (c) How fast must the vector unit become to keep the overall speedup at 9× with the 10× matrix unit?
Answer
(a) 5.26×. (b) 10×. (c) Need → → 4.7× faster vector unit.
Exercise 6 (instruction size). An int8 MAC costs 0.3 pJ and an instruction 70 pJ. How many MACs must one instruction perform for the overhead to be at most 10% of the arithmetic energy? Which instructions of §2.3 qualify?
Answer
2,334 MACs. Of the table: AMX (8,192 — though it is bf16), wgmma and the TPU’s MatrixMultiply qualify; mma.sync (2,048) is just short; SIMD instructions (16–64) are far from it.
Exercise 7 (post-Dennard with rising frequency). Suppose that after Dennard scaling ended, frequency had still risen by per generation while voltage stayed constant. By how much would power density grow per generation, and what share of the chip could switch at full speed after three generations at fixed power?
Answer
Power per transistor ; transistors per mm² grow → power density grows 2× per generation; after 3 generations 8× → 12.5% usable. Frequency scaling had to stop as well — which is what happened.
Exercise 8 (tiling). Using and , how much on-chip memory does an H100 need to make a large GEMM compute-bound in bf16 (ridge 295)? And in fp8 (ridge 591, 1 byte per element)? Explain the result.
Answer
bf16: , 2.0 MiB. fp8: , 1.0 MiB. The fp8 ridge is twice as high, but each element is half as big: the same tile (in elements) gives twice the FLOPs per byte, so the buffer in bytes halves. Precision helps capacity too.
Exercise 9 (energy roofline). With pJ and pJ, what share of the energy of a kernel with intensity 50 FLOP/B goes to DRAM? At which intensity is it 10%?
Answer
pJ per FLOP of data energy; share = 76%. A 10% share means data energy = 1/9 of compute energy: → 1,460 FLOP/B, five times the H100’s time ridge. Energy keeps rewarding reuse far beyond the time ridge.
Exercise 10 (training cost). Estimate the training compute of Llama 3 70B (70.55 B parameters, 15 T tokens) and its H100 GPU-hours at 40% MFU. Meta’s model card reports 6.4 M GPU-hours; what utilization does that imply?
Answer
FLOPs. At 40% of 989 TFLOP/s: = 1.6e10 GPU-s = 4.5 M GPU-hours. Reported 6.4 M → ≈ 28% of dense peak — better than the 8B model’s 16%: larger models keep GPUs busier.
Exercise 11 (programming: multi-GPU decode). Using workloads.model_ops and hw_specs.H100, estimate the batch-1 decode step time of Llama 3 70B split evenly across 8 H100s (assume the bandwidth simply adds up and ignore communication). What does ignoring communication hide?
Answer
Weights read per step: sum(o.weight_bytes for o in model_ops(LLAMA3_70B, 1, 1, 2048)) ≈ 139 GB; / (8 × 3.35 TB/s) ≈ 5.2 ms per token (~190 tokens/s). Ignored: every layer needs all-reduce communication between the 8 GPUs (two per layer with tensor parallelism), each adding microseconds of latency — at batch 1 these small messages can cost as much as the computation (Lecture 17).
Exercise 12 (programming: your machine as a Machine). Run script 05, then add your computer to hw_specs.py with the measured fp32 peak and DRAM bandwidth, and re-run script 02 (Part 4) with it, using fp32 kernels (ml_kernels(4)). Which kernels are compute-bound on your laptop but memory-bound on the H100 (bf16)? Why?
Answer
With the run quoted in §5.7 (~1.8 TFLOP/s, ~72 GB/s, ridge ~25 FLOP/B), the fp32 intensities are: skinny GEMM 7.9 and 128³ GEMM 21 (memory-bound on both machines); 1×1 convolution 26, prefill QK^T 31, 512³ GEMM 85 and 3×3 convolution 144 — compute-bound on the laptop, while their bf16 versions (51, 62, 171, 287 FLOP/B) are memory-bound on the H100 (ridge 295). The laptop’s ridge is much lower: relative to its arithmetic, its memory system is generous, so moderately reusing kernels already saturate the arithmetic. The exact list depends on your measurements (a ridge of 30 would drop the 1×1 convolution); the method is the point.
13. Further reading
- M. Horowitz, “Computing’s energy problem (and what we can do about it)”, ISSCC 2014 — the source of §2.
- S. Williams, A. Waterman, D. Patterson, “Roofline: an insightful visual performance model for multicore architectures”, CACM 2009 — the original roofline paper, with ceilings.
- M. Verhelst, L. Benini, N. Verma, “How to keep pushing ML accelerator performance? Know your rooflines!”, IEEE JSSC 2025 (arXiv:2505.16346) — a survey of ML accelerator trends through extended rooflines.
- A. Vaswani et al., “Attention is all you need”, NeurIPS 2017.
- J. Hennessy, D. Patterson, Computer Architecture: A Quantitative Approach, 6th ed., chapter 7 (domain-specific architectures), and “A new golden age for computer architecture”, CACM 2019.
- V. Sze, Y.-H. Chen, T.-J. Yang, J. Emer, Efficient Processing of Deep Neural Networks, Morgan & Claypool 2020 — chapters 1–3 complement this lecture; later chapters cover Lectures 3–9.
- N. Jouppi et al., “In-datacenter performance analysis of a tensor processing unit”, ISCA 2017 — read §1–§3 now; it is a Lecture 5 reading.
- H. Esmaeilzadeh et al., “Dark silicon and the end of multicore scaling”, ISCA 2011.
- J.-W. Hong, H. T. Kung, “I/O complexity: the red-blue pebble game”, STOC 1981 — the lower bound.
- J. Kaplan et al., “Scaling laws for neural language models”, 2020 — the approximation.
14. Next lecture
Lecture 2, High-Level Synthesis, starts the methodology thread. How does a C++ function become hardware? An HLS tool decides when each operation runs (scheduling), on which unit (binding) and how many units to build (allocation), and pipelines loops so that a new iteration starts every cycle. We will build a toy HLS engine in Python, find the initiation interval of loops with recurrences, trade area for latency with unrolling and partitioning, and simulate the ready/valid channels that connect accelerator blocks — the design style of the labs.