A microcontroller can run a network in 256 KB of memory. Training the same network keeps every layer's activations for the backward pass: 581 KB in our 8-bit toy. Choose what to train and bring it under the line.
Learn why training needs so much more memory than inference. Then learn the tricks that fit fine-tuning onto a chip: bias-only updates, TinyTL, sparse updates, checkpointing, 8-bit training and a compile-time plan.
Pick a strategy, then switch between 32-bit and 8-bit numbers. Watch which layers keep their activations and whether the bar stays under 256 KB. Then we build each strategy, piece by piece.
You need the chain rule, what a layer and its output are, and a little Python. We build the rest from zero.
Based on the on-device training lecture of MIT 6.5940: TinyML and Efficient Deep Learning Computing, from an earlier offering of the course. Song Han and the MIT HAN Lab teach it. Every idea is re-taught here in our own words and devices. It follows Distributed Training. Practise with the efficiency workbook.
A toy 12-layer network at batch size 1, with made-up layer sizes and accuracy gains. Memory counts one forward buffer, kept activations, 1-bit ReLU masks and trainable weights with their gradients. 256 KB is the chip memory in MCUNetV3 (Lin et al., NeurIPS 2022).
Chapter 0
See why a chip that can run a model cannot train it
You ship a wake-word detector in a hearing aid. It works for most voices, but not for its owner's accent. The fix is to fine-tune on a few dozen of the owner's clips, on the device, so the audio never leaves it.
The chip can do the arithmetic. It lacks the memory. An activation is the output of a layer for one input. In inference (running the model), each layer reads its input, writes its output, and the input can go. Watch one input go through the network and back.
The boxes are layers; a filled box is an activation held in memory. The line below is memory over time. Press Play, then switch to Inference.
Toy network: every layer input is 20 KB. Inference holds one input and one output at a time.
In training, the backward pass runs from the loss back to the first layer and computes the gradients. It needs each layer's input again. So the forward pass must keep every input until the backward pass reaches it.
Call the number of layers L. Call the size of the activation that goes into layer i Ai, in kilobytes. The memory kept for the backward pass is Mtrain.
M-train equals the sum over i from one to L of A-i.
Add the input size A-i of every layer. That total, M-train, sits in memory when the forward pass ends.
With the toy above, 12 layers of 20 KB: M-train = 12 × 20 = 240 KB. Inference peaks at 20 + 20 = 40 KB. Training needs 6 times more, and the gap grows with every layer.
Why not send the clips to a server and train there? That works for a fixed task. But voices, photos and medical signals should stay on the device. Chapter 8 shows that even sending gradients can leak them.
The failure is an out-of-memory crash on the first training step. Measure it before you flash the chip: add up the layer inputs with the formula. The fix is to keep fewer of them. Each chapter below removes some.
Chapter 1
Split one layer's backward pass into three gradients and find the one that needs the stored input
Take one layer. It multiplies its input vector x by a weight matrix W and adds a bias b, so its output is y = Wx + b. The backward pass hands it δ (delta), the gradient of the loss with respect to y: how much the loss moves when each output moves.
From δ the layer can make three things: the gradient for W, the gradient for b, and the gradient to send to the layer below. Choose what this layer trains and see what it must keep.
The top row is the forward pass, the bottom row the backward pass. A warm glow means "kept from the forward pass". Pick a mode.
Byte counts are for a layer whose input is 28 × 28 pixels by 32 channels in 8-bit numbers: 25,088 values. We assume a layer below trains, so the gradient must pass through.
d-L by d-W equals delta times x transpose.
Multiply every entry of delta by every entry of x. Row i, column j of the gradient is delta-i times x-j. Without x, you cannot form it.
With made-up numbers x = (2, −1, 3) and δ = (0.5, −2): row 1 is 0.5 × x = (1, −0.5, 1.5). Row 2 is −2 × x = (−4, 2, −6).
d-L by d-b equals delta.
The bias gradient is delta itself. The layer needs nothing from the forward pass to get it. In a convolution, add delta over all pixel positions.
The same layer: ∂L/∂b = (0.5, −2). No stored input was read.
The gradient for the layer below is WTδ, the transpose of W times delta. It reads W, which sits in flash memory anyway, and not x. With W = [[1, 0, 2], [−1, 1, 0]]:
One piece remains: the ReLU, max(0, y), between layers. Its backward pass lets delta through where y was positive and blocks it elsewhere. So it needs one bit per value, the sign, called a mask. In 8-bit numbers a mask is an eighth of the activation.
The failure: a network uses sigmoid or h-swish, and bias-only training saves less than planned. Measure it: their slopes depend on the input value, not just its sign, so the layer keeps the full input. The fix is ReLU-style activations in the frozen part, or count those inputs as kept.
Chapter 2
Compare three classic fine-tuning modes and see why training fewer parameters barely saves memory
Fine-tuning starts from a pretrained model, trained on a large dataset in the cloud. Its early layers detect edges and textures that most tasks share. The question is which part to update on the device.
| Mode | What trains | Where the backward pass stops |
|---|---|---|
| Full | every weight and bias | at the first layer |
| BN + Last | BatchNorm scale and shift, plus the classifier | at the first layer |
| Last only | the classifier | at the classifier |
BatchNorm (BN) normalises each channel to mean 0 and spread 1, then applies a learned scale γ (gamma) and shift β (beta). That is two numbers per channel, a tiny share of the parameters. So BN + Last looks cheap. Is it?
Six blocks of convolution, BatchNorm and ReLU, then a classifier. The bars compare each mode with full fine-tuning. Pick a mode.
Toy network, 64 × 64 input, channels 16 to 96, 32-bit numbers, batch size 1. We compute parameter and byte counts from that shape.
Why does memory stay high? Look at the gradient of one channel's scale. Call the normalised value at position j x̂j (x-hat-j), and the gradient arriving at the BN output there δj.
d-L by d-gamma equals the sum over j of delta-j times x-hat-j.
Multiply each delta-j by the saved x-hat-j and add over the channel. So the layer must keep every x-hat-j: a full-size tensor at every BN layer, to train two numbers per channel.
A made-up channel of three positions: δ = (0.5, −1, 2), x̂ = (1.2, −0.3, 0.4). ∂L/∂γ = 0.6 + 0.3 + 0.8 = 1.7. The shift's gradient is the sum of δ alone, 1.5, with nothing saved.
That is the trap. Parameter count and activation memory are two different budgets. Memory follows which gradients read saved tensors, not how many numbers you train. The TinyTL paper makes this point on real networks.
Last only keeps almost nothing, because the backward pass stops at the classifier. But the frozen features cannot adjust to the new data, so accuracy suffers when the new task looks different.
The failure: BN + Last runs out of memory almost like full fine-tuning. Measure it by counting the saved x-hat tensors. The fix is to train shifts and biases, which read nothing saved. Chapter 3 starts there.
Chapter 3
Freeze every weight, train only biases, and buy back accuracy with a branch that keeps tiny activations
TinyTL (Cai et al., NeurIPS 2020) asks how little memory training can use, not how few parameters. Its first move uses Chapter 1: freeze every weight and train only the biases. Bias gradients read nothing saved, and each ReLU mask costs one bit per value.
Biases shift features but cannot reshape them, so accuracy drops. The second move adds a lite residual: a small new branch beside each frozen block, with its own trainable weights. Those weights need saved inputs, so TinyTL makes the inputs small.
Each square's area is the number of values in a tensor. The frozen block keeps only a mask; the branch keeps its input. Move the slider.
A block at 56 × 56 pixels with 24 channels and expansion 6, an example size of our choosing. The ratio is our own arithmetic.
Call the expansion ratio e, so the block's largest activation has e times C channels at R by R pixels. Call the downsample factor s. The branch saves C channels at R/s by R/s. Call the ratio of the two r.
r equals one over s squared times e.
Shrinking each side by s cuts the pixels by s squared. Not expanding cuts the channels by e. Multiply the two cuts to get r.
s = 2 and e = 6: r = 1 / (4 × 6) = 1/24, about 4%. At 56 × 56 with 24 channels, the block's largest activation is 451,584 values and the branch saves 18,816.
The TinyTL paper reports up to 6.5 times less training memory than fine-tuning the full network, with little accuracy loss.
The failure: the branch lifts accuracy and memory jumps with it. Measure r for your s and width. A branch built like the block, at s = 1 and 6C, saves as much as the block. The fix is to downsample first and stay at C.
Chapter 4
Choose, layer by layer, how much to train, and search for the plan with the most gain under a budget
TinyTL uses one rule for every layer. A sparse update picks per layer: nothing, biases only, part of the weights, or all of them. MCUNetV3 (Lin et al., NeurIPS 2022) chooses such a plan to train on a 256 KB chip.
Two facts set the price. Weight updates need saved inputs. And the backward pass only has to reach the lowest layer you train; below it, the network keeps nothing. So late layers are cheap to train, and early layers, with the largest inputs, are dear.
Columns are layers, first on the left. Height is input size; the bar above is the gain. Press a layer button to cycle its mode.
– skip · b biases · ¼W a quarter of the weights · W all weights
Made-up sizes and gains; gains add, then saturate below 20 points. Memory counts kept inputs and masks. "Best" tries all 65,536 plans.
Call the input size of layer i Xi, in KB at 8 bits. Call U the set of layers whose weights train. Call ri the fraction of input channels whose weights train, and f the lowest layer with anything trained.
M equals the sum over i in U of r-i times X-i, plus one eighth of the sum over i from f to L of X-i.
For each layer in U, keep the fraction r-i of its input X-i. For every layer from f up, keep a mask of one eighth of X-i. Add both to get M.
The best plan: biases from layer 4, a quarter of the weights in layers 5 and 6, all weights in 7 and 8. M = 0.25 × 24 + 0.25 × 16 + 16 + 8 + (24 + 24 + 16 + 16 + 8) / 8 = 34 + 11 = 45 KB. All weights need 225 KB.
Why input channels? A weight that reads input channel j needs only channel j to get its gradient. Training a quarter of the output channels cuts compute, but every weight still reads the whole input.
How do you find the gains? Contribution analysis: fine-tune one layer, or its biases, at a time, and record the accuracy gain and the memory cost. Then search for the best plan that fits. MCUNetV3 uses an evolutionary search.
The failure: a plan fits on paper and crashes on the chip. Measure the updated weights and their gradients too, because they must sit in fast memory. Fix it by counting those buffers in the budget; Chapter 7 shrinks them.
Chapter 5
Keep a few activations, recompute the rest, and find the count that holds the least
Sometimes you must train every weight, say on a phone GPU with a few gigabytes. Gradient checkpointing (Chen et al., 2016) keeps only some activations and recomputes the others during the backward pass. It trades compute for memory.
The curve is peak memory for every checkpoint count; the dot is yours. The strip below shows checkpoints and the segment you recompute now. Drag the sliders.
Memory in units of one layer's activation, all layers the same size. Compute assumes a backward pass costs two forward passes.
Call the number of layers L and the number of checkpoints C. Count memory in activations of one layer. The peak is M(C).
M of C equals C plus L over C.
Hold C checkpoints all the time. While you redo one segment, also hold its L over C activations. The sum is smallest where the two parts are equal. Then C equals the square root of L, and M is twice the square root of L.
L = 36: C = 6 gives 6 + 36/6 = 12 activations, against 36 with no checkpoints: 3 times less. L = 100: C = 10 gives 20, 5 times less.
The price is compute. You recompute each dropped activation once, so a step costs about one extra forward pass. If a backward pass costs two forward passes, a step grows from 3 units to 4: about a third more.
The failure: you turn checkpointing on and memory barely moves. Measure the activation sizes: one huge early activation can dominate, and the formula counts layers, not bytes. Fix it by placing checkpoints by size, or by a sparse update so the early layers need no backward pass.
On a microcontroller, extra compute costs time and battery. Chapters 3 and 4 remove activations without recomputing anything, so they come first there.
Chapter 6
Store and compute in INT8 for a quarter of the bytes, then fix the gradient scale that breaks it
A microcontroller computes well in 8-bit integers (INT8) and poorly, or not at all, in 32-bit floats. An INT8 value is a quarter of the size, so INT8 training cuts every kept activation by 4. There are two ways to say "quantized training":
| Fake quantization | Real quantized training | |
|---|---|---|
| Weights stored as | 32-bit floats | 8-bit integers |
| Arithmetic | floats, with rounding simulated | 8-bit multiplies, 32-bit sums |
| Training memory saved | none | 4 times on stored tensors |
| Used for | preparing a model for INT8 inference | training on the chip |
Real INT8 training has a trap. Quantization stores a real weight W as an integer W̄ (W-bar) and a scale s, the real size of one integer step: W = s · W̄. Call the gradient for W GW and the gradient for W̄ GW̄.
G sub W-bar equals s times G sub W.
W equals s times W-bar, so a nudge of 1 in W-bar moves W by s. By the chain rule, G sub W-bar is s times G sub W.
W = 0.5 and s = 0.01, so W̄ = 50. If GW = 0.2, then GW̄ = 0.002.
The weight grew 100 times (0.5 to 50) and its gradient shrank 100 times. Their ratio grew 1/s2 = 10,000 times. With a float learning rate, each update is 10,000 times too small and rounds to zero. Quantization-aware scaling (QAS), from MCUNetV3, divides by s squared:
G-tilde equals s to the minus two times G sub W-bar.
Divide the integer gradient by s squared to get G-tilde. A step of eta times G-tilde on W-bar then moves W by eta times G sub W. That is the step float training takes.
G̃ = 0.002 / 0.0001 = 20. With learning rate η = 0.1, W̄ moves 2 steps, so W moves 2 × 0.01 = 0.02. Float training moves W by 0.1 × 0.2 = 0.02. They match.
Each bar is one layer's weight-to-gradient ratio, on a power-of-ten scale. The shaded band is where float training sits. Pick a format.
Toy layer scales from 0.002 to 0.05 and toy float ratios. The shift of 1/s2 per layer is exact.
A bias uses the scale sW times sx, the weight scale times the input scale. The same argument divides their gradient by (sW sx)2.
The failure: INT8 loss stays flat while float training learns. Measure the weight-to-gradient ratio per layer and compare it with float. The fix is QAS.
Chapter 7
Prune every backward step that feeds no trainable parameter, and apply each update as soon as it is ready
The algorithm says which gradients you want. The runtime decides what memory that takes. Server frameworks such as PyTorch build the backward graph while the model runs. They are far too large for a chip with 256 KB.
The Tiny Training Engine (TTE) from MCUNetV3 moves this work to compile time, on your laptop, before the chip runs. It traces the forward graph, derives the backward graph, and prunes it. Then it writes plain code for the chip. MCUNetV3 trains this way on a microcontroller with 256 KB of SRAM and 1 MB of flash.
Top row: forward layers. Below each: its three backward steps (pass down, weight, bias). The compiler prunes the faded steps. Press a layer button to cycle frozen, biases, weights.
– frozen · b biases · W weights and bias
Toy graph and buffer sizes. With pruning off, the device shows a dense backward pass that computes and keeps everything.
TTE also reorders operators. A naive order computes every gradient and then applies every update, so all gradient buffers exist at once. TTE applies each layer's update as soon as its gradient is ready, then frees the buffer. Peak gradient memory falls from the sum of the buffers to the largest one.
With made-up buffers of 2, 4, 8 and 12 KB: 26 KB in the naive order, 12 KB after reordering.
PockEngine (Zhu et al., MICRO 2023) carries the same compile-time idea to phones and edge GPUs, with sparse backpropagation for larger models.
The failure: you change the sparse-update plan and the chip still keeps the old tensors. The plan is fixed at compile time. Recompile for every new plan.
Chapter 8
Recover a private input from one gradient, and see why training should stay on the device
If one device trains poorly alone, many can train together. In federated learning with FedAvg (McMahan et al., 2017), each phone trains on its own data and sends its weights. The server averages them, each weighted by its share of the examples.
Three phones with 100, 300 and 600 examples send weights 1.0, 2.0 and 0.5. The server keeps 0.1 × 1.0 + 0.3 × 2.0 + 0.6 × 0.5 = 1.0.
The data stays home. Does the update keep it secret? Deep Leakage from Gradients (DLG; Zhu, Liu and Han, NeurIPS 2019) says it does not. The attacker makes a random dummy input, computes its gradient through the same model, and changes the dummy until the two gradients match. The dummy becomes the private input.
For the first layer you need no search. From Chapter 1, row i of the weight gradient is δi times the input x, and the bias gradient of output i is δi. Call pixel j of the private input xj.
x-j equals d-L by d-W at row i, column j, divided by d-L by d-b at i.
Pick an output i whose bias gradient is not zero. Divide its weight-gradient row by its bias gradient. Delta-i cancels, and x is left, exactly.
A made-up input x = (0.2, 0.9, 0.5) and δi = −0.4. The row is (−0.08, −0.36, −0.2) and the bias gradient is −0.4. Dividing gives (0.2, 0.9, 0.5): the private input.
Left: the private images in one batch. Right: what the server gets by the division above. Drag the sliders.
Toy 8 × 8 images and made-up deltas for one output of a fully connected first layer. The device adds the noise to every gradient entry.
With a batch of several inputs, the gradients add up, and the division returns a weighted blend of them. Larger batches blur the data but do not hide it. The DLG paper also tests added noise and pruning of small gradient entries as defences. In its tests, noise strong enough to stop the attack also hurt accuracy.
The failure: an app sends updates from single examples. Measure it by running the division on one captured update. Fix it with larger local batches and defences, or keep training on the device, which is what this lesson makes possible.
Chapter 9
Keep the numbers, the terms, the checklist and the core code in one place
Training keeps every layer's input for the backward pass, so its memory grows with depth while inference stays flat. Weight gradients need those inputs; bias gradients and the pass-down step do not. Every trick here keeps fewer inputs, keeps them smaller, or plans them better.
| What | Value | Where |
|---|---|---|
| Training memory kept | M = sum of every layer's input size | Chapter 0 |
| Weight, bias, pass-down gradients | δ xT (needs x), δ (needs nothing), WTδ (needs W) | Chapter 1 |
| ReLU mask | 1 bit per value: 1/8 of an INT8 tensor, 1/32 of FP32 | Chapter 1 |
| BatchNorm scale gradient | sum of δ times the saved x̂ | Chapter 2 |
| Lite residual saved input | 1 / (s2 e): 1/24 at s = 2, e = 6 | Chapter 3 |
| TinyTL memory saving | up to 6.5 times against full fine-tuning (paper) | Chapter 3 |
| Checkpointing | C + L/C, best at C = √L; about one extra forward pass | Chapter 5 |
| QAS | weight gradient times s−2; bias times (sW sx)−2 | Chapter 6 |
| MCUNetV3 chip | 256 KB SRAM, 1 MB flash | Chapter 7 |
| First-layer leak | x = weight-gradient row / bias gradient | Chapter 8 |
| Term | Meaning |
|---|---|
| Activation | A layer's output for one input. |
| Mask | One bit per value that tells a ReLU where to pass the gradient. |
| Lite residual | A small trainable side branch beside a frozen block. |
| Sparse update | A per-layer plan of what to train under a memory budget. |
| Contribution analysis | Measure each layer's accuracy gain when trained alone. |
| Checkpoint | An activation kept so you can recompute a segment. |
| QAS | Divide INT8 gradients by the scale squared. |
| Graph pruning | Delete backward steps that feed no trainable parameter. |
pythonimport numpy as np def linear_backward(delta, x, W, train_w, train_b): grads = {} if train_w: grads['W'] = np.outer(delta, x) # needs the saved input x if train_b: grads['b'] = delta # needs nothing saved return W.T @ delta, grads # pass-down: needs W only def kept_kb(X, plan): # X: input KB at 8 bits r = {'-': 0, 'b': 0, 'qW': 0.25, 'W': 1.0} trained = [i for i, m in enumerate(plan) if m != '-'] if not trained: return 0.0 f = trained[0] # lowest trained layer return sum(r[m] * x for m, x in zip(plan, X)) + sum(X[f:]) / 8 def qas_step(W_bar, G_bar, s, lr): # integer weight, its gradient return W_bar - lr * G_bar / s**2 # same real step as float SGD X = [48, 32, 32, 24, 24, 16, 16, 8] print(kept_kb(X, ['-', '-', '-', 'b', 'qW', 'qW', 'W', 'W'])) # 45.0 print(qas_step(50.0, 0.002, 0.01, 0.1)) # 48.0: W moves by 0.02
Inference on a chip came first: MCUNet and TinyEngine fit the forward pass. This lesson adds the backward pass in the same memory. On servers, the same problem returns at scale in Distributed Training, and parameter-efficient methods such as LoRA cut optimizer state, not activations.
This lesson is based on the on-device training lecture of MIT 6.5940: TinyML and Efficient Deep Learning Computing, from an earlier offering of the course. Song Han and the MIT HAN Lab teach it. The current course is on the course site. The works it cites include TinyTL (Cai et al., NeurIPS 2020) and MCUNetV3, "On-Device Training Under 256KB Memory" (Lin et al., NeurIPS 2022). They also include PockEngine (Zhu et al., MICRO 2023), Deep Leakage from Gradients (Zhu, Liu and Han, NeurIPS 2019), FedAvg (McMahan et al., AISTATS 2017) and gradient checkpointing (Chen et al., 2016). All explanations, devices and worked numbers here are our own.
Now press Teach and explain, from memory, why a weight gradient needs the saved input and a bias gradient does not. Then go back to the memory bar at the top and find a plan that fits in both formats.