TinyEngine and Parallel Processing

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.

Race the same multiply

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

A Model That Fits Can Still Be Too Slow

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.

How small the edge gets

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.

Measure the gap

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.

Inside a microcontroller

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.

PartSTM32F746 MCUMacBook Pro (M1 Ultra)Ratio
CPU cores120 (plus 64 GPU and 32 neural-engine cores)20x
Clock216 MHz3,200 MHz15x
L1 cache8 KB320 KB40x
Memory320 KB (SRAM)64 GB210,000x
Storage1 MB (flash)8 TB8,400,000x
Operating systemnonemacOS 

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 is a pyramid

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)SizeWait for one read
L1 cache320 KB0.5 ns
L2 cache48 MB7 ns (14x L1)
Main memory (DRAM)64 GB100 ns (200x L1)
Storage8 TB1 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.

The failure: judging speed by FLOPs

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.

  1. Reorder loops: read memory in the order it is stored.
  2. Tile loops: keep the working data inside the cache.
  3. Unroll loops: spend fewer steps on counting.
  4. SIMD: one instruction, many numbers.
  5. Threads: share the rows among cores.
  6. CUDA and tensor cores: the same ideas on a GPU.
  7. Im2col: a convolution as a matrix multiply, and what it costs.
  8. In-place depthwise and layout: save peak memory, pick the order.
  9. Winograd: fewer multiplies for a 3 by 3 filter.
  10. The field guide: numbers, code and the lab.
A loop reads 1,000 numbers. In case A they all sit in L1 cache (0.5 ns each). In case B they all sit in DRAM (100 ns each). How much longer does case B wait?

Chapter 1

Reorder the Loops So Memory Is Read in Order

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.

The multiply

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.

Say it aloud

C i j equals the sum over k of A i k times B k j.

C[i][j]
C i j the answer cell in row i, column j.
∑k
the sum over k add one term for each k, from 0 to N minus 1.
A[i][k]
A i k the k-th number in row i of A.
B[k][j]
B k j the k-th number in column j of B.
In plain words

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 numbers

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.

How memory stores the grid

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.

Why the plain loop is slow, and the fix

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.

Count the misses

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.

The failure: it only hurts when the matrix is big

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.

In row-major storage of an N by N matrix B, how far apart in memory are B[k][j] and B[k+1][j], the two reads of the plain inner loop?

Chapter 2

Tile the Loops So Data Stays in the Cache

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:

  1. Tile j. B's reads in that stretch fall from N² numbers to N × T.
  2. Tile k as well. B's footprint falls to T². A's falls from N² to N × T.
  3. Tile i as well. A's footprint falls to T².
  4. All three tiled: A, B and C each touch T² numbers inside the innermost three loops.

Choose the tile from the cache

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.

Say it aloud

Three T squared times b is at most S.

3 T²
three T squared the numbers in three tiles of T by T.
b
b bytes per number: 4 for float32, 1 for int8.
≤
is at most the left side must not pass the right side.
S
S the cache size in bytes.
In plain words

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.

With numbers

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.

Fit the working set

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

The failure: a tile that is too big

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.

An MCU has an 8 KB L1 cache. You tile a float32 matrix multiply with a tile of T by T for each of A, B and C. Which T is the largest power of two whose three tiles fit?

Chapter 3

Unroll the Loops to Pay for Fewer Branches

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.

A count you can check by hand

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.

  1. No unrolling: 16 passes. Useful work is 16 × 3 = 48. Control is 16 × 3 = 48. Total: 96 instructions, half of them overhead.
  2. Unroll by 2: 8 passes. Control is 8 × 3 = 24. Total: 72.
  3. Unroll by 4: 4 passes. Control is 12. Total: 60.
  4. Unroll by 8: 2 passes. Control is 6. Total: 54.

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.

Count the bookkeeping

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

The failure: the leftover iterations

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.

You unroll the innermost loop by 4. According to the lecture, what happens to the loop tests and to the code size of that loop?

Chapter 4

SIMD: One Instruction Works on Many Numbers

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 menu of instructions

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.

Wide registers

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.

IntrinsicRead 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_f32the same pattern for multiply and add

The dot product with lanes

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.

  1. Step 1: load (1, 2, 3, 4) and (1, 1, 1, 1). The running sums become (1, 2, 3, 4).
  2. Step 2: load (5, 6, 7, 8) and (1, 1, 1, 1). The running sums become (6, 8, 10, 12).
  3. Final: add the four lanes, 6 + 8 + 10 + 12 = 36. This last add is the horizontal sum.

Widen the register

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

The failure: right answer, but not the same bits

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.

A 128 bit vector register holds int8 numbers. How many fit, and by what factor does it cut the number of multiply steps against one int8 number per step?

Chapter 5

Threads Split the Rows Across Cores

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.

Split the rows

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.

 PthreadsOpenMP
What it isA C library for POSIX threadsAn API for C, C++ and Fortran, portable across platforms
How you write itpthread_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_threadomp_set_num_threads(4), then #pragma omp parallel for above the loop. Also sections, and single, critical, barrier for synchronisation
The slide's point4.1x with 4 threads against the plain loop, Intel Xeon 4114Cleaner 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.

Hand out the rows

Each bar is one row of C, colored by its thread. A red bar with a cross is a row that no thread computes.

10
4

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.

The failure: missing rows, and shared cells

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.

You split the rows of a 10 by 10 multiply among 4 threads with rows_per_thread = N / 4 in integer arithmetic. What happens?

Chapter 6

CUDA and Tensor Cores: Thousands of Threads, Whole Tiles

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.

WordMeaning
Host, deviceThe program on the CPU, which runs step by step; the GPU
KernelA function the host launches; the device runs it once per thread
Thread block, gridA group of threads that can share fast memory; all the blocks of one launch
Private, shared, global memoryPer 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.

Each thread finds its own 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.

Say it aloud

i equals block-index-x times block-dim-x, plus thread-index-x. j is the same with y.

i
i the column of the cell this thread computes.
j
j the row of that cell.
blockIdx.x
block-index-x which block this thread is in, counted across the grid.
blockDim.x
block-dim-x threads per block across: 4 here (3 down).
threadIdx.x
thread-index-x the thread's place inside its block.
In plain words

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.

With numbers

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].

Address a thread

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.

Copy first, then tile in shared memory

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];
}

Tensor cores: a whole tile per cycle

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 typeUnitTFLOPS
FP32CUDA core67
TF32 (tensor cores only)Tensor core989
FP16Tensor core1,979
INT8, FP8, sparse FP16Tensor core3,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.

Step the tiles

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.

The failure: skipping the wait, or the copy

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.

A launch uses 12 by 6 threads with threadsPerBlock = (4, 3). A thread in block (1, 1) has threadIdx (3, 1). Which cell does it compute?

Chapter 7

Im2col Turns a Convolution Into a Matrix Multiply

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.

Rewrite it as one big multiply

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.

Say it aloud

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.

Y
Y the output: one row per output position, one column per output channel.
im2col(X)
im-to-col of X the input with every K by K window copied into its own row. Many numbers appear in several rows.
W
the weights the N filters, each flattened to K²C numbers, side by side as columns. (Here W names this matrix, not the width.)
[HW × N]
H W by N a shape, rows by columns. HW rows means one per position, at stride 1 with same-size output.
In plain words

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.

With numbers

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.

Pay for the copies

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.

56
32

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

The failure: the buffer that does not fit

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.

A layer takes an input of 28 by 28 by 16 (int8) and uses a 3 by 3 filter with same-size output. How large is the im2col matrix, compared with the input?

Chapter 8

In-Place Depthwise Convolution and the Right Layout

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:

  1. A 1 by 1 convolution widens the channels.
  2. A 3 by 3 depthwise convolution gives each channel its own filter and never mixes channels.
  3. A 1 by 1 convolution narrows them again.
  4. An add joins the block's input.

Depthwise layers cut model size and FLOPs. But the wide middle raises peak memory 3 to 6 times.

Two buffers, or one plus a temp

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.

Say it aloud

M-sep equals two times C times H times W. M-in equals one plus C, times H times W.

Msep
M-sep peak memory with separate input and output buffers, in numbers (bytes for int8).
Min
M-in peak memory with the in-place policy.
C
C the number of channels.
H · W
H times W the numbers in one channel map.
1 +
one plus the temp buffer: one extra channel map.
In plain words

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.

With numbers

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.

Reuse the buffer

Press Next channel: the channel goes into the purple temp buffer, then back. The sliders set the memory in bytes.

96
28

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.

Layout: the order of a tensor in memory

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:

LayoutOrder in memoryReads in stride 1 for
NHWCOne pixel with all its channels, then the next pixelA pointwise convolution (1 by 1): a dot product across one pixel's channels. TinyEngine uses NHWC here.
NCHWOne whole channel, then the next channelA depthwise convolution: it slides over one channel. TinyEngine runs its in-place depthwise in this order.

Read in stride 1

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

The failure: writing before the window finishes

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.

A depthwise layer has C = 64 channels of 20 by 20 (int8). What is its peak memory with separate input and output buffers, and with the in-place policy?

Chapter 9

Winograd Trades Multiplications for Additions

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.

See the trick in one dimension

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:

  1. m1 = (d0 − d2) · g0
  2. m2 = (d1 + d2) · (g0 + g1 + g2) / 2
  3. m3 = (d2 − d1) · (g0 − g1 + g2) / 2
  4. m4 = (d1 − d3) · g2
  5. Then y0 = m1 + m2 + m3 and y1 = m2 − m3 − m4.

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.

The two-dimensional recipe

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.

Say it aloud

Y equals A-transpose, times G g G-transpose cell-by-cell times B-transpose d B, times A.

Y
Y the 2 by 2 output block.
G g GT
G g G-transpose the filter transform: the 3 by 3 filter g becomes a 4 by 4 grid. Done offline, once.
BT d B
B-transpose d B the data transform: the 4 by 4 tile d becomes another 4 by 4 grid, online.
⊙
cell by cell times multiply matching cells: 16 multiplies. Add the products over the C channels.
AT … A
A-transpose, then A the output transform, online: it maps the 4 by 4 grid back to 2 by 2.
In plain words

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.

With numbers

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)

Run both methods

Pick a tile and a filter. Step through the stages. The last stage compares the two answers cell by cell.

32

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)

The failure: right in exact arithmetic, off in low precision

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.)

A layer has C = 64 channels and a 3 by 3 filter. For one 2 by 2 output block, how many MACs does direct convolution need, and how many does Winograd need?

Chapter 10

The Field Guide: Fast Inference on One Page

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.

The numbers that matter

WhatNumberWhy it matters
Plain vs reordered matmul24,296 ms to 1,979 ms (12x)Same arithmetic, read in order (Ch 1). Intel Xeon 4114
Tiling, unrolling, 4 threads19x, 2.85x, 4.1xEach against the plain loop on the same Xeon (Ch 2, 3, 5)
CUDA tiled matmul94x end to end, RTX 2080 TiShared-memory tiles on a GPU (Ch 6)
STM32F746 MCU1 core, 216 MHz, 8 KB L1, 320 KB SRAM, 1 MB flashThe budget everything must fit (Ch 0)
H100 memory vs MCU memory80 GB vs 320 kB, about 250,000 timesWhy the edge is hard (Ch 0)
L1 vs DRAM read0.5 ns vs 100 ns, 200 timesA cache miss is expensive (Ch 0, 1)
Tile size rule3 T² x bytes ≤ cache; T = 16 for float32 at 8 KBThree tiles must fit together (Ch 2)
128 bit register4 float32 or 16 int8 lanesSteps fall by the lane count (Ch 4)
One MMA tile product16 x 8 x 16 = 2,048 MACs; 4 MMAs = 8,192A tensor core does a tile per instruction (Ch 6)
H100 throughput by type67, 989, 1,979, 3,958 TFLOPSAbout 60 times from FP32 to INT8 (Ch 6)
Im2col, 56 x 56 x 32, 3 x 3100,352 B to 903,168 B (9x)K² copies; 2.76 times the 320 KB (Ch 7)
Depthwise peak, C = 96, 28 x 28150,528 B to 76,048 B2CHW against (1 + C)HW (Ch 8)
Winograd 2 x 2 output, 3 x 3 filter36C to 16C MACs (2.25x)More additions, fewer multiplies (Ch 9)

The terms

TermPlain meaningWhere
Cache line, cache missThe chunk fetched at once; a read that must go to a slower level0, 1
LocalityReading data near what you just read0, 1
Row-majorA grid stored one row after another1
Loop tilingCutting loops into blocks that fit in cache2
Loop unrollingRepeating the body to pay for fewer jumps3
ISA, CISC, RISCThe chip's menu of actions; many dishes or a short menu4
SIMD, lane, intrinsicOne instruction on many numbers; one slot; a function that is one instruction4
Thread, race conditionOne stream of work; two writers on one cell5
Kernel, block, gridA GPU function; a group of threads; all the groups6
Tensor core, MMAA unit that multiplies a tile; the instruction that drives it6
Im2col, implicit GEMMWindows copied into rows; the same multiply without the copy7
Peak memory, in-placeThe most activation memory alive at once; reuse the input buffer8
NCHW, NHWCChannel by channel; pixel by pixel8
WinogradTransform, multiply 16 cells, transform back9

A checklist before you optimise

The core as code

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:]))

Where this sits

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 lab, and the open-source engines

The last slides invite you to try TinyEngine and TinyChatEngine. Lab 4 and 5 ask for four things:

  1. Quantize a language model to 4 bits with AWQ.
  2. Deploy it with TinyLLMEngine and run a local chatbot on your computer.
  3. Implement loop unrolling and reordering, SIMD and multithreading (Chapters 1 to 5).
  4. Measure the on-device latency each technique buys.

Keep going

The takeaway. Speed on a small chip comes from where the data sits and how many numbers each step handles. Keep working data in the cache, read in stride 1, do more per instruction, and keep extra buffers out of SRAM. Then check that the fast path gives the same answer.
A depthwise layer runs out of SRAM at its peak, though its arithmetic is cheap. Which trick from the lecture addresses it directly?

Credit

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.

TinyML L11: TinyEngine and Parallel Processing
The course page and slides · Back to Lecture 10 · On to Lecture 12 · Back to Gleams