A model that runs is not a model that ships. Pick a chip, set an energy budget, and see which of five models still fit in flash, fit in RAM, and stay accurate enough.
Learn to measure a tiny model on a microcontroller, benchmark it the MLPerf Tiny way, choose a point on the trade-off curve, guard it in CI, and update it in the field without breaking the device.
Choose a chip, then drag the energy budget. Watch the best model change, and watch some models drop out because they do not fit. Then we build, piece by piece, every number behind each dot: flash, RAM, cycles, energy, accuracy, and the update that puts a new model on a device.
You need the idea of a neural network that has been quantized to int8 (fw-ml-02) and a rough idea of what flash and RAM are. We build the rest from zero.
Built from primary sources, with no course slides: the MLPerf Tiny paper (Banbury et al., 2021), the MCUNet paper (Lin et al., NeurIPS 2020), the MCUboot design document and Nordic’s nRF52840 product specification. Every idea is re-taught here in our own words and devices.
A model of the trade-off, not a measurement. The five models (S0 to S4) and their sizes, operation counts and accuracies are illustrative. Chip memory sizes and clocks are the parts’ real figures; cycles per operation and the energy per clock cycle are placeholders, except the nRF52840’s 52 µA per MHz from Nordic’s specification. Chapter 5 shows how to replace each placeholder with your own measurement.
Chapter 0
See the five budgets that a model must meet on a real chip, and why accuracy is only one of them
You trained a small model that spots a spoken word. On your laptop it is right 95 times in 100. You copy it onto a wristband that runs from a coin cell. Now four different things can go wrong, and none of them is about accuracy.
The first: the linker stops and says the firmware image is bigger than the chip. The second: the image fits, but the board resets the first time it runs the model. The third: it runs, but one answer takes 700 ms, so the band misses every word you say. The fourth: it works, but the battery now lasts nine days instead of a year.
Each failure is a budget: a fixed amount of something that the chip gives you, and that the model must not use up. This lesson teaches you to measure each budget, to compare your result with other people’s results fairly, to choose a model that meets all of them, and to change that model later without breaking a device that is already in someone’s hand.
A microcontroller is a small computer on one chip, with its own memory. It has two kinds. Flash keeps its contents when the power goes off. Think of a bookshelf: large, slow to rewrite, and the books stay. RAM (random-access memory) is fast and small, and it forgets everything at power off. Think of a desk: you work on it, and you clear it at the end of the day.
A neural network has two parts, and each part wants its own place. The weights are the learned numbers. They never change while the device runs, so they live on the shelf, in flash. The activations are the in-between results that each layer writes for the next layer. They change on every run, so they live on the desk, in RAM. You met this split in fw-ml-01; here we put numbers on it.
A model ships only when it passes all five at once, on the real part.
Notice the shape of the problem. A bigger model is usually more accurate, and it costs more of the other four. So there is no single best model. There is a set of models that no other model beats on every budget at once. That set is the Pareto front, and Chapter 5 draws it. The instrument at the top of this page already shows the idea: move the budget line, and a different model wins.
Pick a chip, then pick a model. Five bars show how much of each budget the model uses. A bar that crosses its line turns red: that budget has failed.
Illustrative models and placeholder cycle and energy costs, as in the hero. The limits are a 250 ms time slot, a 2 mJ energy allowance and a 90% accuracy floor, which is the keyword-spotting target in the MLPerf Tiny paper. Flash and RAM limits are the chip’s real sizes minus 160 KB of flash and 48 KB of RAM that the rest of the firmware keeps.
Pick S3 and step through the three chips. Its time bar changes a great deal, and it meets the 250 ms slot only on the fastest chip. Its energy bar fails on all three. A budget belongs to a model and a chip together. That is why every number in this lesson names a part.
We take the budgets one at a time, then put them back together and ship.
Chapter 1
Count the bytes on the shelf and on the desk, and find the one layer that sets the size of the desk
You build the firmware, and the toolchain prints a line like this: text 498312, data 2104, bss 61440. Those three numbers answer the first two budgets. Most people read them once and move on. We will read them slowly.
The tool is arm-none-eabi-size. text is the program code and every constant, including the model’s weights, so it lives in flash. data is the variables that start with a value; the value is stored in flash and copied to RAM at boot. bss is the variables that start at zero; they take RAM and no flash. So the flash budget is text plus data, and the static RAM is data plus bss. In this lesson, 1 KB is 1,024 bytes, the way datasheets count.
A quantized model stores one byte for each weight (the int8 format from fw-ml-02), plus a few bytes of scale and zero point for each channel. So the flash cost of a model is about its number of weights, in bytes. The reference keyword model in the MLPerf Tiny paper, a small convolutional network called DS-CNN, is a 52.5 KB file. The reference visual model is 325 KB. Compare that with a typical chip: the STM32F746 that the MCUNet authors use has 1 MB of flash in total, and the code of your firmware also has to live there.
The MCUNet paper puts the problem in one table. A Cortex-M7 chip of this class has 320 kB of SRAM (RAM) and 1 MB of flash. A full ResNet-50 exceeds the flash by about 100 times. MobileNetV2 exceeds the RAM limit by about 22 times, and even its int8 version exceeds it by about 5.3 times (Lin et al., 2020, Section 1). So flash alone does not decide: a model can fit on the shelf and still not fit on the desk.
Now the desk. A network runs layer by layer. Layer 1 reads the input and writes its output. Layer 2 reads that output and writes the next. While one layer works, it needs two buffers alive at once: the one it reads and the one it writes. When the layer is done, the input buffer is free to reuse.
So the RAM the model needs is not the sum of all activations. It is the size of the worst layer. TFLite Micro keeps one block of RAM for this, the tensor arena: you give the interpreter a plain byte array, and a planner packs the layer buffers into it, reusing space once a buffer is dead. The arena also holds some persistent data, such as operator data (see micro_interpreter.h in the TFLM source).
AllocateTensors() fails.A worked example, with every step. Take a small image network with a 96 × 96 × 3 input. Its layers write these int8 tensors:
The largest of the five sums is 108 KB, at dw1. That is the arena the model needs, before any extra. Add the stack, your sensor buffers, and a radio stack, and you have the RAM budget. Now try it on a real size of chip.
Each pair of bars is one layer: the buffer it reads (light purple) and the one it writes (dark purple). The dashed line is the RAM left for the arena on this chip. Widen the network, then switch on in-place depthwise convolution.
The layer sizes come from the worked example above; the width slider scales every tensor except the input. The RAM line is the chip’s RAM minus 48 KB for the rest of the firmware and 6 KB of arena overhead, both placeholders. In-place depthwise needs one more channel plane than the larger of the two buffers, as in Figure 7 of the MCUNet paper (N+1 planes, where a normal layer needs 2N); the stride-2 layer is modelled the same way.
Go to the nRF52840 and set the width to 2.0. The peak layer, dw1, now needs 216 KB, but the line sits at 202 KB, so the model fails. Switch on in-place depthwise. The peak jumps to pw1 at 180 KB, and the model fits. Nothing was retrained. Only the order of the writes changed.
A depthwise convolution filters each channel on its own. Channel 5 of the output depends only on channel 5 of the input. So once channel 5 is done, its input plane is dead, and the next result can be written on top of it. Only the first plane needs a small temporary copy. That is the in-place trick in TinyEngine, the inference engine of MCUNet, and it cuts a depthwise layer from 2N planes to N+1.
But look at what happened to the peak. It moved to a pointwise layer, which mixes all channels and cannot overwrite its own input. So in-place helps only when a depthwise layer is the peak. The MCUNet paper reports the step as a 1.6 times cut in measured memory on its test; your network will differ. The lesson: always find the new peak after each fix.
Symptom. AllocateTensors() returns an error, or the board hard-faults on the first inference. Measurement. After a successful AllocateTensors(), call arena_used_bytes(). The TFLM header says it returns the used arena and gives the best arena size; its comment suggests adding 16 bytes for alignment. Print it once at boot. Fix. Shrink the peak layer (a smaller input, fewer channels), apply the in-place step, or change the layer order. Set the arena size from the number you measured, with a small margin, not from a guess.
c++// one static array is the whole desk for the model alignas(16) static uint8_t tensor_arena[120 * 1024]; tflite::MicroInterpreter interp(model, resolver, tensor_arena, sizeof(tensor_arena)); if (interp.AllocateTensors() != kTfLiteOk) { panic("arena too small"); } printf("arena used: %u of %u bytes\n", (unsigned)interp.arena_used_bytes(), (unsigned)sizeof(tensor_arena));
On real hardware: on an STM32 Nucleo or an nRF52840 DK, build with arm-none-eabi-size and read arena_used_bytes(); the two printouts are the flash and RAM rows of your table. Repeat after each change.
Chapter 2
Measure one inference with the chip’s own counter, and learn which layer to speed up first
A word spotter listens in slices. Every 250 ms a new slice of sound arrives, and the model must answer before the next one. On your desk the model takes 85 ms. In the field, a tester reports 700 ms and a missed word. Is the chip slow, or is the code slow? A stopwatch cannot tell you. A cycle count can.
A processor does its work in tiny steps driven by a clock, a signal that ticks at a fixed rate. One tick is one cycle. A chip at 64 MHz ticks 64 million times a second. So time is simple: time = cycles ÷ clock. The cycle count belongs to the code and the chip design. The clock belongs to how you set the chip up. Keeping them apart tells you where a slowdown comes from.
The main work of a network is the multiply-accumulate, or MAC: take one weight, multiply it by one input, and add the result to a running total. Count the MACs and you know the work. A 1×1 (pointwise) convolution over a 25 × 5 map with 64 channels in and 64 out does 25 × 5 × 64 × 64 = 512,000 MACs. A 3×3 depthwise convolution on the same map does 25 × 5 × 64 × 9 = 72,000 MACs, because each channel is filtered alone.
Now the key number: cycles per MAC. A plain C loop on a Cortex-M4 spends several cycles on each MAC, because it also loads two bytes, widens them, and updates a loop counter. Tuned int8 kernels such as CMSIS-NN use the chip’s SIMD instructions to do two MACs in one instruction, so the cost per MAC drops. The exact figure depends on the layer, the memory and the compiler, so we will not quote one as fact. Measure it.
Each bar is the time one layer takes. The long bar at the bottom adds them up against the 250 ms slot. Change the kernels, then change the clock, and see which layer matters.
Illustrative. The network is DS-CNN shaped: one 10×4 convolution, then four depthwise-plus-pointwise pairs on a 25×5 map with 64 channels, 2.66 million MACs in all (the MAC counts are exact for those shapes). Cycles per MAC are placeholders: plain C 8.0, 10 and 8.0 for convolution, depthwise and pointwise; tuned 2.4, 3.5 and 1.8; tuned and fused 1.8, 2.4 and 1.5. On a real chip the clock also changes flash wait states, so cycles are not constant across clocks.
With tuned kernels at 64 MHz the network takes about 85 ms, a third of the slot. Switch to plain C loops and it takes about 340 ms: the slot is gone, and the answer comes after the next slice has already arrived. Look at which bars are longest. The pointwise layers hold 77% of the MACs and about 68% of the time. Speed up those first. The depthwise layers hold only 11% of the MACs but cost more per MAC, so they matter more than their MAC count suggests.
Cortex-M3, M4, M7 and M33 cores have a free hardware counter in a block called the DWT (Data Watchpoint and Trace unit). The register DWT_CYCCNT at address 0xE0001004 counts every core cycle. You switch it on in two steps: set the TRCENA bit (bit 24) in DEMCR at 0xE000EDFC, then set CYCCNTENA (bit 0) in DWT_CTRL at 0xE0001000. The Cortex-M0 and M0+ cores have no such counter. On the others, bit 25 of DWT_CTRL (NOCYCCNT) tells you if it is missing. These come from the ARMv7-M Architecture Reference Manual; check your own part’s reference manual before you rely on them.
c// Count the cycles of one call. CMSIS names; any Cortex-M3/M4/M7/M33 part. static inline void cyc_init(void) { CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; // 0xE000EDFC bit 24 DWT->CYCCNT = 0; DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; // 0xE0001000 bit 0 } uint32_t t0 = DWT->CYCCNT; run_one_layer(); uint32_t cycles = DWT->CYCCNT - t0; // unsigned subtraction survives one wrap
The counter is 32 bits wide, so it wraps. At 64 MHz it wraps every 67 seconds; at 216 MHz, every 19.9 seconds. Time a single layer, or one inference, and you are always far inside that window. Time a whole minute and you must count the wraps.
Symptom. The bench says 85 ms; the field says 700 ms. Measurement. Read the cycle count of the same inference on both. If the cycles match and the times differ, the clock is different: a clock tree that fell back to a slow internal oscillator is common (see fw-core-03). If the cycles differ, look at the build: a debug build with no optimisation can cost several times more cycles than a release build, and flash wait states cost cycles when code runs from flash at a high clock. Fix. Set the optimisation level, check the clock, and put the hot kernel in the fastest memory your part offers.
On real hardware: on an STM32 Nucleo, enable the counter as above, time each layer call of your interpreter (TFLM has a profiler class you can hook; check your version, and see fw-ml-01), and print cycles per layer to a UART. Repeat at two clock speeds. Cycles should stay close; time should not.
Chapter 3
Turn cycles into microjoules, then into days of battery, and see why the chip should sleep between runs
The band works. It answers in 85 ms, it fits in flash and RAM, and it is accurate. You wear it for a week, and the coin cell is empty. Nothing in the first three budgets warned you. The fourth budget, energy, is a different measurement, and it needs its own care.
Current is how much charge flows each second, in amps (A). A chip like this draws milliamps (mA, a thousandth of an amp) when it computes and microamps (µA, a millionth) when it sleeps. Power is voltage times current: at 3 V and 3.3 mA the chip uses about 10 milliwatts. Energy is power over time, and it is what a battery stores and what a task spends: E = V × I × t. One watt for one second is one joule. A task that takes 10 mW for 85 ms spends about 850 µJ.
Chip makers publish a handy number: the current per megahertz. The nRF52840 product specification lists 52 µA per MHz when the CPU runs CoreMark from flash (spec revisions differ in their other figures, so check yours). At 3.0 V that is 3.0 × 52 = 156 picojoules per clock cycle. Here is the step from Chapter 2 to this chapter:
energy per inference = cycles × energy per cycle = 5.46 million × 156 pJ = 852 µJ
That is the cycle count of the tuned network from Chapter 2, and it is a model: the real chip also has leakage, RAM, and flash reads that this one number hides. That is why you will measure it. But the model teaches something sharp. If the current grows in step with the clock, then the energy per cycle does not depend on the clock. Running at 16 MHz takes four times longer and uses the same 852 µJ.
So is the clock speed irrelevant? Not quite. When the chip is awake, some current flows no matter how fast the clock is: the voltage regulator, the clocks and oscillators, the memory, the sensor you powered up. Call it the fixed overhead. Then the active current is I = Ifixed + k × f, and the energy per inference is V × (Ifixed ÷ f + k) × cycles. The first term shrinks as f grows. A fast clock finishes sooner and pays the overhead for less time. Then the chip goes to sleep, where the overhead stops. That is race to sleep.
With a placeholder overhead of 0.6 mA, the same network costs about 1.47 mJ at 16 MHz and about 1.0 mJ at 64 MHz. The overhead value is an illustration; your board’s value you must measure.
A real device does not run all the time. It wakes, runs one inference, and sleeps. The average current over one period T is the weighted mix: Iavg = (ton × Iactive + (T − ton) × Isleep) ÷ T. The battery life is its capacity divided by that average. For the nRF52840, the documents show a sleep current of about 1 µA to 2.4 µA in System ON, depending on how much RAM stays powered and on the revision; we use 2.35 µA.
Worked example, nRF52840 at 64 MHz, one inference of 85 ms every second:
Now run the model once every 10 seconds instead. The awake fraction falls to 0.85%, the average to about 0.031 mA, and the life to about 300 days. Same model, same chip, ten times fewer runs, ten times longer life. Try it.
The trace shows the current over one period: a tall block while the model runs, a thin line while the chip sleeps. Slide the period, change the clock, and switch the fixed overhead on and off.
The network is the 5.46 million cycle model from Chapter 2. Only 52 µA per MHz at 3.0 V is the nRF52840 figure; the sleep current of 2.35 µA comes from one revision of its documents; the 220 mAh cell is a typical label value that real cells fall below at a 3 mA pulse; the 0.6 mA overhead is a placeholder. Use your own measurements for all four.
Set the period to 60 seconds. The sleep current now matters as much as the pulse. At that point, an extra microamp on the sleep floor costs more than a better kernel. The device is mostly a sleeping chip, and its battery life is decided by how deep it sleeps.
Symptom. The datasheet says a year; the device lasts nine days. Measurement. Put a current meter that records a trace in series with the supply, such as Nordic’s Power Profiler Kit II or a Joulescope, and record several whole periods. Read three things: the height of the pulse, its width, and the floor between pulses. The floor is the usual culprit: a pin that leaks, a sensor left on, or a debug probe that keeps the chip awake. Fix. Run the model less often, gate it with a cheaper detector that wakes the big model only when something happens, cut cycles with the Chapter 2 tools, and then lower the floor.
On real hardware: on an nRF52840 DK, power the chip through the current-measurement header with a power profiler, run 100 inferences on a timer, and integrate the trace. Divide total microjoules by 100. That is your energy per inference, and it is the number MLPerf Tiny reports (Chapter 4).
Chapter 4
Learn the rules that let two chips, from two companies, be compared by one number you can trust
Two vendors each say they have the fastest tiny chip. One ran a small keyword model. The other ran a bigger image model with a lower accuracy bar, and reported its best run. Both numbers are true. Neither number helps you choose. A benchmark is a fixed set of rules that makes two numbers mean the same thing.
MLPerf Tiny is the benchmark for machine learning on microcontrollers. It was made by more than 50 organizations from industry and academia and is described in a 2021 paper by Banbury and colleagues. It measures three things for each task: accuracy, latency and energy. This chapter follows the paper’s first round, version 0.5.
Each task fixes a dataset, a model and a quality target: the least accuracy a result must reach to count. Here is the table from the paper:
| Task | Dataset (input) | Reference model (file size) | Quality target |
|---|---|---|---|
| Keyword spotting | Speech Commands (49×10) | DS-CNN (52.5 KB) | 90% top-1 |
| Visual wake words | VWW (96×96) | MobileNetV1 (325 KB) | 80% top-1 |
| Image classification | CIFAR-10 (32×32) | ResNet (96 KB) | 85% top-1 |
| Anomaly detection | ToyADMOS (5×128) | FC autoencoder (270 KB) | 0.85 AUC |
Top-1 means the model’s single best guess is right. AUC (area under the curve) scores how well the anomaly score separates normal from abnormal sounds; 1.0 is perfect and 0.5 is a coin flip. The reference implementations run the reference models with TensorFlow Lite for Microcontrollers on the NUCLEO-L4R5ZI board, built bare-metal with the GCC Arm toolchain. The paper shows their latency and energy in its Figure 5.
Notice the fit with Chapter 0. The target is a floor to clear. For the visual task the reference model reaches about 86%, but a closed submission only needs 80%, to leave room for the small differences that come from quantization and rounding on different hardware.
The paper offers two ways to enter, so that one suite can serve two goals.
In the first round, submissions covered Arm microcontrollers, a RISC-V microcontroller, a Raspberry Pi 4, a neural-network accelerator and an FPGA. The paper notes that 8-bit integers were the most common number format.
The paper gives the steps. A host program drives the device under test through a benchmark framework based on EEMBC’s platform, because a tiny chip cannot hold files or print to a screen.
Two design choices are worth thinking about. A run of at least 10 seconds averages out small pulses and slow effects. The median of five ignores one strange run, such as a run where an interrupt took the core for a while. Try both ideas below.
Press Run five. Each bar is one run of at least 10 s. The line is the median, which is the score. Raise the noise, run again, and flip the switch to report the best run instead.
A simulation of the procedure in Section 5.3 of the paper, not a measurement. The true values are the tuned network of Chapters 2 and 3 (85.3 ms and 852 µJ per inference); each run adds random noise of the size you choose. Red marks the switch because reporting the best run is not what the benchmark allows.
With 4% noise the median and the best run differ by a few percent. Raise the noise to 12% and the best run flatters the chip by about a tenth. A marketing number can hide in that gap. The median is the number you can repeat.
Look at the energy step again. The loop runs inferences one after another for at least 10 seconds. So the microjoules per inference exclude sleeping, feature extraction and the radio. It answers “how much does the model cost on this chip”, and it does not answer “how long will my product last”. For that you need Chapter 3’s duty cycle and your own whole-system trace.
Symptom. Your result beats a published one by 30%. Measurement. Check the division, the model, the quality target, and whether energy came from a median of five over a window of at least 10 s. Fix. Rerun yours with the reference model and the same rules, or call your result an open division result and say what you changed.
On real hardware: the reference code is public (the paper points to the mlcommons/tiny repository). Run the keyword-spotting reference on a NUCLEO-L4R5ZI or on your own board, and compare your median IPS and microjoules with the published results for the round you pick.
Chapter 5
Plot every model on every chip, throw out the ones that something else beats, and pick from what remains
Your team has five model sizes and three candidate chips. That makes 15 possible products. A manager asks which one to build. “The most accurate” is the answer people reach for, and it is usually wrong, because it ignores what the accuracy costs. A better answer starts by crossing out the choices that are plainly bad.
Take two options, A and B. Say A dominates B when A is at least as accurate as B and costs no more energy, and is strictly better on one of the two. Nobody should pick B: A is a free upgrade. An option that no other option dominates is on the Pareto front, named after the economist Vilfredo Pareto. The front is the short list. Everything else is noise.
Look at the numbers in this lesson’s placeholder model. On the nRF52840 the five models cost about 126 µJ (S0, 84.5% accurate), 851 µJ (S1, 91.0%), 2.5 mJ (S2, 93.6%), 7.9 mJ (S3, 95.0%) and 19 mJ (S4, 95.8%). Each step up in accuracy costs at least 2.4 times the energy, and most steps cost three times. The last step, S3 to S4, buys 0.8 points for 2.4 times the energy, and S4 does not even fit in flash on that chip. A front like this is a staircase that gets steeper.
Two more facts about a front. First, the constraint that binds first picks your point. If the product needs 90% accuracy, S1 is the cheapest model that clears the floor, and the cheaper S0 is out. If the battery allows only 1 mJ per inference, S1 is the best you can afford. Second, the front moves when you add a requirement. If you add a rule that one answer must arrive in 40 ms, a faster chip can bring a point back that the slower chip lost, even at a higher energy.
Each dot is one model on one chip. Dot size is the RAM it needs. A red cross does not fit. A faded dot fails your accuracy floor or your time limit. The green line is the front of what is left, and the ringed dot is the cheapest choice.
Illustrative, as in the hero. Pink, teal and orange only tell the three chips apart; they carry no other meaning on this page. Each chip’s own memory sizes and clock are real; the five models’ accuracies and sizes, the cycles per operation and the energy per cycle (except 52 µA per MHz for the nRF52840) are placeholders. Replace each with a number you measured.
Set the floor to 90% and the time limit to “none”. The cheapest choice is S1 on the nRF52840. Now choose 40 ms. S1 on the nRF52840 takes 85 ms and drops out. S1 on the STM32L4R5 (45 ms) fails too. Only the STM32F746 clears 40 ms with S1, at 19 ms but about 4 mJ. The deadline, not the accuracy, picked the chip.
Treat each candidate as a row in a table and fill every column by measuring, never by estimating.
size and arena_used_bytes() (Chapter 1).The MCUNet paper automates the first step. Its search, TinyNAS, first picks a search space that fits the chip’s memory, then finds the best network inside it. The second half of the system, TinyEngine, is built with the network in mind: its memory scheduler works per layer, and the paper reports it cuts peak memory by 3.4 times and speeds up inference by 1.7 to 3.3 times compared with TF-Lite Micro and CMSIS-NN. The lesson is that the model and the engine form one design. At a better accuracy than int8 ResNet-18 and MobileNetV2 (70.7% against 69.8% ImageNet top-1), MCUNet uses 3.5 times less SRAM and 5.7 times less flash (Figure 8). Read tinyml-10 and tinyml-11 for the details.
Symptom. The team ships the most accurate model that fits; users complain that the device is warm and the battery is short. Measurement. Put the chosen model on the plot. It sits at the far right, two staircase steps beyond the knee. Fix. Move left along the front until the next step would break your floor. The knee is where the cost per extra point of accuracy starts to climb steeply.
On real hardware: pick three models you can build in a day (for example three input sizes) and one board. Measure all four numbers for each, put the three dots on a plot like the one above, and note which constraint binds first for your product.
Chapter 6
Write each budget down as a number the build can check, so a regression fails on Friday and not at a customer
It is Friday. A teammate adds a small feature: a 512-point FFT for a new audio feature. It works on the desk. Nobody opens the map file. The image grows by 20 KB, the RAM peak grows by 16 KB, and the inference gets 12 ms slower. Each number still fits. On Monday a second feature arrives, and now the image does not fit the update slot on the devices already in the field.
Budgets drift in small steps. People do not notice a step; a machine does. A gate is a check in your continuous integration (CI) system, the server that builds and tests every change. If a gate fails, the change cannot merge. The cost of a gate is a few seconds. The cost of a missed regression is a field recall.
Start with a file in the repository. It holds one number per budget and one name for the part it applies to. Then a script compares what the build measured with what the file allows.
json{ "part": "nRF52840, S1 keyword model", "flash_kb": 230, // text + data from arm-none-eabi-size, whole image "ram_kb": 80, // data + bss + arena + peak stack "latency_ms": 100, // median of five runs, on the board "energy_uj": 1000, // median of five, per inference "accuracy_min": 90.0, "parity_max_lsb": 1 // device output vs the Python reference, int8 steps }
Each gate has a different price, so each runs at a different time. This split is the part to get right.
arena_used_bytes()), the cycle count with the DWT counter, and the energy with a power profiler. These need hardware in the loop, so they run less often, and they use the median of five from Chapter 4.Parity deserves a note. Two builds of the same int8 network should produce the same outputs, to within the rounding of the requantization step. If the device output differs from the reference by many steps, something is wrong: a kernel bug, a wrong scale, an overflow. A small tolerance, one quantization step, allows for a different but correct rounding. Pick the tolerance from your own runs, write it in the file, and do not widen it to make a failing build pass.
A limit is not a wish. Each one comes from a fact about the product. The flash limit comes from the size of the slot that holds the firmware image, which Chapter 7 sets at 256 KB. Keep 10% free for growth, and the limit is 256 × 0.9 = 230 KB. The RAM limit is the chip’s RAM minus what the radio stack and the rest of the firmware need. The latency limit is the time between inputs, with room for the other work in the same slot. The energy limit is the battery life you promised, turned around: a year on a 220 mAh cell allows an average of 25 µA, and Chapter 3 shows how that divides into pulses and sleep. The accuracy floor is the quality target of the task. When a limit has no source, nobody can tell whether to fix the change or raise the limit, and the gate becomes an argument.
Choose a change. Six gates compare its numbers with the budgets. A red row means the build fails. Then move the flash limit, the energy limit and the accuracy floor and see which changes still pass.
Illustrative. The baseline is the S1 model on the nRF52840 from the earlier chapters (212 KB flash, 74 KB RAM, 85 ms, 851 µJ, 91.0%). The five changes and their effects are invented to show what each gate catches. The RAM limit is 80 KB, the time limit 100 ms and the parity limit 1 step.
Walk through the changes. “Widen the model” raises accuracy to 92.1% and breaks four gates at once: flash, RAM, time and energy. “Add a 512-point FFT” passes accuracy and parity but fails flash (the code grew) and RAM (the buffers grew). “Update the library” is the interesting one: the model is unchanged, the library is newer, and the output differs by one step. It passes only because the tolerance allows one step; a tolerance of 0 would have blocked it, and you should then decide whether the new rounding is acceptable. Then “Buggy new kernel” fails parity and accuracy together, and “Bad calibration set” fails only accuracy: parity against Python still passes, because both sides share the same bad scales. That last case is why you need both gates.
Symptom. The nightly energy gate fails on Tuesday and passes on Wednesday with no code change. Measurement. Rerun the same build five times and look at the spread. A rig has noise: temperature, supply, a different board. Fix. Gate on the median of five (the Chapter 4 rule), leave a margin of a few percent above your measured value, and store the history of every run so you can see slow drift as well as sudden jumps.
On real hardware: put arm-none-eabi-size and a ten-line script in your CI today. The flash and static RAM gate costs nothing, runs on any laptop, and catches most drift.
Chapter 7
Update a model on ten thousand devices, survive a power cut at every step, and always keep a model that works
Six months after launch, you retrain the keyword model so it understands more accents. The new file is 52 KB. Ten thousand wristbands are already in people’s homes. You will send the file over Bluetooth. Halfway through the transfer on one band, the battery dies, or a child pulls the band off the charger. What state is that device in when the power returns?
This is the last budget, and it is the budget of trust: after any update, at any moment of failure, the device must still run a model that works. fw-core-08 teaches the bootloader and firmware updates in depth. Here we apply the same ideas to a model.
The third design copies the idea in MCUboot, the open-source bootloader behind many MCU products. Its design document describes a primary slot where the image runs and a secondary slot where a new image waits. It swaps them, and it records progress in a small trailer at the end of each slot. An interrupted swap can resume, because the status is in flash. The same document lists a second image area for a second image, so one bootloader can manage the application and a separately signed model.
MCUboot checks an image before it runs it: the image must carry a magic value and a block of metadata that includes a SHA-256 hash of the contents, and a signature (the document lists RSA, ECDSA and Ed25519 options). A model deserves the same two checks. The hash catches a damaged download. The signature catches a file that someone else made. A model file also needs a header that tells the firmware whether it can use the model at all.
c// A model package header. Stored in flash in front of the .tflite bytes. typedef struct { uint32_t magic; // 0x4D4F444C, so a blank or torn slot is obvious uint16_t format_version; // layout of THIS header uint16_t model_version; // monotonic: refuse downgrades unless told to uint32_t body_bytes; // length of the model bytes that follow uint32_t min_firmware; // oldest firmware that can run this model uint32_t arena_bytes; // the arena it needs: refuse if bigger than our array uint32_t op_set; // bit mask of operators; refuse if our resolver lacks one uint8_t sha256[32]; // of the body uint8_t sig[64]; // signature over everything above (e.g. Ed25519) } model_header_t;
Read the fields as a list of refusals. arena_bytes ties back to Chapter 1: if the new model needs more desk than the firmware reserved, the device must say no, and not crash on the first inference. op_set stops a model that uses an operator your firmware did not link. min_firmware covers the case where the model must wait for a firmware update first. model_version never goes backwards by accident.
MCUboot has a three-step habit worth copying. In test mode the new image runs once, and the bootloader will revert to the old one on the next boot unless the application confirms it by setting an image-ok flag in the trailer. The application confirms only after it has proved the new image works. For a model, proof means a self-test: run a few stored inputs through the new model and compare the outputs with the answers stored in the package. If they match, run a few real inferences, then confirm. If anything fails, flip the pointer back.
Pick a design and a step where the power dies, then press Play update. The boxes are regions of flash. Green outline: the model that runs after power returns. Red: a region that is damaged. Then switch on “the new model is bad” and play again.
A model of the designs, not of any one product. The five steps are: 1 download to the idle region, 2 check the hash and signature, 3 switch (swap the images, or flip the pointer), 4 run the self-test, 5 confirm. The sizes (160 KB firmware, 52 KB model) and the 8 KB per second link are illustrative. The test, confirm and revert behaviour of the bundled design follows the MCUboot design document; the other two designs are common patterns, and your product’s details will differ.
Try the cut at step 1 in each design. With overwrite in place, a cut at step 1 leaves a torn model and nothing to fall back on: the feature is dead until a person fixes the device. With bundled in the image and with two slots, the same cut leaves the old model running. Now make the new model bad. Overwrite in place has no way back. The other two designs recover on their own. Compare the bytes sent as well: 212 KB for the bundle, 52 KB for the other two, which is 26 seconds against 6.5 at the illustrative link speed.
A device that survives a bad update can still be a bad update for the fleet. Send the new model to a small group first, say 1% of devices. Watch signals that the device already reports: how often self-tests fail, how often it reverts, how often the wake word fires per hour. If a number moves, stop. Widen to 10%, then to everyone. This is a practice, not a rule from a standard, and it costs only a version number and a counter. The fleet side of OTA is the subject of a later lesson on fleet connectivity and telemetry.
Symptom. Three days after a model update, support gets reports that the band “stopped hearing me”. Measurement. The device logs its model version, the self-test result and the revert count; filter by version. Fix. Roll the pointer back remotely, which needs only a small command because the old model is still in its slot.
On real hardware: on an nRF52840 DK with MCUboot (through the nRF Connect SDK), upload an image in test mode and pull the power at different moments. Repeat with your own two-slot model area and a pointer record. The point is to see that every cut leaves a whole model.
Chapter 8
Keep the formulas, the verified figures and the working code on one page
A tiny model ships when it meets five budgets on a real part and keeps meeting them after every change. Flash and RAM come from the linker and the tensor arena. Time comes from cycles divided by the clock. Energy comes from cycles, current and sleep, and from a duty cycle. Accuracy is a floor. You compare results with MLPerf Tiny rules, choose from the Pareto front, guard the numbers with gates, and update the model with a design that always leaves one that works.
| Number | What it is | Source |
|---|---|---|
| 90% / 80% / 85% / 0.85 AUC | Quality targets: keyword spotting (DS-CNN, 52.5 KB), visual wake words (MobileNetV1, 325 KB), image classification (ResNet, 96 KB), anomaly detection (FC autoencoder, 270 KB) | MLPerf Tiny paper, Table 1 (v0.5) |
| 10 s, 10 iterations, median of 5 | Latency and energy measurement procedure; energy is microjoules per inference | MLPerf Tiny paper, Section 5.3 |
| NUCLEO-L4R5ZI | Reference board (STM32L4R5ZI: Cortex-M4F up to 120 MHz, 2 MB flash, 640 KB SRAM) | MLPerf Tiny paper; board vendor listings |
| 320 kB SRAM, 1 MB flash | The STM32F746 class of chip; ResNet-50 exceeds its flash by about 100×, MobileNetV2 its RAM by about 22×, int8 MobileNetV2 by about 5.3× | MCUNet paper, Section 1 |
| 2N to N+1; 1.6× | In-place depthwise convolution, and the memory cut the paper measures for it | MCUNet paper, Fig. 7 and Fig. 5 |
| 3.4× memory, 1.7 to 3.3× speed | TinyEngine against TF-Lite Micro and CMSIS-NN (the arXiv abstract page of a later revision states 4.8× for memory; read the version you cite) | MCUNet paper (v2 text) |
| 70.7% top-1; 3.5× SRAM, 5.7× flash | MCUNet ImageNet accuracy on an off-the-shelf MCU, and its saving against int8 ResNet-18 and MobileNetV2 (69.8%) | MCUNet paper, Section 4.2 and Fig. 8 |
| 52 µA per MHz | nRF52840 running CoreMark from flash; 3.0 V × 52 = 156 pJ per cycle | nRF52840 product specification, feature list (revisions differ) |
| 1 to 2.4 µA | nRF52840 System ON sleep, by RAM retention and revision (we used 2.35 µA) | nRF52840 product brief and specification |
| 0xE0001004, 0xE0001000, 0xE000EDFC | DWT_CYCCNT, DWT_CTRL (CYCCNTENA bit 0, NOCYCCNT bit 25), DEMCR (TRCENA bit 24) | ARMv7-M Architecture Reference Manual |
| 67 s at 64 MHz; 19.9 s at 216 MHz | Time for the 32-bit cycle counter to wrap (232 ÷ clock) | Our arithmetic |
| test, confirm, revert | MCUboot swap types; the image-ok flag in the trailer; SHA-256 and signature checks | MCUboot design document |
Everything marked illustrative in the devices (the five models, cycles per operation, the energy per cycle of the two STM32 parts, the 0.6 mA overhead, the 8 KB per second link, the gate changes) is a placeholder to be replaced by your measurement.
size and arena_used_bytes() at boot in a debug build. Write both in the budget file.python# ci_gate.py: fail the build if any budget is broken. Size gates run on every commit. import json, subprocess, sys b = json.load(open("budgets.json")) def image_kb(elf): # arm-none-eabi-size prints: text data bss dec hex filename row = subprocess.check_output(["arm-none-eabi-size", elf]).decode().splitlines()[1].split() text, data, bss = map(int, row[:3]) return (text + data) / 1024, (data + bss) / 1024 # flash KB, static RAM KB flash, ram = image_kb(sys.argv[1]) arena_kb = float(open("arena_kb.txt").read()) # from arena_used_bytes() on the rig fails = [] if flash > b["flash_kb"]: fails.append(f"flash {flash:.0f} KB > {b['flash_kb']}") if ram + arena_kb > b["ram_kb"]: fails.append(f"ram {ram + arena_kb:.0f} KB > {b['ram_kb']}") for line in fails: print("FAIL", line) sys.exit(1 if fails else 0)
The cycle counter, from Chapter 2, and the model header, from Chapter 7, are the other two pieces of core code. Between them, you can measure a model and ship it.
This lesson closes the edge-ML track. Run the model first: fw-ml-01. Make it integer: fw-ml-02. Feed it a window of sensor data: fw-ml-03. Give it an accelerator: fw-ml-04. The update machinery is in fw-core-08; the flash that holds it is in fw-core-07; the tools to see inside a running chip are in fw-core-09.
The research behind the tricks is in tinyml-10 (MCUNet) and tinyml-11 (TinyEngine), with the efficiency basics in tinyml-01. Two applications put all five budgets to work: wake words on an MCU and the coin cell year. A safety-critical decoder, with the rules of medical firmware, follows in fw-bio-05.
micro_interpreter.h (arena_used_bytes()).Now press Present or Teach and explain from memory how one model goes from a laptop to ten thousand devices: where each of the five budgets comes from, how you would measure it, and what happens to the device if the power fails mid-update. Then go back to the chip and the energy budget at the top, and explain why the best model changes when you move the line.