AAI, Built

Act III · The Transformer Era

Part 17 of 31

Silicon

why AI runs on GPUs

Undergraduatestarts at this level54 min of film16 chaptersprerequisites: Part 3, Part 10

Why does AI run on graphics processors, and what limits how fast they can go?

The part opens with a count: Llama 3.1's training run on 16,384 H100s used about eighty million times the arithmetic of AlexNet's two gaming cards, almost all of it matrix products. It starts where clocks stopped: Dennard scaling ends when the voltage can fall no further, power grows like the cube of the clock, and the only way left to use transistors is in parallel. The GPU, built to run one small program on millions of pixels, becomes that parallel machine through CUDA, warps of 32 threads and latency hidden by keeping many loads in flight, and AlexNet shows what it is for. The part then turns from history to arithmetic: a matrix product costs 2mnk operations but needs each number fetched only once, tiling earns that reuse, and the roofline says any program runs at most at the smaller of the chip's peak and its memory bandwidth times the operations per byte. The computer rendering the film is measured against its own roofline. Systolic arrays and tensor cores build the reuse into the wiring, smaller number formats raise the peak, and the alpha-beta model prices the links between chips, where a ring all-reduce meets the bandwidth bound. It ends with kernels and Triton, the trends in FLOPs, dollars and watts, chips beyond the GPU, and the racks of late 2026.

What you need. School physics (power, voltage) and matrix multiplication; no computer architecture is assumed.

Mathematics and history
GPUs and SIMT, tiling and arithmetic intensity, the roofline, systolic arrays, number formats, interconnects
Models, data
the machine rendering the video

What you will be able to do

Undergraduate

  • Explain why clock speeds stopped rising in the early 2000s and why that made parallel chips the way forward.
  • Count the operations of a matrix product, and say what a GPU spends its transistors on that a CPU does not.

Master's

  • Derive the arithmetic intensity of a matrix product and of its tiled form, and place a workload on a chip's roofline.
  • Derive the time of a ring and of a tree all-reduce in the alpha-beta model, and find where they cross.
  • Compute a floating-point format's unit roundoff and largest finite number from its bit layout.

Research

  • State Hong and Kung's lower bound on the traffic of a matrix product and the bandwidth lower bound for all-reduce, and say which algorithms meet them.
  • Explain why the ridge of the roofline keeps moving right, and what that asks of future kernels and number formats.

Engineering

  • Read a datasheet's peak, bandwidth and link speed, compute the ridge, and decide whether a matrix-vector or a matrix-matrix workload can reach the roof.
  • Estimate a kernel's occupancy from its registers per thread, and say when fewer warps doing more work per load are faster.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Undergraduate 22 min · Master's 51 min · Research 54 min · Engineering 33 min.

  1. 0Eighty million times the arithmeticUndergraduate2 min
  2. 1The power wallUndergraduate4 min
  3. 2From pixels to GPGPUUndergraduate4 min
  4. 3Warps, divergence and latencyMaster's3 min
  5. 4AlexNet: the momentUndergraduate3 min
  6. 5Matrix multiply is the workloadUndergraduate4 min
  7. 6The memory hierarchyUndergraduate3 min
  8. 7The rooflineMaster's4 min
  9. 8Tensor cores and systolic arraysMaster's4 min
  10. 9Number formats in hardwareMaster's4 min
  11. 10Interconnect and collectivesMaster's4 min
  12. 11Writing a kernelEngineering4 min
  13. 12FLOPs, dollars and wattsEngineering3 min
  14. 13Beyond the GPUEngineering4 min
  15. 14The frontier, late 2026Research3 min
  16. Recap, problems, and what comes nextAll tracks2 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.

Eighty million times the arithmeticUndergraduate2 min

In 2012, the neural network that started the deep learning boom, AlexNet, was trained in five to six days on two graphics cards made for video games. Twelve years later Meta trained Llama 3.1, a language model of 405 billion parameters, on 16,384 of NVIDIA's H100 GPUs: here they are, one square each. By Epoch AI's count, that run used about 81 million times as many floating-point operations as AlexNet. Almost all of them were multiplications and additions of matrices.

The computer making this video reports its processor as Intel Xeon Processor. We measured how fast one of its cores multiplies matrices: at best, about 102 billion operations a second. At that speed, AlexNet's training would take about 53 days. Llama 3.1's would take about 12 million years.

That gap is the subject of this part. Why does AI run on graphics processors, and what would a chip built for it look like? We'll follow the hardware from the moment clock speeds stopped rising, through the GPU, CUDA and AlexNet, to the arithmetic of matrix products and the roofline that bounds them, Google's TPU, numbers four bits wide, and machines the size of a room that act as one computer. And wherever we can, we'll measure it on the computer making this video.

This is Part 17 of AI, Built, in the third act, the transformer era. In this part: why clocks stopped getting faster; how graphics chips became the engines of AI; why matrix multiplication is the workload, and what bounds its speed, from the memory hierarchy to the roofline; systolic arrays and the number formats in the hardware; how chips talk to each other; how a fast kernel is written; and where the hardware stands now.

1The power wallUndergraduate4 min

In 1965 Gordon Moore, then at Fairchild Semiconductor, noticed that the number of components on a chip had been doubling every year, and guessed it would keep going. Here are fifty years of microprocessors, on a log scale: from Intel's 4004 in 1971, with about 2,300 transistors, to chips with 58 billion. A straight line on a log scale is exponential growth. The fit doubles every 2.0 years, the pace Moore settled on in 1975. For three decades, each doubling also made every program faster, for free.

Why did shrinking make computers faster? The answer came in 1974 from Robert Dennard and his colleagues at IBM, the engineer who had invented the one-transistor memory cell. Shrink every length of a transistor by a factor kappa, and lower the voltage by the same factor. The capacitance it has to charge falls by kappa, and it switches kappa times faster. The power to switch it is C V squared f, which falls by kappa squared. But kappa squared more transistors now fit in the same area. So the power per square millimetre stays the same, while the clock gets faster and the count goes up. That's Dennard scaling, and for thirty years it was the free lunch.

Then, in the early two thousands, the voltage stopped falling. A transistor is a switch, and below a certain voltage it can't switch off cleanly: at room temperature the current falls at most tenfold for every sixty millivolts, so a lower voltage means leakage. With the voltage stuck, each smaller transistor uses as much power as the old one, and packing kappa squared more of them into the same area multiplies the heat by kappa squared. In 2004 Intel cancelled the successor to the Pentium 4 and turned to two cores per chip. A year later the programmer Herb Sutter wrote that the free lunch was over.

You can see the wall in the data. Clock speed doubled every years from 1985 to 2003, and stopped near gigahertz; . Power had been climbing with it, and it levelled off at what a fan and a heat sink can carry away, around a hundred watts. Single-thread speed, what one program gets, doubled every years until then; since 2010, every . What kept growing was the number of cores. The transistors kept coming; the only way left to use them was in parallel.

Why does parallel win? Switching power is C V squared f, and to run a clock faster you have to raise the voltage roughly in proportion. So power grows like the cube of the clock. To do twice the work, one core at twice the clock burns about eight times the power. Two cores at the same clock burn twice the power. The catch is Amdahl's law, from 1967: the part of a program that can't be split limits the speed-up, however many cores you add. So the winning chip for a problem that splits into millions of identical pieces has thousands of slow, simple lanes. That chip already existed. It drew video games.

2From pixels to GPGPUUndergraduate4 min

Think about what a graphics card does. Every pixel on the screen runs the same small program, a shader, on its own coordinates, and no pixel needs to know about any other. A 1080p screen is about two million pixels, sixty times a second: over a hundred million runs of the same program every second, all independent. In 1999 NVIDIA sold the GeForce 256 as the world's first GPU, a graphics processing unit, and in 2001 its shaders became programmable. It was a chip built for doing one thing an enormous number of times.

A CPU and a GPU spend their transistors differently. A CPU spends them on making one stream of instructions fast: large caches, so data is close; branch predictors that guess which way the program will go; machinery to run instructions out of order. A GPU spends them on arithmetic: many small processors, NVIDIA calls them streaming multiprocessors, each a block of simple lanes. The computer making this video has 4 cores, each with vector units 16 numbers wide. An H100 has 132 streaming multiprocessors with 128 lanes each: almost seventeen thousand. Each lane is slow and simple. There are just a great many of them.

Simple lanes are the easy part. The hard part is feeding them, because memory is far away. There's a law from queueing theory, John Little's, from 1961: the number of things in a system equals the rate they arrive times how long each one stays. For memory, it says: to keep a memory busy, the bytes you have asked for but not yet received must equal the bandwidth times the latency. Researchers measured a Hopper GPU's memory at about 270 nanoseconds away. At two terabytes a second, it needs about 560 kilobytes on the way at every moment: thousands of requests. One core of this computer, measured, needs only about 48 cache lines on the way, and it gets them from prefetchers that guess the next addresses of a long, regular read. A GPU gets its thousands the other way: from thousands of threads, each waiting on its own load.

Researchers noticed. In the early two thousands they disguised arithmetic as graphics: store an array as a texture, write the computation as a pixel shader, and read the answer back from the screen. Ian Buck's Brook language at Stanford, in 2004, made that bearable. The same year, Kyoung-Su Oh and Keechul Jung ran a neural network on a graphics card, twenty times faster than on the CPU. Buck went to NVIDIA, and with John Nickolls built CUDA: plain C, plus a way to launch a function on thousands of threads at once. It was announced with the GeForce 8800 in November 2006 and released in 2007. By 2009 Rajat Raina, Anand Madhavan and Andrew Ng at Stanford trained deep networks on a GPU up to seventy times faster than on a CPU. The pieces of the next decade were on the table.

3Warps, divergence and latencyMaster's3 min

Here is a CUDA program. The function, a kernel, says what one thread does: work out which element is mine from my block number and my thread number, and update that element. The launch asks for enough blocks of 256 threads to cover the array: for a million elements, about four thousand blocks. The hardware hands blocks to streaming multiprocessors, and splits each block into warps of thirty-two threads. The thirty-two threads of a warp execute the same instruction at the same moment, each on its own data. NVIDIA calls it SIMT, single instruction, multiple threads: a vector machine that you program one thread at a time.

Lockstep has a price. Suppose the threads of a warp reach an if, and some take it and some don't. The warp can only issue one instruction at a time, so it runs the if-branch with the other threads masked off, then the else-branch with the first group masked off. Both paths cost the whole warp. That's divergence. We simulated a branch on data across four thousand warps.

Now the reason for all those threads. A load from memory takes hundreds of cycles; while a warp waits, the scheduler issues instructions from another warp that's ready. We simulated one scheduler with memory 479 cycles away, the latency measured on a Hopper GPU. If each warp does only four operations per load, even sixteen warps keep it busy just 17 percent of the time. With sixty-four operations per load, 9 warps are enough. The lines are Little's law: you need the latency plus the work, divided by the work, warps in flight. An H100's multiprocessor has four schedulers and room for sixty-four warps. Past that, the only way to hide latency is more arithmetic per byte, an idea that comes back in chapter five.

One more rule of the road. On modern CUDA GPUs, memory requests use thirty-two-byte sectors. The thirty-two threads here each read one four-byte number. Aligned neighbouring addresses need four transactions: the loads are coalesced. Scattered across thirty-two sectors, the same thirty-two numbers need thirty-two transactions, wasting most of each sector. It's the same lesson as a CPU's cache lines, and it will matter for matrices: walk them along the rows.

4AlexNet: the momentUndergraduate3 min

By 2012 the ingredients were in place. In 2009 Fei-Fei Li's group had published ImageNet, millions of labelled photographs, and from 2010 there was a yearly contest: a model sees an image and names it, out of a thousand classes, with five guesses. In 2012 a network from Geoffrey Hinton's lab in Toronto, built by Alex Krizhevsky and Ilya Sutskever, missed on 15.3 percent of the test images. The next best entry missed on 26.2 percent. Nobody had seen a gap like that.

What made it possible was two gaming graphics cards. The network had sixty million parameters, and one GeForce GTX 580, with three gigabytes of memory, couldn't hold it while training. So Krizhevsky split it: half the filters of each layer on one card, half on the other. The two halves exchange their results only at a few layers, to keep the traffic between the cards small. He wrote the convolutions himself, in CUDA, in a library called cuda-convnet. Training took five to six days, for ninety passes over the 1.2 million images.

How much arithmetic was that? About 1.2 million images, times ninety passes, times three quarters of a billion multiply-adds per image, times two operations each, times three, for the backward pass: about times ten to the seventeen floating-point operations; the published estimate is 4.7. The two cards could do about times ten to the eighteen in five and a half days, so the network kept them about percent busy. On the computer rendering this video, at the best speed we measured, one core would take about days

After 2012 the field moved onto GPUs. In 2014 NVIDIA released cuDNN, a library of deep-learning kernels, so researchers no longer had to write their own. In 2016 it built a server around eight GPUs, the DGX-1, and Jensen Huang delivered the first one to OpenAI himself. In 2018 Dario Amodei and Danny Hernandez measured the trend: from AlexNet on, the compute in the largest training runs had doubled every 3.4 months, three hundred thousand times in six years. And in 2020 Sara Hooker gave the history a name: the hardware lottery. Ideas succeed when they suit the hardware of their day, and neural networks, all multiply-adds, had drawn a winning ticket, made for video games.

5Matrix multiply is the workloadUndergraduate4 min

Why are GPUs so good for neural networks in particular? Because almost all of a network's arithmetic is one operation. Take GPT-3. For every token, each of its 175 billion weights is used in one multiply and one add: two operations per weight, all of them in matrix products. Attention's own products, queries against keys, add 1.4 percent. Everything else, the normalizations, the activations, the softmax, is a rounding error, even counted generously. Training does the forward pass and a backward pass twice as expensive: six operations per weight per token. Six times 175 billion parameters times 300 billion tokens gives GPT-3's published compute, to within a fraction of a percent. To make AI faster, make matrix multiplication faster.

So let's count. Each entry of C is a row of A dotted with a column of B. With K terms, that's K multiplies and K minus one adds: about 2K operations. There are M times N entries, so the whole product costs 2MNK floating-point operations. For square matrices of size n: 2 n cubed. Double the size, eight times the work.

The arithmetic is only half the cost. The numbers have to come from memory. The ratio of operations to bytes moved is called the arithmetic intensity. Done naively, every multiply-add fetches its two numbers, four bytes each in single precision: two operations for eight bytes, a quarter of an operation per byte. But the whole product only needs A and B read once and C written once: three n squared numbers for 2 n cubed operations. The intensity grows like n over six. For n of a thousand and twenty-four, that's about 170 operations per byte. Each number is used a thousand times. The whole game is to use it a thousand times while it's close by, instead of fetching it a thousand times.

That's what tiling does. Cut C into b by b tiles. To compute one tile, walk along a strip of A and a strip of B, one b by b tile of each at a time. Bring the two tiles into fast memory, multiply them, add into the tile of C, and move on. Every number brought in is used b times, so the intensity is b over four bytes. The limit is the fast memory: three tiles have to fit. Bigger fast memory, bigger tiles, more reuse. In 1981 Hong Jia-Wei and H. T. Kung proved that no schedule can do much better: any way of computing the product moves at least on the order of n cubed over the square root of the fast memory's size.

We measured this on one core of this computer, multiplying two matrices of size 1,024 The textbook triple loop: billion operations a second. It walks down the columns of B, one cache line per number. The same arithmetic with the loops reordered, so every inner loop walks along rows: . Tiled: , times the textbook loop. The best tile size was : . And the BLAS library numpy calls, tuned by experts, with tiles inside tiles and hand-written vector code: , times the textbook loop, for exactly the same arithmetic.

6The memory hierarchyUndergraduate3 min

A GPU's memory is not one thing. Let's zoom in on an H100. Around the chip sit stacks of high-bandwidth memory, DRAM dies piled on top of each other: 80 gigabytes, read at 3.35 terabytes a second, but hundreds of cycles away. On the chip itself, a level-two cache of fifty megabytes, shared by all 132 streaming multiprocessors, about half as far. Inside each multiprocessor: a combined L1 and shared-memory pool of 256 kibibytes, of which up to 228 can be shared memory that the programmer fills on purpose; and the registers, another 256 kibibytes, right next to the arithmetic, read every cycle. Each step down is smaller and closer, and much faster to read.

That memory is a feat of its own. High-bandwidth memory stacks DRAM dies on top of each other, wired straight through the silicon, and sets the stack right beside the GPU on a slab of silicon with thousands of short wires: far more of them than a circuit board could carry. AMD first used it in a graphics card in 2015. Since the P100, the memory per GPU has grown from 16 gigabytes to 288 for Rubin, and its bandwidth from 0.73 terabytes a second to 19.2: about 26 times in ten years. It's the most expensive part of the package, and, as we'll see, the scarcest resource.

We can see the same hierarchy on this computer's own processor, by timing it. On the left, one core reads an array over and over and adds it up; the array grows from four kilobytes to 256 megabytes. While it fits in the first-level cache, about gigabytes a second. Past that, from the second level, about . From main memory, about . In the first-level cache, a read takes about nanoseconds; in the second, about ; in main memory, about . The dashed lines are the cache sizes the processor reports.

Why build it this way? Distance costs energy. Mark Horowitz tabulated what each operation costs on a 45-nanometre chip. Adding two 32-bit numbers: a tenth of a picojoule. Multiplying two floats: 3.7. Reading 32 bits from a small on-chip memory: about five. Reading them from DRAM: 640, as much as about 173 multiplies. The arithmetic is cheap; moving the numbers is what costs. The newer chips change the numbers, not the ratio's lesson: every byte fetched from far away has to be used many times.

7The rooflineMaster's4 min

Chapters two to six give a program two ways to be slow. If it does W operations on a machine whose peak is P operations a second, it takes at least W over P. If it moves Q bytes through a memory of bandwidth beta, it takes at least Q over beta. It can't beat either, so its speed, W over T, is at most the smaller of P and beta times W over Q. W over Q is the arithmetic intensity, I: operations per byte. So the speed is at most the minimum of P and beta times I. In 2009 Samuel Williams, Andrew Waterman and David Patterson at Berkeley drew this as a picture, and called it the roofline.

Here is the roofline of one core of this computer, measured. The sloped part: the memory bandwidth, 18 gigabytes a second, the fastest we measured one core stream through main memory. A program on the slope is waiting for memory; the classic test, STREAM's triad, sits on or under it. The flat part: the fastest arithmetic we measured, 102 billion operations a second. They meet at the ridge, 5.5 operations per byte. A matrix times a vector does two operations per four-byte weight, and every weight is used once: it can't leave the slope. We measured at most 7.1 billion a second. A matrix times a matrix has intensity n over six. Watch it climb as n grows: at n of 32, overheads dominate and it manages 29; by 4096, it reaches 102, the roof.

Intensity is a property of the algorithm, but it only counts if the code earns it. All four matrix products of chapter five have the same intensity on paper, n over six, about operations per byte. The textbook loop sits far below the roof, because it fetches its numbers over and over: its real intensity is far lower. Reordering and tiling climb towards the roof, and the library reaches it: times higher, on the same line. The roofline says what's possible; the gap below it is the kernel writer's job.

Now put a GPU on the same axes. Our core's roofline is down in the corner. An H100's tensor cores do about 989 trillion operations a second in 16-bit arithmetic, and its memory moves 3.35 terabytes a second. Its ridge is at about 295 operations per byte. In 16-bit numbers, a square matrix product reaches it once n is about 890. Now the problem that Part 19 is about. A language model writing one token at a time multiplies every weight once: about one operation per byte. That's down on the slope, at 0.3 percent of the peak. Google's TPU paper of 2017 used exactly this picture. Their chip's ridge was at 1,350 operations per byte, a K80 GPU's at 9. Whether a chip is fast depends on where your program sits.

8Tensor cores and systolic arraysMaster's4 min

There's an older idea that suits matrix products even better than a GPU's lanes. In 1978 H. T. Kung and Charles Leiserson at Carnegie Mellon proposed systolic arrays: a grid of simple cells, each connected only to its neighbours, with data pulsing through in rhythm, like blood through the heart. A number read from memory enters at the edge and is used by every cell it passes, so the memory is read once while the arithmetic happens many times. In 1982 Kung explained why it matters: for problems like matrix products, the operations per memory access can grow without asking for more bandwidth. The roofline's intensity, built into the wiring.

Here's one computing a product, cycle by cycle, simulated. A four by four grid of cells, each holding a running sum. The rows of A come in from the left, the columns of B from the top, each one staggered a cycle behind the last. Every cycle, each cell multiplies the two numbers passing through it, adds the product to its sum, and hands the A number to the right and the B number down. Watch the active cells: a diagonal front sweeps across the grid. After cycles every cell holds one entry of C.

Why does it work? Because of the stagger, cell i, j meets a i k and b k j at cycle i plus j plus k: exactly the terms of its entry, each once. The last term reaches the far corner at cycle two n minus two plus K minus one, so the product takes K plus two n minus two cycles: ten for our example. And each number is read from memory once and used by n cells, so the memory traffic per operation falls like one over n. A bigger array is a bigger tile, with no cache needed: the reuse is in the wires.

In 2013 Google projected that if people used voice search for three minutes a day, the speech recognition networks alone would need twice its data centres. It built a chip instead, in fifteen months. The Tensor Processing Unit is a systolic array of 256 by 256 eight-bit multiply-adders, running at 700 megahertz: about 92 trillion operations a second. It was in Google's data centres from 2015, and it ran AlphaGo in its match against Lee Sedol. On Google's own workloads it was fifteen to thirty times faster than the CPU and GPU next to it, and thirty to eighty times better per watt. The price of a big fixed grid: work comes in whole tiles. A layer of 257 by 257 weights fills four tiles and uses a quarter of the cells. Shapes that are multiples of the array's size are the ones that run at full speed, on TPUs and GPUs alike.

GPUs took the hint in 2017. NVIDIA's Volta added tensor cores: units that take two four by four matrices and add their product to a third, all in one clock. Sixty-four multiply-adds per instruction, instead of one. A V100 has 640 of them, which gives its 125 trillion operations a second in half precision, eight times its ordinary lanes. Every generation since has made the tensor cores bigger and their numbers smaller: TF32 and bfloat16 in the A100, eight-bit floats in the H100, four-bit in Blackwell and in Rubin. The GPU is still a GPU, but most of its arithmetic now happens in small systolic engines inside it.

9Number formats in hardwareMaster's4 min

A floating-point number is a sign, an exponent and a mantissa: scientific notation in base two. Here is pi, rounded into each format the hardware of this part supports. FP32, the IEEE standard of 1985: eight exponent bits, twenty-three mantissa bits, about seven decimal digits. TF32 and bfloat16 keep FP32's eight-bit exponent, so the same range, but cut the mantissa to ten bits and to seven. FP16 trades the other way: five exponent bits, ten of mantissa. Then eight bits in two flavours, four exponent bits and three of mantissa, or five and two. And four bits: two of exponent, one of mantissa. Pi becomes three.

Two numbers describe a format. With M mantissa bits, each power of two is cut into two to the M equal steps. Rounding to the nearest value is off by at most half a step. For normal values without overflow, the relative error is at most two to the negative of the quantity M plus one, the unit roundoff. That's precision. The exponent bits set the range: the largest number is just under two times two to the largest exponent. For E4M3 that's 448, because one bit pattern is kept to mean not-a-number. FP16 tops out at 65,504, which is why training in FP16 needs care, and bfloat16, with FP32's exponent, doesn't.

Let's measure it. Round a million Gaussian samples into each format and compare. Each step down in mantissa bits multiplies the error. FP32 is off by a few parts in a hundred million, bfloat16 by about 0.17 percent, eight-bit E4M3 by about 2.6 percent, and four bits by 14 percent. The white dots are the prediction: if the rounding error is spread evenly over a step, and values are spread evenly in the logarithm, the root-mean-square relative error is two to the minus M times a constant, the square root of log two over eighteen, about a fifth. The prediction ignores the very small and very large numbers, and the measurements land on it. Four bits miss it most: there, many samples fall below the smallest step.

Four bits have so little range that one scale for a whole matrix doesn't work: a few large values push everything else into the bottom step. The fix, standardized in 2023 by the Open Compute Project, is microscaling: give each block of thirty-two numbers its own shared exponent. We rounded each way. Part 19 uses these formats to run a real model in four bits.

Why go small at all? Because the multiplier's size grows roughly with the square of the mantissa's width, and every bit not moved is bandwidth saved. Halve the bits and the tensor cores do twice the work: an H100 does trillion operations a second in bfloat16 and in FP8; a Blackwell GPU doubles again in four bits. But only on hardware built for it. The history: Kahan's IEEE standard in 1985; bfloat16 from Google Brain for the TPU; eight-bit floats proposed by NVIDIA, Arm and Intel in 2022; microscaling in 2023. Part 18 trains in eight bits; Part 19 serves in four.

10Interconnect and collectivesMaster's4 min

A frontier model doesn't fit on one chip. Llama 3.1's 405 billion parameters take 810 gigabytes in sixteen-bit numbers; training, with gradients and the optimizer's state, needs about sixteen bytes per parameter, some 6.5 terabytes. An H100 holds eighty gigabytes, so at least 81 of them just to hold it, and Meta trained it on 16,384. So the chips have to talk, and every step away is slower. Inside the GPU, its memory: 3.35 terabytes a second. Between GPUs in one server, NVLink: 900 gigabytes a second. Between servers, an InfiniBand network: about a hundred. Each step costs about a factor of ten.

NVIDIA built its own links. NVLink arrived with the P100 in 2016, 160 gigabytes a second per GPU; each generation since has roughly doubled it, to three terabytes a second for Rubin in 2026. Links need a shape. A switch connects everything to everything: NVIDIA's NVL72 racks put seventy-two GPUs on one NVLink fabric, 130 terabytes a second in all, 216 in the Rubin generation. Between racks, a fat tree, Charles Leiserson's design of 1985: more links higher up, so the top isn't a bottleneck. Google wires its TPUs in a three-dimensional torus, each chip linked to its six neighbours, and since TPU v4 reconfigures it with optical switches, 4,096 chips at a time.

To reason about communication, use the simplest model that works. Sending a message of n bytes costs a fixed alpha, the latency, plus n over beta, the bandwidth. We measured it between two processes on this computer, passing messages from eight bytes to thirty-two megabytes. The fit: alpha about 14 microseconds, beta about 3.3 gigabytes a second. Below alpha times beta, about 50 kilobytes here, a message costs the same whatever its size; above it, bandwidth is everything. On a GPU cluster the numbers change, microseconds and hundreds of gigabytes a second, but the shape doesn't.

Training on many GPUs means, every step, adding up everyone's gradients so that all of them get the total: an all-reduce. The ring algorithm splits each GPU's data into p chunks. In each step, every GPU sends one chunk to its neighbour and adds the chunk it receives to its own. After p minus one steps, each GPU holds one chunk of the full sum. Then p minus one more steps pass the finished chunks around, until every GPU has all of them. Each step sends n over p bytes, so the total time is two times p minus one alphas, plus two times p minus one over p, times n over beta. The bandwidth term never exceeds two n over beta, however many GPUs there are, and no algorithm can do better on it. Part 18 builds data parallelism on this.

There's another way: a tree. Add pairs, then pairs of pairs, up to one GPU, and send the total back down. That's two log p steps instead of two p, but each step sends the whole message. Here are both, in units of the latency, for eight, sixty-four and 512 GPUs. For small messages the tree wins: fewer steps. For large ones the ring wins: less data per step. With 512 GPUs the crossover is near alpha beta. With a few microseconds of latency and NVLink's bandwidth, alpha beta is a few megabytes, and gradients are gigabytes: rings for bulk data, trees for latency, and libraries like NVIDIA's NCCL choose for you.

11Writing a kernelEngineering4 min

Here is chapter five's tiling, written for a GPU, the way textbooks teach it. Each block of threads computes one T by T tile of C, one thread per entry. The block declares two tiles of shared memory, the programmer-managed SRAM of chapter six. In each round, every thread copies one number of A and one of B from global memory into the shared tiles: neighbouring threads, neighbouring addresses, coalesced. The threads wait for each other, then each does T multiply-adds out of shared memory, and waits again before the tiles are overwritten. Every number fetched from global memory is used T times: the intensity is T over four. With tiles of thirty-two, that's eight operations per byte, still below an H100's ridge. Real kernels go further: each thread keeps a small tile of its own in registers, and the multiply-adds go to the tensor cores.

How many threads can share a multiprocessor? Chapter three said: as many as it takes to hide memory's latency. But they share its registers and its shared memory. An H100's multiprocessor has 65,536 registers. A kernel whose threads each need R registers can keep at most 65,536 over thirty-two R warps resident, and never more than sixty-four. The fraction is called occupancy. It falls in steps as each thread grows. Our tile kernel, small and simple, runs at 100 percent. A kernel with big register tiles, the kind that feeds tensor cores, at 25. And that can be faster: in 2010 Vasily Volkov showed that fewer threads, each doing more work from its registers, often beat full occupancy. It's chapter three's trade again: hide latency with threads, or with more arithmetic per load.

Writing kernels like that by hand is hard, and getting the last factor of two is harder. In 2019 Philippe Tillet, a graduate student at Harvard, published Triton with H. T. Kung, the Kung of the systolic arrays, and David Cox. You write Python, and you program a block of the output, not a thread. Load a tile of A, a tile of B, multiply them with one dot, accumulate, move on: the tiling of chapter five, in eleven lines. The compiler decides how the threads share the work, stages the tiles through shared memory, coalesces the loads and uses the tensor cores. OpenAI released it in 2021, and PyTorch's compiler now writes Triton kernels itself. NVIDIA's CUTLASS library and JAX's Pallas play the same role in C plus plus and in JAX.

The model example of thinking this way is FlashAttention. Attention computes a score for every pair of positions: a T by T table. The standard implementation writes that table out to high-bandwidth memory, then reads it back for the softmax, then again to weight the values. For long inputs that traffic dominates, while the tensor cores wait. In 2022 Tri Dao and colleagues at Stanford computed attention tile by tile instead, keeping each tile in on-chip SRAM, with a running maximum and sum so the softmax comes out exact. The table is never written out at all. They proved its memory traffic is T squared d squared over M, M the SRAM size: less than the standard version's whenever d squared is smaller than M, as it is in practice. The same arithmetic, faster, because it moves fewer bytes. Part 19 derives it.

12FLOPs, dollars and wattsEngineering3 min

How fast is all this improving? Here are the flagship accelerators of NVIDIA, Google, AMD and Amazon since 2017, from Epoch AI's database. Their sixteen-bit tensor arithmetic doubled every 1.8 years. Their memory bandwidth doubled every 2.6. Arithmetic is outrunning memory. Epoch's own study of forty-seven accelerators found the same, 2.3 years against four, and Amir Gholami and colleagues, looking back twenty years, called it the memory wall. So the ridge of the roofline keeps moving right: in this data the operations a chip can do per byte it reads doubled every 5.5 years. Each generation needs more reuse to stay busy.

Here's the ridge, generation by generation, from the datasheets. In sixteen-bit numbers it moved from about 139 operations per byte for a V100 to about 312 for a Blackwell GPU. But each generation also added a smaller format, and in its smallest format the ridge has climbed to about 1,823 for Rubin. Smaller numbers do double duty: twice the arithmetic per cycle, and half the bytes per number, which is what brings a workload back up to the ridge.

What about energy? Divide each chip's peak by its power: sixteen-bit operations per second per watt doubled every 2.9 years in this data; Epoch found three. The graphics card AlexNet trained on spent about 154 picojoules per floating-point operation. An H100 spends about 0.7: about 220 times less, partly by using fewer bits. Chapter six's lesson still holds, though: fetching the operands from memory costs more than the arithmetic. Price-performance, by Epoch's count, doubles about every two years.

And then there's the electricity. The International Energy Agency estimated that data centres used about 415 terawatt-hours in 2024, about one and a half percent of the world's electricity, and projected about 945 by 2030, with AI the main driver. Training Llama 3.1 took a cluster drawing an estimated twenty-odd megawatts. NVIDIA now describes its Rubin systems in units of a hundred-megawatt AI factory: forty thousand GPUs, about 2.5 kilowatts each once cooling and networking are counted. The constraint on building AI is increasingly the power line.

13Beyond the GPUEngineering4 min

The TPU was the first of many chips built only for neural networks. Google's line went from an eight-bit inference chip in 2015 to training: the TPU v2 in 2017 added high-bandwidth memory, bfloat16 and pods of chips wired together; v4 linked 4,096 of them through optical switches. The seventh generation, Ironwood, in 2025: 4,614 trillion eight-bit operations a second per chip, in pods of 9,216. And in April 2026 Google announced two eighth-generation chips, one for training and one for serving, with training superpods of 9,600 chips. Google trains its Gemini models on its own TPUs. Amazon builds Trainium, Microsoft Maia, Meta MTIA. Most are systolic arrays of some size, fed by high-bandwidth memory: the recipe of chapters six to eight.

Others changed the shape of the chip itself. Chips are cut from a silicon wafer thirty centimetres across. Cerebras doesn't cut it: the whole wafer is one chip. Its third version, from 2024, has four trillion transistors, nine hundred thousand cores, and forty-four gigabytes of SRAM spread among them, so a model's weights can sit next to the arithmetic instead of in memory chips off to the side. It's about fifty-seven times the area of an H100's die. The hard parts were the ones everyone said were impossible: defects on a wafer that size, which it routes around, and cooling and powering it.

Groq took the opposite bet from the GPU. Its founder, Jonathan Ross, had helped start the TPU project at Google. Groq's LPU has no high-bandwidth memory at all: the weights live in on-chip SRAM, and the compiler schedules every cycle in advance, so nothing waits on a cache. For writing one token at a time, the roofline's slope is everything, and SRAM is fast. In December 2025 NVIDIA licensed Groq's technology and hired its founders, and in March 2026 it described the result: a rack of 256 Groq 3 LPUs, each with about 156 terabytes a second of SRAM bandwidth, against 19.2 for a Rubin GPU's memory. The price is capacity: 500 megabytes per chip. A trillion-parameter model in four bits needs about 1,000 of them. So NVIDIA pairs them: GPUs read the long prompt and keep the attention; LPUs run the rest of each new token.

Two older dreams are still being chased. Analog computing in memory: store each weight as the conductance of a cell in a grid, apply the inputs as voltages on the rows, and by Ohm's law each cell's current is a product; by Kirchhoff's law the currents on a column add up. A whole matrix-vector product in one step, with no weights moved at all. In 2023 IBM ran speech recognition on a chip with thirty-five million such cells; the hard parts are noise and precision. And neuromorphic chips compute with spikes, like neurons, and only when something changes: IBM's TrueNorth in 2014, Intel's Loihi, and in 2024 Hala Point, with over a billion artificial neurons. Neither runs today's frontier models. Both are bets on chapter six's lesson: the cheapest data movement is none.

14The frontier, late 2026Research3 min

Where does all this stand at the end of 2026? NVIDIA's Blackwell, announced in March 2024, hit the limit of chipmaking: a die can't be larger than the area a lithography machine exposes at once. So Blackwell is two dies at that limit, joined by ten terabytes a second so they act as one GPU: 208 billion transistors, with tensor cores for four-bit numbers. The unit of sale became the rack. A GB200 NVL72 puts seventy-two of them on one NVLink fabric, liquid cooled, so that the rack behaves like one enormous GPU, and the 2025 Blackwell Ultra raised the memory to 288 gigabytes per GPU.

Its successor is in production now. A Vera Rubin NVL72 rack holds seventy-two Rubin GPUs and thirty-six of NVIDIA's own Arm CPUs. Each GPU has 288 gigabytes of the fourth generation of high-bandwidth memory, read at 19.2 terabytes a second, and does 35 quadrillion four-bit operations a second for training. The sixth NVLink moves 3 terabytes a second per GPU, 216 across the rack. NVIDIA now sells these by the hundred megawatts: forty thousand GPUs in one building. And note the ridge: about 1,823 operations per byte in four-bit arithmetic. Only work with enormous reuse can use all of it.

The unit of computing keeps growing. In 2022 the GPUs that shared a fast fabric were the eight in one server. With Blackwell, seventy-two in a rack. Google's torus pods were larger still: 4,096 TPU v4 chips, 9,216 Ironwood chips in 2025, and 9,600 in a TPU 8t superpod announced this year. Google says its new data-centre network can make a million of them work as one cluster. Part 18 is about what it takes to use machines like these for a single training run.

The newest trend is to split the work by where it sits on the roofline. Reading a prompt multiplies matrices by matrices: high intensity, arithmetic-bound. Writing the answer, one token at a time, multiplies matrices by vectors: low intensity, memory-bound. So NVIDIA pairs Rubin GPUs, and a variant for very long prompts, with Groq's SRAM chips for decoding; and Google's eighth generation is two chips, one for training and one for serving, with three times its predecessor's on-chip memory for the attention cache. The limits now are power, memory bandwidth and the links between chips, the three threads of this part.

Recap, problems, and what comes nextAll tracks2 min

Let's take stock. When the voltage stopped falling, clocks stopped rising, and the only way to use more transistors was in parallel. GPUs run thousands of threads in warps, and pay for divergence. Matrix multiplication is nearly all of a network's arithmetic, and tiling lets each number fetched be used many times. Memory is a hierarchy, small and close to large and far, and the roofline says whether a program is bound by arithmetic or by bytes. Systolic arrays build reuse into the wiring. Fewer bits buy throughput at a measured cost in error. And when one chip isn't enough, a ring all-reduce shares the work at nearly the bandwidth limit.

All of this comes back. Part 18 trains a model across many GPUs, with the alpha-beta model, the ring all-reduce and eight-bit arithmetic. Part 19 puts inference on the roofline: reading a prompt is arithmetic-bound, writing an answer is memory-bound, and FlashAttention and four-bit formats follow. Part 15's memory methods are sized to high-bandwidth memory and written to use the tensor cores, and Part 16's experts trade tokens across an NVLink domain, while the tensor cores' two-in-four sparsity doubles their arithmetic.

Here are six problems to try, from arithmetic intensity to the latency a GPU has to hide. Pause here, and work through them; full solutions are in this part's notes.

Next time: pretraining at scale. Where the trillions of tokens come from and how they're cleaned; how one model is cut across thousands of GPUs, by data, by tensor, by pipeline stage and by expert, with this part's all-reduce at the centre; how training in eight bits stays stable; and what goes wrong on a run of sixteen thousand GPUs.

Hennessy and Patterson's book is the place to go deeper on all of this, and Kirk and Hwu's on GPU programming. Thanks for watching, and see you in Part 18.

Where it goes next. Part 18 trains across many GPUs with the alpha-beta model, the ring all-reduce and eight-bit arithmetic. Part 19 puts inference on the roofline: reading a prompt is arithmetic-bound, writing an answer is memory-bound, and FlashAttention and the four-bit formats follow from that.

Key results

The part's results in one place, for revision.

Switching power\(\displaystyle P=CV^2f;\qquad\allowbreak \text{lengths }\allowbreak \text{and }V\text{ down }\allowbreak \text{by }\kappa\ \Rightarrow\ \text{power }\allowbreak \text{per }\allowbreak \text{area }\allowbreak \text{constant}\)
Arithmetic intensity of C = AB\(\displaystyle I=\frac{W}{Q}=\frac{2mnk}{s\,(mk+kn+mn)}\ \ \text{FLOP/byte}\)
Tiling, and Hong and Kung's bound\(\displaystyle Q\approx\frac{2n^3}{b},\ \ 3b^2\le M;\qquad\allowbreak Q=\Omega\Bigl(\frac{n^3}{\sqrt M}\Bigr)\)
The roofline\(\displaystyle \text{speed}\ \le\ \min\bigl(P,\ \beta I\bigr),\qquad\allowbreak \text{ridge}\ I^\ast=P/\beta\)
A systolic array\(\displaystyle \text{cell }(i,j)\text{ meets }a_{ik},b_{kj}\text{ at }\allowbreak \text{cycle }i+j+k;\quad\allowbreak T=K+2n-2\)
Ring all-reduce\(\displaystyle T_{\text{ring}}=2(p-1)\,\alpha+2\,\frac{p-1}{p}\,\frac{n}{\beta}\)

Try it

Lab 17 · Tiling, traffic and a systolic array

Multiply two 32 x 32 matrices behind a simulated fast memory that holds M numbers, count every number fetched by the untiled loop and by the tiled loop, and compare with 2n^3/b + n^2. Then pulse a product through a systolic array and check its answer, its K + 2n - 2 cycles and its n operations per number read.

Figure produced by Lab 17: Tiling, traffic and a systolic array
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.ai.labs 17 needs numpy, scipy, matplotlib · download lab17.py · source on GitHub
operations in the product, 2n^3             65,536
M =   16 numbers, tiles of  2               tiled fetches 33,792   2n^3/b + n^2 = 33,792   untiled loop 66,560   FLOPs per number 1.9
M =   64 numbers, tiles of  4               tiled fetches 17,408   2n^3/b + n^2 = 17,408   untiled loop 66,560   FLOPs per number 3.8
M =  256 numbers, tiles of  8               tiled fetches  9,216   2n^3/b + n^2 =  9,216   untiled loop 34,816   FLOPs per number 7.1
M = 1024 numbers, tiles of 16               tiled fetches  5,120   2n^3/b + n^2 =  5,120   untiled loop 34,816   FLOPs per number 12.8
slope of tiled traffic against M (log-log)  -0.500   (Hong and Kung: -1/2)
systolic 4 x 4, K = 4                       10 cycles (K + 2n - 2 = 10)   max error 2.2e-16   4 operations per number read (n = 4)
systolic 8 x 8, K = 16                      30 cycles (K + 2n - 2 = 30)   max error 1.8e-15   8 operations per number read (n = 8)

The arithmetic is the same 2n^3 operations every time; what changes is how often a number is used while it is close. Tiles use each fetched number b times, and a systolic array uses it n times with no cache at all.
The code (120 lines; it asserts its own result)
"""Lab 17: count the numbers a matrix product moves through a small fast memory, and run a systolic array."""

from collections import OrderedDict

import numpy as np

from videos.coursekit import labs

TITLE = "Tiling, traffic and a systolic array"
GOAL = ("Multiply two 32 x 32 matrices behind a simulated fast memory that holds M numbers, count every number "
        "fetched by the untiled loop and by the tiled loop, and compare with 2n^3/b + n^2. Then pulse a product "
        "through a systolic array and check its answer, its K + 2n - 2 cycles and its n operations per number read.")
TASKS = [
    "Give the tiled loop a memory of exactly three tiles (M = 3 b^2) instead of four. How far above the formula does "
    "the least-recently-used memory land, and why?",
    "Count cache lines instead of numbers: let one fetch bring in 8 neighbours of a row. Which loop order of the "
    "textbook product improves, i-j-k or i-k-j?",
    "Make the systolic array 8 x 8 and feed it a 9 x 9 product in tiles. What share of the cells' cycles do useful work?",
]
N = 32


def traffic(accesses, M):
    """The numbers fetched from far memory when ``accesses`` run through a least-recently-used memory of M numbers."""
    held, fetched = OrderedDict(), 0
    for key in accesses:
        if key in held:
            held.move_to_end(key)
        else:
            fetched += 1
            held[key] = True
            if len(held) > M:
                held.popitem(last=False)
    return fetched


def product(n, b):
    """The accesses of C = AB computed in b x b tiles (b = n is the untiled triple loop)."""
    for i0 in range(0, n, b):
        for j0 in range(0, n, b):
            for k0 in range(0, n, b):
                for i in range(i0, i0 + b):
                    for k in range(k0, k0 + b):
                        for j in range(j0, j0 + b):
                            yield ("A", i, k)
                            yield ("B", k, j)
                            yield ("C", i, j)


def systolic(A, B):
    """An n x n grid of multiply-add cells.  Row i of A enters from the left i cycles late, column j of B from the
    top j cycles late; each cycle a cell multiplies what passes through it, adds it to its sum, and hands the A
    number right and the B number down.  Returns (C, cycles used, active cells per cycle, numbers read)."""
    n, K = A.shape[0], A.shape[1]
    ra, rb = np.full((n, n), np.nan), np.full((n, n), np.nan)
    acc, active, reads, t = np.zeros((n, n)), [], 0, 0
    while True:
        ra[:, 1:], rb[1:, :] = ra[:, :-1].copy(), rb[:-1, :].copy()
        for i in range(n):
            ra[i, 0] = A[i, t - i] if 0 <= t - i < K else np.nan
            rb[0, i] = B[t - i, i] if 0 <= t - i < K else np.nan
            reads += 2 * (0 <= t - i < K)
        live = ~np.isnan(ra) & ~np.isnan(rb)
        if not live.any() and t >= K:
            return acc, t, active, reads
        acc[live] += ra[live] * rb[live]
        active.append(int(live.sum()))
        t += 1


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    n = N

    # 1. traffic through a fast memory of M numbers
    tiles = (2, 4, 8, 16)
    Ms = [4 * b * b for b in tiles]
    tiled = [traffic(product(n, b), M) for b, M in zip(tiles, Ms)]
    naive = [traffic(product(n, n), M) for M in Ms]
    formula = [2 * n ** 3 // b + n * n for b in tiles]
    lab.row("operations in the product, 2n^3", f"{2 * n ** 3:,}")
    for b, M, t, f, v in zip(tiles, Ms, tiled, formula, naive):
        lab.row(f"M = {M:>4} numbers, tiles of {b:>2}", f"tiled fetches {t:>6,}   2n^3/b + n^2 = {f:>6,}   "
                f"untiled loop {v:,}   FLOPs per number {2 * n ** 3 / t:.1f}")
    slope = np.polyfit(np.log(Ms), np.log(np.array(tiled) - n * n), 1)[0]
    lab.row("slope of tiled traffic against M (log-log)", f"{slope:.3f}   (Hong and Kung: -1/2)")
    assert tiled == formula, "each tile step fetches one tile of A and one of B; C is fetched once"
    assert all(v >= n ** 3 for v in naive), "the untiled loop fetches at least one number per multiply-add"
    assert abs(slope + 0.5) < 0.01, "traffic falls like 1/sqrt(M)"
    assert naive[0] > 3.5 * tiled[-1]

    # 2. a systolic array: the film's 4 x 4 example, and a wider product
    for nn, K in ((4, 4), (8, 16)):
        A, B = rng.standard_normal((nn, K)), rng.standard_normal((K, nn))
        Cs, cycles, active, reads = systolic(A, B)
        ops = 2 * sum(active)
        lab.row(f"systolic {nn} x {nn}, K = {K}", f"{cycles} cycles (K + 2n - 2 = {K + 2 * nn - 2})   "
                f"max error {np.abs(Cs - A @ B).max():.1e}   {ops / reads:.0f} operations per number read (n = {nn})")
        assert np.allclose(Cs, A @ B, atol=1e-12), "every cell holds its entry of C"
        assert cycles == K + 2 * nn - 2 and sum(active) == nn * nn * K and reads == 2 * nn * K
    lab.note = ("The arithmetic is the same 2n^3 operations every time; what changes is how often a number is used "
                "while it is close. Tiles use each fetched number b times, and a systolic array uses it n times with "
                "no cache at all.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    grid = np.geomspace(Ms[0], Ms[-1], 50)
    ax[0].plot(Ms, naive, "o-", color=labs.RED, label="untiled loop")
    ax[0].plot(Ms, tiled, "o-", color=labs.BLUE, label="tiled, b = sqrt(M)/2")
    ax[0].plot(grid, 4 * n ** 3 / np.sqrt(grid) + n * n, color=labs.GOLD, ls="--", lw=1.2, label="4n^3/sqrt(M) + n^2")
    ax[0].set(title=f"Numbers fetched for a {n} x {n} product", xlabel="fast memory M (numbers)",
              ylabel="numbers fetched", xscale="log", yscale="log")
    ax[0].legend()
    ax[1].bar(np.arange(len(active)), active, color=labs.TEAL)
    ax[1].set(title=f"Systolic array {nn} x {nn}, K = {K}: the wavefront", xlabel="cycle",
              ylabel="cells multiplying this cycle")
    ax[1].axvline(K + 2 * nn - 2 - 0.5, color=labs.MUTED, ls="--", lw=1)
    ax[1].text(K + 2 * nn - 3, max(active) * 0.97, "K + 2n - 2 cycles ", color=labs.MUTED, ha="right", va="top", fontsize=9)
    lab.fig = fig
    return lab

Now change it

  1. Give the tiled loop a memory of exactly three tiles (M = 3 b^2) instead of four. How far above the formula does the least-recently-used memory land, and why?
  2. Count cache lines instead of numbers: let one fetch bring in 8 neighbours of a row. Which loop order of the textbook product improves, i-j-k or i-k-j?
  3. Make the systolic array 8 x 8 and feed it a 9 x 9 product in tiles. What share of the cells' cycles do useful work?

Problems, with solutions

Try each problem before opening its solution.

1. Intensity of a matrix product. For C = AB with A of size m × k and B of size k × n, stored in s-byte numbers, each matrix moved once, show that I = 2mnk / (s(mk + kn + mn)). What happens when m = 1?

Solution

The product does mn dot products of length k, 2mnk operations; it reads mk + kn numbers and writes mn, s bytes each. With m = 1 (one token at a time), I = 2nk / (s(k + kn + n)) → 2/s as k and n grow: two operations per weight read, one per byte in 16 bits, half in FP32. That is on the slope of every roofline in this part, whatever the chip.

2. How much tiling saves. Multiply n × n matrices in b × b tiles, with a fast memory of M numbers (3b² ≤ M). Show that about 2n³/b numbers move, about 2√3 n³/√M.

Solution

There are (n/b)² tiles of C, and each takes n/b steps, each loading one b × b tile of A and one of B: (n/b)³ · 2b² = 2n³/b numbers, plus n² to write C. The largest tiles that fit have b = √(M/3), so the traffic is 2n³√3/√M. Hong and Kung (1981) showed that no order of the operations moves fewer than order n³/√M, so tiling is optimal up to a constant.

3. Reaching the roof. An H100 does 989 TFLOP/s in BF16 (dense) and reads 3.35 TB/s. Which square BF16 products can reach the roof? Repeat for a Rubin GPU in NVFP4: 35 PFLOP/s (dense), 19.2 TB/s, half a byte per number.

Solution

The ridge is 989 × 10¹²/3.35 × 10¹² ≈ 295 FLOP/byte. With each matrix moved once, I = 2n³/(3n² · 2) = n/3, so n ≥ 886. For Rubin, the ridge is 35 × 10¹⁵/19.2 × 10¹² ≈ 1,823 FLOP/byte, and I = 2n³/(3n² · 0.5) = 4n/3, so n ≥ 1,368 (ignoring the block scales, which add 1/16 of a byte per number for NVFP4). Smaller products, and every matrix-vector product, are memory-bound.

4. Ring against tree. Derive T_ring = 2(p − 1)α + 2((p − 1)/p)(n/β) and T_tree = 2 log₂p (α + n/β). For p = 8, where do they cross?

Solution

The ring's reduce-scatter takes p − 1 steps; in each, every device sends one chunk of n/p bytes to its neighbour and adds the one it receives; the all-gather passes the finished chunks around in p − 1 more steps. Each step costs α + n/(pβ), which gives T_ring. The binomial tree reduces in log₂p steps of whole messages and broadcasts in log₂p more: T_tree. For p = 8: 14α + 1.75 n/β = 6α + 6 n/β gives n = 8αβ/4.25 ≈ 1.9 αβ. Below that the tree is faster, above it the ring; the ring's bandwidth term stays below 2n/β however large p is, which is the lower bound for all-reduce (Patarasuk & Yuan 2009).

5. Rounding and range. Show that rounding to nearest in a binary floating-point format with M mantissa bits has relative error at most 2^−(M+1) for normal numbers, and find the largest finite FP16, E4M3 and E5M2 numbers.

Solution

In [2^e, 2^(e+1)) the representable numbers are 2^(e−M) apart; rounding to nearest moves x by at most half of that, 2^(e−M−1) ≤ 2^−(M+1)|x|. The largest finite number is the largest mantissa times the largest exponent: FP16 (bias 15, exponent field 30 at most) gives (2 − 2^−10) · 2^15 = 65,504; E5M2 (IEEE-like) gives 1.75 · 2^15 = 57,344; E4M3 (bias 7) keeps only the all-ones pattern for NaN, so exponent field 15 is usable and the largest mantissa there is 1.75: 1.75 · 2^8 = 448.

6. Latency to hide. Memory 3.35 TB/s away by about 273 ns (479 cycles at 1.755 GHz, Luo et al.'s measurement on an H800), 132 SMs, loads of 128 bytes. How many loads must each SM keep in flight? Can 64 warps, one load each, do it?

Solution

By Little's law the bytes in flight are 3.35 × 10¹² × 273 × 10⁻⁹ ≈ 915 KB, about 6.9 KB per SM, or 54 loads of 128 bytes. Sixty-four warps with one load each can cover it, but only near full occupancy and only if every warp is always waiting on a load; real kernels keep several loads in flight per warp (wider loads, unrolled loops, asynchronous copies), which is what lets a kernel with fewer warps, but more registers per thread, keep up.

Notes and sources

Glossary

English 中文
silicon, chip, die, wafer 硅,芯片,裸片,晶圆
transistor 晶体管
Moore's law 摩尔定律
Dennard scaling 登纳德缩放
the power wall 功耗墙
clock speed, frequency 时钟频率
leakage, threshold voltage 漏电,阈值电压
single-thread performance 单线程性能
core, multicore 核心,多核
Amdahl's law 阿姆达尔定律
GPU (graphics processing unit) GPU(图形处理器)
shader 着色器
GPGPU (general-purpose computing on GPUs) GPGPU(GPU通用计算)
CUDA, kernel CUDA,内核(核函数)
thread, thread block, grid 线程,线程块,网格
warp 线程束
SIMT (single instruction, multiple threads) SIMT(单指令多线程)
streaming multiprocessor (SM) 流式多处理器(SM)
lane 通道
branch divergence 分支发散
latency hiding 延迟隐藏
Little's law 利特尔定律
bytes in flight 在途字节
memory coalescing 访存合并
occupancy 占用率
register, register file 寄存器,寄存器堆
shared memory 共享内存
cache, cache line, L1 / L2 / L3 缓存,缓存行,一级/二级/三级缓存
SRAM, DRAM, HBM (high-bandwidth memory) SRAM,DRAM,HBM(高带宽内存)
memory hierarchy 存储层次
bandwidth, latency 带宽,延迟
pointer chasing 指针追逐
prefetcher 预取器
huge pages, TLB 大页,TLB(地址转换缓存)
matrix multiplication (GEMM), matrix-vector product (GEMV) 矩阵乘法(GEMM),矩阵乘向量(GEMV)
FLOP, FLOP/s 浮点运算次数,每秒浮点运算次数
arithmetic intensity 算术强度
tiling, cache blocking, tile 分块,缓存分块,块(瓦片)
BLAS BLAS(基础线性代数库)
the roofline model, ridge point 屋顶线模型,拐点
compute-bound, memory-bound 受算力限制,受内存限制
STREAM triad STREAM三元组测试
systolic array, processing element (PE) 脉动阵列,处理单元
output-stationary, weight-stationary 输出驻留,权重驻留
wavefront 波前
TPU (Tensor Processing Unit) TPU(张量处理器)
tensor core 张量核心
multiply-accumulate (MAC), fused multiply-add (FMA) 乘加
floating point: sign, exponent, mantissa, bias 浮点数:符号位,指数,尾数,偏置
unit roundoff, round to nearest 单位舍入误差,就近舍入
subnormal, saturate 次正规数,饱和
FP32, TF32, BF16 (bfloat16), FP16, FP8, FP4 FP32,TF32,BF16,FP16,FP8,FP4
microscaling (MX), block scale, shared exponent 微缩放(MX),块缩放因子,共享指数
interconnect, link 互连,链路
NVLink, NVSwitch, InfiniBand NVLink,NVSwitch,InfiniBand
scale-up, scale-out 纵向扩展,横向扩展
topology: switch, fat tree, torus 拓扑:交换机,胖树,环面
optical circuit switch 光路交换机
collective, all-reduce, reduce-scatter, all-gather, broadcast 集合通信,全规约,规约-分散,全收集,广播
ring all-reduce, tree all-reduce 环形全规约,树形全规约
the α–β model (latency–bandwidth) α–β模型(延迟–带宽模型)
Triton, CUTLASS Triton,CUTLASS
FlashAttention, IO-aware FlashAttention,IO感知
price-performance, energy efficiency 性价比,能效
the memory wall 内存墙
data centre, AI factory 数据中心,AI工厂
rack, pod, superpod 机柜,集群(pod),超级集群
wafer-scale engine 晶圆级引擎
LPU LPU(语言处理单元)
through-silicon via (TSV), silicon interposer 硅通孔,硅中介层
prefill, decode 预填充,解码
skew (of a systolic array) (脉动阵列的)错位
inference 推断
multi-thread, single-thread 多线程,单线程
load average 平均负载
analog in-memory computing, phase-change memory 模拟存内计算,相变存储器
neuromorphic computing, spiking neuron 类脑计算,脉冲神经元
prefill, decode 预填充,解码
the hardware lottery 硬件彩票

Names: Gordon Moore → 戈登·摩尔; Robert Dennard → 罗伯特·登纳德; H. T. Kung → 孔祥重; Charles Leiserson → 查尔斯·雷瑟尔森; Hong Jia-Wei → 洪加威; Ian Buck → 伊恩·巴克; John Nickolls → 约翰·尼科尔斯; Alex Krizhevsky → 亚历克斯·克里热夫斯基; Ilya Sutskever → 伊利亚·苏茨克维; Geoffrey Hinton → 杰弗里·辛顿; Fei-Fei Li → 李飞飞; Jensen Huang → 黄仁勋; Sara Hooker → 萨拉·胡克; Samuel Williams, Andrew Waterman, David Patterson → 塞缪尔·威廉斯、安德鲁·沃特曼、大卫·帕特森; Philippe Tillet → 菲利普·蒂莱; Tri Dao → Tri Dao; Vasily Volkov → 瓦西里·沃尔科夫; Herb Sutter → 赫伯·萨特; Gene Amdahl → 吉恩·阿姆达尔; John Little → 约翰·利特尔; Mark Horowitz → 马克·霍洛维茨; William Kahan → 威廉·卡亨; Jonathan Ross → 乔纳森·罗斯. Products stay in Latin script (GeForce, CUDA, H100, Blackwell, Rubin, NVLink, TPU, Ironwood, Trainium, Cerebras, Groq, TrueNorth, Loihi, Hala Point).

About this partfrom its README

Part 17 of a thirty-one-part series on how modern AI works and how it came to be (see the series plan and the syllabus). Why AI runs on GPUs: the end of Dennard scaling, the GPU from graphics to CUDA, SIMT and latency hiding, AlexNet, matrix multiplication as the workload, tiling and arithmetic intensity, the memory hierarchy, the roofline, systolic arrays and tensor cores, number formats from FP32 to FP4, interconnects and the α–β model of collectives, writing a kernel, the trends in FLOPs, dollars and watts, other accelerators, and the frontier in late 2026. Wherever it can, the part measures the computer that renders it: its matrix-product speed against size, its memory bandwidth and latency at every cache level, a cache-blocking speed-up in C, its processes passing messages. Everything about GPUs and other chips is from vendors' datasheets and papers, cited on screen.

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. The end of Dennard scaling; parallelism; GPUs and SIMT; CUDA (2007).
  2. Matrix multiply as the workload: FLOP counts; tiling for reuse; arithmetic intensity derived.
  3. The memory hierarchy (registers, SRAM, HBM); the roofline derived (Part 19 builds on it).
  4. Tensor cores and systolic arrays (the TPU): C = AB as a wavefront.
  5. Number formats in hardware: FP32, TF32, BF16, FP8, FP4, microscaling (MX).
  6. Interconnect: NVLink, InfiniBand, topologies; the α–β cost model for collectives (Part 18 uses it).
  7. Writing a kernel: a tiled matmul; occupancy; Triton.
  8. Trends: FLOPs per dollar, energy per FLOP, power and data centres (cited).
  9. Other accelerators: Trainium, Cerebras wafer-scale, Groq; analog and neuromorphic, briefly.

Computed: the roofline of the machine rendering the video (measured matmul throughput vs size); a cache-blocking speed-up; a simulated systolic array. Visuals: data flowing through a systolic array; measured points on the roofline; zooming down the memory hierarchy.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答

1. 矩阵乘积的算术强度。 对 C = AB,A 为 m × k,B 为 k × n,每个数占 s 字节,每个矩阵只搬运一次。证明 I = 2mnk / (s(mk + kn + mn))。m = 1 时会怎样?

解答

乘积要做 mn 个长度为 k 的点积,共 2mnk 次运算;读入 mk + kn 个数,写出 mn 个,每个 s 字节。m = 1(一次生成一个 词元)时,I = 2nk / (s(k + kn + n)),当 k、n 增大时趋于 2/s:每读一个权重做两次运算,16位数下每字节一次,FP32 下每字节半次。 不论哪块芯片,这都落在本部分每条屋顶线的斜坡上。

2. 分块省下多少。 用 b × b 的块计算 n × n 矩阵乘法,快速存储能放 M 个数(3b² ≤ M)。证明大约要搬运 2n³/b 个数, 也就是约 2√3 n³/√M。

解答

C 有 (n/b)² 个块,每块要走 n/b 步,每步读入 A 的一个 b × b 块和 B 的一个:(n/b)³ · 2b² = 2n³/b 个数,再加上写出 C 的 n² 个。能放下的最大的块是 b = √(M/3),所以搬运量为 2√3 n³/√M。洪加威和孔祥重(1981)证明,任何运算顺序的搬运量都不会 少于 n³/√M 的量级,所以分块在常数倍之内是最优的。

3. 碰到屋顶。 H100 的 BF16 算力是每秒 989 万亿次(稠密),内存带宽 3.35 TB/s。多大的 BF16 方阵乘积能达到屋顶?再对 Rubin GPU 的 NVFP4 算一次:35 PFLOP/s(稠密),19.2 TB/s,每个数半个字节。

解答

拐点是 989 × 10¹²/3.35 × 10¹² ≈ 295 次运算每字节。每个矩阵只搬运一次时,I = 2n³/(3n² · 2) = n/3,所以 n ≥ 886。 Rubin 的拐点是 35 × 10¹⁵/19.2 × 10¹² ≈ 1823 次运算每字节,I = 2n³/(3n² · 0.5) = 4n/3,所以 n ≥ 1368(忽略分块缩放因子; NVFP4 的缩放因子每个数再加十六分之一字节)。更小的乘积,以及所有矩阵乘向量,都受内存限制。

4. 环形与树形。 推导 T_ring = 2(p − 1)α + 2((p − 1)/p)(n/β) 和 T_tree = 2 log₂p (α + n/β)。p = 8 时,两者在哪里相交?

解答

环形算法的规约-分散阶段有 p − 1 步:每一步每台设备把一块 n/p 字节发给邻居,并把收到的那块加到自己的上面;全收集阶段 再用 p − 1 步把算完的块传一圈。每一步花 α + n/(pβ),于是得到 T_ring。二叉树用 log₂p 步传整条消息完成规约,再用 log₂p 步 广播:得到 T_tree。p = 8 时,14α + 1.75 n/β = 6α + 6 n/β,得 n = 8αβ/4.25 ≈ 1.9 αβ。比它小,树更快;比它大,环更快。环形的 带宽项无论 p 多大都小于 2n/β,这正是全规约的下界(Patarasuk 和 Yuan,2009)。

5. 舍入与范围。 证明:在有 M 个尾数位的二进制浮点格式中,对规格化数就近舍入的相对误差至多为 2^−(M+1);并求出 FP16、 E4M3 和 E5M2 能表示的最大有限数。

解答

在 [2^e, 2^(e+1)) 中,可表示的数相隔 2^(e−M);就近舍入最多把 x 移动这个间隔的一半,2^(e−M−1) ≤ 2^−(M+1)|x|。最大 有限数是最大尾数乘以最大指数:FP16(偏置 15,指数字段至多 30)得 (2 − 2^−10) · 2^15 = 65504;E5M2(类似 IEEE)得 1.75 · 2^15 = 57344;E4M3(偏置 7)只把全 1 的那个位模式留作 NaN,所以指数字段 15 可用,那里的最大尾数是 1.75: 1.75 · 2^8 = 448。

6. 要隐藏的延迟。 内存带宽 3.35 TB/s,延迟约 273 纳秒(Luo 等人在 H800 上测得:1.755 GHz 下 479 个周期),132 个 SM,每次 读取 128 字节。每个 SM 要同时保持多少个读取在路上?64 个线程束、每个一个读取,够不够?

解答

由利特尔定律,在路上的字节数是 3.35 × 10¹² × 273 × 10⁻⁹ ≈ 915 KB,每个 SM 约 6.9 KB,也就是 54 个 128 字节的读取。 64 个线程束、每个一个读取,刚好能覆盖,但要接近满占用,而且每个线程束都得一直在等一个读取;真实的内核让每个线程束同时有好几个 读取在路上(更宽的读取、展开的循环、异步拷贝),这也是为什么线程束更少、但每个线程寄存器更多的内核,依然能跟得上。

Build the film

python -m videos.ai.ai17.compute        # the part's numbers, into .cache/ai17
python tools/build.py ai17                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py ai17 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/ai/ai17. Setup: see the course page. Source of these notes: the README and the scenes' narration.