Edge, Mobile and Browser Deployment
So far the model has lived on a server and the client has sent it data. Edge deployment turns this around: the model ships to the data, onto a phone, a browser tab, a camera, a car or a microcontroller in a sensor. The reasons are compelling: no network round trip (latency in milliseconds), it works offline, raw data (camera frames, voice, health data) never leaves the device, and the provider pays for no inference servers. The costs are just as real: a device has a fraction of a server's memory and compute, runs on a battery that heats up, comes in hundreds of hardware variants, and is hard to update. This lesson is about fitting a model into those budgets and keeping it up to date.
The constraints
- Memory and storage. The weights must fit in the app's download budget and in RAM next to everything else the device runs. A microcontroller may have 256 KB to 2 MB of flash and less RAM; a browser user waits for every megabyte; app stores and users punish large apps.
- Compute and latency. A phone sustains a fraction of a server's compute (few cores, a few watts of power budget); a real-time camera feature has 33 ms per frame at 30 frames/s, for everything.
- Power and heat. Energy per inference sets battery life, and sustained load throttles the chip after a minute or two, so a benchmark on a cold phone is optimistic.
- Offline and privacy. The feature must degrade gracefully without a network, and on-device processing is often the reason for doing it at all (data stays local, which helps with regulation too).
- Heterogeneity. CPUs, GPUs and NPUs (neural processing units) from many vendors, each runtime supporting a different subset of operators and data types.
Formats and runtimes
A server can run any Python framework. A device runs a small, compiled runtime that executes a model in its own format:
| Target | Format and runtime | Notes |
|---|---|---|
| Android, embedded Linux, microcontrollers | TensorFlow Lite, renamed LiteRT (.tflite) |
delegates hand parts of the graph to GPU or NPU; TFLite Micro for microcontrollers |
| iOS, macOS | Core ML (.mlpackage), converted with coremltools |
runs on CPU, GPU or the Apple Neural Engine, chosen by the system |
| Cross-platform mobile | ONNX Runtime Mobile | an ONNX Runtime build with only the operators your models use; execution providers for NNAPI, Core ML, QNN |
| Browser | ONNX Runtime Web, TensorFlow.js | WebAssembly on the CPU, WebGPU on the GPU; WebNN emerging |
| PyTorch models | ExecuTorch | PyTorch's on-device runtime, models exported with torch.export |
The general rule from the ONNX lesson applies with more force on the edge: a conversion that "works" must be checked for numerical agreement with the original on real inputs, and every operator in the graph must be supported by the target runtime and accelerator, or that part silently falls back to the slow CPU path.
Size budgets
The size of the weights is parameters times bytes per parameter, which is why quantization is close to mandatory on the edge. Approximate parameter counts of some well-known architectures against four budgets:
models = { # parameter counts (approximate, published architectures)
"keyword spotter (small CNN)": 0.08e6,
"MobileNetV2 image classifier": 3.5e6,
"YOLOv8n object detector": 3.2e6,
"DistilBERT text encoder": 66e6,
"7B language model": 7e9,
}
bytes_per = {"fp32": 4, "fp16": 2, "int8": 1, "int4": 0.5}
budgets_mb = {"microcontroller (1 MB flash)": 1, "web page (10 MB)": 10, "mobile app (50 MB)": 50, "laptop (4 GB)": 4000}
print(f"{'model':30s}" + "".join(f"{k:>9s}" for k in bytes_per) + " (MB of weights)")
for name, n in models.items():
print(f"{name:30s}" + "".join(f"{n * b / 1e6:9.2f}" for b in bytes_per.values()))
print()
for budget, mb in budgets_mb.items():
fits = []
for name, n in models.items():
ok = [fmt for fmt, b in bytes_per.items() if n * b / 1e6 <= mb]
if ok:
fits.append(f"{name.split(' (')[0]} ({ok[0]})")
print(f"{budget:28s}: " + (", ".join(fits) if fits else "nothing"))model fp32 fp16 int8 int4 (MB of weights)
keyword spotter (small CNN) 0.32 0.16 0.08 0.04
MobileNetV2 image classifier 14.00 7.00 3.50 1.75
YOLOv8n object detector 12.80 6.40 3.20 1.60
DistilBERT text encoder 264.00 132.00 66.00 33.00
7B language model 28000.00 14000.00 7000.00 3500.00
microcontroller (1 MB flash): keyword spotter (fp32)
web page (10 MB) : keyword spotter (fp32), MobileNetV2 image classifier (fp16), YOLOv8n object detector (fp16)
mobile app (50 MB) : keyword spotter (fp32), MobileNetV2 image classifier (fp32), YOLOv8n object detector (fp32), DistilBERT text encoder (int4)
laptop (4 GB) : keyword spotter (fp32), MobileNetV2 image classifier (fp32), YOLOv8n object detector (fp32), DistilBERT text encoder (fp32), 7B language model (int4)
The table is simple multiplication, and it explains most edge design decisions. A MobileNet-class image classifier (3.5 million parameters) is 14.0 MB in float32 and 3.5 MB in int8, which fits a web page; DistilBERT needs 4-bit weights (33.0 MB) to fit a 50 MB app budget; a 7-billion-parameter language model needs 3,500 MB even at 4 bits, which only a laptop-class device holds. Only the tiny keyword spotter fits a microcontroller. In practice you also budget for activations (often larger than the weights for image models at high resolution), the runtime itself (a few MB, less for a reduced build) and the rest of the app.
Latency and energy budgets
Compute per inference is about 2 floating-point operations per multiply-add. Devices reach an effective throughput well below their datasheet peak, so the numbers below are assumptions for illustration; measure your own model on your own devices, after a warm-up, and under sustained load.
# Latency and energy for one inference. Throughputs are assumed *effective* numbers (what a real
# runtime reaches on such a model), not datasheet peaks; measure your own device.
layers = [(64, 256), (256, 128), (128, 10)] # the digits MLP of the quantization lesson
mlp_flop = sum(2 * a * b for a, b in layers)
workloads = {"digits MLP": mlp_flop, "MobileNetV2, 224x224 image": 2 * 300e6} # 300 M multiply-adds
devices = { # (effective GFLOP/s, watts while busy)
"microcontroller": (0.05, 0.05),
"phone CPU (1 core)": (10, 1.5),
"phone NPU (int8)": (200, 1.0),
"browser, WebAssembly": (5, 5),
}
print(f"digits MLP: {mlp_flop / 1e3:.0f} kFLOP per input")
for wname, flop in workloads.items():
print(f"\n{wname}:")
for dname, (gflops, watts) in devices.items():
t = flop / (gflops * 1e9)
print(f" {dname:22s} {t * 1e3:10.3f} ms {watts * t * 1e3:9.4f} mJ "
f"{'meets' if t <= 1 / 30 else 'misses'} 30 frames/s")
battery_wh = 15
per_inf_j = 1.0 * 2 * 300e6 / 200e9 # NPU, MobileNetV2
print(f"\n{battery_wh} Wh battery = {battery_wh * 3600:.0f} J: one MobileNetV2 inference on the NPU uses "
f"{per_inf_j * 1e3:.1f} mJ, 30 frames/s for an hour uses {per_inf_j * 30 * 3600 / (battery_wh * 3600):.1%} of it")digits MLP: 101 kFLOP per input
digits MLP:
microcontroller 2.017 ms 0.1009 mJ meets 30 frames/s
phone CPU (1 core) 0.010 ms 0.0151 mJ meets 30 frames/s
phone NPU (int8) 0.001 ms 0.0005 mJ meets 30 frames/s
browser, WebAssembly 0.020 ms 0.1009 mJ meets 30 frames/s
MobileNetV2, 224x224 image:
microcontroller 12000.000 ms 600.0000 mJ misses 30 frames/s
phone CPU (1 core) 60.000 ms 90.0000 mJ misses 30 frames/s
phone NPU (int8) 3.000 ms 3.0000 mJ meets 30 frames/s
browser, WebAssembly 120.000 ms 600.0000 mJ misses 30 frames/s
15 Wh battery = 54000 J: one MobileNetV2 inference on the NPU uses 3.0 mJ, 30 frames/s for an hour uses 0.6% of it
The digits MLP from the quantization lesson (101 kFLOP) runs in about 2 ms even on the assumed microcontroller. A MobileNetV2-class model (300 million multiply-adds, from its paper) is another story: 60 ms on one phone CPU core misses a 30 frames/s budget, the browser's WebAssembly path at 120 ms misses it further, and only the NPU with an int8 model (3 ms, 3.0 mJ) leaves room. Energy follows the same pattern: the NPU uses 30 times less energy per inference than the CPU in this example, and an hour of 30 frames/s takes 0.6 % of a 15 Wh phone battery for the model alone. That is why NPUs, and the integer-only quantized models they need, dominate on-device vision.
Will the runtime accept the model?
A reduced runtime build and an NPU accept only certain operators and data types. A recorded example (ONNX 1.23.2, ONNX Runtime 1.31.1, skl2onnx 1.20.0): the course's risk model, a scaler plus logistic regression, and an MLP version of it, converted to ONNX and passed to quantize_dynamic, with the operator inventory of each file.
import logging, os
from collections import Counter
import numpy as np
import onnx
from onnxruntime.quantization import quantize_dynamic, QuantType
from skl2onnx import to_onnx
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X = X.astype(np.float32)
models = {
"risk-lr": make_pipeline(StandardScaler(), LogisticRegression()).fit(X, y),
"risk-mlp": make_pipeline(StandardScaler(), MLPClassifier((256, 256), max_iter=300, random_state=0)).fit(X, y),
}
logging.getLogger().setLevel(logging.ERROR)
for name, model in models.items():
onx = to_onnx(model, X[:1], options={"zipmap": False})
onnx.save(onx, f"{name}.onnx")
paths = [f"{name}.onnx"]
try:
quantize_dynamic(f"{name}.onnx", f"{name}.int8.onnx", weight_type=QuantType.QInt8)
paths.append(f"{name}.int8.onnx")
except ValueError as e:
print(f"{name}: quantize_dynamic refused: {e}")
for path in paths:
g = onnx.load(path).graph
ops = Counter(f"{n.domain or 'ai.onnx'}:{n.op_type}" for n in g.node)
print(f"{path:19s} {os.path.getsize(path) / 1024:7.1f} KiB {dict(sorted(ops.items()))}")risk-lr: quantize_dynamic refused: Failed to find proper ai.onnx domain
risk-lr.onnx 0.6 KiB {'ai.onnx.ml:LinearClassifier': 1, 'ai.onnx.ml:Scaler': 1}
risk-mlp.onnx 268.5 KiB {'ai.onnx.ml:ArrayFeatureExtractor': 1, 'ai.onnx.ml:Scaler': 1, 'ai.onnx:Add': 3, 'ai.onnx:ArgMax': 1, 'ai.onnx:Cast': 2, 'ai.onnx:Concat': 1, 'ai.onnx:MatMul': 3, 'ai.onnx:Relu': 2, 'ai.onnx:Reshape': 1, 'ai.onnx:Sigmoid': 1, 'ai.onnx:Sub': 1}
risk-mlp.int8.onnx 72.1 KiB {'ai.onnx.ml:ArrayFeatureExtractor': 1, 'ai.onnx.ml:Scaler': 1, 'ai.onnx:Add': 3, 'ai.onnx:ArgMax': 1, 'ai.onnx:Cast': 5, 'ai.onnx:Concat': 1, 'ai.onnx:DynamicQuantizeLinear': 3, 'ai.onnx:MatMulInteger': 3, 'ai.onnx:Mul': 6, 'ai.onnx:Relu': 2, 'ai.onnx:Reshape': 1, 'ai.onnx:Sigmoid': 1, 'ai.onnx:Sub': 1}
The logistic-regression pipeline becomes just two operators from the ai.onnx.ml domain, Scaler and LinearClassifier (0.6 KiB), and quantize_dynamic refuses it ("Failed to find proper ai.onnx domain"): ONNX Runtime's quantizer works on standard ai.onnx operators such as MatMul, and at 0.6 KiB there is nothing to gain anyway. The MLP mixes both domains. Quantization shrinks it from 268.5 KiB to 72.1 KiB by replacing each MatMul with DynamicQuantizeLinear, MatMulInteger and Mul, while the ai.onnx.ml operators stay as they are.
Such an inventory is what a reduced ONNX Runtime Mobile build is configured from (its build scripts read the operator list from your model files), and what to check against an accelerator's list of supported operators. Two consequences for edge work: the classical-ML operators of ai.onnx.ml usually run only on the CPU, and dynamic quantization is a CPU technique; NPUs generally want statically quantized int8 models (in ONNX, the QDQ format with QuantizeLinear/DequantizeLinear pairs produced by quantize_static), calibrated as in the quantization lesson.
Updating models on devices
A server model is replaced in minutes. A model on a million phones is not:
- Ship the model separately from the app. Bundle a default model in the app (so the feature works offline from the first start) and download newer versions in the background, on Wi-Fi, with a version check. App-store releases are slow; a model download is not.
- Version for compatibility. A model must match the runtime and operator set of the app version that loads it. Keep a manifest (model version, minimum app/runtime version, checksum) and serve each client the newest compatible model.
- Verify before use. Check the file's hash or signature before loading it, and keep the previous model for an instant local rollback.
- Roll out gradually. Release to a small cohort, compare their on-device metrics with the rest, then expand: the deployment strategies of the next lesson, applied to devices.
- Monitoring without raw data. Collect aggregate metrics (latency percentiles, confidence histograms, fallback rates) rather than inputs, consistent with the privacy promise. Federated learning goes further and trains on the devices, sending only model updates.
Pitfalls
- Benchmarking on a desktop or a cold device. Measure on the slowest supported device, after warm-up, for several minutes (thermal throttling).
- Unsupported operators. One unsupported node can push most of the graph back to the CPU. Check the delegate's or execution provider's report of which nodes it took.
- Preprocessing drift. Image resizing, colour order, normalisation and tokenisation are re-implemented in Swift, Kotlin or JavaScript; small differences change predictions. Test the whole on-device pipeline against the server pipeline on the same inputs.
- Assuming the model is private. Anything on the device can be extracted. Do not ship a model whose weights are a secret, and do not rely on client-side models for security decisions (ML security).
Practice
- A speech model has 25 million parameters. Which precisions fit a 30 MB app budget for the weights?
Answer
float32 100 MB, float16 50 MB, int8 25 MB, int4 12.5 MB: int8 and int4 fit. With the runtime and the rest of the app, int8 is tight; measure the accuracy of int4 before choosing it.
- Using the assumed devices, what is the largest model (in multiply-adds) that one phone CPU core can run within 33 ms?
Answer
10 GFLOP/s x 0.033 s = 330 MFLOP, about 165 million multiply-adds, before preprocessing and the rest of the frame's work.
- Why does the browser row use 5 W in the assumptions, more than the phone CPU?
Answer
It stands for a laptop running WebAssembly on its CPU, whose cores draw more power than a phone core. The point is only that energy per inference = power x time; measure real devices.
Test yourself
How large are the weights of a 3.5-million-parameter model in int8?
- 3.5 MB
- 14 MB
- 1.75 MB
- 28 MB
Which is NOT a usual reason to run a model on the device instead of a server?
- Unlimited memory and compute
- No network round trip
- Works offline
- Raw data stays on the device
What is a safe way to update a model on millions of phones?
- Download versioned, checksummed models compatible with the app's runtime, keep the previous one, roll out to a small cohort first
- Replace the model inside the app binary at every release only
- Load the newest model from any URL at every start
- Ask users to retrain it
In the assumed numbers, why does only the NPU meet 30 frames/s for MobileNetV2?
- Its effective int8 throughput (200 GFLOP/s) gives 3 ms per inference, while the CPU core needs 60 ms
- NPUs use float64
- The CPU cannot run convolutions
- The NPU skips half of the layers