On-Device Training

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.

Fit training into 256 KB

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

The Training Wall

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.

Watch memory over one step

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.

12

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.

Say it aloud

M-train equals the sum over i from one to L of A-i.

Mtrain
M-train the memory kept for the backward pass, in KB.
∑i=1L
the sum over i from one to L one term for each layer, first to last.
Ai
A-i the size of the activation that goes into layer i, in KB.
In plain words

Add the input size A-i of every layer. That total, M-train, sits in memory when the forward pass ends.

With numbers

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.

  1. What the backward pass must keep: three gradients, one needs the input.
  2. The parameter trap: fewer parameters, almost the same memory.
  3. TinyTL: train biases, add a small side branch.
  4. Sparse update: pick what to train in each layer.
  5. Gradient checkpointing: drop activations and recompute them.
  6. Training in eight-bit integers: a quarter of the bytes, and the scale fix.
  7. A compile-time plan: prune the backward graph before it runs.
  8. Gradients leak: why the data should not leave the device.
  9. The field guide: numbers, code and where to go next.
You add one more layer whose input is 20 KB. What happens to memory?

Chapter 1

What the Backward Pass Must Keep

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.

Open one layer's backward pass

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.

Say it aloud

d-L by d-W equals delta times x transpose.

∂L/∂W
d-L by d-W the weight gradient: one number per weight, the same shape as W.
δ
delta the gradient of the loss with respect to the output y, one number per output.
xT
x transpose the layer's input, laid flat as a row. It comes from the forward pass.
In plain words

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 numbers

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

Say it aloud

d-L by d-b equals delta.

∂L/∂b
d-L by d-b the bias gradient, one number per output.
δ
delta the gradient arriving from the layer above.
In plain words

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.

With numbers

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.

Which gradient forces the layer to keep its input x from the forward pass?

Chapter 2

The Parameter Trap

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.

ModeWhat trainsWhere the backward pass stops
Fullevery weight and biasat the first layer
BN + LastBatchNorm scale and shift, plus the classifierat the first layer
Last onlythe classifierat 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?

Count parameters against memory

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.

Say it aloud

d-L by d-gamma equals the sum over j of delta-j times x-hat-j.

∂L/∂γ
d-L by d-gamma the gradient of one channel's scale.
∑j
the sum over j one term for every pixel position in that channel.
δj
delta-j the gradient arriving at the BN output, position j.
x̂j
x-hat-j the normalised value at position j, saved from the forward pass.
In plain words

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.

With numbers

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.

In our toy, BN + Last trains 71 times fewer parameters than full fine-tuning. Why does it keep only about 2 times less activation memory?

Chapter 3

TinyTL: Train the Biases, Add a Lite Branch

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.

  1. Downsample the block input by 2 in each direction before the branch.
  2. Skip the channel expansion. A MobileNet-style block widens C channels to 6C, the inverted bottleneck; the branch stays at C channels, with group convolutions.
  3. Upsample the branch output and add it to the block output.

Size a lite residual

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.

2

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.

Say it aloud

r equals one over s squared times e.

r
r the branch's saved input as a fraction of the block's largest activation.
s2
s squared the downsample factor s, squared: each side shrinks s times, so the pixels shrink s squared times.
e
e the expansion ratio of the main block, 6 in a MobileNetV2 block.
In plain words

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.

With numbers

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.

A lite branch downsamples by s = 2 beside a block with expansion e = 6. What fraction of the block's largest activation does it save?

Chapter 4

Sparse Update: Spend Memory Where It Pays

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.

Plan a sparse update

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.

Say it aloud

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.

M
M the memory for kept tensors, in KB.
∑i∈U
the sum over i in U one term per layer whose weights train.
ri
r-i the fraction of input channels whose weights train: a quarter or 1.
Xi
X-i the input size of layer i, in KB at 8 bits.
⅛
one eighth a ReLU mask is 1 bit for each 8-bit value.
∑i=fL
the sum over i from f to L every layer the backward pass crosses, from the lowest trained layer f to the last layer L.
In plain words

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.

With numbers

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.

You move one weight update from layer 7 down to layer 2 and train nothing else below layer 7. What happens to memory?

Chapter 5

Gradient Checkpointing

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.

  1. Forward pass: keep the activation at the start of each segment of layers, a checkpoint. Drop the others.
  2. Backward pass, one segment at a time, from the last: rerun the forward pass from that segment's checkpoint and keep its activations.
  3. Run the backward pass through the segment, then free its activations.

Place the checkpoints

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.

36
2

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

Say it aloud

M of C equals C plus L over C.

M(C)
M of C the peak number of activations held, with C checkpoints.
C
C the checkpoints, held for the whole backward pass.
L / C
L over C the layers in one segment, all held while you recompute that segment. L is the number of layers.
In plain words

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.

With numbers

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.

A network has 64 equal layers. What is the best number of checkpoints, and how much memory do you save?

Chapter 6

Training in Eight-Bit Integers

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 quantizationReal quantized training
Weights stored as32-bit floats8-bit integers
Arithmeticfloats, with rounding simulated8-bit multiplies, 32-bit sums
Training memory savednone4 times on stored tensors
Used forpreparing a model for INT8 inferencetraining 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̄.

Say it aloud

G sub W-bar equals s times G sub W.

GW̄
G sub W-bar the gradient with respect to the integer weight.
s
s the scale: the real size of one integer step, for example 0.01.
GW
G sub W the gradient with respect to the real weight, what float training sees.
In plain words

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.

With numbers

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:

Say it aloud

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

G̃
G-tilde the corrected gradient used for the update of W-bar.
s−2
s to the minus two one over s squared, one factor per layer or channel.
GW̄
G sub W-bar the raw gradient with respect to the integer weight.
In plain words

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.

With numbers

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.

Line up the update sizes

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.

A layer has scale s = 0.01. Without QAS, how far off is an INT8 update, and why?

Chapter 7

Plan the Backward Pass at Compile Time

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.

  1. Start at the loss.
  2. Keep a backward step if it leads to a trainable weight or bias.
  3. Keep a saved tensor only if a kept step reads it.
  4. Delete the rest. The chip never sees it.

Prune the backward graph

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.

Why can TTE prune the backward graph before the chip runs?

Chapter 8

Gradients Leak

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.

Say it aloud

x-j equals d-L by d-W at row i, column j, divided by d-L by d-b at i.

xj
x-j pixel j of the private input.
(∂L/∂W)ij
d-L by d-W at i j one entry of the weight gradient: delta-i times x-j.
/
divided by the division cancels delta-i.
(∂L/∂b)i
d-L by d-b at i the bias gradient of output i, which is delta-i.
In plain words

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.

With numbers

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.

Read an image out of a gradient

Left: the private images in one batch. Right: what the server gets by the division above. Drag the sliders.

1
0.00

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.

A server sees the first-layer gradients from one example. How does it recover the input?

Chapter 9

The Field Guide

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.

Numbers to keep

WhatValueWhere
Training memory keptM = sum of every layer's input sizeChapter 0
Weight, bias, pass-down gradientsδ xT (needs x), δ (needs nothing), WTδ (needs W)Chapter 1
ReLU mask1 bit per value: 1/8 of an INT8 tensor, 1/32 of FP32Chapter 1
BatchNorm scale gradientsum of δ times the saved x̂Chapter 2
Lite residual saved input1 / (s2 e): 1/24 at s = 2, e = 6Chapter 3
TinyTL memory savingup to 6.5 times against full fine-tuning (paper)Chapter 3
CheckpointingC + L/C, best at C = √L; about one extra forward passChapter 5
QASweight gradient times s−2; bias times (sW sx)−2Chapter 6
MCUNetV3 chip256 KB SRAM, 1 MB flashChapter 7
First-layer leakx = weight-gradient row / bias gradientChapter 8

Terms in one line each

TermMeaning
ActivationA layer's output for one input.
MaskOne bit per value that tells a ReLU where to pass the gradient.
Lite residualA small trainable side branch beside a frozen block.
Sparse updateA per-layer plan of what to train under a memory budget.
Contribution analysisMeasure each layer's accuracy gain when trained alone.
CheckpointAn activation kept so you can recompute a segment.
QASDivide INT8 gradients by the scale squared.
Graph pruningDelete backward steps that feed no trainable parameter.

A checklist for training on a chip

The core as code

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

Where it sits in the field

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.

Keep going

The takeaway. Memory, not arithmetic, stops training on a chip. Weight gradients need saved inputs; biases do not. So train biases and late layers, keep side branches small, store in INT8 with QAS, and let a compiler delete everything the plan does not read.

Credit

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.

You must personalise a model on a chip with 256 KB. Which plan fits the ideas of this lesson?

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.

MIT 6.5940: On-Device Training
The course site · Back to Distributed Training · On to Vision Transformers · Workbook · Back to Gleams