A plain matrix multiply takes 24,296 ms. Reorder three loops and it takes 1,979 ms, 12 times faster, with the same arithmetic. Speed comes from how you move data.
Learn why a model that fits on a tiny chip can still run too slowly, and the loop, vector, thread, GPU and convolution tricks that fix it.
Pick a trick, then press Race. Watch it finish the same multiply while the plain loop is still working. Then we build each trick, piece by piece, from the memory underneath it.
You need a little C or Python (loops and arrays) and the idea of a matrix. We build the rest from zero.
Based on Lecture 11 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. Lecture 11 slides are on the course page. Every idea is re-taught here in our own words and devices; it follows Lecture 10, MCUNet and leads into Lecture 12.
From the lecture: the plain loop took 24,296 ms and loop reordering 1,979 ms (12x), measured on an Intel Xeon 4114. The other times are computed here from the slide speed-ups against that plain loop: tiling 19x, unrolling 2.85x, 4 threads 4.1x, CUDA 94x (end to end, on an RTX 2080 Ti). The SIMD bar is an illustrative ideal, one quarter of the arithmetic steps, not a measurement. The race clock is slowed so you can watch it.
Chapter 0
See how far a 320 KB chip sits from a data-center GPU, and why moving data costs more than computing on it
A doorbell camera must tell a person from a parcel in a split second, on a chip that costs a few dollars. MCUNet found a model small enough to fit such a chip. It can still run too slowly. The fix lives in the inference engine, the program that runs the model.
Edge devices sit next to the data, not in a data center: phones, vehicles, robots, medical devices, vending machines, home appliances. Running the model there keeps data private and needs no network. The cost is size.
Each bar is on a log scale, so every step to the right is ten times more. Switch the view. The teal bar is the microcontroller.
From the slides: H100 80 GB and 1,979 TOPS; M2 Ultra 64 to 192 GB and 31.6 TOPS; S8Gen2 8 to 24 GB and 36 TOPS (low ends plotted); STM32F746NG 320 kB and 462 MOPS. The slide's storage ratios fit 1 microsecond, not its printed 1 ms, so ours come from the latencies.
The data-center card holds 80 GB. The chip holds 320 kB, about 250,000 times less, and its compute is about 4.3 million times lower.
A microcontroller (MCU) is a whole computer on one chip. The lecture's example is the STM32F746, built on an Arm Cortex-M7 core, set beside a laptop.
| Part | STM32F746 MCU | MacBook Pro (M1 Ultra) | Ratio |
|---|---|---|---|
| CPU cores | 1 | 20 (plus 64 GPU and 32 neural-engine cores) | 20x |
| Clock | 216 MHz | 3,200 MHz | 15x |
| L1 cache | 8 KB | 320 KB | 40x |
| Memory | 320 KB (SRAM) | 64 GB | 210,000x |
| Storage | 1 MB (flash) | 8 TB | 8,400,000x |
| Operating system | none | macOS |
Two rows decide the rest of this lesson. One core means the chip cannot split work across cores. An 8 KB cache means the cache decides how fast a loop runs.
Memory forms a pyramid, like a cook's cutting board, pantry and shop. Each level down is larger, slower and cheaper.
| Level (laptop, from the slide) | Size | Wait for one read |
|---|---|---|
| L1 cache | 320 KB | 0.5 ns |
| L2 cache | 48 MB | 7 ns (14x L1) |
| Main memory (DRAM) | 64 GB | 100 ns (200x L1) |
| Storage | 8 TB | 1 ms |
A cache is a small fast memory that keeps copies of recent data. A cache miss is a read that must go down a level. Locality is the habit of reading data near what you read last.
One wrong level costs a lot. A loop reads 1,000 numbers. From L1 the waits add up to 1,000 × 0.5 ns = 500 ns. From DRAM they add up to 100,000 ns: 200 times longer, for the same arithmetic.
Symptom: two layers with equal FLOPs (arithmetic operations) differ ten times in time. Measure: time the layer and count the bytes it moves, not only its operations. Fix: change how the data moves. The race at the top shows it: one multiply, 24,296 ms against 1,979 ms.
Almost every layer, once rewritten, is a matrix multiply, so the lecture works on loops. Its parts: the MCU, four ways to compute in parallel, four inference tricks.
Chapter 1
Swap two lines of a matrix multiply and watch the cache misses fall by a factor you can count
Look up one name in a phone book and the whole page comes with it. Read only the first name on each page, and every read needs a new page. A matrix multiply has the same problem.
Call the answer matrix C and the inputs A and B. The cell of C in row i and column j pairs row i of A with column j of B. A counter k walks along the pairs.
C i j equals the sum over k of A i k times B k j.
Walk along row i of A and down column j of B together. Multiply each pair A i k and B k j. Add the products to get C i j.
With made-up numbers: row i of A is (1, 2, 3) and column j of B is (4, 5, 6). C i j = 1 × 4 + 2 × 5 + 3 × 6 = 32.
Memory is one long line of slots. C and C++ store a grid row-major, row after row, so in an N by N matrix B k j sits at slot k × N + j. Column neighbours are N slots apart. Memory arrives one cache line at a time, a short run of neighbouring slots.
The plain loop runs i, then j, then k. With k innermost, B k j walks down a column and each read lands on a new line. The lecture reorders (i, j, k) as (i, k, j). Now j is innermost, so the loop reads B and C along rows, one slot at a time (stride 1). A i k stays fixed, so the code keeps it in a variable, Aik.
Choose a loop order, then press Replay. Dashed boxes are cache lines of 4 numbers.
Illustrative toy: a 12 by 12 matrix, 4 numbers per line, a 6-line cache that drops the oldest line. Read-out totals: a full 32 by 32 multiply (8 per line, 32 lines). The lecture measured 12 times.
In the plain order all 24 reads miss. In the reordered order 6 of 24 miss, one per new line. The lecture timed naive_mat_mul at 24,296 ms and mat_mul_reordering at 1,979 ms, 12 times faster, on an Intel Xeon 4114.
python# A (M,K), B (K,N), C (M,N) are row-major. Same answer, different visit order. def matmul_plain(A, B, C, M, N, K): for i in range(M): for j in range(N): acc = 0.0 for k in range(K): acc += A[i][k] * B[k][j] # B walks down a column: stride N C[i][j] = acc def matmul_reordered(A, B, C, M, N, K): for i in range(M): for k in range(K): a_ik = A[i][k] # hoisted: one load, kept in a register for j in range(N): C[i][j] += a_ik * B[k][j] # B and C walk along rows: stride 1
C must start at zero, because the reordered loop adds into it.
Symptom: a layer is fine on a small test, then slows far more than its arithmetic as the matrix grows. Measure: does one column of B, N cache lines, still fit in the cache? Fix: put the loop that moves along memory innermost.
Chapter 2
Cut the work into blocks that fit in the cache, and pick the block size from the cache size
The reordered loop sweeps all of B for every row of A. If B is larger than the cache, its first rows are gone before the next sweep, so B comes from slow memory again. The slide: "data in cache will be evicted before reuse".
Loop tiling cuts the loops into blocks of T by T numbers, called tiles. The loop uses each tile many times while it sits in the cache. The slides tile one loop at a time:
Three tiles must sit in the cache together, one each of A, B and C. Call the tile side T, the bytes per number b and the cache size in bytes S.
Three T squared times b is at most S.
Square the tile side T and multiply by 3 for the three tiles. Multiply by b to get bytes. If the result is no more than S, the tiles fit.
The MCU's L1 cache is S = 8,192 bytes, and float32 has b = 4. T = 16 needs 3 × 256 × 4 = 3,072 bytes and fits. T = 32 needs 12,288 bytes and does not. With int8 (b = 1), T = 32 needs only 3,072.
The slide's code uses BLK_SIZE 32 and runs 19 times faster than the plain loop on an Intel Xeon 4114. That chip has a larger cache, so its best tile is not the MCU's. The tile size belongs to the cache.
A chip with an L2 cache gets a second, larger tile, TILE2 by T, that lives in L2 while the T by T tile lives in L1. The STM32F746 has only L1, so one level applies.
Each bar is the miss count for one tile size. Green bars have a working set that fits the cache. Red bars spill.
Illustrative: a 32 by 32 float multiply, order (i, k, j), a cache of 32 lines of 8 numbers that drops the oldest line. Look at the shape: a dip, then a cliff. The lecture measured 19 times.
The toy cache holds 256 numbers. At T = 8 the three tiles hold 192 and fit, for the fewest misses. At T = 16 they need 768 and spill, and the misses jump to four times the T = 8 count.
python# Tiled, reordered matmul. Tile bounds use min() so N need not be a multiple of T. def matmul_tiled(A, B, C, N, T): for ti in range(0, N, T): for tk in range(0, N, T): for tj in range(0, N, T): for i in range(ti, min(ti + T, N)): for k in range(tk, min(tk + T, N)): a_ik = A[i][k] for j in range(tj, min(tj + T, N)): C[i][j] += a_ik * B[k][j] # three T x T tiles are live
Symptom: you add tiling and the code gets no faster. Measure: compare 3 T² × b with S. Fix: shrink T until the tiles fit with room to spare, since other data shares the cache. If N is not a multiple of T, stop the last tile at the edge, as min does above.
Chapter 3
Repeat the loop body so the chip spends less time counting and more time multiplying
Every pass of a loop pays for bookkeeping before it does useful work. The slide lists three costs: pointer arithmetic (step k and find the next address), the end-of-loop test (is k still below N?) and the branch back to the top. None of them multiplies. In the inner loop of a matrix multiply they run N³ times.
Loop unrolling copies the loop body several times, so the bookkeeping runs once per group. The slide unrolls by 4 and counts the change:
The last line is the price, a trade-off between binary size and overhead. On the STM32F746, 1 MB of flash holds both the program and the weights. Each extra copy takes room from the model.
Use a toy cost model, made up for counting: 3 instructions per multiply-add and 3 per loop pass, for 16 multiply-adds in a row.
Overhead falls from 50% to 11%, but each doubling saves less: 24 instructions, then 12, then 6. The 48 instructions of real work are the floor.
Warm blocks are multiply-adds, yellow blocks are loop control. The small boxes count the copies of the body the program stores.
Illustrative toy: 3 instructions per multiply-add and per pass. Real chips overlap instructions. The lecture measured 2.85 times for its kernel (j by 8, k by 4) on an Intel Xeon 4114.
The toy tops out at 1.8 times; the slide measures 2.85. The slide's mat_mul_unrolling also unrolls j by 8 and keeps eight running sums, acc[0] to acc[7]. Independent sums let the chip overlap multiplies, and the toy does not model that.
python# Unroll the k loop by 4. Assumes K is a multiple of 4 (see the failure below). def dot_unrolled4(a, b, K): acc = 0.0 for k in range(0, K, 4): # one test and one jump per 4 products acc += a[k] * b[k] acc += a[k + 1] * b[k + 1] acc += a[k + 2] * b[k + 2] acc += a[k + 3] * b[k + 3] return acc
Symptom: a wrong sum, or a crash, at K = 10. Measure: with a step of 4, the last pass starts at k = 8 and reads k + 3 = 11, past the end. Fix: unroll the first 8, then finish the last 2 in a plain loop. Compilers do this for you; a hand-written kernel must do it too.
Chapter 4
Pack several numbers into one wide register and multiply them all in a single step
One knife chops one carrot per stroke. A wide blade cuts four. SIMD (single instruction, multiple data) is the wide blade: one instruction does the same operation on several numbers.
The instruction set architecture (ISA) is the menu of actions a processor knows: ADD, COMPARE, JUMP, JUMP IF, LOAD, STORE, and input and output. Software reaches the hardware only through it.
A CISC chip (for example Intel x86) has many specialised instructions. A RISC chip (Arm, RISC-V) keeps the common ones. For C = A + B, CISC may need one instruction, add a, b, c. RISC needs four: load, load, add, store. The Cortex-M7 is an Arm design, so it is RISC.
A register is a slot inside the processor that holds the numbers of the next instruction. A normal one holds one 32-bit number. A 128-bit vector register holds four, each in a lane. One instruction then does four multiplies. That raises throughput and saves energy, because one fetch and decode serves four.
Code reaches these instructions through intrinsics, functions that map to one instruction each.
| Intrinsic | Read it as |
|---|---|
_mm_load_ps (x86 SSE) | mm: multimedia; load; ps: packed single-precision |
vld1q_f32 (Arm NEON) | v: vector; ld: load; 1: one vector; q: quadword (128 bits); f32: 32-bit float |
vmulq_f32, vaddq_f32 | the same pattern for multiply and add |
Load four numbers from A and four from B, multiply lane by lane, and add into four running sums. The slide's count: arithmetic operations fall from N³ to N³/4. Take a = (1, 2, 3, 4, 5, 6, 7, 8) and b = all ones. The answer is 36.
The two rows are 16 numbers from A and 16 from B. Purple boxes show what one instruction covers. Press Replay to watch the steps.
Arithmetic of widths, not a measurement: 128 / 32 = 4 float32 lanes, 128 / 8 = 16 int8 lanes. Loads and the horizontal sum also cost time. The slide states only N³ to N³/4 for 4 lanes.
With 16 int8 lanes, the whole dot product is one step plus the horizontal sum. So int8 pays twice: each number takes a quarter of the bytes, and a register carries four times as many.
The slide's SSE and NEON code first transposes B, so both operands are read along k in stride 1.
python# What the intrinsics do, written with numpy lanes. Bt is B transposed: shape (N, K). import numpy as np def dot_simd4(a, bt_row, K): lanes = np.zeros(4, dtype=np.float32) # one vector register of 4 running sums for k in range(0, K, 4): lanes += a[k:k+4] * bt_row[k:k+4] # load 4, load 4, multiply, add: 4 products per step return lanes.sum() # horizontal sum, once
Symptom: a test that checks SIMD against scalar for exact equality fails by a tiny amount. Measure: the four lane sums add in a different order, and float addition is not exactly associative. Fix: compare with a small tolerance. Without the transpose, each vector load would gather numbers N slots apart.
Chapter 5
Give each core its own rows of the answer, then check that no row gets lost
Four painters on one wall finish in a quarter of the time, if they split it well. A bad split leaves a bare strip that nobody sees until the end. Multithreading puts more cores to work in the same way.
A thread is the smallest unit of execution in a program. Threads in one process share memory, but each has its own stack and program counter, the marker of its next instruction. Different threads can run on different cores at once. The slides list four gains: speed, a program that stays responsive, cheaper sharing than separate processes and simpler pieces.
The slide splits the outer loop over i, the rows of C. Each thread runs the full j and k loops for its own rows. So each thread writes only its own cells. If you split k instead, threads add into the same C i j at once, a bug called a race condition.
| Pthreads | OpenMP | |
|---|---|---|
| What it is | A C library for POSIX threads | An API for C, C++ and Fortran, portable across platforms |
| How you write it | pthread_create for each thread, pthread_join to wait. Each thread sets rows_per_thread = SIZE_MATRIX / NUM_THREADS, start_row = thread_id * rows_per_thread, end_row = (thread_id + 1) * rows_per_thread | omp_set_num_threads(4), then #pragma omp parallel for above the loop. Also sections, and single, critical, barrier for synchronisation |
| The slide's point | 4.1x with 4 threads against the plain loop, Intel Xeon 4114 | Cleaner code that fits into existing code |
Take N = 100 rows and 4 threads: 25 rows each, rows 0 to 24, 25 to 49, 50 to 74 and 75 to 99. Now take N = 10. Integer division gives 10 / 4 = 2, so the threads cover rows 0 to 7. Rows 8 and 9 belong to nobody.
Each bar is one row of C, colored by its thread. A red bar with a cross is a row that no thread computes.
The split rule is the slide's. The ideal time, plain time over the thread count, ignores memory contention and start-up cost. The lecture measured 4.1 times with 4 threads.
The bug appears whenever N is not a multiple of the thread count. The fix lets the last thread run from its start row to N.
python# Which rows does thread t compute? The fixed rule never drops a row. def rows_for(t, T, N): per = N // T start = t * per end = N if t == T - 1 else (t + 1) * per # the last thread takes the remainder return range(start, end) # C needs, for example: #pragma omp parallel for (one line, each thread gets its rows) # Each thread writes only C[i][*] for its own i, so no two threads touch the same cell.
The STM32F746 has one core, so threads cannot speed it up. Its gains come from the loop tricks and SIMD. Threads matter on laptops and phones, and the lab times them on your own computer.
Symptom: the last rows of C are zero, and only for some sizes. Measure: count the rows covered. The slide's rule covers threads × floor(N / threads), 8 for N = 10. Fix: let the last thread run to N, or use OpenMP, which splits the loop for you.
Chapter 6
Give each GPU thread an address, then let a tensor core multiply a whole tile
A GPU has thousands of workers and much higher instruction throughput and memory bandwidth. CUDA, Nvidia's C-like platform from 2006, tells each worker which cell is its own.
| Word | Meaning |
|---|---|
| Host, device | The program on the CPU, which runs step by step; the GPU |
| Kernel | A function the host launches; the device runs it once per thread |
| Thread block, grid | A group of threads that can share fast memory; all the blocks of one launch |
| Private, shared, global memory | Per thread; per block; the whole device. Each has its own load and store cost |
The slide adds two 12 by 6 arrays with threadsPerBlock = (4, 3) and numBlocks = (12 / 4, 6 / 3) = (3, 2). That is 6 blocks of 12 threads: 72 threads, one per cell.
All threads run the same code, so each computes its own cell. Call a thread's place in its block threadIdx, the block's place in the grid blockIdx and the block's width blockDim.
i equals block-index-x times block-dim-x, plus thread-index-x. j is the same with y.
Skip blockIdx.x whole blocks, each blockDim.x wide. Then step threadIdx.x more. That is column i. Do the same downward for row j.
Block (2, 1), thread (1, 2), blocks of 4 by 3: i = 2 × 4 + 1 = 9 and j = 1 × 3 + 2 = 5. It computes C[5][9].
Tap a cell, or press Next thread, to read its address.
The 12 by 6 grid and 4 by 3 block are the slide's. Every shape gives 72 threads.
Host and device memory are separate: allocate with cudaMalloc and copy with cudaMemcpy before the kernel reads.
The slide's fast multiply loads tiles of A and B into shared arrays As and Bs, waits with __syncthreads(), multiplies and waits again. That is Chapter 2's tiling, in a cache the program controls. On an RTX 2080 Ti it is 94 times faster end to end than the plain CPU loop.
cuda// From the slide: one thread per output cell. Launch: 6 blocks of 12 threads = 72 threads. dim3 threadsPerBlock(4, 3); dim3 numBlocks(Nx / threadsPerBlock.x, Ny / threadsPerBlock.y); // (3, 2) matrixAdd<<<numBlocks, threadsPerBlock>>>(A, B, C); __global__ void matrixAdd(float A[Ny][Nx], float B[Ny][Nx], float C[Ny][Nx]) { int i = blockIdx.x * blockDim.x + threadIdx.x; // column int j = blockIdx.y * blockDim.y + threadIdx.y; // row C[j][i] = A[j][i] + B[j][i]; }
A CUDA core does 1 FP32 or 2 FP16 multiply-adds per cycle. A tensor core does a whole small multiply in FP16 per cycle: 4 by 4 by 4 on Turing, 8 by 4 by 8 on Ampere. On an A6000 it is 3.8 times faster for large multiplies.
| H100, number type | Unit | TFLOPS |
|---|---|---|
| FP32 | CUDA core | 67 |
| TF32 (tensor cores only) | Tensor core | 989 |
| FP16 | Tensor core | 1,979 |
| INT8, FP8, sparse FP16 | Tensor core | 3,958 (about 60x FP32) |
Code drives a tensor core with a fixed-shape matrix multiply intrinsic (MMA). The slides build a 16 by 16 by 32 product from 16 by 8 by 16 MMAs: 2 tiles of A, 4 of B, 2 of C. Four MMAs of 2,048 multiply-adds give 8,192.
Press Next MMA to issue one instruction. Warm tiles are its inputs; purple is the output tile it adds into.
The slides say the order of the four MMAs does not matter.
Symptom: garbage on some runs, or a crash at once. Measure: a thread that reads a shared tile before its neighbour finishes loading gets stale numbers, so the error changes with timing. Fix: call __syncthreads() after loading and after use. A crash at the first access often means a host pointer: copy to the device first.
Chapter 7
Copy every sliding window into a row, use the fast multiply, and pay for the copies in memory
A convolution slides a small filter over an image and adds up the products under it, one output per position. Im2col (image to column) rearranges it into a matrix multiply, so the fast multiply of Chapters 1 to 6 can run it.
Call the input X, with height H, width W and C channels. A filter covers a K by K window over all channels: K²C numbers. Stack the layer's N filters as columns of a K²C by N weight matrix. One multiply gives the output Y.
Y, H W by N, equals im-to-col of X, H W by K squared C, times the weights, K squared C by N.
Copy each window of X into a row, so X becomes HW rows of K²C numbers. Multiply by the weights. Row p of Y holds the N outputs at position p.
Input 56 by 56 with C = 32, K = 3, int8: im2col(X) is 3,136 rows by 288 columns, 903,168 bytes. The input was 100,352 bytes, so the copy is K² = 9 times larger. With N = 64 filters (made up), Y is 3,136 by 64.
A small case: a 5 by 5 input, 1 channel, a 3 by 3 filter, no padding. Its 9 windows of 9 numbers make 81 numbers from 25. The centre pixel sits in all 9 windows, a corner pixel in one.
The grid shows how many windows each pixel of a 9 by 9 patch lands in. The bars show int8 bytes. The dashed line is 320 KB.
Computed: int8, stride 1, same-size output. 320 KB is the STM32F746's SRAM (1 KB = 1,024 bytes). A layer also needs room for filters and output.
At 1 by 1 the matrix equals the input: a 1 by 1 convolution already is a matrix multiply. At 5 by 5 the copy grows 25 times. The 56 by 56 by 32 layer at 3 by 3 needs 2.76 times the MCU's 320 KB.
The slide's pro: im2col reuses a tuned matrix multiply (GEMM). The con: extra memory. The way out is implicit GEMM, a variant of direct convolution that reads each window from the input on the fly and never builds the matrix. It costs harder index arithmetic, not memory.
pythonimport numpy as np def im2col(X, K): # X (H, W, C) int8 -> (H*W, K*K*C), same padding, stride 1 H, W, C = X.shape; r = K // 2 Xp = np.pad(X, ((r, r), (r, r), (0, 0))) rows = [Xp[y:y+K, x:x+K, :].reshape(-1) for y in range(H) for x in range(W)] return np.stack(rows) # every pixel is copied up to K*K times def conv_im2col(X, Wt, K): # Wt (N, K, K, C) -> output (H, W, N) H, W, C = X.shape; N = Wt.shape[0] cols = im2col(X, K).astype(np.int32) # (H*W, K*K*C) Wm = Wt.reshape(N, -1).T.astype(np.int32) # (K*K*C, N) return (cols @ Wm).reshape(H, W, N) # one GEMM
Symptom: out of memory at the first big convolution. Measure: H × W × K² × C bytes, here 903,168 against 327,680. Fix: use implicit GEMM or direct convolution, or build a few rows at a time in a small buffer that you reuse.
Chapter 8
Cut peak memory with one temporary buffer, and store each tensor in the order its layer reads it
Peak memory is the most activation memory alive at one moment. On an MCU it must stay under 320 KB of SRAM, and it decides whether a model fits. The slide points at the inverted residual block of MobileNetV2:
Depthwise layers cut model size and FLOPs. But the wide middle raises peak memory 3 to 6 times.
A depthwise layer reads C channels of H by W and writes the same shape. With separate buffers, both are alive. But channels never mix, so once channel c finishes, its input is dead and its output can take that slot. The slide calls this the in-place policy with a temporary buffer.
M-sep equals two times C times H times W. M-in equals one plus C, times H times W.
Separate buffers hold every channel twice, so M-sep is 2 times C maps. In place holds every channel once plus one temp map, so M-in is C plus 1 maps.
C = 96 and H = W = 28, so one map is 784 bytes. M-sep = 2 × 96 × 784 = 150,528 bytes. M-in = 97 × 784 = 76,048 bytes, about half.
Why the temp buffer? Each output reads its neighbours. Take x = (1, 2, 3, 4) and filter (1, 1, 1) with zero padding: the answer is (3, 6, 9, 7). Overwrite as you go and slot 0 becomes 3, so the second output reads 3 + 2 + 3 = 8, not 6.
Press Next channel: the channel goes into the purple temp buffer, then back. The sliders set the memory in bytes.
Computed with the slide's formulas, int8. The six-slab drawing is a toy. The slide's 3 to 6 times is for a whole block, not this one layer.
An activation has batch N, channels C, height H and width W, but memory is one line. The slide's rule picks the order by what the layer reads:
| Layout | Order in memory | Reads in stride 1 for |
|---|---|---|
| NHWC | One pixel with all its channels, then the next pixel | A pointwise convolution (1 by 1): a dot product across one pixel's channels. TinyEngine uses NHWC here. |
| NCHW | One whole channel, then the next channel | A depthwise convolution: it slides over one channel. TinyEngine runs its in-place depthwise in this order. |
The strip is the tensor in memory: 8 channels of 3 by 3 pixels. Teal slots are what one unit of work reads.
Illustrative: 8 channels; the slide uses 10. A jump is a read that is not in the next slot.
Pointwise in NCHW: 8 reads, 9 slots apart, 7 jumps. In NHWC: 0 jumps. Depthwise flips the result.
pythonimport numpy as np def dw3x3_inplace(act, filt): # act (C, H, W) int8 buffer, filt (C, 3, 3); NCHW order C, H, W = act.shape temp = np.zeros((H, W), dtype=np.int32) # the one extra buffer: H x W for c in range(C): p = np.pad(act[c].astype(np.int32), 1) for y in range(H): for x in range(W): temp[y, x] = (p[y:y+3, x:x+3] * filt[c]).sum() act[c] = np.clip(temp, -128, 127) # write back over channel c: its input is now dead return act # peak memory: (1 + C) x H x W slots
Symptom: in-place output smeared near edges, or accuracy that drops for no clear reason. Measure: run the layer with two buffers and compare. Fix: finish the whole channel in the temp buffer, then write it back. Also, a pointwise layer fed NCHW reads with stride H × W and runs slower.
Chapter 9
Compute four outputs of a 3 by 3 convolution with 16 multiplies per channel instead of 36
A multiply costs a chip more than an add. Winograd convolution does extra additions to skip multiplies, with exactly the same answer, for the common 3 by 3 filter.
Take one 3 by 3 filter over C channels and compute a 2 by 2 output block, 4 numbers. Direct convolution needs 9 × C × 4 = 36C multiply-accumulates (MACs). Winograd needs 16C, 2.25 times fewer.
Take a 3-tap filter g = (g0, g1, g2) and four inputs d = (d0, d1, d2, d3). The outputs y0 = d0g0 + d1g1 + d2g2 and y1 = d1g0 + d2g1 + d3g2 take 6 multiplies. Winograd uses 4:
Check with d = (1, 2, 3, 4) and g = (1, 1, 1): m1 = −2, m2 = 7.5, m3 = 0.5, m4 = −2, so y0 = 6 and y1 = 9, the direct answers. Terms like (g0 + g1 + g2) / 2 use only the filter, so you compute them once, offline.
In 2D the trick runs along rows and columns. Call the 3 by 3 filter g, the 4 by 4 input tile d and the 2 by 2 output Y. Three fixed matrices G, B and A hold only 0, 1, −1 and halves.
Y equals A-transpose, times G g G-transpose cell-by-cell times B-transpose d B, times A.
Turn the filter g into a 4 by 4 grid once. Turn each tile d into a 4 by 4 grid with adds and subtracts. Multiply the grids cell by cell, add over the channels, then fold the result with A into Y.
The device's ramp tile (0 to 15) with the sum filter of nine ones: Winograd and direct both give Y = (45, 54; 81, 90). Each channel took 16 multiplies, not 36. At C = 32 that is 512 MACs instead of 1,152.
| Matrix (from the slide) | Rows |
|---|---|
| AT | (1, 1, 1, 0), (0, 1, −1, −1) |
| G | (1, 0, 0), (1/2, 1/2, 1/2), (1/2, −1/2, 1/2), (0, 0, 1) |
| BT | (1, 0, −1, 0), (0, 1, 1, 0), (0, −1, 1, 0), (0, 1, 0, −1) |
Pick a tile and a filter. Step through the stages. The last stage compares the two answers cell by cell.
Computed live with the lecture's matrices on a made-up tile and filter, one channel, rounded to 2 decimals. The MAC counts 36C and 16C are the slide's.
On the last stage the answers match in every cell. Winograd as drawn fits 3 by 3 filters at stride 1. It wins when multiplies are the bottleneck, not memory, which on an MCU often is.
pythonimport numpy as np Bt = np.array([[1,0,-1,0],[0,1,1,0],[0,-1,1,0],[0,1,0,-1]], float) G = np.array([[1,0,0],[.5,.5,.5],[.5,-.5,.5],[0,0,1]]) At = np.array([[1,1,1,0],[0,1,-1,-1]], float) def winograd_f2x2_3x3(d, g): # d (C, 4, 4) input tile, g (C, 3, 3) filter -> (2, 2) U = np.einsum('ij,cjk,lk->cil', G, g, G) # filter transform, offline: (C, 4, 4) V = np.einsum('ij,cjk,lk->cil', Bt, d, Bt) # data transform: B^T d B, (C, 4, 4) M = (U * V).sum(0) # 16 multiplies per channel, summed over C: (4, 4) return At @ M @ At.T # output transform: (2, 2)
Symptom: accuracy falls after you switch a layer to Winograd. Measure: run the layer both ways on one input; exact arithmetic gives zero difference. In int8 or 16-bit, the transforms widen the value range and rounding grows. Fix: keep the transforms in a wider type, or leave Winograd off there. (Background, not a slide.)
Chapter 10
Review the numbers, the terms and the code, then pick the trick that matches the bottleneck
An inference engine turns a model that fits into a model that runs fast. The slides sort its tools into two groups. Parallel computing: reorder, tile and unroll loops, use SIMD, threads, and CUDA with tensor cores. Inference optimizations: im2col, in-place depthwise convolution, NHWC for pointwise and NCHW for depthwise, and Winograd.
| What | Number | Why it matters |
|---|---|---|
| Plain vs reordered matmul | 24,296 ms to 1,979 ms (12x) | Same arithmetic, read in order (Ch 1). Intel Xeon 4114 |
| Tiling, unrolling, 4 threads | 19x, 2.85x, 4.1x | Each against the plain loop on the same Xeon (Ch 2, 3, 5) |
| CUDA tiled matmul | 94x end to end, RTX 2080 Ti | Shared-memory tiles on a GPU (Ch 6) |
| STM32F746 MCU | 1 core, 216 MHz, 8 KB L1, 320 KB SRAM, 1 MB flash | The budget everything must fit (Ch 0) |
| H100 memory vs MCU memory | 80 GB vs 320 kB, about 250,000 times | Why the edge is hard (Ch 0) |
| L1 vs DRAM read | 0.5 ns vs 100 ns, 200 times | A cache miss is expensive (Ch 0, 1) |
| Tile size rule | 3 T² x bytes ≤ cache; T = 16 for float32 at 8 KB | Three tiles must fit together (Ch 2) |
| 128 bit register | 4 float32 or 16 int8 lanes | Steps fall by the lane count (Ch 4) |
| One MMA tile product | 16 x 8 x 16 = 2,048 MACs; 4 MMAs = 8,192 | A tensor core does a tile per instruction (Ch 6) |
| H100 throughput by type | 67, 989, 1,979, 3,958 TFLOPS | About 60 times from FP32 to INT8 (Ch 6) |
| Im2col, 56 x 56 x 32, 3 x 3 | 100,352 B to 903,168 B (9x) | K² copies; 2.76 times the 320 KB (Ch 7) |
| Depthwise peak, C = 96, 28 x 28 | 150,528 B to 76,048 B | 2CHW against (1 + C)HW (Ch 8) |
| Winograd 2 x 2 output, 3 x 3 filter | 36C to 16C MACs (2.25x) | More additions, fewer multiplies (Ch 9) |
| Term | Plain meaning | Where |
|---|---|---|
| Cache line, cache miss | The chunk fetched at once; a read that must go to a slower level | 0, 1 |
| Locality | Reading data near what you just read | 0, 1 |
| Row-major | A grid stored one row after another | 1 |
| Loop tiling | Cutting loops into blocks that fit in cache | 2 |
| Loop unrolling | Repeating the body to pay for fewer jumps | 3 |
| ISA, CISC, RISC | The chip's menu of actions; many dishes or a short menu | 4 |
| SIMD, lane, intrinsic | One instruction on many numbers; one slot; a function that is one instruction | 4 |
| Thread, race condition | One stream of work; two writers on one cell | 5 |
| Kernel, block, grid | A GPU function; a group of threads; all the groups | 6 |
| Tensor core, MMA | A unit that multiplies a tile; the instruction that drives it | 6 |
| Im2col, implicit GEMM | Windows copied into rows; the same multiply without the copy | 7 |
| Peak memory, in-place | The most activation memory alive at once; reuse the input buffer | 8 |
| NCHW, NHWC | Channel by channel; pixel by pixel | 8 |
| Winograd | Transform, multiply 16 cells, transform back | 9 |
The lecture's decisions are mostly arithmetic on sizes. This small planner checks them before you write a kernel. On the worked examples it prints 16, 903,168, 150,528 and 76,048.
pythondef tile_size(cache_bytes, bytes_per_num): # largest power of two with 3 T^2 b <= S T = 1 while 3 * (T * 2) ** 2 * bytes_per_num <= cache_bytes: T *= 2 return T # tile_size(8192, 4) -> 16 def im2col_bytes(H, W, C, K, bytes_per_num=1): # same padding, stride 1 return H * W * K * K * C * bytes_per_num # im2col_bytes(56, 56, 32, 3) -> 903168 def depthwise_peak(C, H, W, in_place): return (1 + C) * H * W if in_place else 2 * C * H * W # int8: bytes def macs_2x2_block(C, winograd): return 16 * C if winograd else 9 * C * 4 # 3x3 filter, 4 outputs def rows_for(t, T, N): # thread t of T: never drops a row per = N // T return range(t * per, N if t == T - 1 else (t + 1) * per) def dot_lanes(a, b, lanes): # what a SIMD loop does, in lane-sized steps acc = [0.0] * lanes for k in range(0, len(a) - len(a) % lanes, lanes): for l in range(lanes): acc[l] += a[k + l] * b[k + l] return sum(acc) + sum(x * y for x, y in zip(a[len(a) - len(a) % lanes:], b[len(a) - len(a) % lanes:]))
The previous lecture, MCUNet, searched for a model small enough for the chip. This lecture is the engine that runs it. The next, Lecture 12, turns to transformers and language models. For the number types that make SIMD and tensor cores pay off, see quantization. The depthwise and pointwise blocks come from neural network building blocks.
The last slides invite you to try TinyEngine and TinyChatEngine. Lab 4 and 5 ask for four things:
This lesson follows Lecture 11 of MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. The Lecture 11 slides are linked on the course page. The slides cite MCUNet and On-Device Training Under 256KB Memory (Lin et al.), MobileNetV2 (Sandler et al.), Stanford CS149 on GPU architecture and CUDA, Arm's talk on Winograd algorithms, and "Fast Algorithms for Convolutional Neural Networks". Every explanation, example and device here is our own. Toy numbers are labelled where they appear.
Now press Teach and explain, from memory, why reordering two loops made one multiply 12 times faster. Then go back to the race at the top and run each trick once more.