Edge AI Deployment
A model that must fit in two gigabytes, run cold, and keep the battery meter from draining in real time.
EdgePrerequisites
- !Quantization and model compression basics
- !Mobile or embedded memory constraints
- !Over-the-air update pipelines
What You'll Learn
- 1Justify on-device inference against cloud alternatives per workload
- 2Match quantization format to target accelerator
- 3Choose a runtime based on operator coverage rather than benchmark hype
- 4Design fallback paths so a bad model update cannot brick a feature
Why inference moves to the device
Three reasons send inference to the edge, and they have different engineering consequences. Latency: a voice assistant that round-trips to a data center feels sluggish for anything interactive, while on-device inference starts the moment the user speaks. Privacy: health, keyboard and camera data increasingly cannot leave the device at all, by policy or by law. Availability: an industrial inspector or a field technician works where connectivity is intermittent or absent.
Each reason changes the constraint set. Latency-critical work needs small models with predictable worst-case timing, not good average throughput. Privacy-critical work needs the guarantee that no code path sends data out, which is an architecture decision rather than a model choice. Offline-critical work needs the full feature set on-device with no cloud escape hatch.
The trade is capability. A phone cannot host what a data center hosts, so edge deployments involve accepting a smaller model and designing the product around it. Hybrid designs — on-device for the fast path, cloud for the hard cases — are the pragmatic middle, provided the fallback is explicit and measured rather than an implicit degradation nobody monitors.
Quantization formats and accelerators
The format you export in determines which accelerator you can use. INT8 is broadly supported across NPUs, mobile GPUs and CPU runtimes. Four-bit weight-only formats squeeze memory hardest and work well for decode-bound language models, but often fall back to slower paths when the runtime lacks a fused kernel. Mixed precision — quantized weights with higher-precision activations — buys accuracy back where it matters most.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
def export_quantized(model_name, out_dir, bits=4):
"""Load, quantize and export a causal LM for on-device use."""
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16)
if bits == 4:
from transformers import BitsAndBytesConfig
model = AutoModelForCausalLM.from_pretrained(
model_name,
quantization_config=BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16,
),
)
elif bits == 8:
model = AutoModelForCausalLM.from_pretrained(model_name, load_in_8bit=True)
model.save_pretrained(out_dir)
tokenizer.save_pretrained(out_dir)
size_mb = sum(
p.numel() * p.element_size() for p in model.parameters()
) / (1024 * 1024)
print(f"exported {bits}-bit model, weights approximately {size_mb:.0f} MB")
return out_dir
Always validate the exported artifact on the target device rather than on your workstation. Operator coverage differs between platforms, and a graph that runs flawlessly on a desktop GPU may silently fall back to a CPU path on a phone — correct numerically, far too slow to ship.
Choosing a runtime
Runtimes differ in operator support, cold-start time and how much of the quantization scheme they actually accelerate. The benchmark that matters is the one measured on the device your users hold.
| Runtime | Strengths | Best for |
|---|---|---|
| llama.cpp | Broad format support, CPU efficiency | Language models on consumer hardware |
| ONNX Runtime | Mobile delegates, mature tooling | Mixed operator graphs |
| TensorFlow Lite | NNAPI and GPU delegates | Vision and classic mobile workloads |
| Core ML | Deep Apple silicon integration | iOS deployment |
| MediaPipe | Pipeline-focused, low latency | Streaming perception tasks |
from llama_cpp import Llama
def warm_and_bench(model_path, prompts, ctx=2048):
"""Load once, then measure cold and steady-state token rates."""
import time
start = time.time()
llm = Llama(model_path=model_path, n_ctx=ctx, n_threads=4)
cold_load = time.time() - start
start = time.time()
first = llm.create_completion(prompts[0], max_tokens=64)
first_token_time = time.time() - start
start = time.time()
total_tokens = 0
for prompt in prompts:
out = llm.create_completion(prompt, max_tokens=64)
total_tokens += out["usage"]["completion_tokens"]
steady = time.time() - start
return {
"cold_load_s": round(cold_load, 2),
"first_run_s": round(first_token_time, 2),
"tokens_per_s": round(total_tokens / steady, 2),
}
Treat cold load as a first-class metric. A model that generates at thirty tokens per second but takes eight seconds to load is unusable for a launch-from-lock-screen feature; the user has moved on before the first token appears.
Picking the model size the device can carry
Model selection on the edge is a budgeting exercise before it is a quality exercise. Start from the tightest constraint — usually peak memory on the oldest supported device — and work outward to the largest architecture that fits it with headroom for activations and the key-value cache, not just weights.
| Device class | Typical usable RAM for a model | Practical parameter range | Expectation |
|---|---|---|---|
| Low-end phone | 400–700 MB | 0.5–1.5B quantized | Short local tasks only |
| Mid-range phone | 800–1500 MB | 1.5–4B quantized | Quality single-turn features |
| Flagship phone | 1.5–3 GB | 4–8B quantized | Strong local assistant |
| Embedded/industrial | 512 MB–2 GB | 0.5–3B | Domain-specific models |
Parameter count is only half the arithmetic. Context length multiplies cache memory, batch size multiplies it again, and a model that fits at a 512-token context can exhaust memory at 4096 without changing weights at all. Fix the context budget alongside the model choice and test the worst case, not the demo case.
Equally important is knowing what capability you are giving up. A two-billion-parameter model will decline to summarize a long contract gracefully on-device; deciding whether that task moves to the cloud, gets a smaller specialized model, or leaves the feature set entirely is a product decision that should be made before architecture work begins rather than during integration testing.
Memory, heat and battery
Peak memory is a hard wall — exceeding it kills the process — while sustained speed is limited by thermals that ramp over minutes. Both need explicit budgets written down before model selection, not discovered during integration.
edge_budget:
peak_memory_mb: 1800
sustained_memory_mb: 1200
cold_load_ms: 3000
first_token_ms: 800
tokens_per_second_min: 12
battery_per_session_percent_max: 2
thermal_throttle_after_s: 90
Measure battery per interaction rather than inferring it from runtime. A model that streams tokens steadily for a minute can cost several percent of a phone's battery, which users correctly attribute to your app. Budgeting battery alongside latency makes that trade visible before release rather than in store reviews.
Shipping updates safely
An edge model ships inside the app or as a downloaded artifact, and either way a bad release reaches every device before you can intervene. The update design must assume failure: staged rollouts, a remote kill switch, and the ability to keep the previous model cached so a rollback does not require a redownload.
class EdgeModelManager:
"""Fetch, verify and roll back on-device model artifacts."""
def __init__(self, store, verifier, rollout_client):
self.store = store
self.verifier = verifier
self.rollout = rollout_client
def sync(self, current_version):
plan = self.rollout.plan(current_version)
if plan["action"] == "keep":
return {"action": "keep", "version": current_version}
artifact = self.rollout.download(plan["version"])
if not self.verifier.checksum_ok(artifact):
self.rollout.report_failure(plan["version"], "checksum")
return {"action": "rollback", "version": current_version}
metrics = self.verifier.benchmark(artifact)
if not self.verifier.meets_slo(metrics):
self.rollout.report_failure(plan["version"], "slo")
return {"action": "rollback", "version": current_version}
self.store.activate(artifact, plan["version"])
return {"action": "upgraded", "version": plan["version"], "metrics": metrics}
def emergency_revert(self, bad_version):
previous = self.store.previous_good(bad_version)
self.store.activate(previous["artifact"], previous["version"])
self.rollout.block(bad_version)
return previous["version"]
Benchmarking the artifact on-device before activation is the step most teams skip. Checksums catch corruption; they do not catch a model that loads cleanly and then runs four times slower on the hardware profile it was exported for.
On-device evaluation and fallback
You cannot pull telemetry with private inputs, so evaluation must run where the data lives. Differential privacy or aggregated local metrics let you learn whether a new model helped without exporting user content. Sample-based evaluation on synthetic or consented inputs covers the cases where even aggregated metrics are unavailable.
def local_eval(model, eval_cases, slo):
"""Score a candidate model against device-level acceptance criteria."""
results = {"cases": len(eval_cases), "passed": 0, "p95_ms": 0.0}
latencies = []
for prompt, checker in eval_cases:
start = time.time()
output = model.generate(prompt, max_tokens=64)
latencies.append((time.time() - start) * 1000)
if checker(output):
results["passed"] += 1
latencies.sort()
results["p95_ms"] = round(latencies[int(0.95 * len(latencies)) - 1], 1)
results["pass"] = (
results["passed"] / results["cases"] >= slo["accuracy_min"]
and results["p95_ms"] <= slo["p95_ms_max"]
)
return results
Design the fallback before the feature. When confidence is low or the device is too slow, the product should do something defined — fall back to a smaller on-device model, ask the server, or degrade to a non-AI path — and that path should be measured. An edge feature with no fallback is one thermal throttle away from a crash report.
⚠️Benchmark on the slowest device you support
Desktop benchmarks predict almost nothing about the phone in your user's pocket. Test on the oldest device in your support matrix, at low battery, with the thermal state you will actually ship into.
Common Mistakes
Exporting a quantized model without verifying accelerator support on-device
Fix: Benchmark the exported artifact on target hardware — silent CPU fallback is correct but far too slow.
Optimizing tokens per second while ignoring cold load time
Fix: Budget load latency explicitly; users abandon interactive features before the first token appears.
Shipping model updates with no rollback path
Fix: Keep the previous artifact cached, gate rollouts by stage, and support remote reversion.
Skipping battery measurement because latency looks fine
Fix: Measure battery per interaction and cap it in the release checklist alongside performance SLOs.
Best Practices
- Write memory, latency and battery budgets before choosing a model
- Match quantization format to the accelerator the target device actually exposes
- Treat cold load and first-token time as first-class metrics
- Verify artifacts on-device before activation, not just with checksums
- Design and measure an explicit fallback for every on-device AI feature
Key Takeaways
- Edge inference buys latency, privacy and offline capability at the cost of model capacity
- Quantization format determines which accelerator you can use — verify on the target device
- Runtime choice should follow operator coverage, and cold load deserves its own metric
- Updates need staged rollouts, checksums, on-device benchmarks and a rollback path
- Every edge AI feature needs a defined, measured fallback when the model cannot deliver