TinyML Efficiency Workbook

Price any model on any chip by hand: its bytes, its work, its memory peak and the speed limit they set. 70 exercises run from one convolution to a video diffusion model.

A workbook for the whole MIT 6.5940 course. Each section names its formulas, reads them aloud, then hands you the numbers.

Pick a chip, a model size, a bit width and a batch. Watch the point move on the roofline and the bar fill the memory. Then compute the same numbers yourself in the exercises.

You need multiplication, logarithms and a little JavaScript for the Build exercises. Each section links the lesson that teaches it.

Built on MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), taught by Song Han and the MIT HAN Lab. The exercises and their numbers are ours, not the course's labs.

Price a model on a chip

7B
1

Chip numbers are dense FP16 TOPS, memory bandwidth and memory from the Lecture 1 table. The model is a toy: each step reads every weight once and the maths runs at FP16 (like W4A16). It ignores the KV cache and activations.

Workbook progress
0 / 70 exercises (0%)
0
Day streak
Best: 0
70 exercises in five kinds: Derive, Trace, Build, Debug, Design. Build exercises run as JavaScript in your browser. Progress saves on this device, and to your account when you sign in.

Section 0

Measure Before You Shrink

Count the bytes of a model, then find whether memory or arithmetic sets its speed

A model costs three things: bytes to store it, operations to run it, and bytes moved for each operation. Most chips wait on memory, not on arithmetic. A DRAM read costs 640 pJ, about 200 times an integer multiply.

Taught in Lecture 1: Why Efficiency Matters and Lecture 2: Basics of Neural Networks.

Say it aloud

Size equals P times b, over 8.

size
size the bytes the weights take in memory or on disk.
P
P the number of parameters (weights).
b
b the bits per parameter: 32, 16, 8 or 4.
/ 8
over 8 eight bits make one byte.
In plain words

Multiply the parameter count P by the bits b. Divide by 8 to turn bits into bytes.

With numbers

GPT-3 has P = 175 billion. At b = 16, size = 175 × 109 × 16 / 8 = 350 GB. An A100 holds 80 GB, so the weights alone need five cards.

Say it aloud

Perf equals the minimum of Peak and B-W times I.

Perf
Perf the operations per second the chip delivers on this work.
min
the minimum of take the smaller of the two.
Peak
Peak the chip's top arithmetic speed, in operations per second.
BW
B-W the memory bandwidth, in bytes per second.
I
I the arithmetic intensity: operations done for each byte moved.
In plain words

Memory can feed BW times I operations each second. The arithmetic can do Peak. The chip runs at the smaller one. The two meet at the ridge, I = Peak / BW.

With numbers

An A100 has Peak = 312 TOPS and BW = 2,039 GB/s, so its ridge is at 153 operations per byte. A 16-bit layer at batch 1 has I = 1. It gets min(312, 2.04) = 2.04 TOPS, under 1% of the peak.

Exercises

Exercise 0.1: Model size in bytes Derive
A MobileNetV2 variant has 3.4 million parameters stored in FP32, 32 bits each. How many megabytes do the weights take? Use 1 MB = 106 bytes.
MB
Hint

Each FP32 parameter takes 32 / 8 = 4 bytes.

Show solution
size = 3,400,000 × 32 / 8 = 13,600,000 bytes
= 13.6 MB

At INT8 it is 3.4 MB, four times less.

Exercise 0.2: Find the ridge of a microcontroller Derive
A microcontroller peaks at 200 million operations per second. Its memory moves 50 MB/s. At what arithmetic intensity does it stop waiting on memory?
ops / byte
Hint

The ridge is where BW × I equals Peak.

Show solution
ridge = Peak / BW
= 200 × 106 / (50 × 106) = 4 ops per byte

Below 4 the chip waits on memory. Most depthwise layers sit below it.

Exercise 0.3: The speed limit of chat Derive
A chat model has 13 billion parameters at 4 bits. Each new token reads every weight once. The board's memory moves 200 GB/s. At batch 1, what is the most tokens per second it can write?
tokens / s
Hint

Find the bytes with size = P × b / 8. Then divide the bandwidth by the bytes.

Show solution
size = 13 × 109 × 4 / 8 = 6.5 × 109 bytes
tokens/s ≤ 200 / 6.5 = 30.8

At 16 bits the model is 26 GB and the limit is 7.7 tokens/s. Fewer bits buy speed, not only space.

Exercise 0.4: Which side of the ridge? Trace
On an A100 (ridge 153 operations per byte), a 4,096 by 4,096 layer runs at 16 bits and batch 1, so I = 1. What limits it, and what moves it toward the ridge? Check it on the calculator above.
Hint

Compare I with the ridge. Which side of 153 is 1 on?

Show why
one weight read: b / 8 bytes, used for 2n operations
I = 2n / (b / 8) = 16n / b; at b = 16, I = n

I = 1 is far under 153, so memory sets the speed. Batch 160 gives I = 160, past the ridge. 32-bit weights halve I and make it worse.

Section 1

Count Every Layer

Read a layer's weights and multiply-adds off its shape alone

Every layer's cost follows from its shape. A convolution reuses each weight at every output position, so its work dwarfs its weights. A depthwise layer gives each channel its own small filter and skips the sum across channels.

Taught in Lecture 2: Basics of Neural Networks.

Say it aloud

MACs equal c-i times k-h times k-w, times h-o times w-o times c-o.

MACs
MACs multiply-adds: one multiply plus one add each.
ci
c-i the input channels.
kh · kw
k-h, k-w the kernel height and width.
ho · wo
h-o, w-o the output height and width.
co
c-o the output channels: one filter each.
In plain words

Each output number reads c-i times k-h times k-w inputs, one multiply-add each. There are h-o times w-o times c-o outputs. Multiply the two counts.

With numbers

AlexNet's conv1: 3 × 11 × 11 = 363 multiply-adds per output, and 55 × 55 × 96 = 290,400 outputs. That is 105,415,200 MACs from only 34,848 weights.

Say it aloud

H-o equals the floor of h-i plus 2p minus k-h, all over s, plus 1.

ho
h-o the output height.
hi
h-i the input height.
p
p the padding added on each side.
kh
k-h the kernel height.
s
s the stride: the jump between two kernel stops.
⌊ ⌋
the floor of round down to a whole number.
In plain words

Pad the input on both sides. Subtract the kernel, because its last stop must fit. Divide by the stride, round down, and add 1 for the first stop.

With numbers

AlexNet's conv1: h-i = 224, p = 2, k-h = 11, s = 4. 224 + 4 − 11 = 217. 217 / 4 = 54.25 rounds down to 54. Add 1: h-o = 55.

Exercises

Exercise 1.1: Count a convolution's weights Derive
A convolution has a 3 by 3 kernel, 32 input channels, 64 output channels and one bias per output channel. How many parameters does it hold?
params
Hint

One filter is 3 × 3 × 32 weights. Count the filters, then add one bias each.

Show solution
one filter = 3 × 3 × 32 = 288 weights
64 filters = 18,432 weights
+ 64 biases = 18,496 parameters
Exercise 1.2: Count its multiply-adds Derive
The same layer writes a 28 by 28 output map. How many million MACs does it run for one image? Ignore the biases.
million MACs
Hint

Each output number costs 3 × 3 × 32 = 288 MACs.

Show solution
outputs = 28 × 28 × 64 = 50,176
MACs = 288 × 50,176 = 14,450,688

14.45 million MACs from 18,432 weights: each weight works 784 times.

Exercise 1.3: Split it the MobileNet way Derive
Replace that layer with a 3 by 3 depthwise layer on 32 channels, then a 1 by 1 layer from 32 to 64 channels. The output is still 28 by 28. How many times fewer MACs is that? Give two decimals.
times fewer
Hint

Depthwise: each of the 32 channels runs its own 3 × 3 filter. Pointwise: a convolution with k = 1.

Show solution
depthwise = 9 × 32 × 784 = 225,792
pointwise = 32 × 64 × 784 = 1,605,632
ratio = 14,450,688 / 1,831,424 = 7.89

In general the ratio is 1 / (1/c-o + 1/9), close to 9 for wide layers.

Exercise 1.4: Write the MAC counter Build
Count the MACs of a square convolution from its shape.
  1. Compute h-o with the floor formula above.
  2. The input and kernel are square, so w-o = h-o.
  3. Return c-i × k × k × h-o × h-o × c-o.
Hint

Use Math.floor for the division by the stride. AlexNet's conv1 must give 105,415,200.

Show solution
javascriptfunction convMACs(ci, co, k, hi, p, s) {
  const ho = Math.floor((hi + 2 * p - k) / s) + 1;
  return ci * k * k * ho * ho * co;
}

Section 2

Remove Weights the Loss Will Not Miss

Score weights by the damage their removal does, and count what a sparse layer stores

Pruning sets weights to zero and fine-tunes the rest. Which weights? Magnitude pruning removes the smallest. Optimal Brain Damage asks the loss how much it would rise. Zeros save time only when the hardware can skip them, as with the 2:4 pattern on NVIDIA GPUs.

Taught in Lecture 3: Pruning and Sparsity I and Lecture 4: Pruning and Sparsity II.

Say it aloud

Importance of w-i equals one half, h-i-i, times w-i squared.

importance
importance how much the loss rises if w-i becomes 0.
wi
w-i the weight.
hii
h-i-i the curvature of the loss along w-i: its second derivative.
½
one half from the second-order term of the loss's Taylor series.
In plain words

Square the weight w-i. Multiply by the curvature h-i-i and halve it. Prune the weights with the smallest scores, not the smallest size.

With numbers

From the lesson: w = 0.1 with h = 100 scores 0.5. A weight of 3 with h = 0.01 scores 0.045. Optimal Brain Damage prunes the big weight, for 11 times less damage.

Say it aloud

S equals b plus 2, over 2b.

S
S the storage of a 2:4 layer as a share of the dense layer.
b + 2
b plus 2 one kept weight of b bits, plus its 2-bit position code.
2b
2b the dense cost of the two weights that one kept weight stands for.
In plain words

Every group of four weights keeps two. Each kept weight costs its b bits plus a 2-bit code that says where it sat. Compare that with two dense weights.

With numbers

At FP16, S = 18 / 32 = 0.5625. A row of 16 weights takes 8 × 16 + 8 × 2 = 144 bits, not 256.

Exercises

Exercise 2.1: Score one weight Derive
A weight w = 0.4 has curvature h = 5.0. What is its Optimal Brain Damage importance?
Hint

Square the weight before you multiply.

Show solution
w2 = 0.16
½ × 5.0 × 0.16 = 0.40

The loss should rise by about 0.40 if this weight goes to zero.

Exercise 2.2: Magnitude or the loss? Trace
You must prune one of two weights. w-1 = 0.2 has curvature 50. w-2 = 2.0 has curvature 0.1. Which does Optimal Brain Damage prune?
Hint

Compute ½ h w2 for both weights.

Show why
w-1: ½ × 50 × 0.04 = 1.0
w-2: ½ × 0.1 × 4 = 0.2

Magnitude pruning would remove w-1. The loss sits in a flat valley along w-2, so the big weight is the cheap one to lose.

Exercise 2.3: Store a 2:4 row Derive
A row holds 16 INT8 weights in the 2:4 pattern. How many bits does it take, values plus position codes?
bits
Hint

Two of every four weights survive. Each survivor has a 2-bit code.

Show solution
kept = 16 / 2 = 8 weights
values = 8 × 8 = 64 bits; codes = 8 × 2 = 16 bits
total = 80 bits, against 128 dense: S = 10 / 16 = 0.625
Exercise 2.4: Store an unstructured sparse matrix Derive
A weight matrix has 1,000,000 FP32 weights. After 90% pruning, 100,000 are nonzero. A sparse format stores each nonzero as a 4-byte value plus a 4-byte column index. How many MB does it take? Use 1 MB = 106 bytes.
MB
Hint

Each nonzero costs 4 + 4 = 8 bytes.

Show solution
sparse = 100,000 × (4 + 4) = 800,000 bytes = 0.8 MB
dense = 1,000,000 × 4 = 4.0 MB

5 times smaller. At 50% density the index cost cancels the saving. Scattered zeros are also hard to skip, which is why chips favour 2:4.

Exercise 2.5: Fix the pruner that keeps the wrong weights Debug
This function should zero the smallest-magnitude share of the weights. On [0.1, −2.0, 0.05, 1.5] at ratio 0.5 it returns [0.1, 0, 0, 1.5]. Click the buggy line.
function magnitudePrune(w, ratio) {  const k = Math.floor(w.length * ratio);  const order = w.map((v, i) => i).sort((a, b) => w[a] - w[b]);  const out = w.slice();  for (let j = 0; j < k; j++) out[order[j]] = 0;  return out;}
Hint

Which weight did it zero that has a large size?

Show explanation

Line 3 sorts by signed value, so −2.0 comes first and dies. Sort by size: Math.abs(w[a]) − Math.abs(w[b]). The right output is [0, −2.0, 0, 1.5].

Section 3

Map Real Numbers to Integers

Derive a scale and a zero point, store a value, and measure what rounding cost

Linear quantization stores each real number r as a small integer q. A scale S sets the real distance between two neighbouring integers. A zero point Z is the integer that means real 0, so zero padding stays exact. Unsigned 8-bit integers run from 0 to 255.

Taught in Lecture 5: Quantization I.

Say it aloud

r equals S times, q minus Z.

r
r the real value the integer stands for.
S
S the scale: real units per integer step.
q
q the stored integer.
Z
Z the zero point: the integer that decodes to 0.
In plain words

Subtract the zero point Z from the stored integer q. Multiply by the scale S. That gives the real value r.

With numbers

The lesson's 2-bit block has S = 1.07 and Z = −1. The stored q = 1 gives r = 1.07 × (1 + 1) = 2.14. The weight was 2.09, so the error is 0.05.

Say it aloud

S equals r-max minus r-min, over q-max minus q-min. Z equals the round of q-min minus r-min over S.

S
S the scale, as above.
rmax, rmin
r-max, r-min the largest and smallest real values to cover.
qmax, qmin
q-max, q-min the largest and smallest integers: 255 and 0 for unsigned 8 bits.
Z
Z the zero point, as above.
round
round to the nearest whole number, so real 0 lands exactly on an integer.
In plain words

Spread the real range over the integer range to get S. Then find the integer where real 0 falls: that is Z. To store r, compute q = round(r / S) + Z and clamp it into the range.

With numbers

The lesson's block runs from −1.08 to 2.12 at 2 bits, so q runs from −2 to 1. S = 3.20 / 3 = 1.07. Z = round(−2 + 1.08 / 1.07) = round(−0.99) = −1.

Exercises

Exercise 3.1: Find the scale Derive
An activation tensor runs from −2.0 to 6.0. You quantize it to unsigned 8 bits, 0 to 255. What is S? Give four decimals.
Hint

The real range is 8.0 wide, and 0 to 255 has 255 steps.

Show solution
S = (6.0 − (−2.0)) / (255 − 0)
= 8.0 / 255 = 0.0314
Exercise 3.2: Find the zero point Derive
Same tensor, S = 8 / 255. Which integer Z stands for real 0?
Hint

q-min is 0 here, so Z = round(−r-min / S).

Show solution
Z = round(0 − (−2.0) / 0.031373)
= round(63.75) = 64

Check: S × (64 − 64) = 0 exactly.

Exercise 3.3: Store a value Derive
With S = 8 / 255 and Z = 64, store the real value 1.5. Which integer q do you write?
Hint

q = round(r / S) + Z, then clamp into 0 to 255.

Show solution
1.5 / 0.031373 = 47.81, which rounds to 48
48 + 64 = 112, inside 0 to 255
Exercise 3.4: Measure the round-trip error Derive
Decode q = 112 back to a real value. How far is it from 1.5? Give four decimals.
Hint

Use r = S(q − Z), then subtract 1.5.

Show solution
r = 0.031373 × (112 − 64) = 0.031373 × 48 = 1.50588
error = 1.50588 − 1.5 = 0.0059

Rounding errs by at most S / 2 = 0.0157.

Exercise 3.5: Write the quantizer Build
Write the signed linear quantizer from the lesson.
  1. Set q-min = −2bits−1 and q-max = 2bits−1 − 1.
  2. Compute S and Z with the formulas above. Use Math.round.
  3. Return round(r / S) + Z, clamped into q-min to q-max.
Hint

The lesson's slide must work: r from −1.08 to 2.12 at 2 bits gives S = 1.07 and Z = −1, and 2.09 stores as q = 1.

Show solution
javascriptfunction quantize(r, rmin, rmax, bits) {
  const qmin = -(2 ** (bits - 1)), qmax = 2 ** (bits - 1) - 1;
  const S = (rmax - rmin) / (qmax - qmin);
  const Z = Math.round(qmin - rmin / S);
  const q = Math.round(r / S) + Z;
  return Math.max(qmin, Math.min(qmax, q));
}

Section 4

Pay for Scales and Train Through Rounding

Count what finer scales cost, pass gradients through a step function, and compute with single bits

One scale for a whole tensor lets a loud channel erase the quiet ones. Smaller scopes fix that: a scale per output channel, or per group of weights. Each scale costs bits, so count them in the width. At one bit, a weight is +1 or −1, and a dot product becomes a bit count.

Taught in Lecture 6: Quantization II.

Say it aloud

B-eff equals b plus b-s over G.

beff
b-eff the effective bits per weight, scales included.
b
b the bits of each stored weight.
bs
b-s the bits of one scale.
G
G the number of weights that share one scale.
In plain words

Each group of G weights carries one scale of b-s bits. Spread that cost over the G weights and add it to their own b bits.

With numbers

From the lesson: 4-bit weights with a 16-bit scale for every 128 give 4 + 16/128 = 4.125 bits. A scale for every single weight gives 20 bits, worse than FP16.

Say it aloud

Y equals minus n, plus popcount of W xnor x, shifted left by one.

y
y the dot product of two vectors of +1 and −1.
n
n the length of the vectors.
xnor
xnor gives 1 where the two bits agree.
popcount
popcount the number of 1 bits.
« 1
shifted left by one times 2.
In plain words

Store +1 as bit 1 and −1 as bit 0. Each pair that agrees adds +1, each pair that disagrees adds −1. So the sum is 2 times the agreements, minus n.

With numbers

The lesson's bits: 1010 xnor 1101 = 1000, so popcount is 1. y = −4 + 2 = −2, the same as 1 − 1 − 1 − 1.

Exercises

Exercise 4.1: Pay for per-channel scales Derive
A convolution has 128 output channels. Per-channel quantization stores one FP32 scale per channel. How many extra bytes is that, compared with one scale for the whole tensor?
bytes
Hint

You already pay for one scale. FP32 is 4 bytes.

Show solution
extra scales = 128 − 1 = 127
127 × 4 bytes = 508 bytes

Tiny next to the weights, and it stops one loud channel from erasing the rest.

Exercise 4.2: Size a group-quantized model Derive
A 7B model stores 4-bit weights with one FP16 scale for every 32 weights. How many GB do the weights take, scales included? Use 1 GB = 109 bytes.
GB
Hint

Find b-eff first. Then use size = P × b / 8 from Section 0.

Show solution
b-eff = 4 + 16 / 32 = 4.5 bits
size = 7 × 109 × 4.5 / 8 = 3.94 × 109 bytes

3.94 GB, against 3.5 GB if you forget the scales.

Exercise 4.3: Train through the rounding Trace
A toy loss: L = (Q(w) − 0.5)2, where Q rounds w to the nearest integer. At w = 0.05, Q(w) = 0. What gradient does the straight-through estimator send to w?
Hint

The estimator treats the derivative of Q as 1. Find dL/dQ at Q = 0.

Show why
dL/dQ = 2 × (Q(w) − 0.5) = −1
true chain rule: −1 × dQ/dw = −1 × 0 = 0

With the true derivative, w never moves. The estimator passes dL/dQ straight through, so gradient descent raises w toward the next integer.

Exercise 4.4: Fix the binary dot product Debug
This function takes two n-bit vectors that store +1 as 1 and −1 as 0. binaryDot(0b1010, 0b1101, 4) returns −3, but 1 − 1 − 1 − 1 = −2. Click the buggy line.
function binaryDot(wBits, xBits, n) {  const mask = (1 << n) - 1;  const same = ~(wBits ^ xBits) & mask;  let pc = 0;  for (let v = same; v; v >>= 1) pc += v & 1;  return pc - n;}
Hint

Count agreements a and disagreements n − a. What is their signed sum?

Show explanation

The sum is a − (n − a) = 2a − n. Line 6 drops the factor 2. Write return 2 * pc - n, which is −n + (pc « 1).

Section 5

Search a Space You Can Count

Size a search space, turn choices into probabilities, and price a soft choice in milliseconds

Neural architecture search picks a network from a space of choices. First count the space: it is far too big to train every member. Gradient methods such as DARTS and ProxylessNAS make the choice soft, so the loss can include an expected latency.

Taught in Lecture 7: Neural Architecture Search I and Lecture 8: Neural Architecture Search II.

Say it aloud

N equals m to the L.

N
N the number of networks in the space.
m
m the options at each place that chooses.
L
L the number of places that choose: layers or edges.
In plain words

Each of the L places picks one of m options on its own. The counts multiply: m times m, L times.

With numbers

From the lesson: m = 6 and L = 20 give N = 620 = 3.7 × 1015. At one GPU-hour per network, that is about 4 × 1011 GPU-years.

Say it aloud

E of latency equals the sum over o of p-o times F of o.

E[latency]
E of latency the expected latency of the soft choice.
Σo
the sum over o one term per candidate operation.
po
p-o the probability of op o: the softmax of its architecture weight alpha-o.
F(o)
F of o the measured latency of op o, read from a lookup table.
In plain words

Turn the architecture weights into probabilities with a softmax. Weight each op's latency F by its probability p and add. The result changes smoothly with alpha, so gradients can push the search toward fast ops.

With numbers

From the lesson: weights of 1/3 each and F = 2.0, 3.5 and 0.4 ms give E[latency] = 5.9 / 3 = 1.97 ms.

Exercises

Exercise 5.1: How big is the space? Derive
A cell has 14 edges. Each edge picks one of 7 operations. How many cells are there? Give log10(N) to two decimals.
log10 N
Hint

log10(mL) = L × log10(m).

Show solution
N = 714
log10 N = 14 × 0.8451 = 11.83

About 6.8 × 1011 cells. No one trains them all.

Exercise 5.2: Turn architecture weights into probabilities Derive
Three ops on one edge have weights alpha = (2.0, 1.0, 0.0). What softmax probability does op 0 get? Give three decimals.
Hint

e2 = 7.389, e1 = 2.718, e0 = 1.

Show solution
sum = 7.389 + 2.718 + 1 = 11.107
p-0 = 7.389 / 11.107 = 0.665

If op 0 still leads at the end, DARTS keeps it: the argmax picks the final op.

Exercise 5.3: Expected latency of a soft choice Derive
Ops with latencies 10, 5 and 2 ms have probabilities 0.6, 0.3 and 0.1. What is E[latency]?
ms
Hint

Multiply each pair, then add.

Show solution
0.6 × 10 + 0.3 × 5 + 0.1 × 2
= 6.0 + 1.5 + 0.2 = 7.7 ms

Lowering p for the 10 ms op lowers this sum the most.

Exercise 5.4: Train a once-for-all network Design
Once-for-all trains one network that holds many sub-networks. Tap the steps in the order that progressive shrinking runs them.
?
→
?
→
?
→
?
→
?
allow fewer layers search a sub-network for the device train the full network allow fewer channels allow smaller kernels
Hint

Start large. Shrink the kernel first, then the depth, then the width.

Show the order
full → smaller kernels → fewer layers → fewer channels → search

Each stage adds smaller sub-networks while the large ones keep training, so they do not forget. The final search trains nothing: it reads accuracy and a latency table.

Section 6

Teach a Small Model With Soft Labels

Soften a teacher's logits with a temperature and mix the soft match with the label loss

A small student learns from a large teacher's probabilities, not only from the label. The small probabilities on wrong classes carry information. A temperature T divides the logits and lifts those small values. The loss mixes the soft match with the usual label loss.

Taught in Lecture 9: Knowledge Distillation.

Say it aloud

P of z-i and T equals e to the z-i over T, divided by the sum over j of e to the z-j over T.

p
p the probability of class i.
zi
z-i the logit, the raw score, of class i.
T
T the temperature: 1 is the plain softmax, higher is flatter.
Σj
the sum over j over every class.
In plain words

Divide every logit by T. Raise e to each result. Divide each by their total, so the shares add to 1.

With numbers

The lesson's logits: cat 5, dog 1. At T = 1 the dog gets 0.018. At T = 10 the logits become 0.5 and 0.1, and the dog gets 0.401.

Say it aloud

L equals alpha times T squared times the KL of p-t-T parallel p-s-T, plus one minus alpha times the cross-entropy of z-s and y.

L
L the student's training loss.
α
alpha the weight of the soft term, between 0 and 1.
T2
T squared softening shrinks the soft gradients by 1 / T squared, so this restores them.
KL( · ‖ · )
K-L how far the student's softened probabilities p-s are from the teacher's p-t.
CE( zs, y )
cross-entropy the usual loss of the student's logits z-s against the label y.
In plain words

Soften both models with T. Measure the gap with KL and scale it by T squared. Mix it with the label loss: alpha of one, one minus alpha of the other.

With numbers

From the lesson: KL = 0.156, CE = 1.099, T = 2, alpha = 0.5. L = 0.5 × 4 × 0.156 + 0.5 × 1.099 = 0.862.

Exercises

Exercise 6.1: Soften three logits Derive
Teacher logits are (4, 2, 1). At T = 4, what probability does class 0 get? Give three decimals.
Hint

Divide by 4 first: (1, 0.5, 0.25).

Show solution
e1 = 2.718, e0.5 = 1.649, e0.25 = 1.284
sum = 5.651; p-0 = 2.718 / 5.651 = 0.481

At T = 1 class 0 gets 0.844. The softer target shows that classes 1 and 2 are close calls.

Exercise 6.2: Why T squared? Derive
You distill at T = 5 and leave out the T2 factor. By what factor do the soft-term gradients shrink, compared with T = 1?
times smaller
Hint

The soft-term gradients scale as 1 / T2.

Show solution
factor = T2 = 52 = 25

Without the fix, the label term drowns the soft term 25 to 1.

Exercise 6.3: Mix the two terms Derive
One training step has CE = 2.0, KL = 0.4, T = 3 and alpha = 0.7. What is L?
Hint

T2 = 9, and the label term gets 1 − 0.7 = 0.3.

Show solution
soft = 0.7 × 9 × 0.4 = 2.52
label = 0.3 × 2.0 = 0.60
L = 2.52 + 0.60 = 3.12
Exercise 6.4: Write a safe temperature softmax Build
The starter code is correct maths, but it fails one test: logits near 1,000 make exp overflow to Infinity. Fix it without changing any answer.
  1. Find the largest logit m.
  2. Use exp((z − m) / T). The shift cancels in the division.
  3. Divide each value by the total, so the shares add to 1.
Hint

ea − m / Σ eb − m = ea / Σ eb, because e−m cancels.

Show solution
javascriptfunction softmaxT(z, T) {
  const m = Math.max(...z);
  const e = z.map(v => Math.exp((v - m) / T));
  const sum = e.reduce((a, b) => a + b, 0);
  return e.map(v => v / sum);
}

Section 7

Fit the Memory Peak in SRAM

Find the layer that sets a microcontroller's peak, and size the tiles that cut it

A microcontroller has two memories. Flash, about 1 MB, holds the weights. SRAM, 256 to 320 kB, holds the activations while the model runs. A layer needs its input and output in SRAM at once, so the largest pair sets the peak. MCUNet runs the early layers patch by patch to cut it. Here 1 kB = 1,024 bytes.

Taught in Lecture 10: MCUNet and Lecture 11: TinyEngine and Parallel Processing.

Say it aloud

Peak SRAM equals the max over l of in-l plus out-l.

Peak SRAM
peak SRAM the most activation memory alive at once.
maxl
the max over l the largest value over all layers.
inl
in-l the bytes of layer l's input map.
outl
out-l the bytes of its output map.
In plain words

For each layer, add the bytes of its input and its output. The largest sum is the peak. It must fit in SRAM next to the runtime's own memory.

With numbers

From the lesson: layer 3 has in-3 = 221,184 B and out-3 = 55,296 B. The sum, 276,480 B, is the largest, so the peak is 270 kB: over a 256 kB chip.

Say it aloud

T-in equals t-out minus one, times s, plus k.

tin
t-in the side of the input tile a layer must read.
tout
t-out the side of the output tile it must write.
s
s the stride.
k
k the kernel side.
In plain words

Walk backward from the last layer. The first output needs one window of k pixels. Each further output needs s more. The extra border is the halo: work that neighbouring tiles repeat.

With numbers

The lesson's pair: conv 3 × 3 at stride 1, then conv 3 × 3 at stride 2, with 12 outputs per side. Conv 2 needs (12 − 1) × 2 + 3 = 25. Conv 1 needs (25 − 1) × 1 + 3 = 27. A perfect split needs 24, so the halo is 3 pixels.

Exercises

Exercise 7.1: Peak SRAM of one layer Derive
A convolution reads a 32 × 56 × 56 INT8 map and writes a 64 × 56 × 56 INT8 map. How many kB must sit in SRAM at once?
kB
Hint

INT8 is one byte per value. Add the input and the output, then divide by 1,024.

Show solution
in = 32 × 56 × 56 = 100,352 B
out = 64 × 56 × 56 = 200,704 B
301,056 / 1,024 = 294 kB

That leaves little of a 320 kB chip for anything else.

Exercise 7.2: The im2col copy Derive
A 3 × 3 convolution with 32 input channels writes a 14 × 14 map. Im2col copies each 3 × 3 × 32 window into one row of a matrix. How many INT8 values does that matrix hold?
values
Hint

One row per output position, one column per window value.

Show solution
rows = 14 × 14 = 196
columns = 3 × 3 × 32 = 288
196 × 288 = 56,448 values

That is 9 times the 14 × 14 × 32 input. TinyEngine avoids the copy.

Exercise 7.3: Size a tile with its halo Derive
The patch stage ends with conv A (3 × 3, stride 1), then conv B (5 × 5, stride 2). Each output tile is 8 × 8. What input tile side must conv A read?
pixels
Hint

Start at conv B and walk backward.

Show solution
conv B: (8 − 1) × 2 + 5 = 19
conv A: (19 − 1) × 1 + 3 = 21

A perfect split would need 8 × 2 = 16, so the halo is 5 pixels.

Exercise 7.4: Find the peak Build
Compute a network's peak SRAM from its activation shapes, in INT8.
  1. Turn each shape [c, h, w] into bytes: c × h × w.
  2. For each layer l, add maps[l] and maps[l + 1].
  3. Return the largest sum, or 0 when there is no layer.
Hint

Loop while l + 1 < maps.length.

Show solution
javascriptfunction peakSRAM(maps) {
  const bytes = maps.map(([c, h, w]) => c * h * w);
  let peak = 0;
  for (let l = 0; l + 1 < bytes.length; l++) {
    peak = Math.max(peak, bytes[l] + bytes[l + 1]);
  }
  return peak;
}

Section 8

Price a Transformer and Its Cache

Count attention's work, the KV cache's bytes and a training run's operations

A decoder-only transformer writes one token at a time. To avoid recomputing old tokens, it caches every earlier key and value. That cache grows with the batch and the text length, and it can outgrow the weights. Training compute follows a simple rule of its own.

Taught in Lecture 12: Transformers and LLMs.

Say it aloud

Cache equals B times L times H-k-v times d-h times N, times 2, times 2 bytes.

Cache
cache the bytes of stored keys and values.
B
B the batch: sequences served at once.
L
L the layers.
Hkv
H-k-v the key-value heads in each layer.
dh
d-h the size of one head.
N
N the tokens in each sequence.
2
two one key and one value.
2 bytes
two bytes per number at FP16.
In plain words

Each token stores a key and a value in every head of every layer. Multiply those counts by the tokens and the batch. Each number takes 2 bytes at FP16.

With numbers

Llama-2-70B with multi-head attention: B = 1, L = 80, H-kv = 64, d-h = 128, N = 4,096 gives 10.7 GB. Grouped-query attention with 8 key-value heads cuts it 8 times.

Say it aloud

C equals six times N times D.

C
C the training compute, in operations.
6
six operations per parameter per token: 2 forward, 4 backward.
N
N in this formula, the number of parameters.
D
D the number of training tokens.
In plain words

Each training token costs about 6 operations per parameter. Multiply by the parameters N and the tokens D.

With numbers

Llama-2-7B: 6 × 7 × 109 × 2 × 1012 = 8.4 × 1022 operations.

Exercises

Exercise 8.1: Attention work grows with the square Derive
One attention layer has N = 1,024 tokens and width d = 512. Scoring Q KT takes N × N × d multiply-adds, and weighting V takes as many again. One MAC is two FLOPs. How many GFLOPs is that?
GFLOPs
Hint

Total MACs = 2 × N2 × d, so FLOPs = 4 × N2 × d.

Show solution
MACs = 2 × 1,0242 × 512 = 1,073,741,824
FLOPs = 2 × MACs = 2.147 × 109

Double N and it rises four times, to 8.6 GFLOPs.

Exercise 8.2: A 7B model's cache Derive
A model has 32 layers and 32 key-value heads of size 128, stored at FP16. It serves one sequence of 512 tokens. How many MB is the cache? Use 1 MB = 106 bytes.
MB
Hint

Per token: 32 × 32 × 128 × 2 × 2 bytes.

Show solution
per token = 32 × 32 × 128 × 2 × 2 = 524,288 B (512 KB, as in the lesson)
× 512 tokens = 268,435,456 B = 268.4 MB

At batch 32 and 4,096 tokens it is 69 GB, almost five times the 14 GB of weights.

Exercise 8.3: Price a Chinchilla run Derive
You train a 1-billion-parameter model on 20 tokens per parameter, the Chinchilla ratio. What is C, in units of 1020 operations?
× 1020
Hint

D = 20 × 109 tokens.

Show solution
C = 6 × 109 × 2 × 1010
= 1.2 × 1020 operations

At 1015 useful operations per second, that is about 33 hours.

Exercise 8.4: Fix the cache estimate that is half too small Debug
This function gives 5.37 GB for Llama-2-70B with multi-head attention at 4,096 tokens. The lesson says 10.7 GB. Click the buggy line.
function kvCacheGB(B, L, Hkv, dh, N, bytes) {  const perLayer = Hkv * dh * bytes;  const perToken = L * perLayer;  const total = B * N * perToken;  return total / 1e9;}
Hint

The answer is off by exactly 2. What does each head store per token?

Show explanation

Each head stores a key and a value. Line 2 must be 2 * Hkv * dh * bytes.

Section 9

Serve an LLM in Fewer Bits

Move outliers from activations to weights, and let a small model draft for a large one

LLM weights quantize well. Activations do not, because a few channels carry giant outliers. SmoothQuant divides those channels by a factor s and multiplies the matching weights by s, so the product stays the same. At batch 1, decoding waits on memory. Speculative decoding lets a small model draft tokens that the large model checks in one pass.

Taught in Lecture 13: LLM Quantization and Deployment.

Say it aloud

S-j equals the max of absolute X-j to the alpha, over the max of absolute W-j to the one minus alpha.

sj
s-j the smoothing factor for input channel j.
max(|Xj|)
max of absolute X-j the largest activation size in channel j, from calibration data.
max(|Wj|)
max of absolute W-j the largest size among the weights that read channel j.
α
alpha the migration strength: 0.5 splits the difficulty evenly.
In plain words

Divide activation channel j by s-j and multiply its weights by s-j. Alpha sets how much of the outlier moves from the activations into the weights.

With numbers

The lesson's channel peaks at 16 in X and 1 in W. At alpha 0.5, s = 4 / 1 = 4. The activation peak falls to 4 and the weight peak rises to 4.

Say it aloud

E equals one minus a to the K plus one, over one minus a. The speedup equals E over one plus K c.

E
E the tokens each round keeps, on average.
a
a the chance the large model accepts one drafted token.
K
K the tokens the draft model writes each round.
c
c the cost of one draft step, as a share of one large-model step.
speedup
speedup tokens per large-model step, against 1 without drafting.
In plain words

The large model checks K drafted tokens in one pass. It keeps them up to the first miss and always adds one of its own. One round costs one large step plus K small ones.

With numbers

From the lesson, with a = 0.8, K = 4 and c = 0.05: E = (1 − 0.328) / 0.2 = 3.36 tokens. The round costs 1.2 steps, so the speedup is 2.8 times.

Exercises

Exercise 9.1: Smooth one channel Derive
Channel j has max |X-j| = 8.0 and max |W-j| = 0.5. With alpha 0.5, what is s-j?
Hint

To the power 0.5 is a square root.

Show solution
s = 8.00.5 / 0.50.5 = 2.828 / 0.707
= 4.0

After smoothing both peaks are 2.0: 8 / 4 and 0.5 × 4.

Exercise 9.2: Is drafting worth it? Derive
A draft model is accepted with a = 0.7, drafts K = 3 tokens per round, and costs c = 0.1 of a large step. What speedup do you get? Give two decimals.
times
Hint

a4 = 0.2401.

Show solution
E = (1 − 0.2401) / 0.3 = 2.533 tokens
one round costs 1 + 3 × 0.1 = 1.3 steps
speedup = 2.533 / 1.3 = 1.95
Exercise 9.3: Prune by weight times activation Trace
Wanda scores each weight by its size times the size of its input channel. A row has weights (2, −3, 0.5, 1). Its input channels have sizes (4, 1, 10, 2). You keep 2 of the 4 weights. Which survive?
Hint

Multiply each weight's size by its channel's size. Keep the two largest products.

Show why
scores = (2 × 4, 3 × 1, 0.5 × 10, 1 × 2) = (8, 3, 5, 2)

The 0.5 sits on a channel ten times louder than the −3's, so it moves the output more. Magnitude pruning would keep the wrong pair.

Exercise 9.4: Fix the quantizer that crushes a negative weight Debug
This 4-bit absmax quantizer turns the group (0.1, −0.8, 0.2, 0.3) into (0.11, −0.30, 0.19, 0.26). The −0.8 should survive. Click the buggy line.
function quantGroup(w, bits) {  const qmax = 2 ** (bits - 1) - 1;  const delta = Math.max(...w) / 2 ** (bits - 1);  return w.map(v => {    const q = Math.round(v / delta);    return Math.max(-qmax - 1, Math.min(qmax, q)) * delta;  });}
Hint

The lesson's step is the largest absolute value over 2N−1.

Show explanation

Line 3 takes the largest signed value, 0.3, so the step is 0.0375 and −0.8 clips at −8 steps, −0.30. Use Math.max(...w.map(Math.abs)). The step becomes 0.1 and every weight in this group comes back exactly.

Section 10

Tune a Large Model Cheaply

Train a thin low-rank branch beside a frozen weight, and grade answers against their siblings

Full fine-tuning of a 7B model at 16 bits needs about 84 GB for weights, gradients and Adam state. LoRA freezes W and trains a thin branch, A then B, beside it. GRPO, a reasoning RL recipe, grades each answer against the other answers to the same prompt.

Taught in Lecture 14: LLM Post-Training.

Say it aloud

h equals x W plus x A B, which equals x times W plus A B.

h
h the layer's output row.
x
x the input row.
W
W the frozen weight, d-in by d-out.
A
A the trained down-projection: d-in by the rank, a small number such as 8 or 16.
B
B the trained up-projection: the rank by d-out.
In plain words

Run the frozen W as before. Add a branch: x times A shrinks to a few numbers, then B grows them back. After training, add A B into W, so serving costs nothing extra.

With numbers

From the lesson: d = 4,096 at rank 8 trains 2 × 4,096 × 8 = 65,536 numbers per matrix. That is 256 times fewer than 16.8 million.

Say it aloud

A-i equals r-i minus the mean of R, divided by the standard deviation of R.

Ai
A-i the advantage of answer i.
ri
r-i its reward, such as 1 if correct and 0 if not.
mean(R)
the mean of R the average reward of the group: all answers to one prompt.
std(R)
the standard deviation of R the spread of those rewards.
In plain words

Sample several answers to one prompt. Subtract the group's mean reward from each reward, then divide by the spread. Answers better than their siblings get pushed up.

With numbers

From the lesson: rewards 0, 0, 1 give a mean of 0.33 and a spread of 0.47. The wrong answers get −0.7 and the right one gets +1.4.

Exercises

Exercise 10.1: Count LoRA's numbers Derive
A 4,096 × 4,096 weight gets a LoRA branch of rank 16. A is 4,096 × 16 and B is 16 × 4,096. How many numbers train?
params
Hint

Count A and B on their own, then add.

Show solution
A = 4,096 × 16 = 65,536; B = 65,536
total = 131,072

16,777,216 / 131,072 = 128 times fewer than tuning W itself.

Exercise 10.2: Fit QLoRA in memory Derive
QLoRA freezes a 7B model at 4 bits, 0.5 bytes per weight, and trains a 20-million-number adapter at BF16, 2 bytes each. How many GB do the two take? Use 1 GB = 109 bytes.
GB
Hint

Two products, then add them.

Show solution
frozen = 7 × 109 × 0.5 = 3.50 GB
adapter = 20 × 106 × 2 = 0.04 GB
total = 3.54 GB

The NF4 scales add a little: the lesson counts 4.127 bits per weight, about 3.6 GB.

Exercise 10.3: Run the LoRA branch by hand Trace
Rank 1: x = (2, 1), A is the column (1, −1), and B is the row (0.5, 0, 1). What does the branch add to x W?
Hint

First compute x A: it is a single number. Then multiply B by it.

Show why
x A = 2 × 1 + 1 × (−1) = 1
1 × B = (0.5, 0, 1)

The branch squeezes x to one number, then spreads it back out. Folding A B into W first gives the same change.

Exercise 10.4: Write the GRPO advantage Build
Turn one group's rewards into advantages.
  1. Compute the mean reward.
  2. Compute the standard deviation, dividing by n, as in the lesson.
  3. If it is 0, return all zeros: the group carries no signal.
  4. Otherwise return (r − mean) / std for each answer.
Hint

Rewards 0, 0, 1 must give −0.707, −0.707 and 1.414.

Show solution
javascriptfunction grpoAdvantages(r) {
  const n = r.length;
  const mean = r.reduce((a, b) => a + b, 0) / n;
  const std = Math.sqrt(r.reduce((a, x) => a + (x - mean) ** 2, 0) / n);
  if (std === 0) return r.map(() => 0);
  return r.map(x => (x - mean) / std);
}

Section 11

Read Long Texts With a Bounded Cache

Keep rotation angles familiar, keep the attention sinks, and read only the pages a query needs

Long texts break a model in three ways. Positions past the training length make rotation angles it never saw. The cache grows with every token. Evicting the first tokens collapses window attention, because those tokens soak up spare attention. Quest keeps every page and reads only the pages the query may need.

Taught in Lecture 15: Long-Context LLMs.

Say it aloud

Angle-i equals m over s, times theta-i.

anglei
angle-i the turn RoPE gives pair i of a query or key, in radians.
m
m the token's position.
s
s the interpolation factor: 1 means none.
θi
theta-i the turn per position for pair i.
In plain words

RoPE turns each pair by an angle that grows with the position m. Position interpolation divides m by s, so long positions reuse angles the model saw in training.

With numbers

From the lesson: the slow pair has theta about 0.0001. Trained to 4,096 tokens, it saw angles up to 0.41 rad. At m = 8,192 with s = 2, the angle is 0.41 rad again.

Say it aloud

Score equals the sum over i of the max of q-i times k-max-i and q-i times k-min-i.

score
score an upper bound on any key's dot product with the query on this page.
Σi
the sum over i over every channel.
qi
q-i channel i of the query.
kmax,i, kmin,i
k-max-i, k-min-i the largest and smallest channel-i values among the page's keys.
In plain words

In each channel, the page's largest or smallest key value gives the best product any key on the page can reach. Add the best of each channel. Read the pages with the highest bounds.

With numbers

The lesson's query scores 23 on page (a) and 40 on page (b), so Quest reads page (b) first.

Exercises

Exercise 11.1: Stay inside the trained angles Derive
A model trained to 4,096 tokens must read 16,384, so you set s = 4. For a pair with theta = 0.0002, what angle does position m = 12,288 get?
rad
Hint

Divide the position by s first.

Show solution
m / s = 12,288 / 4 = 3,072
angle = 3,072 × 0.0002 = 0.614 rad

Training saw up to 4,096 × 0.0002 = 0.819 rad, so this angle is familiar.

Exercise 11.2: How much attention a sink takes Derive
A query sees 8 cached tokens. Token 0 scores 3 and the other seven score 0. With a plain softmax (T = 1 in Section 6), what share of the attention goes to token 0? Give three decimals.
Hint

e3 = 20.09 and e0 = 1.

Show solution
total = 20.09 + 7 × 1 = 27.09
token 0 = 20.09 / 27.09 = 0.742

Evict it and each other token jumps from 0.037 to 0.143, almost 4 times what the model expects.

Exercise 11.3: Bound a page Derive
A query is q = (2, −1, 1). A page's keys have channel maxima (1, 2, 3) and minima (−1, 0, 1). What is the page's Quest score?
Hint

When q-i is negative, the minimum key value gives the larger product.

Show solution
channel 1: max(2 × 1, 2 × (−1)) = 2
channel 2: max(−1 × 2, −1 × 0) = 0
channel 3: max(1 × 3, 1 × 1) = 3
score = 2 + 0 + 3 = 5
Exercise 11.4: Fill a 1,024-token cache Trace
A chat runs past a cache of 1,024 tokens. Which cache keeps the model fluent, as StreamingLLM does?
Hint

Ask what the first tokens do for the softmax.

Show why
window: perplexity 5,158; 4 sinks + 1,020 recent: 5.40

The first tokens absorb attention that has nowhere else to go. Keep them, and the rolling window works.

Section 12

Price an Image in Tokens

Count a picture's tokens, find attention's share of the work, and cut it with windows and linear attention

A vision transformer cuts the image into p × p patches and treats each patch as a token. Attention compares every pair, so its cost grows with the square of the token count. The rest grows linearly. At high resolution, attention takes over. Windows and linear attention cut it back.

Taught in Lecture 16: Vision Transformers.

Say it aloud

N equals H over p, times W over p.

n
n the number of tokens.
H
H the image height in pixels.
W
W the image width in pixels.
p
p the patch side in pixels.
In plain words

Count the patches down and across, then multiply. Each token holds 3 × p × p raw numbers.

With numbers

The lesson's example: H = W = 96 and p = 32 give 3 × 3 = 9 tokens of 3,072 numbers each.

Say it aloud

Share equals n over n plus 6 d.

share
share the part of a block's work that the attention scores take.
n
n the tokens.
6d
six d six times the hidden size d.
In plain words

The attention scores cost 2n²d per block. The projections and the MLP cost 12nd². Divide the first by the total, then cancel 2nd from top and bottom.

With numbers

ViT-Base has d = 768, so 6d = 4,608. At 224 pixels, n = 196 and the share is 4%. At 2,048 pixels, n = 16,384 and the share is 78%.

Exercises

Exercise 12.1: Count the tokens Derive
A 512 × 512 image goes into a ViT with 16 × 16 patches. How many tokens does it make?
tokens
Hint

512 / 16 patches along each side.

Show solution
512 / 16 = 32 per side
n = 32 × 32 = 1,024 tokens

Each token holds 3 × 16 × 16 = 768 raw numbers.

Exercise 12.2: How much is attention? Derive
Those 1,024 tokens run through ViT-Base, d = 768. What percent of each block's work goes to the attention scores? Give one decimal.
%
Hint

6d = 4,608.

Show solution
share = 1,024 / (1,024 + 4,608)
= 1,024 / 5,632 = 18.2%

Between the 4% at 224 pixels and the 47% at 1,024 pixels.

Exercise 12.3: Window it Derive
A 1,024 × 1,024 image with 16 × 16 patches gives 4,096 tokens. Global attention scores every pair. With 7 × 7 windows, each token scores 49 others. How many times fewer scores is that? Give one decimal.
times fewer
Hint

n × n against n × 49.

Show solution
global = 4,096 × 4,096 = 16,777,216
windows = 4,096 × 49 = 200,704
ratio = 4,096 / 49 = 83.6
Exercise 12.4: Write ReLU linear attention Build
Linear attention swaps the softmax for ReLU and changes the order of the maths, so the cost grows with n, not n².
  1. Apply ReLU to every query and key value.
  2. Sum ReLU(K-j)T V-j over all j into a d × dv summary. Sum ReLU(K-j) into a vector z.
  3. Row i is ReLU(Q-i) times the summary, divided by ReLU(Q-i) · z.
  4. Return row i as an array.
Hint

Check the first test by hand: query (1, 0) scores the three keys 1, 0 and 1, so it averages V-1 and V-3.

Show solution
javascriptfunction linAttnRow(Q, K, V, i) {
  const relu = v => v.map(x => Math.max(0, x));
  const Kr = K.map(relu), q = relu(Q[i]);
  const d = q.length, dv = V[0].length;
  const S = Array.from({ length: d }, () => new Array(dv).fill(0));
  const z = new Array(d).fill(0);
  Kr.forEach((k, j) => {
    for (let a = 0; a < d; a++) {
      z[a] += k[a];
      for (let b = 0; b < dv; b++) S[a][b] += k[a] * V[j][b];
    }
  });
  const den = q.reduce((s, x, a) => s + x * z[a], 0);
  const out = new Array(dv).fill(0);
  for (let b = 0; b < dv; b++) for (let a = 0; a < d; a++) out[b] += q[a] * S[a][b];
  return out.map(x => x / den);
}

The code builds the summary S and the vector z once, and every query shares them. That is where the n² goes away.

Section 13

Add Noise, Guess It, Spend Less per Step

Jump an image to any noise level, guide a step, and price the tricks that make each step cheaper

A diffusion model learns to remove noise. Training jumps a clean image to a random noise level and asks the network to guess the noise. Sampling takes many steps, and guidance doubles each one. Lecture 18 cuts the cost per step: sparse attention for video, 4-bit weights and activations, and fewer steps.

Taught in Lecture 17: Diffusion Models I and Lecture 18: Diffusion Models II.

Say it aloud

x-t equals the square root of alpha-bar-t times x-zero, plus the square root of one minus alpha-bar-t times epsilon.

xt
x-t the noisy image at step t.
ᾱt
alpha-bar-t the squared share of signal left at step t. It falls from 1 toward 0.
x0
x-zero the clean image.
ε
epsilon fresh Gaussian noise, the target the network learns to guess.
In plain words

Shrink the clean image by the root of alpha-bar. Add noise scaled by the root of one minus alpha-bar. The two squares add to 1, so the image keeps its overall size.

With numbers

From the lesson: DDPM at t = 500 has alpha-bar 0.079, root 0.280, noise scale 0.960. With made-up x-zero = 1.0 and epsilon = 0.5, x-500 = 0.280 + 0.480 = 0.760.

Say it aloud

Epsilon-tilde equals omega plus one, times epsilon-theta of x-t, t and c, minus omega times epsilon-theta of x-t and t.

ε̃
epsilon-tilde the guided noise guess the sampler uses.
ω
omega the guidance strength.
εθ(xt, t, c)
epsilon-theta of x-t, t and c the network's guess given the prompt c.
εθ(xt, t)
epsilon-theta of x-t and t its guess with no prompt.
In plain words

Run the network twice, with the prompt and without it. Push the guess past the prompted one, away from the unprompted one. Every step now costs two passes.

With numbers

From the lesson, with made-up guesses 0.6 and 0.2 and omega = 4: 5 × 0.6 − 4 × 0.2 = 2.2. Fifty steps now cost 100 passes.

Exercises

Exercise 13.1: Jump to a noise level Derive
A pixel has x-0 = 1.0. At step t, alpha-bar-t = 0.36. The noise draw is epsilon = −0.5. What is x-t?
Hint

√0.36 = 0.6 and √0.64 = 0.8.

Show solution
signal = 0.6 × 1.0 = 0.6
noise = 0.8 × (−0.5) = −0.4
x-t = 0.6 − 0.4 = 0.2
Exercise 13.2: Guide a step Derive
The prompted guess is 0.3 and the unprompted guess is 0.5. With omega = 3, what guess does the sampler use?
Hint

omega + 1 = 4.

Show solution
4 × 0.3 = 1.2
3 × 0.5 = 1.5
epsilon-tilde = 1.2 − 1.5 = −0.3

The prompt pulls the guess below both raw guesses, away from the plain model.

Exercise 13.3: Price SVDQuant's branch Derive
SVDQuant moves a 4,096 × 4,096 layer's outliers into a 16-bit low-rank branch: one 4,096 × 32 matrix and one 32 × 4,096 matrix. The rest stays 4-bit. What percent of the layer's numbers does the branch hold?
%
Hint

Branch numbers over 4,0962.

Show solution
branch = 2 × 4,096 × 32 = 262,144
layer = 4,0962 = 16,777,216
share = 262,144 / 16,777,216 = 1.56%

At 16 bits the branch costs 524 KB, beside 8.4 MB for the 4-bit residual.

Exercise 13.4: Fix the noise that is the wrong size Debug
This function should return x-t from the first formula. With x-0 = 1, epsilon = −0.5 and alpha-bar = 0.36 it returns 0.28, not 0.2. Click the buggy line.
function noisyAt(x0, eps, abar) {  const signal = Math.sqrt(abar);  const noise = 1 - abar;  return signal * x0 + noise * eps;}
Hint

Compare each line with the formula. Both scales sit under a square root.

Show explanation

Line 3 must be Math.sqrt(1 - abar). Without the root, the noise scale is 0.64, not 0.8, and the squares no longer add to 1.

Section 14

Split Training Across GPUs

Shrink a pipeline's bubble, shard the training state, and score how well a job scales

Training state costs 16 bytes per parameter: 2 for FP16 weights, 2 for gradients and 12 for Adam. ZeRO shards that state over N GPUs. Pipeline parallelism splits the layers into stages, and the stages idle while the pipeline fills and drains. Micro-batches shrink that idle bubble.

Taught in Lecture 19: Distributed Training.

Say it aloud

U equals m over m plus S minus one.

U
U the share of time each GPU is busy.
m
m the micro-batches in each step.
S
S the pipeline stages, one GPU each.
In plain words

The pipeline takes S − 1 extra slots to fill and drain. The real work takes m slots. U is the busy slots over all slots.

With numbers

The lesson's case, S = 4: one micro-batch gives 1 / 4 = 25%. Four give 4 / 7 = 57%. Sixteen give 16 / 19 = 84%.

Say it aloud

Psi-max equals C over b.

ψmax
psi-max the largest model that fits, in parameters.
C
C the memory of one GPU, in bytes.
b
b the bytes each GPU keeps per parameter: 16 with no sharding, 2 + 2/N + 12/N with ZeRO-2, 16/N with ZeRO-3.
In plain words

Find how many bytes per parameter stay on each GPU after sharding. Divide the GPU's memory by that number.

With numbers

From the lesson: ZeRO-3 on 64 GPUs gives b = 16 / 64 = 0.25 bytes, so psi-max = 80 GB / 0.25 = 320 billion. GPT-3, at 175 billion, fits.

Exercises

Exercise 14.1: Size the bubble Derive
A pipeline has 8 stages. Each step splits the batch into 24 micro-batches. What percent of the time is each GPU busy? Give one decimal.
%
Hint

S − 1 = 7.

Show solution
U = 24 / (24 + 7) = 24 / 31
= 77.4%

48 micro-batches would give 87%, at the cost of smaller slices.

Exercise 14.2: How big a model fits with ZeRO-2? Derive
You train on 32 GPUs of 80 GB with ZeRO-2: Adam state and gradients are sharded, the weights are not. How many billion parameters fit? Ignore activations.
billion
Hint

b = 2 + 2/32 + 12/32.

Show solution
b = 2 + 14 / 32 = 2.4375 bytes
psi-max = 80 × 109 / 2.4375 = 32.8 × 109

The unsharded FP16 weights now dominate. ZeRO-3 shards them too.

Exercise 14.3: Score the scaling Derive
A job takes 40 hours on 8 GPUs and 1.6 hours on 256 GPUs. Scaling efficiency is the speedup divided by the growth in GPUs. What is it? Give two decimals.
Hint

Speedup 40 / 1.6; growth 256 / 8.

Show solution
speedup = 40 / 1.6 = 25
GPU growth = 256 / 8 = 32
efficiency = 25 / 32 = 0.78

The lesson's TSM run reached 0.82.

Exercise 14.4: Order one data-parallel step Design
Every GPU holds the whole model and a slice of the batch. Tap the steps of one training step in order.
?
→
?
→
?
→
?
→
?
all-reduce the gradients optimizer step on every GPU forward pass on this GPU's slice divide the sum by N backward pass: local gradients
Hint

Each GPU needs its own gradients before any GPU can share them.

Show the order
forward → backward → all-reduce → divide by N → optimizer step

Every GPU ends with the same averaged gradient, so the same update keeps all the copies equal.

Section 15

Train Inside 256 KB

Trade recomputation for memory, rescale integer gradients, and see what gradients reveal

Training needs far more memory than inference, because the backward pass reads every layer's saved input. A bias gradient needs no saved input at all. Checkpointing keeps a few activations and recomputes the rest. Real INT8 training rescales gradients, so integer weights move like float weights.

Taught in On-Device Training and Transfer Learning.

Say it aloud

M of C equals C plus L over C.

M(C)
M of C the activations held at once, counted in layers.
C
C the number of checkpoints kept.
L
L the number of layers. L / C is one segment, rebuilt in the backward pass.
In plain words

Keep C checkpoints through the network. In the backward pass, rebuild one segment of L / C layers at a time. The best C is the square root of L.

With numbers

From the lesson: L = 36 and C = 6 give 6 + 6 = 12 activations, against 36 with no checkpoints. The price is about one extra forward pass.

Say it aloud

G-tilde equals s to the minus two, times G sub W-bar.

G̃
G-tilde the rescaled gradient that updates the integer weight.
s
s the weight's quantization scale. The stored integer is W-bar = W / s.
GW̄
G sub W-bar the gradient with respect to W-bar. It equals s times the float gradient G-W.
In plain words

The gradient of W-bar is s times too small. Each step on W-bar also moves W only s times as far. Divide by s squared to fix both.

With numbers

From the lesson: W = 0.5, s = 0.01, G-W = 0.2. Then G-W-bar = 0.002 and G-tilde = 20. With step size 0.1, W-bar moves 2, so W moves 0.02, as in float training.

Exercises

Exercise 15.1: Place the checkpoints Derive
A network has L = 64 layers. You keep C = 8 checkpoints. How many activations are held at once?
activations
Hint

C + L / C.

Show solution
64 / 8 = 8 layers per segment
M = 8 + 8 = 16, against 64 with no checkpoints

C = √64 = 8 is the best choice: 4 times less memory.

Exercise 15.2: Rescale an INT8 gradient Derive
A weight W = 0.3 has scale s = 0.02, so W-bar = 15. The float gradient is G-W = 0.5. What is G-tilde?
Hint

First G-W-bar = s × G-W.

Show solution
G-W-bar = 0.02 × 0.5 = 0.01
G-tilde = 0.01 / 0.022 = 0.01 / 0.0004 = 25

With step size 0.1, W-bar moves 2.5, so W moves 0.05, the same as 0.1 × 0.5 in float training.

Exercise 15.3: Read a private input from its gradients Derive
A first layer's weight gradient is δ xT, and its bias gradient is δ. For output i, the weight-gradient row is (−0.12, 0.30, 0.06) and the bias gradient is −0.6. What is x-2, the second input value?
Hint

Row i of δ xT is δ-i times x.

Show solution
x = row / δ-i = (−0.12, 0.30, 0.06) / (−0.6)
= (0.2, −0.5, −0.1), so x-2 = −0.5

Shared gradients can leak the training data itself.

Exercise 15.4: What a bias update keeps Trace
You train only the biases of a frozen linear layer. What must that layer save from the forward pass for its own update?
Hint

Write the bias gradient of a linear layer. Does it contain x?

Show why
dL/dW = δ xT needs x; dL/db = δ needs nothing saved

Layers below still need δ passed down through WT, which uses weights already stored. That is why TinyTL trains the biases.

Section 16

Combine the Budgets

Check a model against Flash, time and GPU memory at once, and stack the savings

Each problem here checks more than one budget. Weights must fit Flash, the activation peak must fit SRAM, the work must fit the time, and weights plus cache must fit the GPU. When one fails, pick the technique that targets it.

Uses the formulas of Sections 0, 7 and 8.

If this budget failsTry
FlashFewer bits per weight, then pruning (Sections 2, 3)
SRAM peakPatch-based inference, a narrower early stage (Section 7)
TimeFewer MACs: separable layers, pruning, a searched network (Sections 1, 2, 5)
GPU memory4-bit weights, fewer key-value heads for the cache (Sections 8, 9)

Exercises

Exercise 16.1: Does it fit in Flash? Derive
A microcontroller has 1 MB of Flash, 1,024 kB. The model has 800,000 INT8 weights, and the firmware takes 50 kB. How many kB of Flash are used? Use 1 kB = 1,024 bytes.
kB
Hint

INT8 is one byte per weight.

Show solution
weights = 800,000 / 1,024 = 781.25 kB
total = 781.25 + 50 = 831.25 kB

831 < 1,024, so it fits with 193 kB to spare.

Exercise 16.2: Is it fast enough? Derive
A model runs 30 million MACs per inference. The microcontroller sustains 60 million MACs per second. What is the shortest inference time?
ms
Hint

Time = work / rate. Convert seconds to milliseconds.

Show solution
time = 30 × 106 / (60 × 106) = 0.5 s
= 500 ms

A wake word needs an answer in under 100 ms. Cut the MACs five times, or make the kernels faster.

Exercise 16.3: Weights plus cache on one GPU Derive
You serve a 13B model at 4 bits, 0.5 bytes per weight. The cache holds batch 4, 2,048 tokens, 40 layers and 40 key-value heads of size 128, at FP16. How many GB is that in total? Use 1 GB = 109 bytes.
GB
Hint

Cache = B · L · H-kv · d-h · N · 2 · 2 bytes, from Section 8.

Show solution
weights = 13 × 109 × 0.5 = 6.50 GB
cache = 4 × 40 × 40 × 128 × 2,048 × 2 × 2 = 6.71 GB
total = 6.50 + 6.71 = 13.21 GB

The cache now matches the weights. With 8 key-value heads it would fall to 1.34 GB.

Exercise 16.4: Stack the savings Derive
A model starts at 50 million MACs and 6 MB in FP32. Apply separable layers (8 times fewer MACs), INT8 (4 times smaller) and 50% pruning that the hardware can skip (2 times fewer MACs). How many million MACs remain?
million MACs
Hint

Only two of the three steps change the MACs.

Show solution
MACs = 50 / 8 / 2 = 3.125 million
size = 6 / 4 = 1.5 MB

Each method targets a different waste, so the gains multiply: 16 times less work and 4 times less memory.

Go back to the calculator and price a model you use. Then open Teach and explain the roofline to someone else.

TinyML Efficiency Workbook
Built on MIT 6.5940: TinyML and Efficient Deep Learning Computing (Fall 2026), Song Han and the MIT HAN Lab. The exercises and numbers are ours, not the course's labs.
Start the lessons · Back to Gleams