Lecture 5 · Systolic Arrays: Pumping Data Through a Grid of MACs

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

课程源码 ZIP ↓

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

本篇目录

Maps to: Stanford CS 217 Hardware Accelerators for Machine Learning (Winter 2026), Lecture 5 · Tue 01/20/2026 · Systolic Arrays. Lab 1 is due; Lab 2 is out: design of a vector processing unit (Lecture 6). Reading (from the schedule):

  • H. T. Kung, Why systolic architectures?, IEEE Computer 1982;
  • N. Jouppi et al., In-datacenter performance analysis of a tensor processing unit, ISCA 2017;
  • N. Jouppi et al., TPU v4: an optically reconfigurable supercomputer for machine learning with hardware support for embeddings, ISCA 2023;
  • H. Kwon, A. Samajdar, T. Krishna, A communication-centric approach for designing flexible DNN accelerators, IEEE Micro 2018 (MAERI).

Basis: The slides are not public. This lecture follows the session title and the four readings. Architecture facts about TPU v1, TPU v4 and MAERI are taken from those papers and labelled. The experiments use a cycle-accurate systolic-array simulator and a weight-streaming TPU model written for these notes (systolic.py, tpu_model.py). The simulator’s results are checked against numpy, and its closed-form cycle counts against the simulation. The TPU model is not a TPU simulator. The experiments do not reflect what was said in class. Code: code/lecture05/ (4 scripts + 2 modules; each runs in about a second) Reading time: 3–4 hours including running the code


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. State Kung’s principle: pump data rhythmically through a regular array of simple PEs, so that each value fetched from memory is used many times and all communication is between neighbours. Explain why it matches both 1980s VLSI and today’s energy constraints.
  2. Trace a weight-stationary systolic GEMM cycle by cycle: where each input, weight and partial sum is. Explain the skew and the fill/drain time.
  3. Describe weight-, output- and input-stationary systolic dataflows and derive their cycle counts (M+R+C−2M + R + C - 2, K+R+C−2K + R + C - 2) and their SRAM traffic.
  4. Tile a large GEMM onto a fixed array and pipeline the tiles with double-buffered weights. Predict utilization as a function of the batch (or token) dimension.
  5. Explain why a bigger array is not always better — padding, short streams, weight-load time — and compare one 256 × 256 array with four 128 × 128 arrays.
  6. Describe TPU v1 (256 × 256 int8 MXU, weight FIFO, unified buffer) and derive its roofline and ridge (batch ≈ 1,350). Describe the main features of TPU v4.
  7. Explain what flexible fabrics such as MAERI buy over rigid systolic arrays, and what they cost.

0.2 Prerequisites and scope

AssumedIntroduced hereDeveloped later
Lecture 1: roofline, compulsory trafficsystolic arrays, skew, fill/drain, WS/OS/IS systolic dataflowsthe vector unit next to the array (L6)
Lecture 2: pipelining, II, ready/validtiling and tile pipelining, double bufferingbuffers that feed the array (L7)
Lecture 3: dataflows as loop orders, energy accountingarray geometry vs utilization; TPU v1 / v4NoCs for flexible fabrics (L8); mapping search (L9)

0.3 Map

§1  Kung's idea: compute-bound kernels, local communication, rhythm
§2  anatomy of a weight-stationary array; skew; fill and drain             ← code 01 (Parts 1, 3)
§3  three systolic dataflows; correctness; reuse                           ← code 01 (Parts 2, 4)
§4  large GEMMs: tiling, pipelining, double buffering, traffic             ← code 02
§5  array geometry: size, number, shape; flexible fabrics (MAERI)          ← code 03
§6  TPU v1 and TPU v4: weight streaming and the roofline                   ← code 04
§7  summary   §8 pitfalls   §9 exercises   §10 further reading   §11 next lecture

0.4 Notation

SymbolMeaning
R×CR \times Carray rows × columns of PEs (one MAC each)
CM×N=AM×KBK×NC_{M\times N} = A_{M\times K} B_{K\times N}the GEMM; A = activations, B = weights
WS / OS / ISweight- / output- / input-stationary
tilethe part of a GEMM that fits the array at once (R×CR \times C weights in WS)
fill / draincycles before the first PE starts / after the last PE stops working
MXUMatrix Multiply Unit (Google’s name for its systolic array)

1. Kung’s idea

1.1 Intuition: a bucket brigade

Imagine putting out a fire with buckets from one well. If every helper runs to the well and back, the well is the bottleneck and most of the time is spent running. A bucket brigade lines people up and passes each bucket from hand to hand: nobody runs, the well is visited at a steady rhythm, and every bucket travels the line. A systolic array does the same with data. Values leave memory at a steady rate, travel from PE to PE, and are used at every stop. The name comes from the heart: data is “pumped” through the array in rhythm, like blood with each systole.

1.2 Kung’s argument (1982)

Kung’s paper starts from a balance problem. A processor can only compute as fast as memory feeds it. For a compute-bound problem — many operations per data item, like matrix multiplication or convolution — the operations exist, but a conventional design fetches each operand from memory for each use and starves. His prescription, in his own principles:

  • Use each input many times: once a value is fetched, pass it through many PEs, so that the number of operations per memory access grows with the array size without raising the memory bandwidth.
  • Local communication only: each PE talks to its neighbours, so wires are short and their number does not explode as the array grows.
  • Simple, regular cells: one design replicated many times, easy to lay out and verify. For VLSI in 1982, design cost and wiring were the scarce resources.
  • Rhythm: everything moves on a global clock in lockstep, with no control decisions per element.

1.3 Why it came back for deep learning

Four decades later the constraints are different, but they point the same way:

  • Energy is data movement (Lectures 1 and 3). An SRAM access costs 10–100× a MAC; a register-to-register hop costs about as much as the MAC. An array that turns SRAM reads into neighbour hops saves most of the energy.
  • Matrix multiplication dominates ML (Lecture 1), and it is exactly the compute-bound, regular kernel Kung had in mind.
  • Wires are expensive at modern nodes. Local wires scale; global buses do not.
  • Control is overhead (Lecture 1’s 70 pJ instruction): a systolic array has essentially no per-element control.

Google’s TPU v1 (2015) put a 256 × 256 systolic array at the center of a datacenter inference chip. Every TPU since has a systolic matrix unit at its core, as do many other accelerators — AWS’s NeuronCores among them (Lecture 16).


2. Anatomy of a weight-stationary array

2.1 The cells

Each PE contains a multiplier, an adder and a few registers. In the weight-stationary (WS) array that TPUs use:

  • PE (i,j)(i, j) holds one weight, B[k0+i,n0+j]B[k_0 + i, n_0 + j], preloaded before the computation;
  • inputs move right: in each cycle a PE takes the input value from its left neighbour and passes it right in the next cycle;
  • partial sums move down: each PE adds input × weight to the partial sum arriving from above and passes the result down;
  • finished outputs leave the bottom row, one column per output channel.
            col 0        col 1        col 2
          ┌──────┐     ┌──────┐     ┌──────┐
 A[m,0] → │ w00  │  →  │ w01  │  →  │ w02  │ →
          └──┬───┘     └──┬───┘     └──┬───┘
             ↓ psum       ↓            ↓
          ┌──────┐     ┌──────┐     ┌──────┐
 A[m,1] → │ w10  │  →  │ w11  │  →  │ w12  │ →      (row i receives A[m, i], i cycles late)
          └──┬───┘     └──┬───┘     └──┬───┘
             ↓            ↓            ↓
          ┌──────┐     ┌──────┐     ┌──────┐
 A[m,2] → │ w20  │  →  │ w21  │  →  │ w22  │ →
          └──┬───┘     └──┬───┘     └──┬───┘
             ↓            ↓            ↓
          C[m,0]       C[m,1]       C[m,2]   (to the accumulators)

2.2 Watching it compute

Script 01, Part 1 runs C=ABC = AB on a 3 × 3 WS array with A=[[1,2,3],[4,5,6],[7,8,9]]A = [[1,2,3],[4,5,6],[7,8,9]] and B=[[1,0,2],[0,1,1],[1,1,0]]B = [[1,0,2],[0,1,1],[1,1,0]]. Cycles 0–2 load the weights. From cycle 3, the elements of A enter. Here is cycle 5 (left: the input each PE holds; right: the partial sum each PE outputs):

  cycle  5   inputs held (-> right)      partial sums out (v down)
               7    4    1          7    .    2
               5    2    .          4    2    .
               3    .    .          4    .    .

The bottom-left PE outputs 4: C[0,0]=1⋅1+2⋅0+3⋅1C[0,0] = 1\cdot 1 + 2 \cdot 0 + 3 \cdot 1, the first finished output. Row 0 of A (1, 2, 3) entered rows 0, 1, 2 of the array at cycles 3, 4, 5; its partial sum walked down column 0 picking up 1⋅w001 \cdot w_{00}, 2⋅w102 \cdot w_{10} and 3⋅w203 \cdot w_{20}. Meanwhile rows 1 and 2 of A follow one cycle behind each other. In general, output C[m,j]C[m, j] leaves the bottom of column jj at cycle 3+m+j+23 + m + j + 2, so the outputs leave along a diagonal wavefront. The result equals numpy’s ABAB after 10 cycles = 3 (load) + 3 + 3 + 3 − 2.

2.3 The skew

Why must row ii of the array receive its input ii cycles late? The partial sum for (m,j)(m, j) moves down one row per cycle. To meet it in row ii, input A[m,i]A[m, i] must arrive at PE (i,j)(i, j) exactly ii cycles after A[m,0]A[m, 0] arrived at PE (0,j)(0, j). Script 01, Part 3 removes the skew: 24 of 24 outputs are wrong, because each partial sum now adds products from different input rows. The skew is the price of purely local communication. In hardware it is a triangle of delay registers on the input side, 0+1+⋯+(R−1)0 + 1 + \dots + (R-1) of them, and a mirror triangle that re-aligns the outputs.

2.4 Fill and drain

The first input reaches the last row after R−1R - 1 cycles and the last column after C−1C - 1 more. For one tile of MM input rows:

TWS=R⏟load weights+M+R+C−2.T_{WS} = \underbrace{R}_{\text{load weights}} + M + R + C - 2 .

Utilization is therefore MRCT⋅RC≈MM+2R+C\dfrac{M R C}{T \cdot R C} \approx \dfrac{M}{M + 2R + C} for one tile. The array is efficient only when the streamed dimension MM is long compared with the array. That one sentence explains most of this lecture’s results.


3. Three systolic dataflows

3.1 What stays put

As in Lecture 3, a dataflow is chosen by which operand stays inside the PE:

dataflowstationary in PE (i,j)(i, j)moves rightmoves downone tile takes
WSweight B[k,n]B[k, n]inputs Apartial sumsM+R+C−2M + R + C - 2 (+ RR to load)
OSoutput C[m,n]C[m, n] (accumulator)inputs Aweights BK+R+C−2K + R + C - 2 (+ 1 to drain)
ISinput A[m,k]A[m, k]weights Bpartial sumsWS on B⊤A⊤B^\top A^\top

In OS, rows of A enter from the left (skewed by row) and columns of B from the top (skewed by column), so PE (i,j)(i, j) meets A[m0+i,k]A[m_0+i, k] and B[k,n0+j]B[k, n_0+j] in cycle k+i+jk + i + j and accumulates. IS is WS with the roles of A and B exchanged: C⊤=B⊤A⊤C^\top = B^\top A^\top runs on the same array.

Wavefronts

Figure (script 01): the wavefronts of an 8 × 8 array at one cycle. Left, WS: the input row each PE is working on (an anti-diagonal front). Right, OS: the reduction step each PE is performing (increasing toward the top-left).

3.2 Correctness and cycle counts

Script 01, Part 2 runs all three dataflows on five random GEMMs (15 runs). All 15 equal numpy’s ABAB, and the closed-form cycle counts of estimate() equal the simulated ones in all 15. A few rows:

M × K × Narraydataflowtilescyclesutilization
16×8×88×8WS1380.42
64×8×88×8WS1860.74
8×64×88×8OS1790.81
40×24×168×8OS102550.94
3×30×208×8WS121180.24

A long stream (64 rows) amortizes fill and drain; a 3-row stream cannot.

3.3 Reuse: Kung’s principle in numbers

Script 01, Part 4 counts SRAM accesses per MAC for a 64 × 64 × 64 GEMM on an 8 × 8 array, against an array of 64 independent MACs that each fetch their operands:

designA reads / MACB reads / MACpartial-sum r+w / MACSRAM accesses / MACPE-to-PE hops / MAC
WS0.1250.0160.2340.3751.67
OS0.1250.1250.0160.2661.64
IS0.0160.1250.2340.3751.67
independent MACs11240

The systolic array cuts SRAM accesses 11–15× and replaces them with neighbour hops (a register and a short wire). In WS, each input fetched is used by a whole row of 8 PEs (A reads = 1/C) and each weight is fetched once for all 64 rows (1/M). The partial-sum traffic (written once per 8-deep slice of K and read back) is what WS still pays. With Lecture 3’s costs this is the difference between the buffers dominating the energy and the arithmetic mattering (Exercise 10).


4. Large GEMMs: tiling and pipelining

4.1 Tiles back to back

A real GEMM is much larger than the array, so it is cut into tiles. In WS, each R×CR \times C block of weights is one tile, and every tile streams all MM input rows. Partial sums from the ⌈K/R⌉\lceil K/R \rceil tiles of one output column block are added in an accumulator buffer below the array (TPU v1 has 4 MiB of them).

Two tricks keep the array busy between tiles:

  • Pipelining: the next tile’s inputs follow immediately behind the previous tile’s, so fill and drain are paid once per GEMM, not once per tile. Each PE switches to the new tile when the new data reaches it.
  • Double-buffered weights: every PE holds two weight registers. The next tile’s weights shift in (one row per cycle, RR cycles) while the current tile computes. Without double buffering, every tile costs M+RM + R cycles.

The pipelined WS schedule therefore takes

T=R+⌈K/R⌉⌈N/C⌉⋅max⁡(M,R)+R+C−2,T = R + \lceil K/R\rceil \lceil N/C\rceil \cdot \max(M, R) + R + C - 2 ,

and the simulator reproduces it cycle for cycle. The max⁡(M,R)\max(M, R) term is important: a tile can never be shorter than its weight-load time.

4.2 Utilization vs the streamed dimension

Script 02, Part 1 runs M×4096×4096M \times 4096 \times 4096 on a 128 × 128 array:

dataflowM=1M=8M=32M=64M=128M=512M=4096
WS, double-buffered0.0080.0620.250.501.001.001.00
WS, single-buffered0.0080.0590.200.330.500.800.97
OS0.0080.0620.250.501.001.001.00

Below M=RM = R a WS array is limited by weight loading: every 128 × 128 tile costs 128 cycles however few rows use it. LLM decode at batch 1 uses 0.8% of the array. OS streams the reduction instead (K=4096K = 4096), but only MM of its 128 rows hold real outputs: the same 0.8%. Small-batch inference is the systolic array’s worst case. The roofline (Lecture 1) said decode is memory-bound anyway; the array view says that even with infinite bandwidth, a big array would idle.

Utilization vs M

Figure (script 02): utilization of a 128 × 128 array vs M; the knee is at M = R = 128.

4.3 SRAM traffic by dataflow

The traffic formulas follow from which operand is re-read:

  • WS reads every weight once, re-reads A once per output-column tile (⌈N/C⌉\lceil N/C\rceil times), and writes int32 partial sums once per RR-deep slice of the reduction, reading back all but the first.
  • OS writes each output once, re-reads A once per output-column tile and B once per output-row tile (⌈M/R⌉\lceil M/R\rceil times).
  • IS is WS with A and B exchanged.

Script 02, Part 2 counts bytes (int8 A and B, int32 partial sums) for the layer zoo on a 128 × 128 array:

layerWS B/MACOS B/MACIS B/MACleast
ResNet-50 3×30.0780.0310.086OS
Llama q_proj, 512 tokens0.0710.0170.070OS
Llama attention QKᵀ (K = 128)0.0410.0470.041WS
Llama decode GEMV1.071.011.06~all

OS wins on 6 of 8 layers because it never spills int32 partial sums. WS wins when the whole reduction fits one slice of the array (K = 128): then there are no partial sums to spill. On batch-1 layers every dataflow moves ~1 byte per MAC, because each weight is read once and used once. The TPUs use WS anyway, because WS lets weights stream from DRAM straight into the array (§6) and the accumulators sit right below it.

4.4 Utilization on real layers

Script 02, Part 3 (128 × 128, best dataflow per layer):

layerMKNbest utilization
ResNet-50 conv112,544147640.49 (OS)
ResNet-50 3×33,136576640.48 (OS)
MobileNetV2 depthwise3,136910.004
Llama q_proj, 512 tokens5124,0964,0961.00
Llama attention QKᵀ5121285120.89 (OS)
Llama decode14,09614,3360.008

A 128-wide array needs every dimension it spreads over to be a multiple of 128. ResNet’s 64 output channels fill half the columns. The depthwise layer (K = 9, N = 1) fills almost nothing.


5. Array geometry

5.1 Bigger is not better

Script 03, Part 1 measures the best-dataflow utilization of square arrays:

layer32²64²128²256²512²
ResNet-50 3×31.001.000.480.220.09
Llama q_proj, 512 tokens1.001.001.001.000.97
Llama attention QKᵀ1.000.990.890.500.11
decode, batch 160.500.250.130.060.03
decode, batch 1281.001.001.000.500.25

Only the large prefill GEMM fills big arrays. Everything else loses utilization in proportion to how far the array outgrows the layer’s dimensions.

Array size

Figure (script 03): best-dataflow utilization vs square array size.

5.2 One big array or several small ones?

Keep the MACs fixed at 65,536 and split them differently. Script 03, Part 2 deals out the tiles of each GEMM to several arrays (cycles):

workload1 × 256²4 × 128²16 × 64²
transformer layer, 512-token prefill1,936,3461,926,6181,921,754
decode step, batch 16953,338476,666238,330
ResNet-50 stage 2 + MobileNetV2 block106,10954,17127,498

Smaller arrays waste less on edges and on weight loads, so four 128 × 128 arrays are never slower than one 256 × 256 and are 2× faster on the small-batch and CNN workloads. TPU v1 used one 256 × 256 MXU; TPU v2, v3 and v4 use 128 × 128 MXUs (four per TensorCore in v4), and Google’s TPU v2/v3 paper explains the change by utilization. The model’s verdict that 64 × 64 is better still comes with a caveat: it charges nothing for what many small arrays cost — more control logic, wider operand distribution, more accumulators and wiring. At some size these costs win, and that is where real designs stop.

5.3 Rectangles

Script 03, Part 3 shapes 16,384 MACs as rectangles (best dataflow):

layer32×51264×256128×128256×64512×32
ResNet-50 3×30.820.900.480.900.82
Llama attention QKᵀ0.790.870.890.870.79
decode, batch 160.500.250.130.250.50

A rectangle helps when one side matches a layer dimension: 64 output channels fit a 64-wide side. No shape wins everywhere, the same conclusion as Lecture 3’s PE shape.

5.4 Flexible fabrics: MAERI

Rigid arrays pad. MAERI (Kwon, Samajdar, Krishna) replaces the grid’s fixed wiring with two reconfigurable networks around a pool of multipliers:

  • a distribution tree that delivers any operand to any group of multipliers (with multicast);
  • an augmented reduction tree whose adders and extra forwarding links can sum any group of adjacent multipliers, so that dot products of any length — “virtual neurons” — can be formed side by side.

With nn multipliers and dot products of length KK, it runs ⌊n/K⌋\lfloor n/K\rfloor of them at once. Script 03, Part 4, 16,384 multipliers:

layerKrigid 128 × 128flexible
MobileNetV2 depthwise90.0041.000
ResNet-50 3×35760.480.98
Llama attention QKᵀ1280.891.00
decode, batch 14,0960.0081.00

The flexible fabric wins wherever the rigid array pads. Its costs are what the systolic array was designed to avoid: networks that move operands farther than one neighbour, multicast and reduction logic, and enough bandwidth to feed every multiplier independently. (For decode, “1.00” assumes the weights arrive fast enough, which no memory provides at batch 1.) This is the fixed-vs-flexible trade-off of the whole course: TPUs bet on regular, cheap arrays plus software that shapes the work to fit; MAERI, SIGMA (Lecture 8) and reconfigurable dataflow machines (Lecture 12) bet on flexibility.


6. TPU v1 and TPU v4

6.1 TPU v1 in one paragraph

As described by Jouppi et al. (ISCA 2017), TPU v1 is a PCIe coprocessor for datacenter inference, deployed from 2015. It is built in 28 nm and runs at 700 MHz under a 75 W TDP. Its parts:

  • a 256 × 256 MXU of 8-bit MACs (65,536 MACs, 92 TOPS peak), weight-stationary;
  • a 24 MiB Unified Buffer for activations;
  • 4 MiB of accumulators (4,096 × 256 × 32 bit) below the array;
  • a Weight FIFO, four tiles deep, fed from 8 GiB of DDR3 at 34 GB/s;
  • a handful of CISC-style instructions issued by the host (read host memory, read weights, matrix multiply / convolve, activate, write host memory).

The paper analyzes six production applications — two MLPs, two LSTMs, two CNNs, which it reports as representing most of Google’s datacenter inference workload — on a roofline whose ridge sits at about 1,350 MAC operations per weight byte. It reports the TPU 15–30× faster than contemporary CPUs and GPUs on these workloads and 30–80× better in performance per watt. It also reports that four of the six applications were memory-bound.

6.2 Weight streaming, tile by tile

tpu_model.py models the race between the weight FIFO and the MXU. A 64 KiB weight tile takes 1.93 µs = 1,349 cycles to arrive from DDR3. The MXU uses it for max⁡(batch,256)\max(\text{batch}, 256) cycles. Script 04, Part 1 runs a 2048 × 2048 int8 layer:

batchTOPS (model)TOPS (roofline)utilizationbound
10.070.070.001memory
1288.638.700.094memory
51234.434.80.38memory
1,02468.469.60.75memory
1,35089.891.80.98compute
4,09691.191.80.99compute

The tile-by-tile model lands within ~2% of the roofline everywhere. With a deep enough FIFO and double-buffered weights, the roofline is the performance model of a weight-streaming systolic array, and its ridge sits at batch ≈ 92 TOPS / 34 GB/s / 2 = 1,350.

6.3 What bandwidth would have bought

Script 04, Part 2 gives the same chip more bandwidth:

layer (int8)34 GB/s180 GB/s600 GB/s
MLP-like 2048², batch 20013.5 TOPS68.5 (5.1×)69.2 (5.1×)
LSTM-like 4096², batch 644.322.7 (5.2×)22.7 (5.2×)
CNN-like conv, M = 12,54416.416.9 (1.0×)16.9 (1.0×)

Fully connected and recurrent layers at serving batch sizes would speed up almost in proportion to the bandwidth. Convolutions, whose weights are reused thousands of times, would not. This mirrors the paper’s own retrospective: memory bandwidth, not MACs, limited most of the workload. The convolution’s 16 TOPS have a different cause: 64 output channels fill a quarter of the 256 columns (§4.4).

6.4 TPU v4

TPU v4 (Jouppi et al., ISCA 2023) is a training-and-inference chip in 7 nm. As the paper describes it, each chip has:

  • two TensorCores, each with four 128 × 128 bf16 MXUs plus vector and scalar units;
  • 275 TFLOPS bf16 peak per chip;
  • 32 GiB of HBM at ~1.2 TB/s, plus a 128 MiB on-chip common memory;
  • SparseCores for the embedding lookups of recommendation models.

4,096 chips form a pod whose 3D-torus links are wired through optical circuit switches, so the topology can be reconfigured, and failed parts routed around, without recabling. Script 04, Part 3 runs one TensorCore (4 × 128², ~600 GB/s per core) on a 4096 × 4096 bf16 layer:

batchTFLOPS (model)utilizationbound
3219.10.14memory
12876.30.55memory
512137.11.00compute

The ridge sits at batch ≈ 229, six times lower than TPU v1’s, because HBM gives ~18× the weight bandwidth for 1.5× the peak. TPU v4 is a much more balanced machine for the large-batch training it was built for, and still memory-bound for small-batch LLM decoding, like every machine in Lecture 1.

TPU roofline

Figure (script 04): the tile-by-tile model (dots) on the weight-streaming rooflines of TPU v1 and a TPU v4 TensorCore.

6.5 Why four 128 × 128 MXUs: the weight-shift rate

Script 04, Part 4 compares the same 65,536 bf16 MACs as one 256 × 256 MXU or four 128 × 128 in the weight-streaming model. Four small MXUs are 1.12× faster at every batch below 256 and tie above. The arithmetic does not explain this. Weights shift into an array one row per cycle, so a 256 × 256 bf16 MXU can absorb weights at most at 256 × 2 B × 1.05 GHz = 538 GB/s, less than the 600 GB/s the memory delivers. Four 128 × 128 MXUs absorb 1,075 GB/s. At small batch the big array is limited by how fast it can take in its operands — a rate that shrinks relative to memory bandwidth as arrays grow and memories get faster. (Exercise 11 lets the big array shift two rows per cycle, and the gap disappears.)


7. Summary

  1. Kung’s principle: pump data through a regular grid of simple PEs, use every fetched value many times, communicate only with neighbours. It fits compute-bound kernels — matrix multiplication above all — and today’s energy constraints.
  2. A weight-stationary array holds weights, moves inputs right and partial sums down. Inputs are skewed by one cycle per row (without the skew, every output is wrong). One tile takes R+M+R+C−2R + M + R + C - 2 cycles.
  3. WS, OS and IS differ in what stays put. All compute exactly ABAB, and closed-form cycle counts match the simulator. Systolic reuse cuts SRAM accesses per MAC from 4 to 0.27–0.38 (8 × 8 array).
  4. Large GEMMs are tiled and the tiles pipelined with double-buffered weights: T=R+tiles⋅max⁡(M,R)+R+C−2T = R + \text{tiles} \cdot \max(M, R) + R + C - 2. Utilization collapses when the streamed dimension is short: 0.8% for batch-1 decode on 128 × 128.
  5. OS moves the fewest SRAM bytes on most layers (no partial-sum spills); WS wins when the reduction fits the array, and lets weights stream from DRAM directly.
  6. Geometry: bigger arrays lose utilization on everything but large GEMMs. For the same MACs, four 128² arrays beat one 256² (2× on small-batch and CNN work). Rectangles help when a side matches a layer dimension. Flexible fabrics (MAERI) recover the padding losses at the cost of reconfigurable networks.
  7. TPU v1: a 92-TOPS MXU behind 34 GB/s of DDR3 has its ridge at batch ≈ 1,350. The tile-by-tile model lands within 2% of the roofline. MLPs and LSTMs at serving batches are memory-bound and would have gained ~5× from 180 GB/s.
  8. TPU v4: 4 × 128² bf16 MXUs per core, HBM, ridge at batch ≈ 229. The weight-shift rate of a 256-row array (538 GB/s) cannot keep up with HBM — another reason for smaller arrays.

8. Common pitfalls

  • “A systolic array delivers its peak on any matrix multiplication.” Only when every dimension it spreads over fills the array and the streamed dimension is much longer than the array (§4.2, §4.4).
  • “The skew is an implementation detail.” It is what makes local communication correct (§2.3), and it costs a triangle of registers on each side.
  • “Bigger arrays are more efficient.” Per MAC of hardware, they are usually less efficient on real layers (§5.1).
  • “Weight-stationary is always best for energy.” OS often moves fewer SRAM bytes because it never spills partial sums (§4.3).
  • “More bandwidth would have made TPU v1 faster.” Only on the memory-bound layers (MLPs, LSTMs); convolutions gain nothing (§6.3).
  • “Weight loading is free with double buffering.” Only if the tile is used for at least RR cycles, and only if the array can shift weights in as fast as memory delivers them (§6.5).

9. Exercises

Exercise 1 (cycle counting). A 4 × 4 WS array computes a 10 × 4 × 4 GEMM (one tile). How many cycles, including the weight load? What is the utilization?

Answer

T=R+M+R+C−2=4+10+4+4−2=20T = R + M + R + C - 2 = 4 + 10 + 4 + 4 - 2 = 20 cycles. MACs = 10 × 4 × 4 = 160; capacity = 20 × 16 = 320 MAC-slots; utilization 0.50. With M = 100 it would be 1,600 / ((4 + 100 + 6) × 16) = 0.91: fill, drain and the load are amortized.

Exercise 2 (the wavefront). In the 3 × 3 example of §2.2, at which cycle does C[2,1]C[2, 1] leave the array, and which PEs hold row 2 of A at that moment?

Answer

C[m,j]C[m, j] leaves at cycle 3+m+j+2=3+2+1+2=83 + m + j + 2 = 3 + 2 + 1 + 2 = 8. That matches the trace: at cycle 8 the bottom-middle PE outputs 17, and C[2,1]=7⋅0+8⋅1+9⋅1=17C[2,1] = 7 \cdot 0 + 8 \cdot 1 + 9 \cdot 1 = 17. Row 2 of A entered array row ii at cycle 3+2+i3 + 2 + i, so at cycle 8 its element A[2,i]A[2, i] is in PE (i,j)(i, j) with j=8−(5+i)=3−ij = 8 - (5 + i) = 3 - i: A[2,1]=8A[2,1] = 8 in PE (1, 2) and A[2,2]=9A[2,2] = 9 in PE (2, 1). Both are visible in the cycle-8 trace. (A[2,0]A[2,0] has already left the array.)

Exercise 3 (skew registers). How many delay registers does the input skew of a 256 × 256 array need? The output de-skew? Why does an OS array need skew on two sides?

Answer

Input skew: row ii delayed by ii cycles, 0+1+⋯+255=32,6400 + 1 + \dots + 255 = 32{,}640 registers (of the input width). The outputs leave diagonally too, and re-aligning them needs a mirror triangle of another 32,640 registers (of the accumulator width). In OS, both operands enter skewed — A along the rows, B along the columns — so both edges need a triangle, while the outputs leave from the PEs after the computation (a drain path).

Exercise 4 (traffic formulas). Derive WS’s SRAM traffic for M×K×NM \times K \times N on an R×CR \times C array: A reads, B reads, partial-sum writes and reads. Evaluate for the 512-token q_proj (512 × 4096 × 4096) on 128 × 128 and compare with script 02 (0.0713 B/MAC).

Answer

A: every element once per output-column tile, MK⌈N/C⌉M K \lceil N/C\rceil. B: every weight once, KNKN. Partial sums: written once per k-slice, MN⌈K/R⌉MN\lceil K/R\rceil, and read back for all but the first, MN(⌈K/R⌉−1)MN(\lceil K/R\rceil - 1). For q_proj: A = 512 · 4096 · 32 = 67.1 M B; B = 16.8 M B; partial sums 512 · 4096 · (32 + 31) × 4 B = 528 M B. Total 612 M B / 8.59 G MAC = 0.0713 B/MAC. The int32 partial sums are 86% of WS’s traffic — which is why OS (0.0166) wins here.

Exercise 5 (weight-load bound). A 128 × 128 WS array with double-buffered weights runs batch-64 decode on a 4096 × 4096 layer. What is its utilization, and what are three ways to raise it?

Answer

Each tile occupies max(64, 128) = 128 cycles for 64 useful rows, so utilization ≈ 0.50 (script 02: 0.499). Fixes: (1) batch ≥ 128 (more sequences, or speculative decoding producing several tokens per step); (2) a smaller array (64 × 64: max(64, 64) = 64, utilization ≈ 1); (3) shift weights in faster (two rows per cycle halves the load time to 64 cycles). In practice the step is also memory-bound (§6), so (1) is the fix that helps end to end.

Exercise 6 (TPU v1’s ridge). Derive the ridge point of TPU v1 in MAC/weight-byte and in batch size, from 256 × 256 MACs, 700 MHz and 34 GB/s. Why does the batch size equal the intensity here?

Answer

Peak 65,536 × 0.7 GHz = 45.9 T MAC/s; 45.9e12 / 34e9 = 1,350 MAC per weight byte. A weight-streaming layer uses each int8 weight once per row of the batch, so its intensity is batch MACs per weight byte. The ridge batch is therefore 1,350. With bf16 weights (2 B), the batch would have to double for the same intensity.

Exercise 7 (one big vs four small, by formula). Using the OS formulas, compute the cycles of the ResNet-50 3×3 layer (M = 3,136, K = 576, N = 64) on one 256 × 256 array and on four 128 × 128 arrays. Check against script 03.

Answer

One 256²: tiles = ⌈3136/256⌉ × ⌈64/256⌉ = 13 × 1 = 13; cycles = 13 × 576 + 256 + 256 − 1 = 7,999. Four 128²: tiles = 25 × 1 = 25, ⌈25/4⌉ = 7 per array; cycles = 7 × 576 + 128 + 128 − 1 = 4,287. Both match the table. The big array wastes 3/4 of its columns (N = 64), the small ones half of theirs.

Exercise 8 (MAERI packing). How many K = 9 dot products can a 16,384-multiplier flexible fabric run at once, and with what utilization? What does a rigid 128 × 128 array achieve on the same depthwise layer, and why?

Answer

⌊16384 / 9⌋ = 1,820 dot products using 16,380 multipliers: 99.98%. The rigid array has a reduction depth of 128 (rows) and 128 output columns. A depthwise group has K = 9 and N = 1: 9 of 128 rows and 1 of 128 columns are useful, i.e. under 0.1% per group (0.004 with the best dataflow and the 144 groups run in turn).

Exercise 9 (bandwidth what-if). A 2048² int8 MLP layer runs at batch 200 on TPU v1. Estimate its TOPS at 34 GB/s and at 180 GB/s from the roofline, and compare with script 04.

Answer

Intensity = 2 × 200 = 400 ops/byte. At 34 GB/s: 13.6 TOPS (model 13.5). At 180 GB/s: 72 TOPS, but the array has a second limit: each tile occupies max(200, 256) = 256 cycles. So the MXU-limited rate is 92 × 200/256 = 71.7 TOPS (model 68.5, with the fill/drain). From there, more bandwidth (600 GB/s) changes nothing: the batch is shorter than the array.

Exercise 10 (energy of reuse). With Lecture 1’s 45 nm model (an 8 KiB SRAM costs 1.25 pJ per byte; a 64-byte register about 0.11 pJ per byte), estimate the data-movement energy per MAC of the 8 × 8 WS array of §3.3 and of independent MACs. Count every access as one byte, for simplicity.

Answer

Systolic WS: 0.375 SRAM accesses × 1.25 pJ + 1.67 hops × 0.11 pJ ≈ 0.47 + 0.18 = 0.65 pJ/MAC. Independent MACs: 4 × 1.25 = 5 pJ/MAC, about 8× more, against an int8 MAC of 0.3 pJ. The systolic array brings data movement down to the scale of the arithmetic.

Exercise 11 (programming: faster weight shifting). Add a rows_per_cycle option to tpu_model.run_matmul so that a tile occupies max⁡(batch,rows/rows_per_cycle)\max(\text{batch}, \text{rows}/\text{rows\_per\_cycle}) cycles. Re-run script 04, Part 4 with a 256 × 256 MXU that shifts two rows per cycle. What happens to the 1.12× advantage of four 128 × 128 MXUs?

Answer

It disappears. In the author’s check the ratio drops from 1.12× to 1.004× at batch 16, 128 and 200. At two rows per cycle the big array absorbs 1,075 GB/s of bf16 weights, more than HBM’s 600 GB/s, so both configurations are purely memory-bound at small batch. The hardware price is a weight-loading path twice as wide into every column.

Exercise 12 (programming: a busy map). Modify systolic._simulate_ws to record, every cycle, how many PEs perform a MAC with a non-padded input. Plot it over time for an 8 × 8 array with M = 4 and M = 64 (one tile, K = N = 8). What do the two curves look like?

Answer

The curve is a trapezoid: it rises as the wavefront fills the array (fill), stays flat while it is full (steady state: all 64 PEs busy), and falls during the drain. With M = 4 the wavefront is only 4 rows long, so the array is never full: the curve is a low triangle peaking around 4 × 8 = 32 busy PEs. With M = 64 there is a long flat top at 64. The area under each curve is exactly M × 64 MACs, and the width of the trapezoid is the M+R+C−2M + R + C - 2 of the formula.

10. Further reading

  • H. T. Kung, “Why systolic architectures?”, IEEE Computer 15(1), 1982; H. T. Kung, C. Leiserson, “Systolic arrays (for VLSI)”, 1978.
  • N. Jouppi et al., “In-datacenter performance analysis of a tensor processing unit”, ISCA 2017.
  • N. Jouppi et al., “A domain-specific supercomputer for training deep neural networks”, CACM 2020 — TPU v2/v3 and the move to 128 × 128 MXUs.
  • N. Jouppi et al., “TPU v4: an optically reconfigurable supercomputer for machine learning with hardware support for embeddings”, ISCA 2023.
  • H. Kwon, A. Samajdar, T. Krishna, “MAERI: enabling flexible dataflow mapping over DNN accelerators via reconfigurable interconnects”, ASPLOS 2018; and the IEEE Micro 2018 article of this lecture’s reading list.
  • A. Samajdar et al., “SCALE-Sim: systolic CNN accelerator simulator”, 2018 — a widely used analytical/cycle model of systolic arrays.
  • V. Sze et al., Efficient Processing of Deep Neural Networks, chapter 5 — dataflows, including the systolic cases.

11. Next lecture

Lecture 6, Vector and scalar units, looks at everything the systolic array cannot do: softmax, normalization, activations, residual adds, quantize and dequantize, reductions and data-layout changes. Once the matrix unit is fast, Amdahl’s law hands the critical path to these operations. We will build a cycle-level multi-lane vector unit (the block of Lab 2), approximate exp, reciprocal and GELU in hardware, and return to HW2’s question of where MX block scales are applied, now on the vector unit.

← 返回课程目录