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.
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.
Section 0
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.
Size equals P times b, over 8.
Multiply the parameter count P by the bits b. Divide by 8 to turn bits into bytes.
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.
Perf equals the minimum of Peak and B-W times I.
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.
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.
Each FP32 parameter takes 32 / 8 = 4 bytes.
At INT8 it is 3.4 MB, four times less.
The ridge is where BW × I equals Peak.
Below 4 the chip waits on memory. Most depthwise layers sit below it.
Find the bytes with size = P × b / 8. Then divide the bandwidth by the bytes.
At 16 bits the model is 26 GB and the limit is 7.7 tokens/s. Fewer bits buy speed, not only space.
Compare I with the ridge. Which side of 153 is 1 on?
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
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.
MACs equal c-i times k-h times k-w, times h-o times w-o times c-o.
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.
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.
H-o equals the floor of h-i plus 2p minus k-h, all over s, plus 1.
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.
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.
One filter is 3 × 3 × 32 weights. Count the filters, then add one bias each.
Each output number costs 3 × 3 × 32 = 288 MACs.
14.45 million MACs from 18,432 weights: each weight works 784 times.
Depthwise: each of the 32 channels runs its own 3 × 3 filter. Pointwise: a convolution with k = 1.
In general the ratio is 1 / (1/c-o + 1/9), close to 9 for wide layers.
Use Math.floor for the division by the stride. AlexNet's conv1 must give 105,415,200.
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
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.
Importance of w-i equals one half, h-i-i, times w-i squared.
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.
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.
S equals b plus 2, over 2b.
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.
At FP16, S = 18 / 32 = 0.5625. A row of 16 weights takes 8 × 16 + 8 × 2 = 144 bits, not 256.
Square the weight before you multiply.
The loss should rise by about 0.40 if this weight goes to zero.
Compute ½ h w2 for both weights.
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.
Two of every four weights survive. Each survivor has a 2-bit code.
Each nonzero costs 4 + 4 = 8 bytes.
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.
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;}
Which weight did it zero that has a large size?
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
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.
r equals S times, q minus Z.
Subtract the zero point Z from the stored integer q. Multiply by the scale S. That gives the real value r.
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.
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.
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.
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.
The real range is 8.0 wide, and 0 to 255 has 255 steps.
q-min is 0 here, so Z = round(−r-min / S).
Check: S × (64 − 64) = 0 exactly.
q = round(r / S) + Z, then clamp into 0 to 255.
Use r = S(q − Z), then subtract 1.5.
Rounding errs by at most S / 2 = 0.0157.
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.
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
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.
B-eff equals b plus b-s over G.
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.
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.
Y equals minus n, plus popcount of W xnor x, shifted left by one.
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.
The lesson's bits: 1010 xnor 1101 = 1000, so popcount is 1. y = −4 + 2 = −2, the same as 1 − 1 − 1 − 1.
You already pay for one scale. FP32 is 4 bytes.
Tiny next to the weights, and it stops one loud channel from erasing the rest.
Find b-eff first. Then use size = P × b / 8 from Section 0.
3.94 GB, against 3.5 GB if you forget the scales.
The estimator treats the derivative of Q as 1. Find dL/dQ at Q = 0.
With the true derivative, w never moves. The estimator passes dL/dQ straight through, so gradient descent raises w toward the next integer.
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;}
Count agreements a and disagreements n − a. What is their signed sum?
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
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.
N equals m to the L.
Each of the L places picks one of m options on its own. The counts multiply: m times m, L times.
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.
E of latency equals the sum over o of p-o times F of o.
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.
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.
log10(mL) = L × log10(m).
About 6.8 × 1011 cells. No one trains them all.
e2 = 7.389, e1 = 2.718, e0 = 1.
If op 0 still leads at the end, DARTS keeps it: the argmax picks the final op.
Multiply each pair, then add.
Lowering p for the 10 ms op lowers this sum the most.
Start large. Shrink the kernel first, then the depth, then the width.
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
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.
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.
Divide every logit by T. Raise e to each result. Divide each by their total, so the shares add to 1.
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.
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.
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.
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.
Divide by 4 first: (1, 0.5, 0.25).
At T = 1 class 0 gets 0.844. The softer target shows that classes 1 and 2 are close calls.
The soft-term gradients scale as 1 / T2.
Without the fix, the label term drowns the soft term 25 to 1.
T2 = 9, and the label term gets 1 − 0.7 = 0.3.
ea − m / Σ eb − m = ea / Σ eb, because e−m cancels.
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
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.
Peak SRAM equals the max over l of in-l plus out-l.
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.
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.
T-in equals t-out minus one, times s, plus k.
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.
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.
INT8 is one byte per value. Add the input and the output, then divide by 1,024.
That leaves little of a 320 kB chip for anything else.
One row per output position, one column per window value.
That is 9 times the 14 × 14 × 32 input. TinyEngine avoids the copy.
Start at conv B and walk backward.
A perfect split would need 8 × 2 = 16, so the halo is 5 pixels.
Loop while l + 1 < maps.length.
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
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.
Cache equals B times L times H-k-v times d-h times N, times 2, times 2 bytes.
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.
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.
C equals six times N times D.
Each training token costs about 6 operations per parameter. Multiply by the parameters N and the tokens D.
Llama-2-7B: 6 × 7 × 109 × 2 × 1012 = 8.4 × 1022 operations.
Total MACs = 2 × N2 × d, so FLOPs = 4 × N2 × d.
Double N and it rises four times, to 8.6 GFLOPs.
Per token: 32 × 32 × 128 × 2 × 2 bytes.
At batch 32 and 4,096 tokens it is 69 GB, almost five times the 14 GB of weights.
D = 20 × 109 tokens.
At 1015 useful operations per second, that is about 33 hours.
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;}
The answer is off by exactly 2. What does each head store per token?
Each head stores a key and a value. Line 2 must be 2 * Hkv * dh * bytes.
Section 9
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.
S-j equals the max of absolute X-j to the alpha, over the max of absolute W-j to the one minus alpha.
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.
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.
E equals one minus a to the K plus one, over one minus a. The speedup equals E over one plus K c.
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.
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.
To the power 0.5 is a square root.
After smoothing both peaks are 2.0: 8 / 4 and 0.5 × 4.
a4 = 0.2401.
Multiply each weight's size by its channel's size. Keep the two largest products.
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.
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; });}
The lesson's step is the largest absolute value over 2N−1.
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
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.
h equals x W plus x A B, which equals x times W plus A B.
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.
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.
A-i equals r-i minus the mean of R, divided by the standard deviation of R.
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.
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.
Count A and B on their own, then add.
16,777,216 / 131,072 = 128 times fewer than tuning W itself.
Two products, then add them.
The NF4 scales add a little: the lesson counts 4.127 bits per weight, about 3.6 GB.
First compute x A: it is a single number. Then multiply B by it.
The branch squeezes x to one number, then spreads it back out. Folding A B into W first gives the same change.
Rewards 0, 0, 1 must give −0.707, −0.707 and 1.414.
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
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.
Angle-i equals m over s, times theta-i.
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.
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.
Score equals the sum over i of the max of q-i times k-max-i and q-i times k-min-i.
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.
The lesson's query scores 23 on page (a) and 40 on page (b), so Quest reads page (b) first.
Divide the position by s first.
Training saw up to 4,096 × 0.0002 = 0.819 rad, so this angle is familiar.
e3 = 20.09 and e0 = 1.
Evict it and each other token jumps from 0.037 to 0.143, almost 4 times what the model expects.
When q-i is negative, the minimum key value gives the larger product.
Ask what the first tokens do for the softmax.
The first tokens absorb attention that has nowhere else to go. Keep them, and the rolling window works.
Section 12
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.
N equals H over p, times W over p.
Count the patches down and across, then multiply. Each token holds 3 × p × p raw numbers.
The lesson's example: H = W = 96 and p = 32 give 3 × 3 = 9 tokens of 3,072 numbers each.
Share equals n over n plus 6 d.
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.
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%.
512 / 16 patches along each side.
Each token holds 3 × 16 × 16 = 768 raw numbers.
6d = 4,608.
Between the 4% at 224 pixels and the 47% at 1,024 pixels.
n × n against n × 49.
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.
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
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.
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.
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.
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.
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.
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.
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.
√0.36 = 0.6 and √0.64 = 0.8.
omega + 1 = 4.
The prompt pulls the guess below both raw guesses, away from the plain model.
Branch numbers over 4,0962.
At 16 bits the branch costs 524 KB, beside 8.4 MB for the 4-bit residual.
function noisyAt(x0, eps, abar) { const signal = Math.sqrt(abar); const noise = 1 - abar; return signal * x0 + noise * eps;}
Compare each line with the formula. Both scales sit under a square root.
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
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.
U equals m over m plus S minus one.
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.
The lesson's case, S = 4: one micro-batch gives 1 / 4 = 25%. Four give 4 / 7 = 57%. Sixteen give 16 / 19 = 84%.
Psi-max equals C over b.
Find how many bytes per parameter stay on each GPU after sharding. Divide the GPU's memory by that number.
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.
S − 1 = 7.
48 micro-batches would give 87%, at the cost of smaller slices.
b = 2 + 2/32 + 12/32.
The unsharded FP16 weights now dominate. ZeRO-3 shards them too.
Speedup 40 / 1.6; growth 256 / 8.
The lesson's TSM run reached 0.82.
Each GPU needs its own gradients before any GPU can share them.
Every GPU ends with the same averaged gradient, so the same update keeps all the copies equal.
Section 15
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.
M of C equals C plus L over C.
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.
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.
G-tilde equals s to the minus two, times G sub W-bar.
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.
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.
C + L / C.
C = √64 = 8 is the best choice: 4 times less memory.
First G-W-bar = s × G-W.
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.
Row i of δ xT is δ-i times x.
Shared gradients can leak the training data itself.
Write the bias gradient of a linear layer. Does it contain x?
Layers below still need δ passed down through WT, which uses weights already stored. That is why TinyTL trains the biases.
Section 16
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 fails | Try |
|---|---|
| Flash | Fewer bits per weight, then pruning (Sections 2, 3) |
| SRAM peak | Patch-based inference, a narrower early stage (Section 7) |
| Time | Fewer MACs: separable layers, pruning, a searched network (Sections 1, 2, 5) |
| GPU memory | 4-bit weights, fewer key-value heads for the cache (Sections 8, 9) |
INT8 is one byte per weight.
831 < 1,024, so it fits with 193 kB to spare.
Time = work / rate. Convert seconds to milliseconds.
A wake word needs an answer in under 100 ms. Cut the MACs five times, or make the kernels faster.
Cache = B · L · H-kv · d-h · N · 2 · 2 bytes, from Section 8.
The cache now matches the weights. With 8 key-value heads it would fall to 1.34 GB.
Only two of the three steps change the MACs.
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.