跳到正文
DEV Community· mp3sss·· 1 小時前AI 評分55

感測器數據的邊緣推理:如何選擇執行時並縮小模型

Edge Inference for Sensor Data: Choosing a Runtime and Shrinking the Model

AI 導讀

這篇指南説明如何為感測器數據邊緣推理選擇執行時、縮小模型並驗證部署。例如,裸機 MCU 上參數少於 100k 的模型可選 TFLite Micro,Linux ARM64 閘道上小於 50 MB 的模型則可選 ONNX Runtime。模型縮小依次採用 int8 量化、結構化剪枝和知識蒸餾,並在目標硬件負載下檢查警報率漂移及 p99 延遲。

正文

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.

Start from a budget, not from a framework

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:

  • Model footprint ceiling: 256 KB − 96 KB = 160 KB of RAM, and you want the model weights in flash, not RAM.
  • Compute ceiling: 10 ms at 480 MHz with no FPU is roughly 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 2–4 MMACs per inference.

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 comparison

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:

  • Bare-metal MCU, model < 100k params, fixed shapes → TFLite Micro.
  • Linux gateway (ARM64), model < 50 MB → ONNX Runtime.
  • Hard real-time with a fixed, simple model (e.g., a 3-layer MLP or a single conv layer) → hand-written C, because predictable timing beats cleverness in a control path.
  • Fleet with mixed silicon → stick to one framework and accept suboptimal performance on some devices; portable ops beats peak throughput.

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.

Shrinking: quantize first, prune second, distill third

Do these in order. Each step is cheaper than the next, and later steps are much easier once quantization has made the model small.

1. Post-training int8 quantization

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

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:

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.

2. Structured pruning

Unstructured pruning gives sparse weights that integer kernels cannot exploit. Prune whole filters or channels instead:

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.

3. Distillation, if you still do not fit

Train the small model to match the large model's outputs on unlabeled field data:

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.

Reading the deployment report

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:

  • arena / RAM budget ratio — if the tensor arena exceeds 60% of your free RAM, one added layer will break the build.
  • p99 latency vs. deadline — measure on the device under realistic load (TLS handshakes, flash writes), not on an idle board. TLS alone can stall a single-core MCU for tens of milliseconds.

Do not forget the parts that are not the model

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:

  1. Use fixed-point normalization with a precomputed scale, if the sensor range is known.
  2. Use int8-friendly scaling — store (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.

The checklist I actually use

Before a model ships to an edge fleet, I want these answers in the PR description:

  • [ ] Peak RAM (tensor arena + buffers) ≤ 60% of free RAM after RTOS/network stack
  • [ ] p99 inference latency ≤ 50% of the decision deadline, measured on target hardware under load
  • [ ] int8 alarm-rate drift ≤ 10% relative to float on a holdout set covering the full operating range
  • [ ] Model version string compiled into the firmware and included in every alert payload
  • [ ] Raw-data ring buffer sized for at least 2× the model window
  • [ ] A documented rollback path that does not require physical access

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.

來源:DEV Community · dev.to