A matrix multiply can leave its compute units idle two thirds of the time, waiting for data. Overlap the copy with the maths and the same chip, at the same clock, reaches 78% of peak.
Learn how an accelerator kernel is cut into tiles, fed through a small on-chip memory, scheduled, generated as code, and then checked against counters and a simulator.
Press Double buffering and watch the gaps in the orange lane close. Then pick the 256 tile and watch it fall off a cliff. Then we build, piece by piece, the loop nest, the memory budget, the overlap, the schedule, the generator and the counters.
You need a rough idea of matrix multiplication and a little C. We build the rest from zero.
Built from primary sources, all listed in the Field Guide: the Google TPU paper, the Horowitz energy table, the NVIDIA CUTLASS documentation and the Arm DWT cycle counter. The machine on this page is a small made-up one, labelled illustrative wherever it appears.
A toy machine, not a real chip. Matrix unit: one 16 × 16 × 16 multiply-accumulate (4,096 MACs) per cycle. On-chip memory: 128 KiB. Each DMA transfer costs 240 cycles of setup before data moves. Tile depth is 64. Utilisation is the steady-state share of cycles the matrix unit works. All numbers are illustrative.
Chapter 0
Find out why a matrix multiply can use a third of a chip and why a faster clock does not fix it
A new accelerator chip arrives on your desk. Its data sheet promises 4.1 trillion multiply-adds every second. You write the first matrix multiply for it, run it, and read the profiler. The chip is doing a third of that.
You try the obvious fix. You raise the clock. The kernel gets a little faster, and the share of the chip you use gets smaller. Something else is the limit, and the clock is not it.
A kernel is a small program that runs on the accelerator and does one job. The job here is GEMM, general matrix multiply: multiply two grids of numbers to make a third grid. Neural networks spend most of their time doing this.
Peak is the most work the chip can do per second if every compute unit is busy on every cycle. Utilisation is the share of that peak you reach: achieved work divided by peak work. People also call it MFU, for model FLOPs utilisation. A kernel at 31% uses 31 cycles of every 100 for real work.
The last word is stall. A stall is a cycle where a unit has nothing to do because it waits for something else. Almost every low number in this lesson is a stall in disguise.
Think of a chef and a delivery driver. The chef can cook a dish in 4 minutes. The driver needs 9 minutes to fetch the next set of ingredients and the chef waits at the stove for them. A faster stove changes nothing. A second driver, or a driver who fetches the next batch while the chef cooks this one, changes everything.
The kernel does not multiply the whole matrices at once. It cuts them into small square pieces called tiles and handles one tile per step, like a chef cooking one batch at a time. Chapter 1 shows how to choose the tile.
On the chip, the chef is the matrix unit, the block of hardware that multiplies small squares of numbers. The driver is the DMA engine, short for direct memory access: a copy engine that moves blocks of bytes between big slow memory (DRAM) and a small fast on-chip memory (SRAM) without using the compute units. The matrix unit can only read SRAM.
So a kernel works in steps. Each step has two jobs. Load the next pieces of data into SRAM, then do the maths on them. Call the time for the first job td and the time for the second tc.
The hero at the top uses these two lines. Take the default settings: a 128 × 128 tile, 100 bytes moved per cycle. The maths takes 256 cycles. The setup takes 240. The load takes 328. Without overlap one step costs 240 + 328 + 256 = 824 cycles, and the matrix unit works 256 of them. That is 256 / 824 = 31%.
With overlap, the step costs max(256, 328) = 328 cycles. The matrix unit works 256 of 328, or 78%. Nothing about the chip changed. Only the order of the work changed.
A faster clock shortens the maths. It does not shorten the time to pull bytes out of DRAM, because DRAM has its own speed in bytes per second. In the device below, the setup and the load stay fixed in nanoseconds while the maths shrinks as you raise the clock.
One tile step as a bar of time: yellow is setup, blue is loading, orange is maths. Drag the clock up. Then switch double buffering on and drag again.
Toy machine, 128 × 128 × 64 tile, 100 bytes of DRAM bandwidth per nanosecond at the 1.00× clock (a 1 GHz chip). Setup (240 ns) and load (328 ns) do not change with the chip clock. Maths is 256 cycles. Illustrative numbers.
At 1× clock without overlap, one step takes 824 ns. At 2× it takes 696 ns. You doubled the clock and gained 18%. Utilisation against the new, higher peak falls from 31% to 18%. With double buffering on, the step is 328 ns at 1× and still 328 ns at 2×. The clock now buys exactly nothing, because the load is the longest job.
This is the pattern of the whole lesson. A low utilisation number is a symptom. The cause is one of two things. Either the compute units wait for data (a DMA stall), or they sit idle between instructions (a bubble in the schedule). You cannot tell which by looking at the clock. You tell by reading performance counters: hardware registers that count how many cycles each unit was busy or waiting. Chapter 7 reads them. The simulator you build the kernel against must report the same counters, so the same questions get the same answers before and after silicon.
Each chapter fixes one cause of a low number. The hero's controls map to the chapters.
Chapter 1
Cut a big multiply into small tiles so every byte you fetch does many multiplies
You want to multiply two 1,024 × 1,024 matrices. The school method is three loops. For each row i of A and each column j of B, walk along k, multiply the pair, and add it to a running sum.
Count the memory trips. Each multiply-add reads one number from A and one from B. With 16-bit numbers that is 4 bytes of DRAM traffic for 2 operations (one multiply and one add). The ratio is half an operation per byte. A chip that can do thousands of operations per cycle will starve on that diet.
Arithmetic intensity is the number of operations you do for each byte you move. It is the one number that tells you whether a kernel waits for data or for the maths. High intensity means each fetched byte feeds many multiplies. Low intensity means the compute units spend their time waiting.
You raise intensity by reuse. The element A[i,k] is needed by every column j. If you keep a small block of A and a small block of B close to the compute units, you use each fetched number many times before you throw it away. That block is a tile.
Tiling splits each loop in two: an outer loop over tiles and an inner loop inside one tile. Three loops become six. The outer three move tiles from DRAM into SRAM. The inner three work on the tile that is already in SRAM. A third level sits below: the MMA instruction (matrix multiply-accumulate), which does one small block in one go. On the toy machine it multiplies a 16 × 16 block by a 16 × 16 block per cycle.
// C[M][N] += A[M][K] * B[K][N], tiled. Tm, Tn, Tk are the SRAM tile sizes. for (int i0 = 0; i0 < M; i0 += Tm) // DRAM level: pick an output tile of C for (int j0 = 0; j0 < N; j0 += Tn) { zero_acc(acc); // Tm x Tn fp32 sums stay in SRAM for (int k0 = 0; k0 < K; k0 += Tk) { // walk along K, one slice at a time dma_load(sA, &A[i0][k0], Tm*Tk*2); // DRAM -> SRAM, 2 bytes per fp16 number dma_load(sB, &B[k0][j0], Tk*Tn*2); for (int i = 0; i < Tm; i += 16) // SRAM level: one MMA block per cycle for (int j = 0; j < Tn; j += 16) for (int k = 0; k < Tk; k += 16) mma_16x16x16(&acc[i][j], &sA[i][k], &sB[k][j]); } dma_store(&C[i0][j0], acc, Tm*Tn*4); // write the finished tile once }
Look at what moves. The sums in acc never leave SRAM while the k0 loop runs. Only slices of A and B stream through. That choice is called keeping C resident, and the whole lesson uses it.
Derive it for a square tile of side b, in 32-bit numbers, so the count is easy. The tile does b × b × b multiply-adds, which is 2b³ operations. It reads a b × b piece of A and one of B, then writes a b × b piece of C. That is 3 × b² numbers of 4 bytes, or 12b² bytes.
b = 1: 1/6 ≈ 0.17 | b = 16: 2.7 | b = 64: 10.7 | b = 128: 21.3 FLOP per byte
The tile at b = 1 is the naive loop. It moves 12 bytes for 2 operations. A tile of 128 moves the same bytes per number but reuses each one 128 times. On the toy machine the inputs are 16-bit and the sums stay put, so each K slice moves 2Tk(Tm+Tn) bytes for 2TmTnTk operations. For a square tile that is b / 2 FLOP per byte: 64 for b = 128.
Why does the effort matter in energy? Horowitz measured a 32-bit DRAM read at 640 picojoules and a 32-bit read from an on-chip SRAM cache at 5, in a 45 nm process. That is 128 times. A 32-bit floating multiply cost 3.7. So one DRAM read costs as much energy as about 170 multiplies. The numbers are old. The gap is still large today.
The matrix unit takes 16 × 16 × 16 blocks. A tile of 100 × 100 × 64 is not a multiple of 16. The hardware rounds up: 7 blocks across, 7 down, 4 deep, so 196 cycles. The real work is 100 × 100 × 64 / 4,096 = 156 cycles. The matrix unit spends the difference on zeros. Use the picker to see where the padding lands.
Each square is one 16 × 16 block of the matrix unit. Orange is useful work. Red is padding: zeros the unit multiplies anyway. Drag both sliders and watch the reuse number and the waste.
Toy machine: 16 × 16 × 16 MMA block, 16-bit inputs, tile depth Tk = 64, sums kept on chip. Intensity is Tm × Tn / (Tm + Tn) FLOP per byte, derived above. Illustrative machine; the energy ratio (640 pJ against 5 pJ) is Horowitz’s 45 nm table.
At 100 × 100 the unit is 80% efficient. At 96 × 96 it is 100%, because 96 is six blocks. The efficiency is the useful area divided by the padded area, so a tile one element over a multiple of 16 is the worst case: 17 pays for 32.
In a real design the MMA shape is part of the instruction set. Sizes change between chips, and the kernel must read them from the hardware description. Chapter 6 shows a generator that does exactly that.
Board: STM32 Nucleo-H743ZI2 (Cortex-M7). It has no scratchpad you control the same way, but its data cache plays SRAM’s role. Multiply two 128 × 128 float32 matrices with the plain loops and again with 16 × 16 blocking. Read the cycle counter, DWT->CYCCNT, before and after. Divide by 2,097,152 multiply-adds. Compare the two cycles-per-MAC figures.
Chapter 2
Add up what a tile needs on chip, and find the size where the plan falls off a cliff
Chapter 1 told you to make tiles bigger. Try that on a desk. A big desk holds more papers, so you walk to the filing cabinet less. But the desk has an edge. Once the papers pile past the edge, they fall on the floor, and you spend your day picking them up.
The on-chip memory is the desk. Its edge is hard, and you set the plan before the chip runs. This chapter finds the edge.
On the toy machine the on-chip memory is SRAM: static RAM, small, fast and close to the compute units. It is a scratchpad, which means software manages it. There is no cache that guesses what you need. Your kernel decides what lives there and for how long.
The working set is everything the kernel needs in SRAM at one moment. For one step of the tiled loop that is three things: the tile of A, the tile of B, and the sums for the output tile of C. Their sizes follow from the tile shape and the number width.
Work the hero’s default tile, 128 × 128 with depth 64. A is 128 × 64 × 2 = 16,384 bytes, or 16 KiB. B is the same, 16 KiB. C is 128 × 128 × 4 = 65,536 bytes, or 64 KiB. The total is 96 KiB. The chip has 128 KiB, so it fits with 32 KiB to spare.
Notice that C is the biggest piece. It grows with the square of the tile side, while A and B grow only in step with it. That is why C sets the edge.
Chapter 3 will ask for two copies of A and two of B, one being used while the other fills. Then the footprint is 2 × 16 + 2 × 16 + 64 = 128 KiB. That is exactly the chip. Check the algebra for a square tile with depth 64: the footprint is 4b² + 512b bytes. Set it equal to 131,072 and the largest b is 128. The hero’s default tile is the largest square double-buffered tile that fits.
Suppose the tile is 144 × 144 with double buffering. The footprint is 73,728 + 82,944 = 156,672 bytes. That is 153 KiB against 128. The sums cannot all stay on chip.
A scratchpad has no floor to catch them gently. The kernel must park part of C in DRAM and fetch it back for each K slice. On the toy machine we model the worst case: the whole C tile goes out and comes back every step. The step now moves 36,864 bytes of A and B plus 2 × 82,944 bytes of sums. That is 202,752 bytes. At 100 bytes per cycle, loading takes 2,028 cycles for 324 cycles of maths. Utilisation falls to 16%.
So the curve of utilisation against tile size is not a smooth hill. It climbs as reuse grows, then drops off a cliff at the edge. The device draws the curve for the settings you choose.
Top: the on-chip memory as a bar, with the A, B and C pieces stacked inside it. Bottom: utilisation for every square tile size at your settings; the dot is your tile. Drag the tile past the edge.
Toy machine, 100 bytes per cycle of DMA, 240 cycles of setup per transfer. The spill model is the worst case: the whole C tile is written out and read back every step. A real compiler might spill less. Illustrative numbers.
Try 256 KiB. The desk grew, so the largest double-buffered square tile grows too: 4b² + 512b ≤ 262,144 gives b = 199, and the slider steps of 16 reach 192. The 256 tile still spills, because it needs 384 KiB. Memory size is a design choice with a price in chip area. The Google TPU paper gives a real scale: its first chip carries a 24 MiB Unified Buffer, and 4 MiB of accumulators beside it. The accumulators are 4,096 sets of 256 numbers of 32 bits. The paper says the 24 MiB size was picked partly to fit the matrix unit and partly to make the compiler simpler. Our desk is 192 times smaller.
The TPU buffer is also software-managed, like ours. That is the point of this chapter: the plan about what sits where is made in advance, so the planner must add up the bytes.
A spill leaves a clear mark. The count of bytes moved per step jumps from the 36,864 you planned to 202,752. The utilisation counter drops. If your kernel generator printed the plan, those two numbers would not match the counter. Chapter 7 uses that mismatch as an alarm.
Board: STM32 Nucleo-H743ZI2. Its Cortex-M7 has tightly coupled data memory (DTCM) that behaves like a scratchpad. Place a 16 KiB tile buffer in DTCM and again in slower external memory, using a linker section. Time the same inner loop with DWT->CYCCNT and compare cycles per tile.
Chapter 3
Load the next tile while the matrix unit works on this one, and watch the yellow gaps close
Picture a short-order cook with one cutting board. She chops onions, then waits while a helper clears the board and brings carrots, then chops carrots. The helper is fast. The cook still stands idle for half of every minute.
Give her two boards. While she chops on board one, the helper loads board two. When she finishes, she turns to board two at once. Nobody waits for the swap. This is double buffering, and it is the single biggest win in the lesson.
A buffer is a region of SRAM that holds one tile. In the single-buffered plan there is one buffer for A and one for B. The DMA fills them, the matrix unit reads them, and the two jobs take turns. In the double-buffered plan there are two of each, called ping and pong. The matrix unit reads ping while the DMA fills pong. Then they swap.
Here is the loop. The first load happens before the loop starts, and it fills ping.
// Double-buffered tile loop. Two buffers per operand: [0] = ping, [1] = pong. dma_start(sA[0], &A[i0][0], bytesA); // prologue: fill ping, nothing to overlap yet dma_start(sB[0], &B[0][j0], bytesB); for (int s = 0; s < steps; s++) { int cur = s & 1, nxt = cur ^ 1; dma_wait(cur); // the tile for this step must be complete if (s + 1 < steps) { // start loading the NEXT tile into the other buffer dma_start(sA[nxt], &A[i0][(s+1)*Tk], bytesA); dma_start(sB[nxt], &B[(s+1)*Tk][j0], bytesB); } mma_tile(acc, sA[cur], sB[cur]); // maths on this tile, in parallel with the DMA above }
Two details carry the whole idea. The dma_wait(cur) comes before the maths, so the matrix unit never reads a half-loaded tile. And the dma_start for the next tile comes before the maths, so the copy runs while the unit works. Swap those lines and you lose the overlap or you read garbage.
Once the pipeline is full, each step costs the longer of the two jobs. The shorter job hides inside it. For the default tile the load is 328 cycles and the maths is 256, so the step is 328 cycles and the matrix unit is idle for the other 72. That gives 256 / 328 = 78%.
This is also the limit. Double buffering can hide the shorter job, not the longer one. If the load is longer than the maths, the DMA is the bottleneck and the unit will always wait. To go higher you need more bandwidth or a tile that reuses more. Double the bandwidth to 200 bytes per cycle and the load falls to 164 cycles, so the maths is the longer job and utilisation reaches its peak in steady state.
The 78% is a steady-state number. The loop has a start. The first tile cannot overlap with anything, because nothing is computing yet. The first load pays the setup cost too: 240 cycles of waiting plus 328 of moving. Only then does the overlap begin.
Take six steps at the default settings. Each load moves 32,768 bytes, which is 327.68 cycles at 100 bytes per cycle (this page rounds it to 328). The last load ends at 240 + 6 × 327.68 ≈ 2,206 cycles. The last maths ends 256 cycles later, at 2,462. The matrix unit did 6 × 256 = 1,536 cycles of work. Utilisation over the whole run is 1,536 / 2,462 = 62%.
Longer runs amortise the start. At 16 steps (K = 1,024) the figure is 71%. At 64 steps (K = 4,096) it is 76%. The single-buffered plan stays at 31% at every length, because every step pays everything. Use the device to see both.
Blue is the DMA lane, orange is the matrix unit, yellow is waiting. Turn double buffering on and off, then drag the number of steps. The first step cannot overlap, so short runs look worse.
Toy machine, 128 × 128 tile, depth 64. With two buffers, a load may start only when its buffer is free (the maths that used it has finished). Each step along K is 64 deep, so 6 steps means K = 384. Illustrative.
Real systems use the same trick. NVIDIA’s CUTLASS library says it uses software pipelining “to overlap memory accesses with other computation” and that it does this by double buffering at several scopes. In firmware the same pattern is the DMA ping-pong you may know from audio and sampling code: the DMA fills one half of a buffer while the CPU processes the other.
The symptom of a missing overlap is simple. The matrix unit sits idle for long runs, and the DMA sits idle in the gaps between. Neither unit is ever busy at the same time. The measurement is two counters: matrix-busy cycles and DMA-wait cycles. If they add up to the total, the work is serial. The fix is the loop above.
A second failure is a race. If you start the next load into the buffer the maths is still reading, you overwrite the tile mid-use. The result is wrong, but it looks fine and it runs fast. Chapter 6 shows how to catch it: compare every output against a plain reference.
Board: STM32 Nucleo-H743ZI2. The DMA streams have a double-buffer mode: the DBM bit in the stream control register, two memory addresses (M0AR and M1AR), and a current-target bit (CT) that says which one is filling. Stream a sensor or a memory block with it and run a 5,000-cycle loop on the half that is not filling. Read DWT->CYCCNT at each transfer-complete interrupt. The gap between interrupts should equal the transfer time, not transfer plus loop.
Chapter 4
Overlap the small steps inside a tile, and see why more overlap needs more registers
Think of a laundrette with one washer and one dryer. You can wash a load, wait for it, dry it, fold it, and only then start the next load. Or you can start load two in the washer the moment load one moves to the dryer. The machines are the same. The second plan finishes six loads in about half the time.
Chapter 3 overlapped big jobs: a DMA load and a tile of maths. This chapter overlaps small ones, inside the matrix unit’s own instruction stream. The idea is the same. The tools are different.
An instruction has a latency: the number of cycles from when it starts to when its result is ready. A load from SRAM into a register might take 6 cycles. An MMA might take 4. A store might take 2. These are the toy machine’s numbers, not a real chip’s.
The throughput is how often a unit can accept a new instruction. A unit with a long latency can still take a new instruction every cycle or two, because it works on several at once, like the washer taking a new load while the dryer is busy. The unit is pipelined inside.
Now look at one loop iteration. It loads two fragments of data, runs one MMA on them, and stores a result. Each step needs the one before it. So one iteration, on its own, takes 6 + 4 + 2 = 12 cycles. Run eight iterations one after another and you wait 96 cycles. Most of that time each unit is idle.
Software pipelining starts a new iteration before the last one has finished. The gap between starts is the initiation interval, written II. If II is 2, a new iteration begins every 2 cycles, and up to 6 are in flight at once.
II = 2: T = 12 + 7 × 2 = 26 cycles | II = 12 (no overlap): T = 96 cycles | speed-up 3.7×
What stops you from picking II = 1? A unit can start only so many instructions per cycle. Our load port issues two loads per iteration and takes one per cycle. So the port is busy 2 cycles per iteration, and II cannot go below 2. This is the resource limit. The scheduler also respects dependencies: the MMA waits for its loads. The final II is the larger of what resources and dependencies allow.
Each iteration in flight holds values in registers: the fastest storage, a few dozen slots next to the units. On the toy machine one iteration needs 8 registers (two data fragments, the result, and some addresses). The number in flight is the iteration latency divided by II, rounded up. That is the number of stages.
registers = ceil(12 / II) × 8 | II = 2: 6 stages, 48 registers | II = 3: 4 stages, 32 | II = 4: 3 stages, 24
Give the machine 32 registers. At II = 2 the plan needs 48. Sixteen values have nowhere to live, so the register allocator (the tool that assigns values to registers) must spill them: store them to SRAM and load them back later. Those extra stores and loads use the very port that set the limit. On the toy machine we charge one extra port cycle per four spilled registers. At II = 2 that makes the port take 2 + 4 = 6 cycles per iteration. The loop now runs at II = 6 and finishes in 12 + 7 × 6 = 54 cycles. At II = 3 there is no spill, and it finishes in 33.
So the plan that looks best on paper (II = 2) loses to the one that fits (II = 3). This is the trade at the heart of scheduling: more overlap raises register pressure, and enough pressure spills data to memory and undoes the gain. Drag II in the device and look for the lowest total.
Each row is one iteration: purple loads and stores, orange the MMA. A lower II stacks rows closer together. Drag II down and watch registers climb. When they pass the limit the schedule stretches.
Toy loop: load 6 cycles, MMA 4, store 2, 8 iterations, 8 registers per iteration in flight, load port limit II ≥ 2. The spill cost (one extra port cycle per four spilled registers) is an assumption chosen to show the shape of the trade-off, not a measured value. Illustrative.
With 64 registers, II = 2 fits (48 registers) and the loop finishes in 26 cycles. A bigger register file buys more overlap, at a cost in chip area. Chip designers weigh that cost against the speed gain.
Nobody wants to place instructions by hand across 12 cycles. A compiler or kernel generator does it. It reads the latency table, finds the best II the resources allow, allocates registers for the stages, and adds the lead-in and lead-out (the first and last iterations, which cannot be fully overlapped). If it cannot fit, it raises II. That search is why kernel generators carry their own machine model. Chapter 6 builds a small one.
The scheduler works at three levels, and you have met all three. Chapter 3 hid DMA behind maths. This chapter hides latency behind other iterations. The MMA instruction itself hides a 16 × 16 × 16 multiply inside a few cycles. Each level has the same shape: a long job, a short job, and a schedule that makes the shorter one free.
Board: STM32 Nucleo-H743ZI2. The Cortex-M7 can issue two instructions per cycle. Write a float32 dot product of length 256 as a plain loop, then unrolled by 4 and by 8. Read DWT->CYCCNT around each. Check whether cycles per element fall, then check the generated code for spills (extra str and ldr to the stack).
Chapter 5
Apply the next operation while the data is still on chip, and skip a trip to DRAM
A neural network layer is rarely just a matrix multiply. After the multiply comes an activation: a small function applied to every output number, such as GELU or ReLU. It costs almost nothing in arithmetic. It can cost a great deal in memory trips.
Follow one output matrix. The multiply finishes a tile of C. Plan one: write the tile to DRAM, end the kernel. Start a second kernel that reads C back, applies the function, and writes it again. Plan two: apply the function to the tile while it still sits in SRAM, then write it once. The second plan is kernel fusion: two operations in one kernel, so the data between them never leaves the chip.
Take M = N = 4,096 with 16-bit numbers. The matrix C has 4,096 × 4,096 × 2 = 33.5 million bytes. Every pass over C costs 33.5 million bytes of DRAM traffic, in one direction.
The unfused plan writes C once (33.5 MB), then reads it (33.5 MB), then writes the result (33.5 MB). The fused plan writes once. The unfused plan moves 67.1 MB of extra traffic. At 100 bytes per cycle that is 671,000 extra cycles, whatever K is.
The fused plan is not free. The activation runs on the chip’s vector unit, once per output tile. Suppose it handles 128 numbers per cycle (an illustrative assumption). A 128 × 128 tile has 16,384 numbers, so it takes 128 cycles. There are 1,024 tiles, so the fused plan adds 131,000 cycles. That is five times less than the extra pass.
The multiply itself takes longer when K is large. The cost of the activation pass does not depend on K at all, because C is the same size. So the benefit of fusion is large for small K and small for large K.
K = 64: fused 802,000 cycles, unfused 1,342,000 | K = 4,096: fused 21.94 million, unfused 22.48 million
At K = 64 the unfused plan is 67% slower. At K = 4,096 it is only 2.5% slower. Real networks have both shapes. Layers with a small inner dimension, or many small operations in a row, lose the most to unfused passes. Try both in the device.
Each bar is the time for one 4,096 × 4,096 output. Orange is the multiply, blue is writing C, yellow is the extra pass over DRAM, purple is the activation done on chip. The faint bar is the other plan. Switch fusion and the inner size K.
Toy machine: 128 × 128 tiles, double buffered, 100 bytes per cycle, 16-bit numbers. The multiply takes the longer of its maths and its traffic (A and B are re-read once per tile column and row). The vector unit handles 128 numbers per cycle (assumed). Illustrative.
The pattern generalises. Every extra pass over a big tensor costs a full trip to DRAM. A bias add, a scale, a residual add, a cast to a smaller number type: each can ride along inside the kernel while the tile is on chip. A kernel generator treats these as an epilogue (code that runs after the main loop, on the finished tile) that you attach to the template.
Attention is two matrix multiplies with a softmax between them. The first makes a score matrix S, with one row and one column per token. The softmax turns each row into weights. The second multiplies the weights by V.
Count the score matrix for a sequence of 4,096 tokens, for one head, in 16-bit numbers: 4,096 × 4,096 × 2 = 33.5 MB. The straightforward way writes S to DRAM, reads it for the softmax, writes the weights, and reads them for the second multiply. That is four passes, 134 MB of traffic for a single head, or about 1.3 million cycles at 100 bytes per cycle. All of it exists only to hold a matrix we throw away a moment later.
FlashAttention’s idea, from Dao and colleagues, is to be IO-aware. The paper “uses tiling to reduce the number of memory reads/writes between GPU high bandwidth memory (HBM) and GPU on-chip SRAM.” It takes a small tile of queries, then streams tiles of keys and values past them, keeping the scores and a running softmax in SRAM. The big score matrix never exists in DRAM. The algorithm is the subject of other lessons: GPU kernels in Triton and FlashAttention 4. What matters here is that it is the same bargain as this whole lesson. Choose tiles that fit SRAM, keep the intermediate on chip, and the extra passes vanish.
So a custom accelerator needs three kernels first: the GEMM with fused epilogues, an attention kernel in the FlashAttention shape, and custom activations. They all lean on the same four facts: tiles, SRAM budget, overlap, and a fused epilogue.
Board: STM32 Nucleo-H743ZI2. Run a 64 × 64 float32 matrix multiply, then a separate ReLU loop over the result. Fuse the ReLU into the multiply’s last store. Read DWT->CYCCNT for both versions. The gap is the extra pass over memory. Keep the matrices in the SRAM region that is not cached, so the gap is easy to read.
Chapter 6
Write the loop once as a program that prints code, then let a search pick the tile
You now have a list of choices. The tile shape. The tile depth. Double buffering on or off. The unroll of the inner loop. The initiation interval. The activation to fuse. Each combination is a different program for the chip. Writing them by hand would take weeks, and you would miss the best one.
The way out is to write one program that writes the kernels. This is a kernel generator: a template with holes for the choices, which prints the instructions of the target chip as text.
First, the template. It is the tiled loop from Chapter 1 and the double-buffered loop from Chapter 3, written as code that loops over tiles at generation time and prints one instruction per line. The instruction set is the chip’s ISA (instruction set architecture): the list of instructions the hardware understands. A custom chip has a custom ISA, so no off-the-shelf compiler emits it for you.
Second, the parameters: tile sizes, depth, buffering, unroll. The generator reads the machine description (SRAM size, MMA shape, latencies) and refuses any combination that cannot fit. That refusal is the Chapter 2 footprint test, run at generation time.
Third, the search. An autotuner generates many variants, scores each on the simulator or on the chip, and keeps the fastest. On GPUs the same pattern appears as CUTLASS templates parametrised by tile shape, and as Triton’s autotuner over a list of configurations. Our toy ISA is invented for this lesson, but the structure is the real one.
The device below emits code for a 12 × 12 × 12 multiply on a toy machine with a 4 × 4 × 4 MMA. The problem is small so that the page can really run the emitted instructions and check the answer. Five instructions are enough: zero the sums, dma.ld a tile, dma.wait for it, mma on the tiles, dma.st the result. A load finishes in the background two instructions after it starts, which is how a real DMA behaves: it is not done when the instruction returns.
// The generator in miniature: one function, loops at generation time, one line out per instruction. function emit({ M, N, K, Tm, Tn, Tk, db }) { const out = []; for (let i0 = 0; i0 < M; i0 += Tm) for (let j0 = 0; j0 < N; j0 += Tn) { const tm = Math.min(Tm, M - i0), tn = Math.min(Tn, N - j0); // clip the edge tiles out.push('acc.zero'); for (let k0 = 0, s = 0; k0 < K; k0 += Tk, s++) { const tk = Math.min(Tk, K - k0), b = db ? s & 1 : 0; out.push(`dma.ld sA[${b}], A[${i0},${k0}], ${tm}x${tk}`); out.push(`dma.ld sB[${b}], B[${k0},${j0}], ${tk}x${tn}`); out.push(`dma.wait ${b}`); // never skip: the load is still in flight out.push(`mma acc, sA[${b}], sB[${b}] ; ${tm}x${tn}x${tk}`); } out.push(`dma.st C[${i0},${j0}], acc`); } return out; }
Read it as a recipe. The two outer loops pick an output tile. The inner loop walks K and prints four lines per slice. The Math.min calls clip tiles that hang over the edge, so a 12-wide problem works with a tile of 8. The double-buffered version only changes which buffer index b each slice uses; the full pipelined form also issues the next load before the mma, as in Chapter 3.
A generator that is fast and wrong is worse than a slow one that is right. It ships bad results at full speed. Two bugs are common, and both are easy to write.
The first is the dropped remainder. A tile of 8 does not divide 12, so the last tile is only 4 wide. A lazy loop skips partial tiles. The kernel runs, and part of C is silently zero. The second is the missing wait. Leave out dma.wait and the matrix unit reads a buffer that the DMA has not finished filling. Sometimes the old data happens to be right. Usually it is not.
The cure is dull and complete. After generating, run the kernel and compare every output against a plain reference matrix multiply, for example numpy’s. Use a tolerance for floating-point numbers, because a different order of addition changes the last bits. Use the toy device to cause both bugs and see what the check reports.
Pick a tile and a generator, then press Emit and run. The page runs the emitted lines and compares C with a reference. Then press Autotune to search the tile space of the big machine.
The toy ISA, the 12 × 12 × 12 problem and the 4 × 4 × 4 MMA are invented so the page can run the code for real. The data are small integers, so the check is exact. The scatter uses the big toy machine of the earlier chapters (128 KiB, 100 bytes per cycle): 5 × 5 × 4 × 2 = 200 candidates.
The scatter shows what the autotuner sees. Each dot is a generated kernel. The x position is the memory it needs, the y position is its utilisation. Red dots are over the memory limit. Of the 200 candidates, 165 fit. The best fitting one is a 128 × 128 tile with depth 64 and double buffering, at 78.1%: the same answer you reached by reasoning in Chapters 2 and 3. Depths 16 and 32 tie on utilisation (depth 128 spills), so the tuner breaks the tie with the larger depth, which means fewer DMA transfers.
Why search if reasoning found it? On a real chip the model is never exact. The search over measured counters finds the surprises. And the search runs again for every new chip, matrix shape and memory size, without a person redoing the algebra.
Board: STM32 Nucleo-H743ZI2. Write a small Python script that prints a C file for a float32 matrix multiply with a block size passed as an argument. Generate block sizes 4, 8, 16 and 32, compile each, and read DWT->CYCCNT around the call. Compare each result with numpy on the host over a serial link. Pick the fastest block that is also correct.
Chapter 7
Read the counters to find which stall you have, and check the simulator against the chip
A doctor does not guess why you feel ill. She takes your temperature, your pulse and your blood pressure. Three numbers, read in the right order, narrow the cause. A kernel engineer does the same with performance counters: small hardware registers that count events. How many cycles was the matrix unit busy? How many cycles did it wait? How many bytes did the DMA move?
You have used these ideas all through the lesson without naming them. Utilisation is the busy count divided by the total. A spill is bytes moved higher than planned. A missing overlap is busy plus waiting adding up to the total. This chapter names the counters and shows how to use them.
Four counters answer most questions about a kernel.
Read them like a decision tree. Busy plus stalls equals total. If the stalls are mostly setup, you have too many small transfers: make tiles bigger or batch the transfers. If they are mostly data wait, the DMA is the limit: raise intensity or add overlap. If the bytes are higher than your plan, you are spilling. If none of the stalls are large and utilisation is still low, the unit is idle between instructions: look at the schedule (Chapter 4).
You will not tune a kernel on the chip alone. The chip may not exist yet, or it is scarce, or it is slow to instrument. So you tune against a simulator: a program that models the chip’s timing. A cycle-accurate one models every clock. A faster one, like the toy model in this lesson, models the large effects only.
The simulator is useful only if it matches silicon. Correlation is the check: run the same kernels on both and compare the counters. You set a tolerance, such as 5%, and the model must stay inside it. When it does not, the mismatch points at a missing piece of the model.
Here is a worked case on the toy machine. The simulator as shipped says DMA delivers 100 bytes per cycle and a transfer starts after 240 cycles of setup. The silicon is modelled differently: it delivers 88 bytes per cycle and the setup takes 264. Its matrix unit also loses 2% to issue gaps. These silicon numbers are made up for the exercise, but the process is what real teams do.
Take the default tile, 128 × 128 with double buffering. The simulator predicts 78.1% utilisation. The silicon measures 68.8%. The simulator is 13.6% too optimistic. Now look at the pattern across seven configurations: the optimism is large (9 to 14%) on every one. The error is largest where the DMA dominates, and the one counter that tells you why is the achieved bandwidth: bytes moved divided by DMA-busy cycles gives 88, not 100.
Fit that one number into the simulator. The double-buffered rows now agree to 0%. The single-buffered rows still show 3 to 7%, because they also pay the setup, which is 264, not 240. Fit that too. Every row falls under 1%. The model is now trustworthy for these kernels, and it is trustworthy for a reason you can name.
The bars show where the cycles of one step go, on silicon (top) and in the simulator (bottom). The table compares every configuration. Choose how much of silicon you have fitted into the simulator, and set the tolerance.
Silicon is a made-up model for this exercise: 88 bytes per cycle of DMA, 264 cycles of setup, and a matrix unit 2% slower than ideal. Nothing here is a measurement of a real chip. Click a row to see its bars. Illustrative.
Two traps are worth naming. The first is to trust the simulator’s number because it is the one you can get. A simulator is a claim about the chip. The chip decides. The second is to fix a mismatch by tuning the kernel. If the model is wrong, a kernel tuned to it is tuned to a chip that does not exist.
The counters you read on silicon should have the same names as the simulator’s. If they do not, you cannot compare them, and a mismatch tells you nothing. Define the counters once, in the machine description, and have both the simulator and the hardware report them.
Board: STM32 Nucleo-H743ZI2. The Cortex-M7 data watchpoint unit has cycle and event counters: DWT->CYCCNT for total cycles, DWT->LSUCNT for extra load and store cycles, DWT->CPICNT for extra multi-cycle and fetch-stall cycles. The event counters are 8 bits wide, so read them often. Enable tracing in DEMCR first. On some Cortex-M7 parts the DWT block also needs unlocking through its lock access register, DWT->LAR, so check the reference manual. Run a kernel, record all three, and check that your model predicts the cycles within 5%.
Chapter 8
Keep the numbers, the terms and the tuning loop on one page, and take the model home as code
The whole lesson is one loop. Tile the multiply so each fetched byte feeds many operations. Budget the tiles against the on-chip memory. Buffer twice so loading hides behind maths. Schedule the instructions inside the tile and respect the register file. Fuse what can ride along. Generate the variants and let a search pick. Count the cycles on the simulator and on silicon, and correlate them. Then go round again, because the counters will show a new limit.
The order matters. A faster clock, a cleverer schedule or a bigger tile cannot fix a limit that sits somewhere else. The counters tell you where to look first.
| Quantity | Value | Source |
|---|---|---|
| DRAM against SRAM read energy | 640 pJ against 5 pJ for 32 bits, 128× | Horowitz, 45 nm, as tabulated by Han et al. |
| Float multiply energy | 3.7 pJ for 32 bits | The same table |
| TPU v1 matrix unit | 65,536 8-bit MACs, 92 TOPS, 700 MHz | Jouppi et al., 2017 |
| TPU v1 on-chip memory | 24 MiB Unified Buffer + 4 MiB accumulators | Jouppi et al., 2017 |
| TPU v1 weight memory bandwidth | 34 GB/s; ridge point 1,350 operations per byte | Jouppi et al., 2017 |
| Square fp32 tile intensity | b / 6 FLOP per byte | Derived in Chapter 1 |
| Toy machine | 4,096 MAC per cycle, 128 KiB, 100 B/cycle, 240 setup | Illustrative |
| 128 tile, single buffered | 256 of 824 cycles busy, 31.1% | Illustrative |
| 128 tile, double buffered | 256 of 328 cycles busy, 78.1% | Illustrative |
| 256 tile, double buffered | 384 KiB needed, spills, 17.4% | Illustrative |
| Largest double-buffered square tile | 4b² + 512b ≤ 131,072 gives b = 128 | Derived in Chapter 2 |
| Software pipeline, 8 iterations | 96 cycles plain, 33 at II = 3, 54 with spills at II = 2 | Illustrative |
| Unfused activation penalty | +67% at K = 64, +2.5% at K = 4,096 | Illustrative |
| Autotune space | 200 candidates, 165 fit, best 78.1% | Illustrative |
| Term | Plain meaning |
|---|---|
| Kernel | A small program that runs on the accelerator and does one job. |
| GEMM | General matrix multiply: C = A × B plus C. |
| Utilisation | Achieved work divided by peak work. Also called MFU. |
| Arithmetic intensity | Operations done per byte moved. |
| Tile | A small block of a matrix, sized to fit on chip. |
| SRAM scratchpad | Small fast on-chip memory that software manages. |
| DMA | A copy engine that moves blocks of bytes without the compute units. |
| Working set | Everything a step needs in SRAM at once. |
| Spill | Moving data to DRAM because it did not fit on chip or in registers. |
| Double buffering | Two buffers per operand: load one while using the other. |
| Initiation interval | Cycles between the starts of two loop iterations in a software pipeline. |
| Fusion | Running two operations in one kernel so data between them stays on chip. |
| Kernel generator | A program that prints kernels for the target ISA. |
| Performance counter | A hardware register that counts cycles or events. |
| Correlation | Checking that simulator and silicon counters agree within a tolerance. |
This is the whole cost model of the lesson in Python, plus a check that a tiled multiply gives the same answer as numpy. It is the code behind the hero. Change the numbers and compare with the table above.
import numpy as np from math import ceil def step_cycles(Tm, Tn, Tk, double_buffer, bw=100, setup=240, sram_kib=128, mma=16): # cycles the matrix unit is busy: one 16x16x16 block per cycle, padded up tc = ceil(Tm / mma) * ceil(Tn / mma) * ceil(Tk / mma) useful = Tm * Tn * Tk / mma**3 a, b, c = Tm * Tk * 2, Tk * Tn * 2, Tm * Tn * 4 # bytes: fp16 A, fp16 B, fp32 sums footprint = (2 if double_buffer else 1) * (a + b) + c spill = footprint > sram_kib * 1024 moved = a + b + (2 * c if spill else 0) # a spill moves the sums out and back td = moved / bw step = max(tc, td) if double_buffer else setup + td + tc return useful / step, footprint, spill def tiled_matmul(A, B, Tm, Tn, Tk): M, K = A.shape; N = B.shape[1]; C = np.zeros((M, N), np.float32) for i0 in range(0, M, Tm): for j0 in range(0, N, Tn): acc = np.zeros((min(Tm, M - i0), min(Tn, N - j0)), np.float32) for k0 in range(0, K, Tk): # clip edge tiles with slicing acc += A[i0:i0+Tm, k0:k0+Tk].astype(np.float32) @ B[k0:k0+Tk, j0:j0+Tn].astype(np.float32) C[i0:i0+Tm, j0:j0+Tn] = acc return C for db in (False, True): u, f, s = step_cycles(128, 128, 64, db) print("double" if db else "single", f"{u:.1%}", f // 1024, "KiB", "spill" if s else "") # 31.1%, then 78.1% rng = np.random.default_rng(0) A = rng.standard_normal((200, 150)).astype(np.float16); B = rng.standard_normal((150, 170)).astype(np.float16) ref = A.astype(np.float32) @ B.astype(np.float32) assert np.allclose(tiled_matmul(A, B, 64, 64, 64), ref, rtol=1e-4, atol=1e-3) # odd sizes, clipped tiles
This lesson stayed on a small, made-up machine on purpose, so every number could be derived. The same ideas run the real ones. Google’s first TPU is a matrix unit fed by a software-managed buffer and a programmable DMA controller. NVIDIA’s CUTLASS cuts GEMM into threadblock, warp and thread tiles and double buffers at several scopes. Triton and ThunderKittens give a programmer tile-shaped building blocks on GPUs. The vocabulary changes. The loop does not.
Companies that build their own accelerators describe the same work in public: write kernel generators that emit low-level assembly, schedule instructions, allocate registers, pipeline loops, hunt for places where the compiler misses the hardware’s peak, and tune tiling and fusion to save bandwidth and on-chip data movement. The GPU programming models in this lesson, CUDA and its relatives, belong to the GPU lessons below. This lesson only used them as analogues.
Two lessons that this one builds on are planned for the same track and are not yet written: one on accelerator microarchitecture, where the matrix unit and its dataflow are drawn, and one on DRAM and bandwidth, where the bytes-per-cycle figure comes from. Treat the toy machine here as a sketch of both.
Now explain it back. Open Teach and draw the double-buffered timeline from memory, or go back to the hero and find the 78% yourself.