Act XI · The Research Frontier
Part 60 of 61Domain-Specific Hardware
When a general-purpose processor stops getting faster, what does hardware built for one kind of work buy, and what does it cost?
The part opens on a table of energies at 45 nm: an 8-bit add costs 0.03 pJ and a 64-bit read from DRAM as much as 90,000 of them, so a processor that spends 10 pJ fetching an instruction to do a 0.1 pJ add is at most 1% useful. The roofline model is derived from two inequalities and this machine's two roofs are measured, with each kernel placed under them. Then H. T. Kung's systolic array is built from Part 4's multipliers and simulated gate by gate: the operands of a matrix product meet in cell (i, j) at cycle i + j + k, so the product crosses an N by N grid as a diagonal wave in 3N - 2 cycles, exact against NumPy. Which number stays put decides utilization: a third for one output-stationary product, above 80% for a long weight-stationary stream. The same grid at 256 by 256 with 8-bit numbers is Google's first TPU, and its paper's 92 TOPS is recomputed. The part goes on through GPUs and tensor cores, spatial machines, computing near memory, sparsity and approximation, and how hardware is designed, and then turns the Job itself into a four-stage circuit that counts one byte every cycle: ledger row 21, the thirty novels in about 31 ms. It ends on accelerators for language models, where decoding one token at batch 1 uses 0.3% of the peak.
What you need. Matrix multiplication, binary arithmetic and logarithmic axes; the gates, adders and registers come from Parts 3 to 5.
- Mathematics, ideas and history
- the roofline, systolic arrays, the TPU, GPUs and tensor cores, dataflow, near-memory computing, sparsity, high-level synthesis
- What we build or compute
- a gate-level systolic array; the Job in hardware (ledger row 21)
What you will be able to do
Degree
- Compute a kernel's arithmetic intensity from its flops and its compulsory bytes, and place it under a roofline.
- Trace a 2 by 2 systolic product cycle by cycle and say when each cell is busy.
Graduate
- Derive the roofline bound from T >= F/P and T >= Q/beta, and find the ridge point.
- Derive the 3N - 2 cycles of an output-stationary grid and the utilizations N/(3N - 2) and M/(M + 3N - 2).
- Derive that stochastic rounding is unbiased with variance at most a quarter of the step squared, and bound the accumulator width an int8 product needs.
Research
- State Hong and Kung's red-blue pebble game and what an I/O lower bound for a grid of cells with local memories would have to show.
- Explain why decoding a language model at batch 1 sits far below the ridge, and compare the remedies by what they change in the roofline.
Industry
- Read an accelerator paper's headline number (cells times operations times clock) and say whether its workloads are compute-bound or memory-bound.
- Quantize a matrix product or a linear classifier to int8 and report the error and the change in answers.
- Size a direct-mapped counting table from the expected number of words that find their slot taken, m(1 - exp(-n/m)).
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 18 min · Graduate 39 min · Research 53 min · Industry 39 min.
- 0Hardware that does one thingDegree2 min
- 1The end of general-purpose scalingDegree4 min
- 2The roofline modelDegree5 min
- 3A systolic arrayDegree5 min
- 4Which number stays putResearch4 min
- 5The TPU, and fewer bitsIndustry5 min
- 6GPUs revisitedIndustry4 min
- 7Spatial machines: dataflow, CGRAs and FPGAsIndustry4 min
- 8Computing near memoryResearch4 min
- 9Sparsity and approximationResearch4 min
- 10How hardware is designedIndustry4 min
- 11The Job in hardwareIndustry5 min
- 12Frontier: accelerators for language modelsResearch2 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
Hardware that does one thingDegree2 min
Here is what things cost on a chip, in energy. Adding two eight-bit integers costs about three hundredths of a picojoule. A thirty-two-bit add, a tenth. An eight-bit multiply, a fifth. A thirty-two-bit floating-point multiply, nearly four. Now fetch the numbers. Reading sixty-four bits from a small memory on the chip costs ten picojoules, more than any of those operations. From a megabyte of on-chip memory, a hundred. And from DRAM, off the chip, thirteen hundred to twenty-six hundred: as much as 90,000 eight-bit additions, for one read. A general-purpose processor spends most of its energy on neither: it goes on fetching, decoding and scheduling instructions, and on moving data between them. When Rehan Hameed and colleagues measured a video encoder in 2010, a chip built for that one job used about five hundred times less energy than general-purpose cores running it.
This part's machine is very different from Pebble. It is a grid of sixteen cells, and each cell holds only a multiplier and an adder from Part 4, and a running sum. On every clock tick, each cell multiplies the two numbers it has just received, adds the product to its sum, and passes the numbers on: the blue ones from the left to the right, the purple ones from the top downwards. The rows of one matrix enter from the left, the columns of another from the top, each a step later than the one before, so the work sweeps across the grid as a diagonal wave. There is no program, no instruction fetched, no register file. After ten cycles the grid holds the product of two matrices, simulated gate by gate and checked.
1The end of general-purpose scalingDegree4 min
Part 10 opened with this picture: fifty years of microprocessors, on a logarithmic scale. The transistors kept coming, doubling about every two years. For three decades a single thread got faster with them, and so did the clock, by about a third every year. Then, around 2005, the voltage stopped falling, Dennard scaling ended, and the clock stopped: since then it has not grown at all. But there is a second way to spend transistors. Instead of more copies of a general machine, build a machine that does one kind of work, and does it with far less waste. To see where the waste is, we count energy.
Every instruction a general-purpose processor runs goes through the stages of Part 7's pipeline. It is fetched from the instruction cache, decoded, its registers are read, it is executed, and its result is written back. Only one of those stages is the work we asked for. By Mark Horowitz's figures for a forty-five nanometre chip, a thirty-two-bit add costs a tenth of a picojoule, and just reading sixty-four bits from a small eight-kilobyte memory, the size of an instruction cache, costs ten. So write the useful share of the energy as the operation over the whole. Throw away every overhead except the fetch: the share can only grow. Put in the numbers: at most about one percent. Ninety-nine parts in a hundred go on organizing the work, not doing it.
The way out is not to make the fetch cheaper. It is to make one instruction do more. If one fetch drives k operations, the overhead is shared k ways, and the useful share climbs towards one. With one add per instruction it is one percent. A vector instruction, Part 10's SIMD, does sixteen adds at once: about fourteen percent. Now imagine an instruction that starts sixty-five thousand five hundred and thirty-six eight-bit multiply-adds, on a grid of two hundred and fifty-six by two hundred and fifty-six cells. The overhead all but disappears. That grid is not imaginary: it is Google's TPU, and this part builds a small one. Moving the data costs energy too: that is the next chapter.
In June 2018 John Hennessy and David Patterson gave their Turing Award lecture, later published as A New Golden Age for Computer Architecture. Their argument was that with Dennard scaling gone and Moore's law slowing, the remaining road to large gains is domain-specific architecture, for four reasons. First, it can use the kind of parallelism the domain really has: a grid of cells in lockstep, with nothing to coordinate. Second, it can manage its own memories, filling buffers on purpose instead of hoping a cache guesses right. Third, it can use no more precision than the work needs. And fourth, its programs come from domain-specific languages that make the parallelism plain. Each of these is a chapter of this part.
Specialization has a price, and Part 10 already named it. An accelerator speeds up only the fraction of the work it was built for, say f, by some factor s; the rest runs as before. So the speedup is one over one minus f, plus f over s. If nine tenths of a program suits the accelerator and it is fifty times faster there, the whole runs about eight times faster. And no accelerator, however fast, gets past ten. A chip that does one thing pays only if that thing is most of the work. In 2013 Google projected that speech recognition by neural network alone could double the computing its data centres needed, and what a neural network does most is multiply matrices.
2The roofline modelDegree5 min
Part 9 ended by naming the roofline model; now we derive it, as Samuel Williams, Andrew Waterman and David Patterson did in 2009. A kernel does F floating-point operations and moves Q bytes between memory and the processor. The processor can do at most P operations a second; memory can deliver at most beta bytes a second. So the time is at least F over P, and at least Q over beta. Divide the work by the time: the speed is at most the smaller of P, and F over Q times beta. F over Q is called the arithmetic intensity, I, the operations done for each byte moved. The bound is the minimum of P and I times beta: a sloped roof for low intensity, a flat one for high.
Intensity is a matter of counting. Axpy, Part 52's simplest kernel, sets y to a x plus y. Each element costs two operations, a multiply and an add, and twenty-four bytes: x and y read, y written, eight bytes each. The intensity is one twelfth. A matrix product of size n does two n cubed operations, but needs to read only two matrices and write one: twenty-four n squared bytes. The intensity is n over twelve, and it grows with n. Here are the kernels we will measure. The vector kernels sit below one, and the largest matrix product at about one hundred and seventy-one. Getting close to that ideal is exactly what the blocking of Part 9 is for.
Now the two roofs of the computer making this video. For the flat roof, time matrix products of four sizes through NumPy's BLAS, on one core, and keep the best: about seventy-eight billion operations a second. For the sloped roof, stream arrays of five hundred and twelve megabytes, as John McCalpin's STREAM benchmark does, too large for the caches. The four kernels disagree, by a factor of about one point seven; the roof is the best of them, about twenty-eight gigabytes a second, and the others remind us it is an optimistic one. Divide one by the other: the ridge sits at about two point eight operations per byte. A kernel needs at least that intensity before the processor, rather than memory, is what limits it.
Here is the result, on logarithmic axes. The orange line is the roof: rising with intensity, at the bandwidth we measured, until it meets the flat peak at the ridge. The vector kernels, axpy, the dot product, matrix times vector and the stencil, sit far to the left, on or under the sloped roof: memory decides their speed. The matrix products sit to the right of the ridge, close under the flat roof: the processor decides theirs. The open circles are Part 52's timings of the same three levels of linear algebra, and the red dot is the Job itself, counting words in Python, with its operations estimated at four per byte.
What does the picture tell us? Axpy runs at ninety-three percent of its sloped roof: nothing will make it much faster on this machine. The stencil manages only ten percent, because NumPy builds a temporary array for every addition and so moves far more bytes than the count we made. The matrix products run within sight of the peak, as a kernel with high intensity should. And the Job sits about six hundred times below its roof. Neither memory nor arithmetic holds it back; the interpreter's own instructions do, the overhead of chapter one. An accelerator raises the flat roof, and pushes the ridge far to the right. Google's first TPU, with ninety-two trillion operations a second and thirty-four gigabytes a second of memory, has its ridge near two thousand seven hundred operations per byte. Only work like the matrix product can feed it.
3A systolic arrayDegree5 min
Start with what we want to compute. Two four by four matrices, A and B, and their product C. Each entry of C is a row of A times a column of B: multiply the pairs, and add them up. : . That is four multiply-adds for each entry, and sixteen entries: N cubed, sixty-four in all. In 1978 H. T. Kung and Charles Leiserson proposed giving every entry its own cell, and having the numbers flow past it rhythmically, like blood pumped by a heart. They called it a systolic array, after the heartbeat.
Here is one cell. A multiplier from Part 4 takes an eight-bit number a arriving from the left and an eight-bit number b arriving from above. An adder adds the product to the cell's running sum, a twenty-four-bit register from Part 5. Two more registers hold a and b for one clock tick and pass them on, a to the right and b downwards. With Dadda's tree multiplier and the Kogge-Stone adder, the cell has seven hundred and twenty-three gates and a depth of twenty-nine. With the plain array multiplier and a ripple-carry adder it is smaller, four hundred and sixty-one gates, but its depth is sixty-one. Depth sets the clock, as Part 7 showed, so we use the tree. Both were checked gate by gate on four thousand and ninety-six random inputs.
The trick is in the timing. Row i of A enters the grid's left edge i cycles late, so the number A i k enters at cycle i plus k, and after j more cycles it reaches column j. Column j of B enters the top j cycles late, so B k j enters at j plus k, and reaches row i at i plus j plus k. The same cycle: the two numbers that must be multiplied always meet, in the right cell, at the right moment. The last product has all three indices at N minus one, at cycle three N minus three, so a product takes three N minus two cycles: ten for our four by four grid. And since a cell starts work at cycle i plus j, the busy cells form diagonals that sweep from the top left corner to the bottom right.
Now watch it run, one clock tick at a time. Each cell shows its running sum, with the blue number from A and the purple number from B that it is multiplying. In the first cycle only the corner cell has a pair: times . In the second, its two neighbours start, and the corner adds times . Watch the corner: , and it is finished, while the far corner has not yet begun. The wave of work crosses the grid diagonally, the lit cells always on one anti-diagonal band. Each number is fetched from outside the grid once, and then used four times, by four cells in turn. That reuse is the arithmetic intensity of chapter two, built into wires.
Now the evidence. We built grids of two, four and eight cells a side out of Part 4's gates and Part 5's registers, fed each sixteen random pairs of eight-bit matrices, and clocked the simulator cycle by cycle. Each finished in exactly three N minus two cycles, and every one of the products matched NumPy's exact integer answer. The eight by eight grid has gates, and that is exactly sixty-four cells' worth: there is nothing else, no control, no program counter. The TPU's grid has two hundred and fifty-six cells a side, sixty-five thousand five hundred and thirty-six of them. But first, a choice this design made without telling us: it keeps the outputs still and moves both inputs. That is not the only way.
4Which number stays putResearch4 min
Every multiply-add in a neural network touches three numbers: a weight, an input, and the partial sum they add to. The grid of chapter three kept each partial sum in its cell and moved both inputs past it. That is output-stationary. But the weights could stay instead, loaded once, while the inputs flow across and the partial sums flow down. That is weight-stationary, and it is what Google's TPU does. Or the inputs could stay. Whatever stays is fetched from memory once and reused from a register beside the multiplier, and a read from DRAM costs thousands of times the energy of an eight-bit multiply. Yu-Hsin Chen, Joel Emer and Vivienne Sze's Eyeriss chip of 2016 mixed the choices to minimize that movement. Let us watch the TPU's choice.
Here is a weight-stationary grid, at gate level. First, for four cycles, the weights are shifted down the columns, the last row first, until each cell holds its own weight, shown in purple. They will not move again. Then the inputs stream in from the left, six rows of them, each row a step behind the one before. Each cell multiplies the input passing through by its weight, adds the partial sum arriving from above, and passes the result down. What comes out of the bottom edge is one entry of the product, and the next row of inputs is already following behind. The weights were fetched once, and used six times each; with a longer stream of inputs, they would be used more.
How much of the time is the grid doing useful work? Call it the utilization: the multiply-adds done, over the cells times the cycles. The output-stationary grid does N cubed multiply-adds, on N squared cells, in three N minus two cycles. Cancel N squared: N over three N minus two, which falls towards one third. For one product, two thirds of the time a cell is waiting for the wave. The weight-stationary grid does M N squared multiply-adds for M rows of input, in N cycles to load and M plus two N minus two to compute. Cancel again: M over M plus three N minus two. This one tends to one, as the stream of inputs grows longer. And both formulas agree exactly with the gate-level simulations we just watched.
Here are the formulas as curves, with the simulations as points. Output-stationary, for one product, starts at one half for a two by two grid and settles towards a third. Weight-stationary with as many input rows as the grid has columns does worse, towards a quarter, because loading the weights costs N cycles of its own. But give it a long stream, sixteen times as many rows, and it climbs above eighty percent at every size. Open circles are gate-level grids, filled points the integer model for larger ones, and all lie on the curves. So the weights should stay only when many inputs will pass the same weights: in a neural network, a batch.
5The TPU, and fewer bitsIndustry5 min
Google put its Tensor Processing Unit into its data centres in 2015, and Norman Jouppi and colleagues described it in 2017. It is a coprocessor on the PCI Express bus: the host sends it instructions. At its centre is the matrix unit, a grid of two hundred and fifty-six by two hundred and fifty-six cells, each an eight-bit multiplier and an adder. Weights come from eight gibibytes of off-chip DRAM, through a queue, and are loaded into the grid from the top, where they stay. Activations stream in from the left, out of a twenty-four mebibyte buffer. Thirty-two-bit sums leave from the bottom, pass through the nonlinearity, and return to the buffer as the next layer's input.
Where does the paper's famous figure come from? Sixty-five thousand five hundred and thirty-six cells. Each does a multiply and an add on every tick, counted as two operations, at seven hundred million ticks a second. Multiply: ninety-one point eight trillion operations a second: the paper's ninety-two tera-operations. Divide by the thirty-four gigabytes a second of weight memory: the ridge of chapter two, about two thousand seven hundred operations for every byte fetched.
Put the TPU's roof beside this machine's. Ours, measured, in blue. The TPU's, in orange: a flat roof more than a thousand times higher, but a sloped roof that hardly moves, because its weights came from ordinary DRAM. The ridge slides far to the right. The paper drew this picture for Google's own networks, and most of them sat under the slope, limited by memory, not by the grid. Its headline, fifteen to thirty times the speed of a contemporary CPU and GPU, is real, but it is a claim about inference, in eight bits, on those networks.
The grid multiplies eight-bit integers, but weights are real numbers, so they are quantized. Write each number as a scale, s, times a small integer, q. Choose the scale so that the largest magnitude in the tensor becomes one hundred and twenty-seven. Then divide by the scale and round to the nearest integer: one of two hundred and fifty-five levels. For this vector, one point nine five sets the scale; divided by it, the numbers land between levels, and rounding moves each a little. Never more than half a step: Part 4's rounding argument, with one exponent shared by the whole tensor.
Now a dot product, the work of one column. Replace each input and weight by its scale times its integer. The scales come out of the sum: the grid adds products of small integers, and one multiplication per output restores the units. How wide must the sum be? Each product is at most sixteen thousand one hundred and twenty-nine, sixteen bits; two hundred and fifty-six of them fit in twenty-three. Thirty-two-bit accumulators cannot overflow. We checked: through int8, the largest sum in a two hundred and fifty-six by two hundred and fifty-six product was , and a slice run through chapter four's model of the grid gave exactly the integer answer.
Is eight bits enough? We multiplied two random matrices three ways against sixty-four-bit floating point. Float32 is off by parts in ten million; sixteen-bit inputs, parts in ten thousand; eight bits, about one and a half percent. That sounds bad, until you ask what a network needs. A small classifier in float32 and in int8 gives the same answer on ninety-nine point six percent of five thousand test points, and its accuracy changes in the fourth digit. And the saving: by Horowitz's figures an eight-bit multiply takes about an eighteenth of the energy of a float32 one, and in our own circuits from Part 4 it is about a ninth of the gates.
6GPUs revisitedIndustry4 min
Part 10 met the graphics processor's bargain: thousands of simple lanes instead of a few clever cores. Threads run in warps of thirty-two that share one instruction stream. One instruction is fetched and decoded, and thirty-two lanes each do a multiply-add: chapter one's overhead, shared thirty-two ways. The price is divergence. When the lanes disagree at a branch, the warp runs both paths, with some lanes switched off. A matrix product never diverges: every lane does the same multiply-add on different numbers. So in 2017 NVIDIA added hardware that does nothing else.
NVIDIA's Volta GPU of 2017 added tensor cores. Each computes D equals A times B plus C, on four by four matrices, every clock: four times four times four, sixty-four multiply-adds at once. Every output adds four products to its starting value, exactly what a cell of chapter three's grid did over four ticks. The products are taken in sixteen-bit floating point and the sums kept in thirty-two bits: multiply small, add wide, as in the TPU. NVIDIA has not published how a tensor core is wired, so this drawing is a sketch, but the idea is plain: a small matrix-multiply block, placed in every multiprocessor.
Count the multiply-adds that one instruction buys. A scalar core: one. A vector instruction of Part 10, sixteen floats wide: sixteen. A warp's multiply-add: thirty-two. And one warp-wide matrix step, on sixteen by sixteen tiles: sixteen cubed, four thousand and ninety-six. So write the energy of one multiply-add as the operation itself, plus the instruction's overhead shared among n. At four thousand operations per instruction, the overhead that dominated chapter one all but disappears, and a GPU running matrix work begins to look like an accelerator.
Now the memory wall of Part 9, once more. Here is this machine's measured roof, and the roof of Volta's V100 from NVIDIA's datasheet: fifteen point seven trillion thirty-two-bit operations a second on its ordinary lanes, and nine hundred gigabytes a second from stacked memory. The tensor cores lift the flat roof eightfold, to a hundred and twenty-five trillion. But the memory is the same, so the ridge moves from about seventeen to about one hundred and thirty-nine operations per byte. Chapter two's vector kernels sit far to the left, on the slope, whichever chip runs them. Faster arithmetic only makes more of the work wait for memory. That is why accelerators since have paired their arithmetic with stacked memory beside the chip, chapter eight's subject, and why the other remedy, reuse, matters more each generation.
How does any kernel climb that slope? By reuse, the blocking of Part 9. To compute one tile of the output, b by b, a multiprocessor reads a strip of A and a strip of B through its fast memory, a chunk at a time. The tile needs two b squared K operations, and the strips hold two b K numbers, two bytes each. Divide: the intensity is b over two. Bigger tiles, more reuse. To reach the tensor-core ridge, b must be about two hundred and seventy-eight. No single level of fast memory does that alone, so real kernels tile at every level at once, registers, shared memory and the cache: Part 9's lesson, stacked three deep.
7Spatial machines: dataflow, CGRAs and FPGAsIndustry4 min
Every machine so far, the TPU's grid apart, does its work in time. Here is a small filter: each output is three times this input plus two times the previous one. A processor runs it as eight instructions, one after another, through the same arithmetic unit, for every result. A spatial machine lays the same computation out in space instead. Each operation gets its own unit, the values flow between them on wires, and no instruction is fetched at all: the program has become a circuit.
The oldest spatial idea is dataflow. Draw the computation as a graph, and let each node fire as soon as all of its inputs have arrived. Here a and b arrive, so the addition fires at once; the subtraction must wait for d, which comes late. Only then can the multiplication fire. There is no program counter: the order of events comes from the data itself. Jack Dennis and David Misunas proposed such a processor in 1975, and Arvind's group at MIT built tagged-token machines in the 1980s. They never displaced the ordinary processor, but Part 8's out-of-order core is a dataflow engine inside one.
Between the processor and fixed hardware sits the coarse-grained reconfigurable array, or CGRA. It is a grid of small processing elements, each a word-wide arithmetic unit, a register and a switch, wired to its neighbours. A configuration tells each one what to do, once, before the data starts. To run the loop, a compiler places each node of the graph on an element. Then it routes each edge along the wires between neighbours. There is a catch: the two paths into the adder must take the same number of cycles, so one element does nothing but pass a value on. Placement and routing are hard search problems.
Now let it run. On every tick a new x enters, and every element passes its result on. The multiplier by three works on this x while the multiplier by two works on an older one, held back a cycle by the delay. On the fifth tick the first output reaches the store, and from then on one result leaves every cycle, where the processor needed eight instructions for each. This is a pipeline, Part 7's idea, but made out of the program itself.
The most flexible spatial machine is the FPGA. Its building block is Part 3's lookup table: sixteen bits of memory and a selector. Four input bits choose one of the sixteen entries, so the table computes any function of four inputs. Here, parity. Load different bits, and the same table computes something else, say, whether at least two inputs are set. An FPGA is a sea of these tables, each beside a flip-flop of Part 5, with programmable wires between them, and columns of hard multipliers and memories. The flexibility has a price. Ian Kuon and Jonathan Rose measured it in 2007: the same logic took around thirty-five times the area of a custom chip, and ran several times slower.
8Computing near memoryResearch4 min
Chapter one began with Mark Horowitz's table. Put it in terms of a single byte. Adding two bytes costs three hundredths of a picojoule. Fetching one byte from a small memory beside the arithmetic costs about forty times that; from a megabyte of on-chip memory, four hundred times. And from DRAM, off the chip: a sixty-four-bit read costs thirteen hundred to twenty-six hundred picojoules, so one byte costs between about a hundred and sixty and three hundred and twenty-five. That is the energy of five thousand to eleven thousand eight-bit additions, spent to bring in one byte. For most programs, the arithmetic is a rounding error; the bill is for transport.
Why should distance cost energy? Sending a bit along a wire means charging the wire, and Part 10 gave the energy: about a half of C V squared for each change. A wire's capacitance grows with its length. So the energy of a bit grows with the distance it travels. A register is micrometres from the arithmetic, an on-chip memory millimetres, and DRAM centimetres away, through the pins, the package and the board, wires with far more capacitance. And a DRAM chip must open a whole row of its cells, thousands of them, to deliver the few that were asked for.
The first answer is to bring memory closer. A conventional DRAM module sits centimetres from the processor, across the board, on a channel sixty-four data wires wide. High Bandwidth Memory, standardized in 2013, stacks several DRAM dies on top of one another, joins them with vertical wires through the silicon, and sets the stack beside the processor on a slab of silicon, with one thousand and twenty-four data wires per stack, millimetres long. Shorter wires cost less energy per bit, and many more of them run at once. Chapter six's GPU gets its nine hundred gigabytes a second this way, and so do later TPUs. But the data still has to make the trip.
The second answer is bolder: do the arithmetic where the data already is. Take a simple job, summing a quarter of a billion numbers, a gigabyte, spread over sixteen banks of DRAM. A processor must pull every byte across the channel, more than a billion of them. Put a small adder beside each bank instead. Each sums its own share, and only sixteen partial sums of eight bytes cross the channel, a hundred and twenty-eight bytes in all, about eight million times less. The banks are still read, so the saving is the trip, not the whole bill. This suits work with little reuse: scans, filters, sums, the left of the roofline. UPMEM sells such memory, and Samsung announced stacked memory with arithmetic inside in 2021.
The boldest answer stops moving the weights at all. Store each weight as the conductance of a cell where a row wire crosses a column wire. Put the inputs on the rows as voltages. By Ohm's law, each cell passes a current equal to its conductance times its voltage. And by Kirchhoff's law, the currents meeting on a column wire add up. So the column currents are a matrix-vector product, computed in one step, by physics, where the weights are stored. The catch is that this is analog. Values drift and are noisy, worth only a few bits, and the converters at the edges cost energy of their own. Research chips built from phase-change or resistive memory are still working on that.
9Sparsity and approximationResearch4 min
A trained network is full of zeros. Here is one row of weights after pruning, and the inputs it meets. A dense engine multiplies every pair: sixteen multiplies, eleven of them by zero. The cheap fix is to notice a zero and hold the multiplier still, which saves energy but not time. The better fix is to skip: feed only the five pairs that matter, and get the same sum in five steps. The zeros are real. In 2015 Song Han and colleagues pruned nine in ten of AlexNet's weights without losing accuracy, and then built an engine, EIE, to run such networks.
To skip zeros, the hardware must not store them. The commonest format is compressed sparse rows: the nonzero values, row by row; beside each, its column; and where each row starts. But indices cost bytes too. Here the dense matrix takes twenty-four bytes, the compressed one twenty-eight. With z nonzeros, compression wins only if z times b plus c is less than m n b: the density must be below b over b plus c. For eight-bit values and sixteen-bit indices, below a third. And every lookup by column is a read from a scattered address.
Arbitrary zeros make the work unpredictable, so in 2020 NVIDIA's A100 asked for a pattern. Cut the weights into groups of four, and in each group keep the two largest and zero the rest. Store the eight survivors, each with a two-bit position in its group. In hardware, each position drives a selector that picks the matching input, so two multipliers do the work of four. Exactly half the multiplies, every time, and thirty-two bits a group become twenty. The network is retrained after pruning to recover its accuracy.
Part 4 rounded to the nearest number. That is the best single answer, but it is biased. Put x a fraction p of the way from one level, L, to the next, L plus delta. Round to nearest always gives L, off by p delta. Stochastic rounding flips a biased coin: up with probability p, down with probability one minus p. The expected result is one minus p times L, plus p times L plus delta. Expand it: L plus p delta. That is x: the rounding is exact on average. The price is noise, a variance of p times one minus p times delta squared, at most a quarter of delta squared.
Approximate computing gives up accuracy on purpose. An eight-bit multiplier forms sixty-four partial products, one AND gate each, and adds them up by column. Drop the ten in the four lowest columns, and their adders with them. The answer is off by at most forty-nine, under a tenth of a percent of the largest product. Is that acceptable? It depends on who reads the answer. Chapter five's eight-bit classifier had its scores off by about one percent, yet changed its answer on only zero point four percent of the points. Images, sound and learning tolerate error; addresses, branches and the Job's word counts do not.
10How hardware is designedIndustry4 min
Chips are not drawn gate by gate. A designer writes a register-transfer description, in Verilog or VHDL, languages of the 1980s, which says what each register holds on the next tick. Synthesis turns it into gates, and place and route lays them out on silicon. In 2012 Jonathan Bachrach and colleagues at Berkeley released Chisel, hardware embedded in Scala: a class that, run with a width, produces a multiply-accumulate cell of that width. This series has worked that way since Part 3. Our hardware description is Python, and chapter eleven's hash stage is a function that returns a circuit.
High-level synthesis starts from ordinary C. Here is a dot product, with one extra line asking for a pipelined loop. The tool splits each iteration into a load, a multiply and an add, and overlaps them like Part 7's pipeline, starting a new iteration every cycle. Two hundred and fifty-six iterations take two hundred and fifty-eight cycles. One thing cannot overlap: each add needs the previous sum, so the adder must finish within a cycle. This is how many software people program chapter seven's FPGAs, though the result depends heavily on how the C is written.
Choosing among designs is design-space exploration. Chapter three built two multiply-accumulate cells. Plot each by its gates, a proxy for area, and its depth. The tree has seven hundred and twenty-three gates and a depth of twenty-nine; the array, four hundred and sixty-one gates and a depth of sixty-one. Neither wins on both. Turn depth into a clock: ten picoseconds a gate, plus seventy for the register. The tree's period is three hundred and sixty picoseconds, the array's six hundred and eighty. Multiply area by time per result, and the tree wins, by about a fifth. Real tools sweep thousands of such points.
One knob moves a design further than any other: the number of bits. We built the same tree multiplier at eight bits, for int8; at eleven, the significand of a sixteen-bit float; and at twenty-four, that of a thirty-two-bit float. An n by n multiplier forms n squared partial products, so it should grow as n squared. Divide each count by n squared: about six and a half, every time. Three times the width costs nine times the gates, while the depth grows only slowly. That is chapter five's case for eight bits, as a point in the design space.
Co-design chooses the algorithm and the hardware together, and our own unit is an example. Its word hash, Daniel Bernstein's, multiplies by thirty-three. Thirty-three is thirty-two plus one, and multiplying by thirty-two is a shift, which in hardware is only rewiring. So the hash stage is two adders, nine hundred and seventy-seven gates. The same move runs through this part: networks quantized for an eight-bit grid; pruned two in four for tensor cores; bfloat16, Google's format with float32's range in fewer bits; and Tri Dao's FlashAttention of 2022, which reorders a model's arithmetic into tiles that fit in on-chip memory, Part 9's blocking again.
11The Job in hardwareIndustry5 min
Here is the Job as a circuit, taking one byte on every clock tick. Stage one asks whether the byte is a letter, and gives its five-bit code. Stage two keeps a rolling hash of the word: thirty-three times the hash, plus the code, in two of Part 4's adders. When a word ends, stage three folds the hash into a twelve-bit index and keeps all of it as a tag. Stage four reads that entry of a table, compares the tags, adds one and writes it back. Registers between the stages let all four work at once, each on a different byte, like Part 7's pipeline. In all, one thousand seven hundred and sixty-one gates and one hundred and forty-one flip-flops, beside the table.
How fast can it tick? Classifying takes nine gate delays, hashing twenty-five, emitting one, and counting nineteen. But counting must also read the table, and a memory read takes a nanosecond, more than all the logic together. So the period is the table read, plus nineteen gate delays, plus the register: twelve hundred and sixty picoseconds, about seven hundred and ninety-four megahertz. The critical path is the table read. The logic alone could run at three gigahertz: the bill, again, is for memory.
Now feed it the opening of Pride and Prejudice. The I of It enters, and a cycle later stage one holds its code, nine. The hash grows by a letter every cycle. The space ends the word; its hash moves to stage three and becomes an index and a tag, and at cycle five stage four writes a count of one into that slot. Meanwhile the next word is already being hashed. Faster now: truth, universally, acknowledged, each counted four cycles after its last letter, a byte every cycle, never stalling.
Is it right? We ran all of chapter one through eight copies of the unit, gate by gate, and compared everything with the software. Every hash leaving stage three was the software's. Every table held exactly what a model of the table says it should. The top twenty is the software Job's, word for word. And every word is counted or lost. Four words came up short: each table has one slot per index and never looks elsewhere, so a word whose slot is taken is not stored, and the overflow register says so.
How big must the table be? For the thirty novels we swept it from four thousand entries to four million. Lost occurrences fall from over a million to under three thousand, and the words not counted exactly fall with them. Part 17's birthday argument predicts that curve from two numbers: with n words in m slots, a slot stays empty with probability about e to the minus n over m, and every word beyond the occupied slots is short. The prediction lands within a few percent. At a million entries, seven megabytes, the unit loses zero point four percent of occurrences, and the top twenty is exact. A direct-mapped table loses words; Part 17's probing would not, at the cost of cycles.
For more speed, use more units. Cut the text at word boundaries into lanes, each with its own unit and table, and merge the tables at the end. One lane takes thirty-one milliseconds for the thirty novels; four take eight; sixteen, a little over two. Sixty-four take about one, but merging now costs more than reading: Amdahl's law, from chapter one. And sixty-four lanes want twenty-three gigabytes a second of text, nearly all that this machine's memory delivers: the slope of the roofline again.
The ledger gets row twenty-one. A word-counting unit, one byte per cycle at seven hundred and ninety-four megahertz, counts the thirty novels in about thirty-one milliseconds, the fastest row yet. Part 17's hash table on Pebble spent about twenty-nine cycles on every byte; the circuit spends one, because it fetches no instructions at all. Two honest caveats: the text must arrive a byte a cycle, and a seven-megabyte table answering in a nanosecond is optimistic. The arithmetic is now nearly free; what remains, again, is moving the data.
12Frontier: accelerators for language modelsResearch2 min
Why does generating text one word at a time leave most of a chip idle?
The newest accelerators are built for language models, and the roofline of chapter two explains their hardest problem. Here is the roofline of a datacentre GPU from 2022: nearly a thousand trillion sixteen-bit operations a second, but only 3.35 terabytes a second from its memory, so its ridge sits at about 295 operations per byte. To generate one token, a model with P parameters does about two P operations, and reads every one of its weights, two P bytes. That is one operation per byte. For a single conversation, the chip runs at about 0.3 percent of its peak. Serving many conversations at once reuses each weight read across the batch, and the point slides up the roof. Every remedy is the memory wall again: batch the users; quantize the weights to eight or four bits, Part 4's floats once more; guess several tokens with a small model and check them with one pass of the large one; and, as Tri Dao and colleagues showed with FlashAttention in 2022, reorder attention so that it stays in on-chip memory.
The largest models do not fit on one chip, and the frontier is in how chips are put together. Cerebras made a single processor out of an entire silicon wafer, its memory spread among hundreds of thousands of cores, with spare cores so that manufacturing defects can be routed around. Most others went the opposite way: chiplets, several small dies in one package, joined by short and dense wires, which yield better than one huge die and can mix manufacturing processes. And memory is stacked into towers of DRAM dies right beside the processor, wide and close, which is where an accelerator's bandwidth comes from. All three are the fight of chapter eight, at a larger scale: shorten the distance that every byte must travel.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. A roofline, measured on this machine, which says whether a kernel waits for arithmetic or for memory. A cell that multiplies and adds, from Part 4's gates, and a grid of them that multiplies matrices in a diagonal wave, verified gate by gate. Two dataflows, and the utilization each one earns. The TPU's bargain: eight-bit products and thirty-two-bit sums, for a sliver of the energy. GPUs, spatial machines, memory that computes, and sparsity, which are all ways to move fewer bytes. And the Job as a circuit, counting one byte every cycle. One idea runs through it: when the free speedups ended, speed came from fitting the machine to the work.
Where this comes back. The roofline was measured once, on one machine, and Part 61, the last part, is about how to measure without fooling yourself. The open problems of this part join all the others on one map there. And the ledger, with its twenty-first row from this part's circuit, is read one last time.
In practice. Put each kernel on the roofline before you optimize it, so you know which ceiling you are under. Tile loops so that each value fetched is used many times. Quantize inference to eight bits, and check the accuracy on real data, not on a benchmark. Send to an accelerator only work that is dense, regular and large enough to pay for the transfer. And profile the movement of data, not only the arithmetic.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: give the word-counting unit linear probing, so that it stops losing words to collisions, and measure what that costs in gates and in clock speed. The last, marked with a star, is a research problem: Hong and Kung's pebble game, played on a grid of small memories.
Next time, Part 61, the last part of the series: doing research. Every result the series quoted was made by someone. How do you measure without fooling yourself, when the size of an unused environment variable can change a program's speed? How do you read a paper, find a problem and know when it is solved? And where, on one map, are the open problems we met?
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 61 asks how a number such as this machine's roofline should be measured and reported, gathers this part's open problems with the others on one map, and reads the ledger, with its twenty-first row from this part's circuit, one last time. The roofline also meets AI, Built Part 17 on Part 61's bridges.
Key results
The part's results in one place, for revision.
Try it
Lab 60 · A matrix product as a wave
Simulate a 4 by 4 output-stationary systolic array gate by gate on 16 random products, then run both dataflows as integer models up to 64 by 64 and compare their cycles and utilization with the closed forms; finally push a Gaussian product through int8.
python -m videos.cs.labs 60
needs numpy, scipy, matplotlib · download lab60.py ·
source on GitHub4 x 4 grid at gate level 11,568 gates, 10 cycles, 16 of 16 products exact: True
busy cells per cycle 1 3 6 10 12 12 10 6 3 1 (sum 64 = N^3)
output-stationary utilization, N = 4 ... 64 0.400 0.364 0.348 0.340 0.337 (N/(3N-2) -> 1/3)
weight-stationary, a stream of 16N rows 0.865 0.853 0.848 0.845 0.843 (M/(M+3N-2))
relative error of a 128 x 128 Gaussian product float32 2.0e-07 int8 1.4e-02
largest int32 accumulator 45,796 (16 bits of headroom); a 32 x 32 int8 slice through the grid is exact: True
The grid computes every product exactly in 3N - 2 cycles, but one product alone keeps only a third of the cells busy; holding the weights still and streaming rows through fills the grid, and eight bits lose about a percent of a product's accuracy.
The code (87 lines; it asserts its own result)
"""Lab 60: clock a systolic array at gate level, check its wave against 3N - 2, and multiply in eight bits."""
from videos.coursekit import labs # noqa: I001 (must stay first: it lets explainer.cs import without manim)
import numpy as np
from explainer.cs.hw import systolic
TITLE = "A matrix product as a wave"
GOAL = ("Simulate a 4 by 4 output-stationary systolic array gate by gate on 16 random products, then run both "
"dataflows as integer models up to 64 by 64 and compare their cycles and utilization with the closed forms; "
"finally push a Gaussian product through int8.")
TASKS = [
"Build the cells with kind='array' (an array multiplier and a ripple-carry adder). The products stay exact: what "
"changes in gates and in depth (cell_stats())?",
"Stream M = N, 4N and 64N rows through the weight-stationary grid. At what M does its utilization pass the "
"output-stationary grid's N / (3N - 2)?",
"Quantize to 4 and to 6 bits (systolic.quantize(x, bits)) and plot the product's relative error against bits. "
"By what factor does each extra bit shrink it?",
]
def run(seed=0):
lab = labs.Lab()
# 1. gate level: 16 random 4 x 4 products at once, clocked for 3N - 2 cycles
g = systolic.output_stationary(4, trials=16, seed=seed)
busy = [sum(k is not None for row in step["k"] for k in row) for step in g["trace"]]
lab.row("4 x 4 grid at gate level", f"{g['gates']:,} gates, {g['cycles']} cycles, 16 of 16 products exact: "
f"{g['correct']}")
lab.row("busy cells per cycle", " ".join(str(b) for b in busy) + f" (sum {sum(busy)} = N^3)")
assert g["correct"], "the grid's accumulators must hold A B exactly"
assert g["cycles"] == 3 * 4 - 2 and g["gates"] == 16 * 723, "3N - 2 cycles; N^2 cells of 723 gates"
assert sum(busy) == 4 ** 3 == g["macs"], "every multiply-add of the product happens exactly once"
wave = [sum(0 <= t - i - j < 4 for i in range(4) for j in range(4)) for t in range(10)]
assert busy == wave, "cell (i, j) works on k = t - i - j: a diagonal wave"
# 2. the same dataflows on integers, for larger grids, against the closed forms
ns = (4, 8, 16, 32, 64)
os_u, ws_u = [], []
for n in ns:
a = systolic.dataflow_model(n, dataflow="os", seed=seed + n)
b = systolic.dataflow_model(n, 16 * n, "ws", seed=seed + n)
assert a["correct"] and b["correct"], "both dataflows must reproduce numpy's product"
assert a["cycles"] == 3 * n - 2 and abs(a["utilization"] - n / (3 * n - 2)) < 1e-12
assert abs(b["utilization"] - 16 * n / (16 * n + 3 * n - 2)) < 1e-12
os_u.append(a["utilization"])
ws_u.append(b["utilization"])
lab.row("output-stationary utilization, N = 4 ... 64", " ".join(f"{u:.3f}" for u in os_u) + " (N/(3N-2) -> 1/3)")
lab.row("weight-stationary, a stream of 16N rows", " ".join(f"{u:.3f}" for u in ws_u) + " (M/(M+3N-2))")
assert os_u[-1] < 0.34 < 0.8 < ws_u[-1], "one product keeps a third of the cells busy, a long stream over 80%"
# 3. fewer bits: the same product through int8, with int32 accumulators
q = systolic.quantized_matmul(n=128, seed=seed, systolic_n=32)
lab.row("relative error of a 128 x 128 Gaussian product", f"float32 {q['float32_rel_error']:.1e} int8 "
f"{q['int8_rel_error']:.1e}")
lab.row("largest int32 accumulator", f"{q['max_abs_int32_acc']:,} ({q['int32_headroom_bits']:.0f} bits of "
f"headroom); a 32 x 32 int8 slice through the grid is exact: "
f"{q['systolic_int8_exact']}")
assert q["float32_rel_error"] < 1e-5 and 2e-3 < q["int8_rel_error"] < 5e-2, "int8 costs about a percent"
assert q["systolic_int8_exact"] and q["max_abs_int32_acc"] < 128 * 127 * 127, "128 products of at most 127^2"
lab.note = ("The grid computes every product exactly in 3N - 2 cycles, but one product alone keeps only a third "
"of the cells busy; holding the weights still and streaming rows through fills the grid, and eight "
"bits lose about a percent of a product's accuracy.")
fig, ax = labs.figure(2, size=(11, 4.4))
n = 8
t = np.arange(3 * n - 2)
profile = [sum(0 <= c - i - j < n for i in range(n) for j in range(n)) for c in t]
ax[0].bar(t, profile, color=labs.GOLD, width=0.8, label="cells doing a multiply-add")
ax[0].axhline(n * n, color=labs.MUTED, ls="--", label=f"all {n * n} cells")
ax[0].set_axisbelow(True)
ax[0].set(xlabel="cycle", ylabel="busy cells", ylim=(0, n * n * 1.3),
title=f"The wave through an {n} x {n} grid: {3 * n - 2} cycles")
ax[0].legend(loc="upper left")
grid = np.arange(2, 65)
ax[1].plot(grid, grid / (3 * grid - 2), color=labs.BLUE, label="output-stationary: N / (3N - 2)")
ax[1].plot(grid, 16 * grid / (16 * grid + 3 * grid - 2), color=labs.GREEN,
label="weight-stationary, M = 16N: M / (M + 3N - 2)")
ax[1].plot(ns, os_u, "o", color=labs.BLUE)
ax[1].plot(ns, ws_u, "o", color=labs.GREEN, label="simulated (dots)")
ax[1].axhline(1 / 3, color=labs.MUTED, ls="--", lw=1)
ax[1].set(xlabel="grid size N", ylabel="share of cell-cycles doing work", ylim=(0, 1.19),
title="Utilization: simulation on the closed forms")
ax[1].legend(loc="upper right", ncol=1)
lab.fig = fig
return lab
Now change it
- Build the cells with kind='array' (an array multiplier and a ripple-carry adder). The products stay exact: what changes in gates and in depth (cell_stats())?
- Stream M = N, 4N and 64N rows through the weight-stationary grid. At what M does its utilization pass the output-stationary grid's N / (3N - 2)?
- Quantize to 4 and to 6 bits (systolic.quantize(x, bits)) and plot the product's relative error against bits. By what factor does each extra bit shrink it?
Problems, with solutions
Try each problem before opening its solution.
-
Tiled intensity. Derive the arithmetic intensity of an n × n matrix product with b × b tiles in a fast memory of 3b² words, and the b that reaches this machine's ridge.
Solution
Keep one b × b tile of C in fast memory, starting at zero. For each of the n/b steps along the inner index bring in one b × b tile of A and one of B (2b² words), and add their product, 2b³ flops, into the C tile; after the last step write the C tile out (b² words). The three tiles are the 3b² words. Over all (n/b)² tiles of C the flops are 2n³ and the words moved are (n/b)²((n/b)·2b² + b²) = 2n³/b + n². With 8-byte words, I = 2n³ / (8(2n³/b + n²)) = b / (8 + 4b/n), which is b/8 when b ≪ n; at b = n it is n/12, chapter 2's compulsory count, since then each matrix is touched once. Reuse grows linearly with the tile's side. This machine's ridge is P/β = 78.4/28.4 ≈ 2.76 flops per byte, so b/8 ≥ 2.76 needs b ≥ 22.1, and at n = 2,048 the correction term raises that to 22.2: b = 23, a fast memory of 3 · 23² = 1,587 words, about 12.4 KB. That is the least b that could reach the ridge; reaching the flat roof in practice also needs register tiling and a bandwidth as good as the best STREAM kernel.
-
Systolic timing. Show that an output-stationary N × N grid needs 3N − 2 cycles, and a weight-stationary one M + 2N − 2 after loading.
Solution
Number the cycles from 0. Output-stationary: row i of A enters the west edge i cycles late, so A_ik is in column 0 at cycle i + k and, moving one cell east per cycle, in column j at i + j + k; column j of B enters the north edge j cycles late, so B_kj reaches row i at the same cycle i + j + k. Every product A_ik B_kj is therefore formed exactly once, in cell (i, j), at t = i + j + k. The first is at t = 0 and the last, with i = j = k = N − 1, at t = 3N − 3, so the product needs the 3N − 2 cycles 0, …, 3N − 3; cell (i, j) is busy for the N cycles from i + j. Weight-stationary: during loading one row of W enters the top of each column per cycle, last row first, so after N shifts row k of W sits in row k of the grid. Then X_rk enters row k at cycle r + k, moves east one cell per cycle, and reaches cell (k, j) at r + k + j, where it is multiplied by W_kj and added to the partial sum from cell (k − 1, j), formed there at r + (k − 1) + j and moved one row down: the timings agree, so Y_rj accumulates down column j and leaves the bottom row at cycle r + (N − 1) + j. The last output, r = M − 1 and j = N − 1, leaves at M + 2N − 3, so the stream needs M + 2N − 2 cycles. Dividing the multiply-adds by cells × cycles gives N/(3N − 2) → 1/3 and M/(M + 3N − 2) → 1, and the gate-level runs agree exactly (N = 4: 10 cycles; with M = 6, 4 + 12).
-
Accumulator width. An int8 product of length K sums into 32 bits. How large can K be before the sum can overflow?
Solution
A 32-bit two's-complement accumulator holds [−2³¹, 2³¹ − 1]. With chapter 5's symmetric quantization the integers lie in [−127, 127], so each product has |q r| ≤ 127² = 16,129 and a sum of K of them has magnitude at most 16,129 K. That is at most 2³¹ − 1 = 2,147,483,647 while K ≤ 133,144; at K = 133,145 inputs at the extremes can overflow. If −128 is allowed, the largest product is (−128)² = 2¹⁴, and K · 2¹⁴ ≤ 2³¹ − 1 gives K ≤ 2¹⁷ − 1 = 131,071 (the most negative product, −128 · 127, allows K ≤ 132,104, so the positive side binds). Either way K can be about 2¹⁷, over five hundred times the TPU's 256-long columns; in chapter 5's measured 256 × 256 product the largest sum was only 56,572, because random terms cancel.
-
Batch size. Decoding one token reads every weight once. Find the batch size at which a chip with the roofline of chapter twelve becomes compute-bound.
Solution
A model with P parameters in 16-bit weights reads 2P bytes per decoding step, however many sequences share the step. With B sequences in the batch each weight read serves B multiply-adds, 2PB flops, so the intensity is about B flops per byte. Chapter twelve's chip has ridge 989/3.35 ≈ 295.2 flops per byte, so it becomes compute-bound at B ≈ 296; at batch 1 it reaches 3.35/989 ≈ 0.34% of its peak. With 8-bit weights the bytes halve and so does the batch needed, to about 148; with 4-bit weights, about 74. The count leaves out attention's reads of each sequence's key–value cache: that cache serves only its own sequence, so its intensity stays near 1 whatever the batch, and with long contexts it keeps the overall intensity below B, and the break-even batch higher.
-
Build. Add linear probing to the word-counting unit, and measure its gates, its clock and the words it no longer loses.
Solution
Solution notes. Start with the functional model: give
table_modelinexplainer/cs/hw/accel.pya probe window of w slots, i, i + 1, …, i + w − 1 (mod 2^k), in which the first slot holding the word's tag or empty wins and a word that finds all w owned by other tags is lost to the overflow register. Run with the unit's own hash on the thirty novels, that model at 2²⁰ entries loses 133 distinct words (1,223 occurrences) with w = 2 and 4 words (35 occurrences) with w = 4, against the direct-mapped 1,581 (18,362); unbounded probing loses none and never needs more than 9 probes. At 2¹⁶ entries (88% full) unbounded probing still loses none but needs up to 1,832 probes, while w = 4 loses 7,984 words. For one byte a cycle, read the window in parallel: interleave the table over w banks by the index's low bits, so that w consecutive slots lie in different banks and are read in the same access; givecount_stagew tag comparators (each 32 XNOR gates and a tree of 31 AND gates, like the one it has), a priority encoder picking the first hit or the first empty slot, and w-to-1 multiplexers for the count and the bank; the unit's write port then takes a bank as well as an index. Measure the new stage withtiming(gates fromc.size(), depth fromc.depth()): the comparators work in parallel, so the period grows only by the encoder and the multiplexers, a few gate delays beside the 1 ns table read. The alternative, one probe per cycle with the input stalled, keeps the gates down but needs a ready signal the unit does not have, and gives up one byte per cycle in the worst case. Check it as the instruments check the present unit: extendrunso that each lane's table is compared with the probing model, keepaccounted(counted plus lost equals words), make the lanes' merge probe too, and add tests besidetest_collisions_reportedintests/test_cs60_hw.py. Words still end at least two cycles apart, so a read never sees a stale entry. -
★ Research. The least data movement for a matrix product on a grid of small memories, with a matching dataflow.
Discussion. Open in the form asked. Hong and Kung's red–blue pebble game (1981) bounds the words that any evaluation of the classical n³ product must move between a fast memory of M words and a slow one, Θ(n³/√M); Irony, Toledo and Tiskin (2004) proved the parallel analogue, Ω(n³/(P√M)) words for some one of P processors, and Cannon's algorithm on a 2D torus and the 2.5D algorithms of Solomonik and Demmel (2011) meet such bounds up to constants. Those models charge a word once, whatever distance it travels. On a systolic grid the cost is a word times the hops it makes between neighbours, the inputs enter only at the edges, and when n > N the product must be tiled through the grid, so the edge bandwidth and the traffic to memory off the grid count as well. Chapter 3's grid, with M = O(1) words a cell, makes Θ(1) hops per multiply-add; a cell holding a √M × √M block of C can bring that down to about 1/√M. A good partial answer would fix the model (an N × N mesh, M words a cell, edge input and output, cost in word-hops), prove a lower bound on total hops for n = N with the constant, and give a dataflow meeting it; then extend to n > N, where it would also have to say whether replicating data, as 2.5D algorithms do, pays when distance is charged.
Notes and sources
Glossary
- domain-specific architecture (DSA), accelerator, ASIC — hardware built for one kind of work; a chip made for one design.
- energy per operation, data movement — the cost of an operation against the cost of fetching its operands (Horowitz's table).
- the roofline model, arithmetic intensity, ridge point, compute-bound, memory-bound — attainable speed min(P, Iβ); flops per byte moved; P/β; which roof a kernel sits under.
- STREAM — McCalpin's benchmark of sustained memory bandwidth on arrays larger than the caches.
- systolic array, cell (processing element), wavefront, skew — a grid of identical cells passing data to their neighbours each clock; the diagonal of active cells; the delay that lines the inputs up.
- multiply-accumulate (MAC) — s ← s + a · b, the operation of every cell.
- output-, weight-, input- and row-stationary — which of the three numbers in a multiply-add stays in the cell.
- utilization — multiply-adds done over cells × cycles.
- TPU, matrix unit, unified buffer, accumulators — Google's inference accelerator and its parts.
- quantization, scale, symmetric per-tensor int8, headroom — a real number as a scale times a small integer; the bits an accumulator has to spare.
- SIMT, warp, divergence — threads sharing one instruction stream in groups of 32; lanes idling at a branch they disagree on.
- tensor core — a small matrix multiply-accumulate unit in each GPU multiprocessor.
- tiling (blocking) — computing on a block that fits in fast memory so each fetched value is used many times.
- the memory wall — arithmetic outgrowing the bandwidth that feeds it.
- dataflow machine, token, firing rule — execution ordered by the arrival of operands rather than by a program counter.
- CGRA, placement and routing — a grid of word-wide configurable elements; assigning operations to elements and edges to wires.
- FPGA, lookup table (LUT), hard blocks — a fabric of small programmable truth tables, flip-flops, wires, multipliers and memories.
- near-memory and in-memory computing (PIM), HBM, through-silicon via, interposer — computing beside or inside the memory; stacked DRAM joined by vertical wires on a slab of silicon.
- analog crossbar — conductances at wire crossings computing a matrix-vector product by Ohm's and Kirchhoff's laws.
- pruning, compressed sparse rows (CSR), 2:4 structured sparsity — removing weights; storing values, columns and row starts; two nonzeros in every group of four.
- stochastic rounding — rounding up with probability equal to the fraction, unbiased in expectation.
- approximate computing, loop perforation — giving up accuracy on purpose, in circuits or by skipping iterations.
- RTL, synthesis, netlist, place and route, tape-out — the stages from a hardware description to a chip.
- hardware generator (Chisel), high-level synthesis (HLS), initiation interval — programs that produce circuits; compiling C to hardware; cycles between iterations of a pipelined loop.
- agile hardware, design-space exploration, co-design — iterating on working designs; searching among alternatives; choosing algorithm and hardware together.
- bfloat16 — a 16-bit float with float32's exponent range.
- direct-mapped table, tag, overflow, lanes — one slot per index and no probing; the stored hash that identifies a word; the count of words lost; copies of the unit working on pieces of the text.
- decoding, batching, speculative decoding, KV cache — generating one token per step; sharing each weight read across sequences; guessing tokens with a small model and checking them with the large one; stored attention keys and values.
- wafer-scale processor, chiplets, UCIe — one processor the size of a wafer; several dies in one package; a standard for joining them.
- red–blue pebble game, I/O complexity — Hong and Kung's model of moving data between fast and slow memory.
Sources
- J. Hennessy and D. Patterson, Computer Architecture: A Quantitative Approach, 6th ed., ch. 7 ("Domain-specific architectures"); V. Sze, Y.-H. Chen, T.-J. Yang and J. Emer, Efficient Processing of Deep Neural Networks (Morgan & Claypool, 2020).
- J. Hennessy and D. Patterson, "A new golden age for computer architecture", Communications of the ACM 62(2), 2019 (the 2018 Turing lecture).
- H. T. Kung and C. Leiserson, "Systolic arrays (for VLSI)", Sparse Matrix Proceedings 1978 (SIAM, 1979); H. T. Kung, "Why systolic architectures?", IEEE Computer 15(1), 1982.
- J.-W. Hong and H. T. Kung, "I/O complexity: the red-blue pebble game", STOC 1981; D. Irony, S. Toledo and A. Tiskin, "Communication lower bounds for distributed-memory matrix multiplication", J. Parallel Distrib. Comput. 64(9), 2004; E. Solomonik and J. Demmel, "Communication-optimal parallel 2.5D matrix multiplication and LU factorization algorithms", Euro-Par 2011.
- S. Williams, A. Waterman and D. Patterson, "Roofline: an insightful visual performance model for multicore architectures", Communications of the ACM 52(4), 2009; J. McCalpin, "Memory bandwidth and machine balance in current high performance computers", IEEE TCCA Newsletter, December 1995.
- M. Horowitz, "Computing's energy problem (and what we can do about it)", ISSCC 2014; R. Hameed et al., "Understanding sources of inefficiency in general-purpose chips", ISCA 2010; K. Rupp, Microprocessor Trend Data (CC BY 4.0).
- N. Jouppi et al., "In-datacenter performance analysis of a tensor processing unit", ISCA 2017; Y.-H. Chen, J. Emer and V. Sze, "Eyeriss: a spatial architecture for energy-efficient dataflow for convolutional neural networks", ISCA 2016.
- NVIDIA, Tesla V100 datasheet (2017), A100 architecture whitepaper (2020) and H100 datasheet (2022); JEDEC JESD235, High Bandwidth Memory (2013).
- J. Dennis and D. Misunas, "A preliminary architecture for a basic data-flow processor", ISCA 1975; I. Kuon and J. Rose, "Measuring the gap between FPGAs and ASICs", IEEE Trans. CAD 26(2), 2007; A. Putnam et al., "A reconfigurable fabric for accelerating large-scale datacenter services", ISCA 2014; R. Prabhakar et al., "Plasticine: a reconfigurable architecture for parallel patterns", ISCA 2017.
- S. Han, J. Pool, J. Tran and W. Dally, "Learning both weights and connections for efficient neural networks", NIPS 2015; S. Han et al., "EIE: efficient inference engine on compressed deep neural network", ISCA 2016; S. Gupta, A. Agrawal, K. Gopalakrishnan and P. Narayanan, "Deep learning with limited numerical precision", ICML 2015; S. Sidiroglou-Douskos, S. Misailovic, H. Hoffmann and M. Rinard, "Managing performance vs. accuracy trade-offs with loop perforation", ESEC/FSE 2011.
- J. Bachrach et al., "Chisel: constructing hardware in a Scala embedded language", DAC 2012; Y. Lee et al., "An agile approach to building RISC-V microprocessors", IEEE Micro 36(2), 2016.
- T. Dao, D. Fu, S. Ermon, A. Rudra and C. Ré, "FlashAttention: fast and memory-efficient exact attention with IO-awareness", NeurIPS 2022.
About this partfrom its README
Part 60 of a sixty-one-part course in computer science (see the series plan and the syllabus), the fifth part of Act XI, The Research Frontier. When Act II's free speedups ended, the industry's answer was specialization: hardware that does one kind of work and spends almost nothing on organizing it. We measure this machine's roofline, build H. T. Kung's systolic array out of Part 4's multipliers and simulate it gate by gate, read the numbers in Google's TPU paper, and end by turning the Job itself into a four-stage circuit that counts one byte every cycle.
The instruments are in explainer/cs/hw/ (tested in tests/test_cs60_hw.py), built on Part 3's gates, Part 4's
adders and multipliers and Part 5's registers (explainer/cs/pebble/):
systolic.py: a multiply-accumulate cell at gate level in two versions (a Dadda tree multiplier with a Kogge–Stone adder; an array multiplier with a ripple-carry adder), checked against s + ab; output-stationary and weight-stationary N × N grids of those cells, clocked by the HDL simulator, traced cycle by cycle and checked against NumPy's exact integer products; an integer model of both dataflows for grids up to 256 × 256, checked against the closed forms for cycles and utilization; symmetric per-tensor int8 quantization of a 256 × 256 product and of a linear classifier; Horowitz's energy and area per operation beside our multipliers' gate counts and the TPU's published figures.roofline.py: this machine's two roofs, measured on one thread (peak float64 FLOP/s from BLAS matrix products at four sizes; bandwidth from STREAM-style copy, add, daxpy and dot on 512 MB arrays, counted as STREAM counts); kernels placed under them with intensities from their compulsory traffic: axpy, dot, matrix–vector, matrix products at four sizes, a 5-point stencil, Part 52's three BLAS levels, and the Job in Python (four operations a byte, estimated); Horowitz's 45 nm table as data.accel.py: the Job as a netlist of four pipeline stages (classify a byte; hash the word, h ← 33h + code, in two Kogge–Stone adders; emit a k-bit index folded from the hash, with the whole hash as a tag; count, by reading a direct-mapped table, comparing tags at gate level and incrementing, with an overflow register for words that find their slot taken); gates, depth and clock per stage from the series' timing model; gate-level runs in parallel lanes checked against the software Job and against a functional model of the table; the thirty novels through that model for 1, 4, 16 and 64 lanes and six table sizes; ledger row 21.
Chapter notes
- Hook. Energy per operation at 45 nm (Horowitz, approximate): an 8-bit add 0.03 pJ, a 32-bit add 0.1, an 8-bit multiply 0.2, a 32-bit float multiply 3.7; reading 64 bits from an 8 KB SRAM 10 pJ, from a 1 MB SRAM 100, from DRAM 1,300–2,600, as much as 90,000 8-bit additions; Hameed et al.'s video encoder (2010), about 500 times less energy as a dedicated chip. A 4 × 4 output-stationary grid multiplies two matrices in a diagonal wave in 10 cycles, at gate level and checked. The plan: the Job as a circuit, ledger row 21, the thirty novels in about 31 ms.
- 1. The end of general-purpose scaling. Part 10's trend data: the clock grew 33% a year in 1985–2004 and −0.7% a year in 2006–2021. The energy of an instruction against that of its operation: a 10 pJ fetch for a 0.1 pJ add leaves a useful share of at most 1%. One instruction driving k operations: 1% for a scalar add, 14% for a 16-wide vector add, 99.9% for the 65,536 8-bit multiply-adds of a 256 × 256 grid. Hennessy and Patterson's four reasons for domain-specific architecture (Turing lecture, June 2018). The price, Amdahl again: f = 0.9 and s = 50 give 8.5 times, and no accelerator gives more than 10.
- 2. The roofline model. T ≥ F/P and T ≥ Q/β, so F/T ≤ min(P, Iβ) with I = F/Q, derived. Intensities from compulsory traffic: axpy 0.083 (2 flops for 24 bytes), dot 0.125, matrix–vector 0.25, the stencil 0.25, a matrix product n/12, 171 at n = 2,048. This machine on one core: matrix products at 65, 69, 73 and 78 GFLOP/s for n = 256 to 2,048; on 512 MB arrays copy 27, add 16, daxpy 28 and dot 18 GB/s; the ridge 78/28 ≈ 2.8 flops per byte (load average 0.7 when measured). Axpy at 93% of its roof, the stencil at 10% (NumPy's temporaries), matrix products at 91–95% of the peak, Part 52's kernels beside them, and the Job in Python about 600 times under its roof. TPU v1's ridge, about 2,700.
- 3. A systolic array. C₀₀ = 70 + 104 + 156 + 15 = 345: N³ = 64 multiply-adds for 4 × 4. One cell: with the tree multiplier and Kogge–Stone adder 723 gates (1,923 as NAND gates), depth 29; with the array multiplier and ripple carry 461 gates (1,321), depth 61; 40 flip-flops; both checked on 4,096 random inputs. A_ik and B_kj meet in cell (i, j) at cycle i + j + k, so a product takes 3N − 2 cycles. The wave cycle by cycle (the corner cell 70, 174, 330, 345). Grids of 2, 4 and 8 cells a side at gate level: 4, 10 and 22 cycles, 2,892, 11,568 and 46,272 gates (exactly N² × 723), 16 random products each, all exact.
- 4. Which number stays put. Output-, weight- and input-stationary; Eyeriss's row-stationary mix (2016). A weight-stationary 4 × 4 grid at gate level with 6 input rows: 4 load cycles and 12 compute cycles. Utilization derived: N/(3N − 2) → 1/3 and M/(M + 3N − 2) → 1, checked against the simulations (0.40 and 0.375; 0.50 counting only compute cycles). Curves against grid size: weight-stationary with M = N tends to a quarter, with M = 16N stays above 80%. At N = 16, 64 and 256 every utilization equals its formula; at 256, 33.4% for one output-stationary product against 84.2% for a long weight-stationary stream. Holding weights costs 25 more gates per cell.
- 5. The TPU, and fewer bits. The first TPU (in Google's data centres from 2015; Jouppi et al. 2017): a 256 × 256 matrix unit, a 24 MiB unified buffer, 8 GiB of weight DRAM at 34 GB/s, 4 MiB of 32-bit accumulators. 65,536 cells × 2 × 700 MHz = 9.18 × 10¹³, the paper's 92 TOPS; its ridge about 2,700 operations per byte. Beside this machine: a flat roof about 1,200 times higher, bandwidth 1.2 times; most of the paper's networks were memory-bound; 15–30 times faster than a contemporary CPU and GPU on inference. Quantization: s = 1.95/127 = 0.01535, error at most half a step. Products below 2¹⁴, 256 of them below 2²²; measured, the largest accumulator was 56,572 (15 bits of headroom), and a 64 × 64 slice through chapter 4's model was exact in 254 cycles. Relative error of a 256 × 256 product against float64: float32 2.9 × 10⁻⁷, float16 inputs 2.9 × 10⁻⁴, int8 1.5 × 10⁻²; a 10-class classifier 75.54% in float32, 75.52% in int8, the same answer on 99.6% of 5,000 points. An 8-bit multiply costs 0.2 pJ against 3.7 (about an eighteenth) and 420 gates against 3,790 (about a ninth).
- 6. GPUs revisited. Warps of 32 sharing one instruction; divergence. A tensor core: D = AB + C on 4 × 4 matrices, 64 multiply-adds per clock, 16-bit products and 32-bit sums (its wiring unpublished; drawn as a sketch). Multiply-adds per instruction: 1, 16, 32 and 4,096 (a 16 × 16 × 16 warp step). The V100 (datasheet): 15.7 TFLOP/s on its lanes, 125 on tensor cores, 900 GB/s, so the ridge moves from 17 to 139. Tiles: I = b/2 for 16-bit numbers, so b ≥ 278 to reach the tensor-core ridge, which is why kernels tile at every level at once.
- 7. Spatial machines: dataflow, CGRAs and FPGAs. y_i = 3x_i + 2x_{i−1}: 8 instructions per result in time, one unit per operation in space. Dataflow firing on tokens: (5 + 3)(7 − 4) = 24 (Dennis and Misunas 1975; Part 8's out-of-order core as a hidden dataflow engine). The loop placed and routed on a 3 × 4 CGRA, with one element that only passes a value on; then one result per cycle after the pipeline fills (6, 7, 14, 17, 21, 16, 22, 15). A 4-input lookup table computing parity, then "at least two set"; the FPGA fabric; Kuon and Rose's gap (2007): around 35 times the area and several times slower. The spectrum from CPU to ASIC; Catapult (2014), FPGAs to rent (2017), Plasticine (2017).
- 8. Computing near memory. One byte: an 8-bit add 0.03 pJ; from an 8 KB SRAM 1.25 pJ, a 32 KB SRAM 2.5, a 1 MB SRAM 12.5, DRAM 162–325, the energy of 5,400–10,800 additions. Wire energy ½CV² with C ∝ length. HBM (a JEDEC standard since 2013): 1,024 data wires per stack, millimetres long, against a DDR channel's 64 across the board. Processing in memory: summing 2²⁸ four-byte numbers moves 1,073,741,824 bytes over the channel, or 128 bytes of partial sums from 16 banks, about 8 million times less (UPMEM; Samsung's HBM-PIM, 2021). An analog crossbar: Ohm and Kirchhoff give I = GᵀV in one step, here (7, 5, 3, 4); a few bits of precision.
- 9. Sparsity and approximation. A pruned row: 16 multiplies, 11 of them by zero, against 5 skipped to the same sum (Han et al. 2015 pruned about nine in ten of AlexNet's weights; EIE). Compressed sparse rows: 24 bytes dense against 28 compressed for the example; with 8-bit values and 16-bit indices compression wins only below a third density. 2:4 structured sparsity (A100, 2020): 32 bits a group become 20, exactly half the multiplies. Stochastic rounding derived: E[r(x)] = x, variance at most Δ²/4; 24 quarter-step updates, round to nearest stuck at 0, one stochastic run ending at 6 as the exact sum does (Gupta et al. 2015). An approximate 8 × 8 multiplier dropping the 10 partial products in the four lowest columns: error at most 49, under 0.08% of 255²; chapter 5's classifier, scores off by 0.9% and answers changed on 0.4% of points; loop perforation.
- 10. How hardware is designed. RTL, synthesis, netlist, place and route, tape-out; Chisel (2012) beside this series' Python HDL. High-level synthesis of a pipelined dot product: 3 + 255 = 258 cycles for 256 iterations, the sum's recurrence the limit. Agile hardware (Lee et al. 2016) against the waterfall. Design-space exploration of chapter 3's two cells: periods 360 ps and 680 ps; gates × period 260,280 against 313,480, so the tree does 1.2 times the work per gate. Bits as the biggest knob: 420, 807 and 3,790 gates at 8, 11 and 24 bits, about 6.6 n² each; G(24)/G(8) = 9.02; depth 19, 23, 32. Co-design: 33h = (h ≪ 5) + h makes the hash stage two adders, 977 gates; quantization, 2:4 pruning, bfloat16, FlashAttention.
- 11. The Job in hardware. Four stages: classify (23 gates, depth 9), hash (977, depth 25), emit (12, depth 1), count (749, depth 19); 1,761 gates and 141 flip-flops beside a 4,096 × 57-bit table (1,769 gates with the 2²⁰-entry table for the novels). The clock: 1,000 ps for the table read + 19 × 10 + 70 = 1,260 ps, about 794 MHz; the logic alone would take 320 ps (3.1 GHz). The opening of Pride and Prejudice cycle by cycle ("I" enters, code 9; the first count written at cycle 5). Chapter 1 of the novel (4,709 bytes) through 8 lanes at gate level in 598 cycles: every hash and every table as the software and the model say, the top twenty exact, 885 counted + 5 lost = 890 words, 4 of 331 distinct words short. Table size swept from 4,096 to 4,194,304 entries on the thirty novels: lost occurrences from 1,185,921 to 2,747, words not counted exactly predicted by m(1 − e^{−n/m}) within a few percent (19,452 against 19,450 at 2¹⁶; 1,581 against 1,569 at 2²⁰; 407 against 398 at 2²²); at 2²⁰ entries (7.1 MB) 18,362 of 4,609,954 occurrences lost (0.4%), the top twenty exact from 16,384 entries up. Lanes: 31.46, 8.02, 2.27 and 1.06 ms for 1, 4, 16 and 64 (0.8 to 23.5 GB/s), merging costing more than streaming at 64 (453,234 cycles against 390,194), lost occurrences down to 3,937. Ledger row 21: about 31 ms at 794 MHz, one cycle a byte against about 29 for Part 17's hash table on Pebble; the caveats (a byte every cycle, a 7 MB table in 1 ns).
- 12. Frontier: accelerators for language models. A 2022 datacentre GPU (989 TFLOP/s dense 16-bit, 3.35 TB/s): ridge 295 flops per byte; decoding one token is about 1 flop per byte, 0.3% of the peak at batch 1; batches of 1, 8, 64 and 512 on the roof; remedies (batching, quantized weights, speculative decoding, FlashAttention). Wafer scale (Cerebras, 2019), chiplets (AMD's server chips, 2017; UCIe, 2022), stacked memory. Four open problems and the ★ research problem (Hong and Kung's red–blue pebble game on a grid of cells).
- Outro. Recap, payoffs, practice, problems, next part.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- The end of general-purpose scaling (callback to Part 10); Hennessy & Patterson's "new golden age" (2018 Turing lecture); the energy of an instruction against the energy of an operation.
- The roofline model (Williams, Waterman & Patterson 2009): arithmetic intensity, derived; this machine's roofline measured.
- Systolic arrays (Kung & Leiserson 1978): a matrix multiplier built from Part 4's multipliers, simulated at gate level and verified; weight-stationary against output-stationary dataflow.
- The TPU (Jouppi et al. 2017): a 256 × 256 systolic array; quantization (callback to Part 4's floats); what the numbers in its paper mean.
- GPUs revisited (Part 10): SIMT, tensor cores, the memory wall again.
- Dataflow and spatial architectures; coarse-grained reconfigurable arrays; FPGAs (Part 5) as accelerators.
- Near-memory and in-memory computing; the cost of moving a byte.
- Sparsity and approximation: sparse accelerators, stochastic rounding, approximate computing.
- Design methodology: high-level synthesis, Chisel and the agile hardware movement, design-space exploration; co-design of algorithm and hardware.
- The Job in hardware: a pipelined word-hashing and counting unit built in Pebble's HDL, verified against the software Job; ledger row 21.
- Frontier: accelerators for language models; wafer-scale and chiplets; open problems in hardware design automation.
- Outro.
Computed: a gate-level systolic array multiplying matrices, cycle by cycle, against numpy; the roofline of this machine measured; the energy per operation table (cited); the word-counting accelerator's throughput, area in gates, and the Job's time on it. Visuals: numbers flowing through the systolic grid in diagonal waves; the roofline with each kernel as a point; the Job's accelerator as a pipeline of hash stages. In practice: ML accelerators (TPU, Trainium, tensor cores), FPGA offload in data centres, video and crypto engines, hardware design roles. Reading: Hennessy & Patterson, Computer Architecture, 6th ed., ch. 7; Sze, Chen, Yang & Emer, Efficient Processing of Deep Neural Networks; Kung & Leiserson 1978; Kung 1982; Williams, Waterman & Patterson 2009; Jouppi et al. 2017; Hennessy & Patterson 2019 (CACM).
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
分块后的算术强度。 推导 n × n 矩阵乘法在容量为 3b² 个字的快速存储中使用 b × b 分块时的算术强度,并求出达到本机拐点所需的 b。
解答
在快速存储中保留 C 的一个 b × b 块,初值为零。沿内层下标走 n/b 步,每步调入 A 的一个 b × b 块和 B 的一个 b × b 块 (2b² 个字),把它们的乘积(2b³ 次浮点运算)累加进 C 块;最后一步之后把 C 块写回(b² 个字)。这三个块正好是 3b² 个字。对 C 的全部 (n/b)² 个块,浮点运算共 2n³ 次,搬运的字数为 (n/b)²((n/b)·2b² + b²) = 2n³/b + n²。每字 8 字节时, I = 2n³ / (8(2n³/b + n²)) = b / (8 + 4b/n),b ≪ n 时约为 b/8;b = n 时为 n/12,正是第 2 章按必经流量算出的值,因为此时每个矩阵只碰 一次。复用随块的边长线性增长。本机的拐点是 P/β = 78.4/28.4 ≈ 2.76 次浮点运算每字节,所以 b/8 ≥ 2.76 要求 b ≥ 22.1;n = 2,048 时 修正项把它抬到 22.2,于是 b = 23,快速存储为 3 · 23² = 1,587 个字,约 12.4 KB。这只是可能达到拐点的最小 b;实际要贴近平顶,还需要 寄存器级分块,以及与最好的 STREAM 内核一样高的带宽。
-
脉动阵列的时序。 证明输出驻留的 N × N 阵列需要 3N − 2 个周期,权重驻留的阵列在装载之后需要 M + 2N − 2 个周期。
解答
周期从 0 计起。输出驻留:A 的第 i 行晚 i 个周期从西边进入,所以 A_ik 在周期 i + k 位于第 0 列,每周期向东移一格,在 i + j + k 到达第 j 列;B 的第 j 列晚 j 个周期从北边进入,所以 B_kj 也在 i + j + k 到达第 i 行。因此每个乘积 A_ik B_kj 恰好形成一次, 在单元 (i, j)、周期 t = i + j + k。第一个在 t = 0,最后一个(i = j = k = N − 1)在 t = 3N − 3,所以一次乘法需要 0, …, 3N − 3 这 3N − 2 个周期;单元 (i, j) 从 i + j 起忙 N 个周期。权重驻留:装载时每周期把 W 的一行送入各列顶端,最后一行最先,所以移位 N 次后 W 的 第 k 行停在阵列的第 k 行。之后 X_rk 在周期 r + k 进入第 k 行,每周期向东一格,在 r + k + j 到达单元 (k, j),在那里乘以 W_kj,并加上 从单元 (k − 1, j) 传下来的部分和;那个部分和在 r + (k − 1) + j 形成、再下移一行,时间正好对上,于是 Y_rj 沿第 j 列向下累加,在周期 r + (N − 1) + j 离开最底行。最后一个输出(r = M − 1,j = N − 1)在 M + 2N − 3 离开,所以输入流需要 M + 2N − 2 个周期。乘加次数除以 单元数 × 周期数,得到 N/(3N − 2) → 1/3 和 M/(M + 3N − 2) → 1,与门级模拟完全一致(N = 4 时 10 个周期;M = 6 时 4 + 12)。
-
累加器的宽度。 长度为 K 的 int8 点积累加到 32 位中。K 最大是多少,和才不可能溢出?
解答
32 位补码累加器能表示 [−2³¹, 2³¹ − 1]。按第 5 章的对称量化,整数落在 [−127, 127],所以每个乘积 |q r| ≤ 127² = 16,129, K 个乘积之和的绝对值至多 16,129 K。只要 K ≤ 133,144,它就不超过 2³¹ − 1 = 2,147,483,647;K = 133,145 时,取极值的输入就可能溢出。 若允许 −128,最大乘积为 (−128)² = 2¹⁴,由 K · 2¹⁴ ≤ 2³¹ − 1 得 K ≤ 2¹⁷ − 1 = 131,071(最负的乘积 −128 · 127 允许 K ≤ 132,104, 所以起约束作用的是正的一侧)。两种情形下 K 都可以到约 2¹⁷,是 TPU 每列 256 项的五百多倍;第 5 章实测的 256 × 256 乘积中最大的和只有 56,572,因为随机的项会互相抵消。
-
批大小。 解码一个词元要把每个权重读一遍。求批大小多大时,具有第十二章屋顶线的芯片转为受算力限制。
解答
参数量为 P、权重为 16 位的模型,每个解码步读 2P 字节,无论这一步由多少个序列共享。批中有 B 个序列时,每读一个权重就服务 B 次乘加,共 2PB 次浮点运算,所以算术强度约为每字节 B 次。第十二章的芯片拐点为 989/3.35 ≈ 295.2 次每字节,所以在 B ≈ 296 时转为受 算力限制;批大小为 1 时只能达到峰值的 3.35/989 ≈ 0.34%。权重为 8 位时字节数减半,所需的批也减半,约 148;4 位时约 74。这个算法没有 计入注意力对各序列键值缓存的读取:这份缓存只服务它自己的序列,无论批多大,它的算术强度都在 1 左右;上下文很长时,它会把总体强度压到 B 以下,使所需的批更大。
-
动手。 给词频计数单元加上线性探测,并测量它的门数、时钟,以及它不再丢失的词。
解答
解答要点。 先改功能模型:给
explainer/cs/hw/accel.py中的table_model加一个 w 个槽位的探测窗口 i, i + 1, …, i + w − 1 (mod 2^k),窗口中第一个存着该词标签或为空的槽位胜出;若 w 个槽位都被别的标签占着,这个词就丢失,记入溢出寄存器。用单元自己的哈希在 三十部小说上运行,这个模型在 2²⁰ 个表项时,w = 2 丢 133 个不同的词(1,223 次出现),w = 4 丢 4 个词(35 次出现),而直接映射丢 1,581 个(18,362 次);不设上限的探测一个也不丢,最多只需 9 次探测。在 2¹⁶ 个表项(88% 已占用)时,不设上限的探测仍然不丢词,但最多要探测 1,832 次,而 w = 4 丢 7,984 个词。要保持每周期一个字节,就并行地读整个窗口:按下标的低位把表交错分成 w 个存储体,使 w 个相邻槽位落在 不同的存储体里、在同一次访问中读出;给count_stage配 w 个标签比较器(每个是 32 个 XNOR 门和一棵 31 个 AND 门的树,与现有的那个 一样)、一个挑出第一个命中或第一个空槽的优先编码器,以及计数值和存储体的 w 选 1 多路选择器;单元的写端口除了下标还要接收存储体号。 用timing测量新的一级(门数取自c.size(),深度取自c.depth()):比较器并行工作,所以周期只因编码器和多路选择器增加几个门延迟, 相对 1 ns 的读表时间很小。另一种做法是每周期探测一次、同时让输入停顿:门更少,但需要一个单元现在没有的就绪信号,并且在最坏情况下放弃 每周期一个字节。照仪器检查现有单元的方式来检查它:扩展run,把每条通道的表与探测模型比较,保持accounted(计入加丢失等于词数), 让通道之间的合并也做探测,并在tests/test_cs60_hw.py中test_collisions_reported旁边加上测试。相邻两个词的结束仍至少相隔两个周期, 所以读表永远不会读到过时的表项。 -
★ 研究。 在由小存储组成的网格上做矩阵乘法所需的最少数据搬运,并给出相匹配的数据流。
讨论。 按题目的提法尚未解决。Hong 与 Kung 的红蓝卵石游戏(1981)给出了:经典 n³ 矩阵乘法的任何计算顺序,在 M 个字的快速存储与慢速 存储之间必须搬运 Θ(n³/√M) 个字;Irony、Toledo 与 Tiskin(2004)证明了并行版本:P 个处理器中必有一个要通信 Ω(n³/(P√M)) 个字; 二维环面上的 Cannon 算法和 Solomonik 与 Demmel(2011)的 2.5D 算法在常数因子内达到这类下界。这些模型对一个字只计一次,不管它走多远。 在脉动网格上,代价是字数乘以它在相邻单元之间走过的跳数,输入只能从边缘进入;n > N 时乘法必须分块穿过网格,于是边缘带宽和网格外存储的 流量也要计入。第 3 章的网格每个单元 M = O(1) 个字,每次乘加 Θ(1) 跳;单元若保留 C 的一个 √M × √M 块,可以把它降到约 1/√M。好的部分 结果应当先固定模型(N × N 网格,每单元 M 个字,边缘输入输出,代价按字·跳计),对 n = N 证明一个带常数的总跳数下界,并给出达到它的数据流; 然后推广到 n > N,那时还要说明:在计入距离的情况下,像 2.5D 算法那样复制数据是否划算。
Build the film
python -m videos.cs.cs60.compute # the part's numbers, into .cache/cs60
python tools/build.py cs60 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs60 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs60. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs60.compute
python -m unittest tests.test_cs60_hw
python tools/build.py cs60