Lecture 1 · Introduction: The Energy Problem, the Roofline, and What ML Asks of Hardware

Hardware Accelerators for Machine Learning · Lecture 01。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. Explain why on-chip memory raises intensity (tiling: intensity ∝ √buffer size), and why energy follows a different roofline than time.
  7. 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.
  8. Apply Amdahl’s law to an accelerator whose matrix unit keeps growing.
  9. 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.
  10. 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:

AssumedIntroduced hereDeveloped later
what a processor, a cache and DRAM areenergy per operation and per access; instruction overheadPEs (L3), systolic arrays (L5), vector units (L6), memory systems (L7)
matrix multiplication; big-O notationFLOPs, bytes, arithmetic intensity, the rooflinedataflows and mapping (L9), fusion (L10)
what a neural network layer computesGEMMs, convolution as GEMM, attention, transformer layersquantization (L4), FlashAttention and PagedAttention (L10)
a little Pythonanalytical models of hardware, numpy timingcycle-level simulators of every block (L2–L8)

If “a matrix multiplication of size nn costs 2n32n^3 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

SymbolMeaning
FLOP, opone arithmetic operation (FLOP for floating point, op for integers)
MACone multiply-accumulate c←c+a⋅bc \leftarrow c + a \cdot b = 2 operations
PPpeak compute throughput of a machine (FLOP/s or op/s), the compute roof
BBmemory bandwidth (bytes/s), the bandwidth roof
WW, QQwork (FLOPs) and memory traffic (bytes) of a kernel
I=W/QI = W/Qarithmetic intensity (FLOP/byte)
I∗=P/BI^* = P/Bridge point of a machine
bbbytes per element (4 for fp32, 2 for bf16/fp16, 1 for int8/fp8)
M,N,KM, N, KGEMM dimensions: CM×N=AM×KBK×NC_{M\times N} = A_{M\times K} B_{K\times N}
pJpicojoule = 10−1210^{-12} J; a 1 W chip spends 101210^{12} pJ per second

Rates and data sizes use powers of ten (1 TB/s = 101210^{12} B/s, 1 TFLOP/s = 101210^{12} 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:

ModuleWhat it holds
hw_specs.pydatasheet numbers of seven reference machines (a Xeon CPU, V100, A100, H100, B200, TPU v1, TPU v4), each with its source
energy_model.pyHorowitz’s 45 nm energy/area table, Eyeriss’s normalized storage costs, scaling fits, an EnergyBreakdown
roofline.pyattainable performance, ridge points, hierarchical and energy rooflines, terminal and matplotlib plots
workloads.pyFLOPs 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:

HowTime per multiply-addRate
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 6ND=7.2×10236ND = 7.2\times 10^{23} 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 S≈1.4S \approx 1.4, its capacitance CC and supply voltage VV shrink by 1/S1/S and it can switch SS times faster. Dynamic power per transistor is
Ptransistor=C V2f  ∝  1S⋅1S2⋅S=1S2,P_{\text{transistor}} = C\,V^2 f \;\propto\; \frac{1}{S}\cdot\frac{1}{S^2}\cdot S = \frac{1}{S^2},

and since S2S^2 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 VV and ff roughly fixed, power per transistor only falls like 1/S1/S, so power density grows by S≈1.4S \approx 1.4 per generation. Script 01 (Part 5) tabulates this simple model:

GenerationTransistors / mm²Power density, DennardPower density, post-DennardShare of the chip usable at fixed power
01.0×1.00×1.00×100%
24.2×1.00×2.04×49%
417.3×1.00×4.16×24%
672.2×1.00×8.50×12%
8300.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 PbudgetP_{\text{budget}} is fixed,

throughput (ops/s)=Pbudget (J/s)Eop (J/op).\text{throughput (ops/s)} = \frac{P_{\text{budget}}\ (\text{J/s})}{E_{\text{op}}\ (\text{J/op})} .

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?

  1. A few kernels dominate. Almost all of the arithmetic is matrix multiplication (§7.1), plus a short list of element-wise functions.
  2. Massive, regular parallelism. Millions of independent multiply-adds with static, predictable data access: no need for branch prediction, speculation or caches that guess.
  3. Tolerance to low precision. Networks work with 8-bit or even 4-bit numbers (Lecture 4), and narrow arithmetic is dramatically cheaper (§2).
  4. 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)ExampleWhat is specializedWhat generality remainsLectures
Genericmulticore CPUSIMD units; recently small matrix extensions (Intel AMX, Apple’s matrix unit)everything: any programbaseline throughout
Repurposed and augmentedGPU with tensor coresmassive multithreading built for graphics, augmented with matrix units and low-precision formatsany data-parallel program (CUDA)11, 17
Bespoke and customizedGoogle TPUa large systolic matrix unit, a software-managed memory hierarchy, a narrow instruction setonly tensor programs compiled by XLA5, 6
Flexible and reconfigurableSambaNova RDU (dataflow), FPGAs, CGRAsthe datapath itself is configured per programany program expressible as a dataflow graph12, 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):

OperationEnergy (pJ)× an 8-bit addArea (µm²)
8-bit integer add0.03136
32-bit integer add0.13137
8-bit integer multiply0.27282
32-bit integer multiply3.11033,495
16-bit float add0.4131,360
32-bit float add0.9304,184
16-bit float multiply1.1371,640
32-bit float multiply3.71237,700
SRAM read, 8 KB (64 bits)10333
SRAM read, 32 KB (64 bits)20667
SRAM read, 1 MB (64 bits)1003,333
DRAM read (64 bits)1,300–2,60043,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):

UnitEnergy grows likeArea grows like
integer addbits^0.87bits^0.96
integer multiplybits^1.98bits^1.82

An integer multiplier is essentially a b×bb \times b grid of partial products, hence ∼b2\sim b^2; an adder is a chain of bb cells, hence ∼b\sim b. 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 CC laid out as a square has sides ∝C\propto \sqrt{C}, 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 formatMAC energy (pJ)MACs per instruction to break even
fp32 (fp32 mul + fp32 add)4.615
fp16 (fp16 mul + fp32 accumulate)2.035
int8 (int8 mul + int32 accumulate)0.3233

and compares real instructions:

InstructionMACs per instructionOverhead per MACOverhead / arithmetic
scalar FMA (any CPU)170 pJ15
AVX-512 FMA, fp32 (16 lanes)164.4 pJ0.95
AVX-512 VNNI, int8641.1 pJ3.6
Intel AMX TDPBF16PS (16×16×32)8,1920.009 pJ0.004
NVIDIA mma.sync m16n8k16 (one warp)2,0480.034 pJ0.017
NVIDIA wgmma m64n256k16 (Hopper)262,1440.0003 pJ0.0001
TPU v1 MatrixMultiply, 256 rows16,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:

  1. Amortize control: make each instruction (or each configuration of a reconfigurable fabric) cover as much work as possible.
  2. Exploit locality: arrange the computation so that operands come from small, nearby memories, and each value fetched from far away is reused many times.
  3. Use the narrowest arithmetic that works: multipliers shrink quadratically with width.
  4. 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:

EMAC  =  Emul+Eadd⏟arithmetic  +  EinstrMACs per instruction⏟control  +  ∑levels ℓbytes per operandreuse at ℓ  eℓ⏟data movement.E_{\text{MAC}} \;=\; \underbrace{E_{\text{mul}} + E_{\text{add}}}_{\text{arithmetic}} \;+\; \underbrace{\frac{E_{\text{instr}}}{\text{MACs per instruction}}}_{\text{control}} \;+\; \sum_{\text{levels } \ell} \underbrace{\frac{\text{bytes per operand}}{\text{reuse at } \ell}\; e_\ell}_{\text{data movement}} .

The last term is the important one: if each value fetched from level ℓ\ell (energy eℓe_\ell per byte) is used by RℓR_\ell MACs, then each MAC pays only 1/Rℓ1/R_\ell 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

DesignFormatHow it runs the GEMM
scalar corefp32per MAC: load a, load b, FMA = 3 instructions; both operands from the 32 KB L1 cache every time
SIMD core (AVX-512-like)fp32register-blocked micro-kernel: 9 instructions per 64 MACs, 80 bytes from L1 per 64 MACs
GPU-style matrix enginefp16 in, fp32 accumulatea 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 arrayint8 in, int32 accumulateone instruction streams the whole matrix; each activation is used by 256 MACs as it flows across the array

Result (script 01, Part 3):

DesignArithmeticInstruction overheadOn-chip SRAMDRAM (compulsory)Total pJ/MAC
scalar core, fp324.6 (2%)210 (89%)20 (8%)1.9 (1%)237
SIMD core, fp324.6 (24%)9.84 (51%)3.12 (16%)1.9 (10%)19.5
matrix engine, fp162.0 (56%)0.04 (1%)0.55 (15%)0.95 (27%)3.54
systolic array, int80.3 (25%)~0 (0%)0.44 (36%)0.48 (39%)1.22

Energy breakdown of four designs

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 throughputvs scalar
scalar core, fp322.5 Top/s1×
SIMD core, fp3231 Top/s12×
matrix engine, fp16169 Top/s67×
systolic array, int8494 Top/s195×

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:

ChipFormatPeak / TDPpJ per MAC at TDP
TPU v1 (28 nm)int81.23 Top/s per W1.63
A100 (7 nm)bf160.78 Top/s per W2.56
H100 (4 nm)bf161.41 Top/s per W1.41
H100 (4 nm)fp82.83 Top/s per W0.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 levelEnergy 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×
DRAM200×

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 atEnergy per MACShare spent moving data
register file5×80%
PE network9×89%
global buffer25×96%
DRAM801×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 c←c+a⋅bc \leftarrow c + a\cdot b and is counted as 2 operations (one multiply, one add).
  • A matrix multiplication CM×N=AM×KBK×NC_{M\times N} = A_{M\times K}B_{K\times N} performs MNKMNK MACs =2MNK= 2MNK FLOPs. A matrix-vector product (M=1M=1) performs 2NK2NK.
  • Peak throughput = number of MAC units × 2 × clock frequency. TPU v1: 256×256=65,536256 \times 256 = 65{,}536 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

attained throughput=peak×utilization,\text{attained throughput} = \text{peak} \times \text{utilization},

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

MetricWhat it measuresWatch out for
TOPS (or FLOP/s)peak throughputwhich format, dense or sparse, at which clock
TOPS/Woperations 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 deploymentdepends on the model, batch size and accuracy target
latency vs throughputtime for one request vs requests per secondbatching 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 WW operations and moves QQ bytes between memory and the chip. The machine performs at most PP operations per second and moves at most BB bytes per second. If computation and transfers overlap perfectly, the time is

T=max⁡ ⁣(WP,  QB),attainable performance=WT=min⁡(P,  B⋅I),I=WQ.T = \max\!\left(\frac{W}{P},\; \frac{Q}{B}\right), \qquad \text{attainable performance} = \frac{W}{T} = \min\left(P,\; B \cdot I\right), \qquad I = \frac{W}{Q}.

II is the kernel’s arithmetic intensity (Williams et al. call it operational intensity), in FLOPs per byte. On log-log axes, min⁡(P,B⋅I)\min(P, B\cdot I) is a line of slope 1 (the bandwidth roof) that meets a horizontal line (the compute roof) at the ridge point

I∗=PB.I^* = \frac{P}{B}.
  • I<I∗I < I^*: memory-bound. The kernel runs at B⋅IB\cdot I; adding arithmetic units does nothing; only more bandwidth or more intensity helps.
  • I≥I∗I \ge I^*: compute-bound. The kernel can run at PP; more bandwidth does nothing.

Why is the roofline so useful? Because it reduces a kernel to one number (II) and a machine to two (PP, BB), 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 QQ come from? In these notes QQ 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:

MachineKindYear16-bit peakRidgeBest-format peak (Top/s)RidgeMemoryBandwidth
Xeon 8380generic2021fp32: 5.89 TFLOP/s29int8: 23.6115DDR4 × 8205 GB/s
V100repurposed2017fp16: 125 TFLOP/s139fp16: 125139HBM2900 GB/s
A100repurposed2020bf16: 312 TFLOP/s153int8: 624306HBM2e2.04 TB/s
H100repurposed2022bf16: 989 TFLOP/s295fp8: 1,979591HBM33.35 TB/s
B200repurposed2024bf16: 2.25 PFLOP/s281fp4: 9,0001,125HBM3e8 TB/s
TPU v1bespoke2015int8: 92 Top/s2,706int8: 922,706DDR334 GB/s
TPU v4bespoke2020bf16: 275 TFLOP/s229bf16: 275229HBM21.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.

Kernels on the H100 roofline, and four GPU generations

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

KernelIntensity (FLOP/B)Bound% of peak attainable
vector add (2262^{26} elements)0.167memory0.06%
RMSNorm (8192 × 4096)1memory0.34%
GEMV 4096 × 4096 (batch 1)1memory0.34%
“skinny” GEMM, batch 1615.9memory5.4%
GEMM 128³42.7memory14%
GEMM 512³171memory58%
GEMM 2048³683compute100%
GEMM 8192³2,731compute100%
ResNet-50 3×3 conv (batch 32, 64→64 channels, 56×56)287memory97%
1×1 conv 256→64 (batch 32)51memory17%
attention, decode (Llama 3 8B, 4096 context)4.0memory1.4%
attention QK^T, prefill 4096 (unfused)62memory21%
softmax, prefill 4096 (unfused)0.63memory0.2%
attention fused, prefill 40961,655compute100%

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 M=N=K=nM=N=K=n in bf16: I=2n3/(3n2⋅2)=n/3I = 2n^3 / (3n^2 \cdot 2) = n/3. Intensity grows linearly with the matrix size, so big GEMMs are compute-bound and small ones are not.
  • GEMV (M=1M = 1): every weight is read once and used for one MAC: I≈2/b=1I \approx 2/b = 1 FLOP/B in bf16. This is LLM decoding at batch 1 (§7.5). More generally, a linear layer with MM tokens and a square d×dd\times d weight has I=Md/(2M+d)≈MI = Md/(2M+d) \approx M for M≪dM \ll d: the batch size is the intensity.
  • Convolution reuses each input pixel for R×SR\times S 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 nheads/nkv heads=4n_{\text{heads}}/n_{\text{kv heads}} = 4 query heads of its group with 2 FLOPs each, so I=4I = 4 — independent of the batch size, because every sequence has its own cache.
  • Unfused prefill attention writes the 4096×40964096 \times 4096 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 SS bytes. The classic blocked algorithm computes CC in T×TT\times T tiles: for each tile, it streams the matching row panel of AA and column panel of BB through the buffer, which holds about three tiles (S≈3T2bS \approx 3T^2 b). Each element of AA and BB is then read n/Tn/T times:

Q(T)=2n3bT+n2b,I(T)=2n3Q(T)≈Tb  ∝  S.Q(T) = \frac{2 n^3 b}{T} + n^2 b, \qquad I(T) = \frac{2n^3}{Q(T)} \approx \frac{T}{b} \;\propto\; \sqrt{S}.

Script 02 (Part 5) evaluates this for an 8192³ bf16 GEMM on the H100:

Buffer SSTile TTIntensity (FLOP/B)Bound% of peakDRAM energy per MAC (45 nm)
16 KiB5226memory9%12.5 pJ
256 KiB209103memory35%3.2 pJ
1 MiB418204memory69%1.6 pJ
4 MiB836398compute100%0.82 pJ
64 MiB3,3441,389compute100%0.23 pJ

To reach the ridge (295 FLOP/B) the tile must be T≈295×2≈590T \approx 295 \times 2 \approx 590, 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 Θ(n3/S)\Theta(n^3/\sqrt{S}) 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:

EFLOP=eflop+ebyteI,IE=ebyteeflop(energy ridge: data energy = compute energy).\frac{E}{\text{FLOP}} = e_{\text{flop}} + \frac{e_{\text{byte}}}{I}, \qquad I_E = \frac{e_{\text{byte}}}{e_{\text{flop}}} \quad\text{(energy ridge: data energy = compute energy)}.

With Horowitz’s numbers (eflop=1.0e_{\text{flop}} = 1.0 pJ for half an fp16 MAC, ebyte=162.5e_{\text{byte}} = 162.5 pJ for DRAM), IE=162I_E = 162 FLOP/B. Script 02 (Part 6):

KernelIntensitypJ per FLOPShare spent on DRAM
vector add0.167976100%
GEMV, batch 1116499%
skinny GEMM, batch 1615.911.291%
GEMM 512³1711.9549%
GEMM 2048³6831.2419%
GEMM 8192³2,7311.066%
attention fused, prefill 40961,6551.109%

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

FormatUnitPeakRidge (FLOP/B)
fp32CUDA cores (no tensor cores)67 TFLOP/s20
tf32tensor cores495 TFLOP/s148
bf16tensor cores989 TFLOP/s295
fp8tensor cores1,979 TFLOP/s591

Code that misses the tensor cores sees a roof 15× lower. And precision moves both the roof and the kernel:

KernelFormatIntensityBoundTime
GEMV 4096×4096fp32 / bf16 / fp80.5 / 1.0 / 2.0memory20 / 10 / 5.0 µs
GEMM 512³fp32 / bf16 / fp885 / 171 / 341compute / memory / memory4.0 µs / 470 ns / 235 ns
GEMM 8192³fp32 / bf16 / fp81,365 / 2,731 / 5,461compute16.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.

Measured bandwidth and roofline of a laptop (one loaded run)

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:

LeverRaisesCostCourse
more processing elements, higher clockcompute roofarea, powerL3, L5
lower precision (int8, fp8, fp4)compute roof and intensityaccuracy risk, scaling logicL4
sparsity (skip zeros)effective compute roofirregularity, metadata, interconnectL4, L8
more DRAM bandwidth (HBM, more channels)bandwidth roofcost, power, packageL7, L17
more on-chip memory, better tilingintensity (reuse)areaL7, L9
batchingintensity of weight-bound layerslatency, KV-cache capacityL1 §7.5, L10
operator fusionintensity (no DRAM round trips between operators)compiler complexityL10
better mapping, matching array shapesutilization (distance to the roof)compiler / hardware flexibilityL5, L9
balanced vector unitsAmdahl fractionareaL6

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

LeverTTFTSpeedupPrefill boundTPOTSpeedupDecode bound
baseline574 ms1.00×array (91%)39 ms1.00×DRAM (100%)
2× MACs (32 × 64)317 ms1.81×array39 ms1.00×DRAM
2× DRAM bandwidth568 ms1.01×array19.5 ms2.00×DRAM
4× SRAM (8 MiB)574 ms1.00×array39 ms1.00×DRAM
1/64 SRAM (32 KiB)815 ms0.70×DRAM39.6 ms0.98×DRAM
int8 weights + activations (2× MACs/cycle)306 ms1.88×array19.5 ms2.00×DRAM
weight-only int8 (16-bit math)570 ms1.01×array19.7 ms1.98×DRAM
4× vector lanes555 ms1.03×array39 ms1.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):

BatchTime per stepTokens/sThroughput vs batch 1Bound
139.0 ms25.61.0×DRAM
440.2 ms99.63.9×DRAM
1644.8 ms35713.9×DRAM
3251.3 ms62424.4×array (61%)
64102 ms62624.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.

Levers, Amdahl's law and the area budget

6.3 Amdahl’s law

If a fraction ff of the time can be sped up by a factor ss, the overall speedup is

speedup=1(1−f)+f/s  →s→∞  11−f.\text{speedup} = \frac{1}{(1-f) + f/s} \;\xrightarrow{s\to\infty}\; \frac{1}{1-f}.

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:

ArrayPeakTTFTSpeedupLinear layersof which DRAM-boundAttention GEMMsVector ops
1× (32 × 32)2.05 Top/s574 ms1.00×88%2%5%7%
2× (45 × 45)4.05 Top/s319 ms1.80×82%3%5%13%
4× (64 × 64)8.19 Top/s188 ms3.06×72%6%6%22%
8× (90 × 90)16.2 Top/s126 ms4.55×60%77%8%32%
64× (256 × 256)131 Top/s126 ms4.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 MACsArraySRAMTTFT @ 32 GB/sBoundTTFT @ 128 GB/sBound
10%18 × 186.1 MiB1.69 sarray1.67 sarray
55%43 × 433.1 MiB363 msarray338 msarray
80%52 × 521.4 MiB276 msarray247 msarray
90%55 × 55698 KiB341 msDRAM226 msarray
98%58 × 58140 KiB593 msDRAM209 msarray
99.5%58 × 5835 KiB1.6 sDRAM426 msDRAM

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 KK steps:

GEMMM × N × K1 × 128²4 × 64²16 × 32²64 × 16²
qkv_proj, prefill512 × 3072 × 204889%94%97%98%
QK^T per KV head, prefill2048 × 512 × 6420%33%50%67%
qkv_proj, decode batch 11 × 3072 × 204817%18%18%18%
qkv_proj, decode batch 1616 × 3072 × 204889%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 Y=XWY = XW with XX of shape (tokens × dind_{\text{in}}) and WW of shape (din×doutd_{\text{in}} \times d_{\text{out}}) is a GEMM with MM = tokens, K=dinK = d_{\text{in}}, N=doutN = d_{\text{out}}.
  • A convolution with NN images, CC input channels, KK filters of size R×SR\times S and output size P×QP\times Q is a GEMM with M=NPQM = NPQ, Ngemm=KN_{\text{gemm}} = K, Kgemm=CRSK_{\text{gemm}} = CRS (“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 tt needs token t−1t-1) 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 xix_i is projected into a query qi=xiWQq_i = x_i W_Q (“what am I looking for?”), a key kj=xjWKk_j = x_j W_K (“what do I contain?”) and a value vj=xjWVv_j = x_j W_V (“what do I pass on?”). Token ii‘s output is a weighted average of all values, weighted by query-key similarity:

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V,softmax(s)j=esj∑j′esj′.\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{Q K^\top}{\sqrt{d_k}}\right) V, \qquad \text{softmax}(s)_j = \frac{e^{s_j}}{\sum_{j'} e^{s_{j'}}} .

Why each piece is there:

  • Dot products as similarity: cheap, and exactly what a matrix engine computes (QK⊤QK^\top is one GEMM for all pairs).
  • Division by dk\sqrt{d_k}: if the entries of qq and kk have unit variance, their dot product has variance dkd_k. Large scores push the softmax toward a one-hot distribution with vanishing gradients; dividing by dk\sqrt{d_k} 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: hh independent attentions on dmodel/hd_{\text{model}}/h-dimensional slices, concatenated. Different heads can attend to different things; for hardware they are one batched GEMM.
  • Causal mask: in a decoder, token ii may only attend to tokens ≤i\le i (add −∞-\infty 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 2×10−162\times10^{-16}); permuting the tokens permutes the outputs (2×10−162\times10^{-16}); 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 nq×nkn_q \times n_k 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 exe^x overflows for x>11.09x > 11.09. Logits [12,11,10,0][12, 11, 10, 0] give nan with 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 3×10−43\times10^{-4} 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 KK fp16 numbers accumulated sequentially in fp16 drifts: with K=16,384K = 16{,}384 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 TT 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:

OperatorIntensityBoundShare of timeShare of FLOPs
qkv_proj1,120compute7.7%11.1%
QK^T (scores)59memory6.4%1.9%
softmax0.63memory11.8%0.0%
PV59memory6.4%1.9%
o_proj1,020compute5.1%7.4%
gate_up_proj1,300compute35.9%51.8%
down_proj1,250compute17.9%25.9%
norms, RoPE, residuals, SiLU×up, cache append≤ 1memory8.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:

  1. Prefill: process the whole prompt at once. Linear layers are GEMMs with MM = prompt length — compute-bound for prompts of more than a few hundred tokens.
  2. Decode: generate tokens one at a time. Each step processes one new token per sequence, so linear layers are GEMVs (MM = 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):

BatchStep time (2k context)Tokens/sIntensityWeights’ share of trafficKV cacheFits in 80 GB?
14.56 ms2191.198%256 MiByes
44.81 ms8314.093%1 GiByes
165.82 ms2,75013.277%4 GiByes
649.83 ms6,51131.346%16 GiByes
12815.2 ms8,43340.530%32 GiByes
25625.9 ms9,89347.517%64 GiBno

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

Decode throughput vs batch size

Prefill vs prompt length (script 04, Part 5; fused attention):

Prompt tokensGFLOP per tokenAttention share of FLOPsIntensityTTFT
12814.00%1094.9 ms
2,04814.54%77434 ms
32,76822.638%1,906812 ms
131,07248.771%4,2196.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):

ModelWeightsKV per tokenSaved by GQAMax sequences on H100 @ 8k / 32k / 128kon B200
Llama 3.2 1B2.47 GB32 KiB4×288 / 72 / 18706 / 176 / 44
Llama 3 8B16.1 GB128 KiB4×59 / 14 / 3163 / 40 / 10
Llama 3 70B141 GB320 KiB8×weights don’t fit18 / 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: ≈6ND\approx 6ND FLOPs for NN parameters and DD training tokens (2N per token forward, 4N backward). Llama 3 8B on 15 T tokens: 7.2×10237.2\times10^{23} 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 6ND6ND — 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).
TrainingInference: prefillInference: decode
Typical boundcompute (large batches) + interconnectcomputememory bandwidth and capacity
Precisionbf16/fp8 with fp32 master copies; stochastic roundingint8/fp8weight-only int4/int8, fp8/fp4
What a chip is judged onFLOP/s, memory capacity, scale-out bandwidthFLOP/s, TTFTbytes/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

  1. 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.
  2. 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.
  3. 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.
  4. The roofline: attainable=min⁡(P,B⋅I)\text{attainable} = \min(P, B\cdot I), ridge I∗=P/BI^* = P/B. Accelerators need hundreds of FLOPs per DRAM byte; the ridge rises every generation (the memory wall).
  5. 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 S\sqrt{S}; energy adds where time overlaps; lower precision raises both the roof and the intensity.
  6. 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.
  7. Attention = softmax(QK⊤/dkQK^\top/\sqrt{d_k})VV: parallel over tokens, quadratic in sequence length; its intermediate score matrix decides its intensity. Softmax needs max-subtraction in fp16; accumulators must be wide.
  8. 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 ~6ND6ND 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) I=n/3=341I = n/3 = 341 > 153 → compute-bound; T=2⋅10243/312×1012T = 2\cdot1024^3 / 312\times10^{12} = 6.9 µs. (c) I≈1I \approx 1 → 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 d×dd \times d bf16 weight and processes MM tokens. (a) Show that I=Md/(2M+d)I = Md/(2M + d). (b) For d=4096d = 4096 on an H100 (ridge 295), how many tokens per step make it compute-bound? (c) What does this mean for decode?

Answer

(a) FLOPs =2Md2= 2Md^2; bytes =2(Md+d2+Md)=2d(2M+d)= 2(Md + d^2 + Md) = 2d(2M + d); ratio =Md/(2M+d)= Md/(2M+d). (b) Md/(2M+d)=295⇒M=295d/(d−590)≈Md/(2M+d) = 295 \Rightarrow M = 295d/(d - 590) \approx 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 M≪dM \ll d, I≈MI \approx M: 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

2×80×8×128×22 \times 80 \times 8 \times 128 \times 2 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) 1/(0.1+0.9/10)=1/0.19=1/(0.1 + 0.9/10) = 1/0.19 = 5.26×. (b) 1/0.1=1/0.1 = 10×. (c) Need 0.1/v+0.09=1/9=0.1110.1/v + 0.09 = 1/9 = 0.111 → 0.1/v=0.02110.1/v = 0.0211 → v≈v \approx 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

70/n≤0.03⇒n≥70/n \le 0.03 \Rightarrow n \ge 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 S=1.4S = 1.4 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 ∝CV2f∝(1/S)(1)(S)=1\propto C V^2 f \propto (1/S)(1)(S) = 1; transistors per mm² grow S2≈2S^2 \approx 2 → 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 I≈T/bI \approx T/b and S=3T2bS = 3T^2 b, 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: T=295×2=590T = 295 \times 2 = 590, S=3⋅5902⋅2≈S = 3 \cdot 590^2 \cdot 2 \approx 2.0 MiB. fp8: T=591×1=591T = 591 \times 1 = 591, S=3⋅5912⋅1≈S = 3\cdot 591^2 \cdot 1 \approx 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 eflop=1.0e_{\text{flop}} = 1.0 pJ and ebyte=162.5e_{\text{byte}} = 162.5 pJ, what share of the energy of a kernel with intensity 50 FLOP/B goes to DRAM? At which intensity is it 10%?

Answer

162.5/50=3.25162.5/50 = 3.25 pJ per FLOP of data energy; share 3.25/(3.25+1.0)3.25/(3.25 + 1.0) = 76%. A 10% share means data energy = 1/9 of compute energy: 162.5/I=1.0/9162.5/I = 1.0/9 → I=9×162.5≈I = 9 \times 162.5 \approx 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

6ND=6×70.55×109×15×1012=6.35×10246ND = 6 \times 70.55\times10^9 \times 15\times10^{12} = 6.35\times10^{24} FLOPs. At 40% of 989 TFLOP/s: 6.35×1024/3.96×10146.35\times10^{24} / 3.96\times10^{14} = 1.6e10 GPU-s = 4.5 M GPU-hours. Reported 6.4 M → 6.35×1024/(6.4×106⋅3600⋅989×1012)6.35\times10^{24}/(6.4\times10^6 \cdot 3600 \cdot 989\times10^{12}) ≈ 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 n3/Sn^3/\sqrt{S} lower bound.
  • J. Kaplan et al., “Scaling laws for neural language models”, 2020 — the 6ND6ND 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.

← 返回课程目录