Try Embedded

TinyML: machine learning on MCUs

Quantised models, TensorFlow Lite Micro and fitting the budget.

Machine learning on a microcontroller

TinyML means running trained machine-learning models on microcontrollers: milliwatts of power, hundreds of kilobytes of memory, no operating system. The model is trained on a PC or in the cloud, then compressed and compiled to run on the device. Typical applications:

ApplicationInputModel
Keyword spotting ("Hey device")Microphone, MFCC featuresSmall CNN or depthwise-separable CNN
Gesture or activity recognitionAccelerometer windowsSmall CNN or fully connected network
Anomaly detection, predictive maintenanceVibration spectraAutoencoder, or classical models
Person or object detectionLow-resolution cameraMobileNet-style CNN
Sensor calibration and virtual sensorsSeveral sensorsSmall regression network

Running inference on the device avoids sending raw data to the cloud: lower latency, lower radio energy (the dominant cost in many products), privacy, and it works offline.

The workflow

  1. Collect and label data from the real sensor on the real device, in realistic conditions.
  2. Extract features (often the same code on PC and device): FFT or MFCC for audio, statistics or spectra over windows for motion.
  3. Train a small model (TensorFlow/Keras, PyTorch), keeping the target's limits in mind.
  4. Quantise to 8-bit integers.
  5. Convert and deploy: TensorFlow Lite for Microcontrollers (LiteRT for Microcontrollers), vendor tools (STM32Cube.AI, NXP eIQ, Edge Impulse) generate C code or a flatbuffer plus a small interpreter.
  6. Validate on the device: accuracy with real data, inference time, RAM peak, flash size and energy per inference.

Quantisation

Models are trained in 32-bit float. Converting weights and activations to int8 makes the model about 4× smaller and lets integer SIMD instructions run it many times faster, usually with a small accuracy loss. Each tensor gets a scale and zero point:

real_value = scale × (int8_value − zero_point)

This is the fixed-point arithmetic from the fixed-point lesson, applied systematically. Quantisation-aware training simulates int8 during training to recover most of the lost accuracy.

#include <stdio.h>
#include <stdint.h>

/* A tiny int8 fully connected layer with ReLU: the core operation of most TinyML models. */
#define IN 4
#define OUT 2

int main(void) {
  /* Quantised input, weights and bias (as a converter would produce). */
  const int8_t x[IN] = { 12, -40, 85, 7 };
  const int8_t w[OUT][IN] = { { 30, -12, 25, 4 }, { -20, 18, 9, -33 } };
  const int32_t bias[OUT] = { 150, -80 };
  const float in_scale = 0.05f, w_scale = 0.01f, out_scale = 0.1f;

  for (int o = 0; o < OUT; o++) {
    int32_t acc = bias[o];                         /* 32-bit accumulator: int8 x int8 products add up */
    for (int i = 0; i < IN; i++) acc += (int32_t)x[i] * w[o][i];
    /* Requantise: real = acc * in_scale * w_scale, output int8 = real / out_scale (real kernels use an
       integer multiplier and shift instead of float). */
    float real = (float)acc * in_scale * w_scale;
    int32_t q = (int32_t)(real / out_scale + (real >= 0 ? 0.5f : -0.5f));
    if (q < 0) q = 0;                              /* ReLU */
    if (q > 127) q = 127;                          /* saturate to int8 */
    printf("output %d: accumulator %d, real %.3f, int8 %d\n", o, acc, real, q);
  }
  return 0;
}

CMSIS-NN implements these kernels with Cortex-M SIMD instructions; Cortex-M55 and M85 add the Helium vector extension, and some MCUs include a neural processing unit (Arm Ethos-U, vendor NPUs) for further speed-ups.

Fitting the budget

ResourceTypical MCU budgetWhat uses it
Flash100 KB to 1 MB for the modelWeights (one byte each after int8 quantisation) and the inference code
RAM20 KB to 300 KBThe tensor arena: activations of the largest layers alive at once, plus input buffers
TimeMilliseconds per inferenceMultiply-accumulates: a keyword-spotting model needs a few million per second of audio
EnergyMicrojoules per inferenceTime × active current; fewer, cheaper inferences save battery

Techniques: smaller architectures (depthwise-separable convolutions), pruning, fewer input features, lower input resolution or sample rate, running inference only when a cheap trigger fires (a sound-level threshold, motion), and duty cycling.

Classical alternatives

Not every problem needs a neural network. A threshold, a few hand-crafted features with a decision tree, or a simple logistic regression often achieve similar accuracy with far less code and energy, and are easier to explain and verify. Start simple, and use a neural network when the simple approach is not good enough.

Pitfall: A model trained on data from a lab or a different sensor often fails in the field. Collect training data on the product's own hardware, mounting and environment, and keep a held-out test set from real conditions.

Interview question: How would you add keyword spotting to a battery-powered device?

Answer: Collect labelled audio of the keyword and background from the product's own microphone. Compute features such as MFCCs over short frames on device and in training with identical code, train a small depthwise-separable CNN, quantise it to int8 with quantisation-aware training, and deploy with TensorFlow Lite Micro or a vendor tool using CMSIS-NN kernels. On the device, stream audio by I2S or PDM with DMA, compute features incrementally, and run inference on a sliding window. To save power, gate inference with a cheap voice-activity or sound-level detector, and measure RAM peak, latency, false accept and reject rates, and energy per hour in real conditions.

Build it: run the gesture model in integers

This is step 1 of the module project, a gesture remote for a TV: flick your wrist left or right to change channel, draw a circle to open the menu. A small neural network trained on recorded gestures decides which one it was, from features of the accelerometer signal (step 2). The microcontroller has no FPU and 32 KB of RAM, so the model is quantised to int8 and its layers run in integer arithmetic only, exactly the way the converter specified. One mistake in the requantisation, and the remote switches channel when the viewer reaches for a drink.

Lab: An int8 dense layer, requantised in integers, and a confident answer

Each tensor's int8 values mean real = scale × (q − zero_point). The weights are symmetric (zero point 0); the bias is already in the accumulator's scale.

  • requant(acc, mult, shift, out_zp) turns a 32-bit accumulator into an int8 output: out_zp + round(acc × mult / 2^shift), computed as (acc × mult + 2^(shift−1)) >> shift in 64 bits (an arithmetic shift, so negative values round correctly too), then saturated to −128 … 127. mult / 2^shift is the converter's integer form of in_scale × w_scale / out_scale.
  • dense(x, x_zp, w, bias, in, out, mult, shift, out_zp, relu, y) computes each output o: acc = bias[o] + Σ (x[i] − x_zp) × w[o × in + i], then y[o] = requant(...). With relu set, an output below out_zp becomes out_zp: in the quantised world, real 0 is the zero point, not the int8 value 0.
  • gesture(scores, n, min_score) returns the index of the highest score, or -1 (no gesture) when that score is below min_score. At equal scores the lower index wins.

Going deeper

Interview question: How would you deploy a vibration anomaly model on a factory sensor's microcontroller?

Answer: Train on the PC with data from healthy and faulty machines, quantise the model to 8-bit, and convert it for the MCU (TensorFlow Lite Micro or a vendor tool), checking accuracy after quantisation. Measure RAM, flash and inference time on the target, run inference on features rather than raw data, and plan how models are updated over the air.

Interview question: What is the tensor arena in TensorFlow Lite for Microcontrollers?

Answer: A single statically allocated block of RAM that the interpreter uses for all intermediate tensors (activations) and scratch buffers, so there is no dynamic allocation. Its size is set by the application; the interpreter plans which tensors can share memory because they are not alive at the same time, and reports the actual size needed. Its peak is determined by the largest layers' inputs and outputs that coexist, which is why reducing activation sizes reduces RAM use.

Explain it: In your own words, explain why running inference on the device can save energy compared with sending data to the cloud.

Answer: In many battery-powered products the radio is the biggest energy consumer: transmitting raw sensor data such as audio or vibration continuously costs far more energy than computing on the microcontroller. Running a small quantised model locally means the device only needs to transmit a rare result, such as a detected keyword or an anomaly flag, so the radio stays off most of the time. It also cuts latency and keeps raw data private, at the cost of fitting the model into the device's limited memory and compute.