Edge Inference for Sensor Data: Choosing a Runtime and Shrinking the Model A developer outlined a practical workflow for deploying sensor-data inference on constrained edge hardware, starting with a written resource budget (single-core 480 MHz CPU, 160 KB usable RAM, a ~4 MMAC compute ceiling) and a runtime comparison covering TFLite Micro, ONNX Runtime, hand-written C, and vendor NPU SDKs. The approach prioritizes int8 quantization with a representative calibration dataset spanning the full operating range, then verifies drift using alarm rate rather than AUROC, since a model that preserves AUC but doubles its alarm rate will overwhelm operators. Once you have decided that inference belongs on the device or the gateway, the next question is boringly practical: what do I run it with, and how small does the model need to be? This post walks through the runtime choice, the shrinking process, and the verification steps that keep you from shipping a model that is fast in the lab and wrong in the field. Every edge inference decision starts with a budget. Write it down before you open a notebook: CPU : single core, 480 MHz, no FPU, no SIMD RAM : 256 KB total, 96 KB already used by RTOS + MQTT + TLS Flash : 1 MB, 512 KB used Sample rate: 100 Hz per channel, 3 channels Deadline : decision within 200 ms → max 10 ms of compute per window Window : 512 samples per channel 5.12 s at 100 Hz Two numbers fall out of this immediately: 256 KB − 96 KB = 160 KB of RAM, and you want the model weights in flash, not RAM. 4.8 M cycles . A quantized model can do maybe 1–2 MACs per cycle in a tight int8 kernel, so the ceiling is on the order of A 4 MMAC budget is small. It rules out almost every unmodified CNN with a few million parameters. It does not rule out useful models — a 1D CNN with 20k parameters over a 512-sample window is often 1–2 MMACs — but it does mean you will be designing for the budget rather than discovering it late. | Runtime | Best for | Strengths | Costs | |---|---|---|---| | TFLite Micro | MCUs with ≤ 512 KB flash | Tiny footprint, int8 kernels, well-tested on Cortex-M | C++ API, limited op set, painful to debug | | ONNX Runtime mobile | Linux gateways, ARM64 SBCs | Broad op coverage, easy converter path | ~2–10 MB binary, not viable on bare-metal MCUs | | Hand-written C | Fixed-shape tiny models | Zero dependencies, fully predictable timing | You write the kernels; no autodiff safety net | | Vendor NPU SDK | Chips with a DSP/NPU | Fastest per watt | Lock-in, poor portability across a fleet | The decision rule I use: A common mistake is picking the framework by benchmark speed on a single board. Timing predictability, debuggability, and update tooling matter more once you have 5,000 devices in the field. Do these in order. Each step is cheaper than the next, and later steps are much easier once quantization has made the model small. This is almost always the highest return. Converting float32 to int8 cuts weight size by 4× and, on integer-only hardware, speeds up matmul by 2–4×. python import numpy as np import tensorflow as tf def representative dataset : 300 windows of real or realistically simulated sensor data for x in calibration windows: shape: 300, 512, 3 yield x np.newaxis, ... .astype np.float32 converter = tf.lite.TFLiteConverter.from saved model "model float" converter.optimizations = tf.lite.Optimize.DEFAULT converter.representative dataset = representative dataset converter.target spec.supported ops = tf.lite.OpsSet.TFLITE BUILTINS INT8 converter.inference input type = tf.int8 converter.inference output type = tf.int8 tflite int8 = converter.convert open "model int8.tflite", "wb" .write tflite int8 The critical detail is calibration windows . Quantization error is data-dependent : calibrate on data that covers the operating range, not on a clean lab recording. If your model sees 0–50 °C in production, calibrating on 20–25 °C data will produce systematic error at the edges of the range. Verify quantization drift with the metric that matters , not with accuracy on a balanced dataset: python def alarm rate model, windows, threshold : preds = model.predict windows return preds threshold .mean f32 rate = alarm rate model float, holdout, T i8 rate = alarm rate model int8, holdout, T print f"alarm rate float={f32 rate:.4f} int8={i8 rate:.4f}" For alerting, a shift in alarm rate matters more than a shift in AUROC. A model that keeps its AUC but doubles its alarm rate will bury your operators — that is the failure mode that gets ML systems switched off. Unstructured pruning gives sparse weights that integer kernels cannot exploit. Prune whole filters or channels instead: python import tensorflow model optimization as tfmot prune low magnitude = tfmot.sparsity.keras.prune low magnitude model for pruning = prune low magnitude model, pruning schedule=tfmot.sparsity.keras.PolynomialDecay initial sparsity=0.10, final sparsity=0.60, begin step=0, end step=2000 , block size= 1, 1, 4 , group-of-4 granularity: maps to int8 SIMD lanes model for pruning.compile optimizer="adam", loss="binary crossentropy", metrics= "accuracy" model for pruning.fit train x, train y, epochs=8, validation data= val x, val y stripped = tfmot.sparsity.keras.strip pruning model for pruning block size= 1, 1, 4 matters on hardware with 4-lane int8 SIMD: pruning in groups of four keeps the dense kernel layout and lets the runtime skip whole groups. Unstructured 60% sparsity often runs slower than dense on such hardware. Re-check the alarm-rate drift after pruning. Pruning is not free, and the accuracy loss is usually not uniform across the input space — it often hurts exactly the rare high-magnitude signals that your alarms depend on. Train the small model to match the large model's outputs on unlabeled field data: python def distill loss student logits, teacher logits, temperature=3.0 : p = tf.nn.softmax teacher logits / temperature q = tf.nn.log softmax student logits / temperature return -tf.reduce mean tf.reduce sum p q, axis=-1 temperature 2 Distillation is the step that actually buys accuracy at tiny sizes, because unlabeled field data is abundant and labels are not. You are transferring the teacher's decision boundary rather than relearning it from sparse labels. After conversion, always print a deployment report and commit it next to the model. This becomes your regression baseline: interpreter = tf.lite.Interpreter model path="model int8.tflite" interpreter.allocate tensors detail = interpreter.get tensor details arena = interpreter. get arena usage if hasattr interpreter, " get arena usage" else None print "tensors:", len detail print "arena bytes:", arena Latency on the target, not on your laptop import time inp = interpreter.get input details 0 x = np.zeros inp "shape" , dtype=inp "dtype" interpreter.set tensor inp "index" , x interpreter.invoke warm up t0 = time.perf counter for in range 200 : interpreter.set tensor inp "index" , x interpreter.invoke print "mean latency ms:", time.perf counter - t0 / 200 1000 Two derived numbers are worth tracking in CI: On a real device, the model is often not the bottleneck. The surrounding pipeline usually is: // Pseudocode for the hot path. Note where time actually goes. while 1 { read adc &buf n , 3 ; // DMA, ~free if ++n == WINDOW { normalize i8 buf, WINDOW, 3 ; // often 10-20% of budget tflm invoke &model, buf ; // the model uint8 t score = buf out 0 ; // int8 → 0..255 rule engine feed score, &ctx ; // hysteresis + hold-down n = 0; } os delay until &last, 10 ; // 100 Hz } Normalization is the sneaky one. Computing mean and standard deviation in float on a Cortex-M0+ with no FPU can cost more than the inference. Two fixes that work: x - offset scale as an integer affine transform, so normalization is a multiply-shift per sample. Also budget for the TLS handshake : if the device publishes only on state change, its connection may be idle for hours, which means every alarm triggers a fresh handshake. Either keep the connection warm or measure the handshake separately from the inference — otherwise you will blame the model for a 300 ms network stall. Before a model ships to an edge fleet, I want these answers in the PR description: That last item is not a modelling concern, but it is the one that decides whether you can afford to update models at all — which is the subject of a later post in this series. Next: Feature Engineering for Sensor Telemetry — Windowing, Rolling Stats, and the Leaks That Fool You.