Shipping Edge LLMs
Close models, heterogeneous hardware, MCU/host boundaries, and operational evidence into a shippable system
Suggested reading: about 20 min
Learning goal
Chapter keywords
| Keyword | Explanation | ESP32 engineering analogy |
|---|---|---|
| Safety boundary | Permission and range constraints that a deterministic component must enforce. | Like hardware interlocks and a state machine before a GPIO or motor driver. |
| Delegate | An interface that compiles and runs a partitioned subgraph on a CPU, GPU, NPU, or other backend. | Like handing supported work to a peripheral while still matching entry format, DMA ownership, and synchronization. |
| Peak RSS | The maximum resident physical memory reached by a process during measurement, exposing load or prefill peaks. | Record the heap high-water mark, not merely firmware image size. |
| Explicit fallback | Moving to another backend or the cloud only under defined permission, privacy, deadline, and failure policy. | Enter an accepted backup state machine after a primary link failure instead of retrying arbitrarily. |
Bridge from the previous chapter
The first fourteen days progressed from neural foundations to LLM structure, runtimes, quantization, frameworks, and cross-scale performance. This chapter compresses everything into a product: who has authority, where every byte and joule goes, how failure remains safe, and how versions ship and roll back.
Historical development
On-device LLMs also arise from two tracks. Chips move from CPU SIMD toward mobile GPUs, DSPs, NPUs, and MCU accelerators. Software moves from lightweight interpreters and graph compilers toward quantized formats, AOT delegates, and complete generation pipelines. Hardware creates possibilities; software determines whether a model ships consistently across devices.
Edge chips and heterogeneous compute
CPU SIMD brings data parallelism into general processors
Vector instructions map quantized dot products, activations, and preprocessing onto wide registers. Current edge CPU backends still rely on layout, thread placement, and cache reuse.
Official Arm SIMD documentation ↗Mobile GPUs and DSPs take on media and machine-learning flows
Programmable shaders, compute APIs, and signal processors offer higher parallelism than CPUs while introducing command submission, buffer domains, and operator-coverage boundaries.
Official Khronos OpenCL registry ↗NPUs make low-precision neural graphs a dedicated execution path
Mobile SoCs add neural engines. Real gains depend on graph coverage, supported shapes and dtypes, and the conversion cost at partition boundaries.
Official Android NNAPI documentation ↗MCU accelerators keep TinyML at milliwatt endpoints
Designs such as Ethos-U target constrained SRAM, low-precision operators, and real-time embedded systems. They suit small models and do not imply that a general LLM belongs on a microcontroller.
Official Arm Ethos-U55 material ↗Generative-AI SoCs strengthen unified memory and heterogeneous cooperation
CPU, GPU, NPU, and shared-memory controllers share a package, reducing some discrete transfers while bandwidth, coherence, power budget, and thermal throttling still bound sustained generation.
MLCommons MLPerf Client benchmark ↗Edge software and model delivery
TensorFlow Lite brings conversion, an interpreter, and delegates to mobile
A lightweight runtime, quantization, and platform delegates establish the core edge pattern: preserve model semantics, partition around hardware capability, and retain a CPU path.
Original TensorFlow Lite paper ↗TVM separates model graphs from hardware schedules
An end-to-end compiler uses intermediate representations, automated or templated scheduling, and multi-target code generation. Portability requires explicit lowering rather than one kernel binary for every device.
Original TVM paper ↗llama.cpp and GGUF lower the barrier to local quantized LLMs
A low-dependency C/C++ runtime, quantization tools, and multiple backends let ordinary PCs, Macs, SBCs, and mobile devices run open-weight models and provide a reproducible experimental entry point.
Official llama.cpp repository ↗MLC LLM and ExecuTorch strengthen AOT, partitioning, and portable delivery
Compiler-generated platform code or PyTorch export with delegated subgraphs brings model optimization closer to application SDKs and device backends.
Original MLC LLM paper ↗LiteRT-LM, MNN, and peers fill out generation pipelines and product APIs
Edge frameworks increasingly package tokenizers, sessions, KV, language bindings, multimodal components, and CPU/GPU/NPU backends as a generation delivery surface instead of executing one static graph only.
Official LiteRT-LM repository ↗Illustrated analogy
Put a hotel kitchen into a food truck
A cloud hotel kitchen can serve many tables with a giant pantry, rows of appliances, and dedicated runners. An edge food truck has finite battery, storage, burners, and cooling. A quantized model package is a standardized compact ingredient case. IR and delegates assign recipe steps to a cutting board, stove, or specialized oven; CPU, GPU, and NPU each suit different work. KV cache is the prep box reserved for the current customer, prefill prepares ingredients in one pass, and decode streams dishes one at a time. If the special oven cannot perform one step, carrying food back and forth to the ordinary stove may be slower. A long order can fill every prep box. An ESP32 is the truck's sensor and safety controller; the main LLM belongs on the more capable host.
Where the analogy stops: The food-truck story clarifies capacity, heterogeneous work, and thermal budget. It cannot convert TOPS to tokens/s or predict quantization quality, delegate coverage, and OS scheduling. End-to-end results depend on model, shape, backend, memory path, software version, and thermal state; remeasure on target hardware.
Chapter walkthrough
Work backward from acceptance criteria to system boundaries
First specify required events, end-to-end latency, offline duration, false-positive and false-negative budgets, safe states, power, and cost. Then decide whether the model belongs on the MCU, an Edge Host, or the cloud. If an emergency stop must still occur in milliseconds without a network, neither the decision nor actuation can depend on a host LLM. If the task needs a large context, interpretation can live on the host while the device retains threshold rules. Map every requirement to a responsible component and a measurable signal so the architecture diagram contains commitments, not just arrows.
Define host messages as proposals, not commands
Use a versioned structured schema containing device_id, request_id, sequence, deadline, action, typed parameters, and authentication data. On receipt, the ESP32 verifies source, version, deduplication, freshness, the action allowlist, parameter ranges, and current state before converting the message into an internal event. Natural language must never drive GPIO directly. Test duplicate frames, reordering, replay, partial packets, and unknown fields, and make rejection reasons auditable.
Normal and degraded paths must share one state machine
Define explicit states and transitions for online operation, a slow host, link failure, model failure, sensor anomalies, and actuator faults; do not improvise actions inside exception callbacks. After a timeout, cancel the host request, discard late replies, and switch the device to a local threshold or safe-hold mode. Reconnection requires a fresh handshake and sequence synchronization. Inject network loss, restarts, packet loss, host saturation, and watchdog resets to verify that every path returns to a known state.
An edge chip is a heterogeneous memory system, not a TOPS label
The CPU owns control flow, tokenization, sampling, and unsupported operators. A GPU suits regular parallel work but command submission, shader compilation, buffer conversion, and contention with graphics all enter latency. A DSP or NPU can execute supported dtype, shape, and graph patterns at low energy, but may require static dimensions, specific quantization, or vendor compilation. Unified memory removes some explicit PCIe copies; it does not make movement free, because cache coherence, page migration, bandwidth contention, and layout conversion still consume time and energy. Advertised TOPS is usually an arithmetic peak at one low precision and includes neither tokenization, KV management, nor sampling. It also says nothing about operators falling back to CPU. Inspect runtime traces for subgraph placement, copied bytes at every boundary, first-compilation latency, and interference from camera or UI work before explaining TTFT and ITL.
A model file is only part of the delivery contract
GGUF packages tensors, quantization types, and inference metadata for llama.cpp's low-dependency, multi-backend ecosystem. ExecuTorch exports a PyTorch model ahead of time into a .pte artifact and uses partitioners and delegates for target backends. MLC LLM compiles model representations into platform code and parameters. LiteRT-LM assembles tokenizers, decoders, and cross-platform APIs over LiteRT. MNN-LLM connects a mobile runtime, multiple backends, and product integration. A format name does not guarantee equal semantics: tokenizer assets, chat templates, RoPE settings, special tokens, per-tensor scales, KV dtype, and sampling defaults belong to the package contract. Release metadata must capture the source checkpoint, conversion-tool commit, command, hashes, license, supported context, and verification prompts. Validate schema and compatibility before loading so a runtime cannot silently choose a wrong default. Successful parsing proves that bytes are readable, not that output, speed, and permissions satisfy the product.
Treat lowering, partitioning, and fallback as an observable compilation process
On-device deployment usually captures or exports a graph, normalizes operators, fuses patterns, inserts quantize or dequantize boundaries, and asks a partitioner to assign supported subgraphs to CPU, GPU, or NPU delegates. Each boundary may convert layout, dtype, or memory domain. One unsupported operator can fragment a graph into several regions, introduce repeated synchronization and copies, and make an enabled NPU slower than CPU-only execution. Preserve a compiler report: delegated nodes, fallback nodes, subgraph input contracts, workspace, and first-run compilation caches. Dynamic sequence lengths may need shape buckets, chunked prefill, or dedicated decode graphs, with boundary tests. A delegate failure path must be tested rather than merely theoretically runnable; define its capacity limit, timeout, logs, and recoverable model version. Join compiler logs, runtime traces, and system power samples with one request ID.
Accept quality, experience, energy, temperature, and recoverability together
An edge benchmark pins the checkpoint, quantization, prompt suite, backend, threads, power mode, ambient conditions, and software versions. Report cold versus cache-warm loading, prefill throughput and TTFT, decode throughput and ITL, peak RSS, joules per token or average power, device temperature, and frequency after sustained use. Generation speed must remain paired with task quality, format compliance, and refusal policy. Telemetry carries the model hash, delegate-partition summary, and trace ID so a fleet can compare releases. Ship signed model bundles with a compatibility matrix, staged rollout percentage, health gates, and rollback. Drill offline operation, delegate initialization failures, excess temperature, memory exhaustion, and cloud-fallback timeout. The deliverable is not the highest tokens/s from one cool prototype; it is evidence that the target device population maintains experience and safety across real thermal state, networking, and foreground load.
Infrastructure map and cross-scale lessons
Technical status verified on:
This project map follows delivery paths rather than ranking products. Supported models, backends, quantization, and CLIs move quickly. The boundaries identify what to verify and do not claim cross-vendor performance.
Low-dependency quantized runtimes
-
llama.cpp / GGUF ↗
- Problem
- Run quantized open-weight LLMs with few dependencies on desktops, SBCs, and mobile platforms.
- Core mechanism
- GGUF packages tensors and metadata; ggml kernels target CPU, Metal, CUDA, Vulkan, and other backends, with conversion and llama-bench tools.
- Scope and boundary
- Backends and CLI flags evolve. Loading GGUF does not prove template semantics, quality, power, or device compatibility.
-
bitnet.cpp ↗
- Problem
- Explore coordinated 1-bit or low-bit models and specialized kernels.
- Core mechanism
- Optimize BitNet model structure, weight representation, and CPU kernels together.
- Scope and boundary
- It is not a lossless compressor for arbitrary checkpoints; value depends on model-to-kernel co-design.
Compiler and AOT deployment
-
MLC LLM ↗
- Problem
- Compile and deploy LLMs to multiple CPU/GPU platforms and application APIs.
- Core mechanism
- Use an ML compiler to generate target code, quantized model libraries, and platform bindings.
- Scope and boundary
- Model and toolchain support are versioned; a compiled artifact is not a universal cross-device binary.
-
ExecuTorch ↗
- Problem
- Export PyTorch models ahead of time into mobile and embedded runtimes.
- Core mechanism
- Export .pte and use partitioners for XNNPACK, Core ML, Qualcomm, and other delegates, then run through C++, Swift, or Java APIs.
- Scope and boundary
- Delegate coverage and dynamic shapes set boundary costs; a model fitting PyTorch does not automatically fit a device.
On-device generation pipelines
-
LiteRT-LM ↗
- Problem
- Provide cross-platform on-device generation pipelines and application SDKs.
- Core mechanism
- Compose tokenizers, model components, sessions, and CPU/GPU/NPU backends on LiteRT.
- Scope and boundary
- Platform and NPU support change by release; use the official matrix for the exact target version.
-
MNN-LLM ↗
- Problem
- Integrate lightweight multi-backend LLMs and multimodal applications across phones, PCs, and IoT.
- Core mechanism
- Connect the MNN runtime, CPU and Metal/OpenCL/Vulkan backends, model conversion, and mobile application APIs.
- Scope and boundary
- Repository benchmarks cannot rank runtimes outside the stated device, model, threads, and thermal conditions.
Platform-specific paths
-
MLX-LM ↗
- Problem
- Run and fine-tune LLMs on Apple silicon unified-memory systems.
- Core mechanism
- Use MLX arrays, the Metal backend, and platform memory behavior for quantization, generation, and training tools.
- Scope and boundary
- Platform-specific optimization does not extrapolate to Android, discrete GPUs, or MCUs; memory pressure and thermal steady state still require measurement.
Source mechanism, engineering lesson, and boundary
| Source mechanism | Engineering lesson | Scope and boundary |
|---|---|---|
| I/O-aware kernels, fusion, fewer copies | Transfer directly: device bandwidth and battery make intermediate materialization especially expensive. | Choose or generate kernels for the target shape and backend, not merely by algorithm name. |
| Paged KV, prefix reuse, chunked prefill | Adapt for batch one and bounded context to reduce fragmentation, duplicate work, and peak blocking. | Paging metadata and scheduling cost something; prefixes need versioning and privacy isolation. |
| Continuous batching and cross-node TP/PP | Do not transfer by default; prove a real queue or beneficial heterogeneous partition first. | CPU/GPU/NPU are not cheap homogeneous ranks, and boundary copies can exceed computation savings. |
| Data-center topology awareness | Map it to delegate coverage, shared memory, coherence, and CPU/GPU/NPU boundaries. | Unified memory reduces explicit copies; it does not provide infinite bandwidth or zero synchronization. |
| SLOs, versioning, rollback, observability | Transfer fully, then add joules/token, peak RSS, temperature, and thermal throttling. | Cool-device laboratory averages cannot represent sustained fleet experience or battery life. |
Interactive process
The lifecycle of an on-device token, from budget to telemetry
The animation joins offline conversion, first load, and each request into one path, showing why edge performance belongs to more than the model kernel.
Budget gate · device tier + privacy + context + deadline
Choose a local model, reduced task, or explicit cloud fallback using capability, permission, temperature, and network policy
Routing is a product and safety decision before it is a performance decision
Loop / return condition: A multi-turn session returns to the budget gate. Remaining context, resident KV, temperature, battery, and privacy policy decide whether to continue, compact, unload, or explicitly request cloud use. Stop generation before reclaiming KV and delegate resources on cancellation or model switches.
View the complete static diagram
sensor/actuator ↔ MCU deterministic gate ↔ Edge Host LLM
│ validate tool proposal │
└── explicit cloud fallback
model package → runtime/backend → telemetry → staged OTA/rollbackCode or command example
proposal = edge_llm(request)
validated = policy_and_schema_check(proposal)
if validated:
mcu_execute(validated)
else:
enter_safe_degraded_state()
record(version_set, latency, energy, thermal, failures)Hands-on lab
Lab notes and export
Engineering pitfall
Knowledge check
Answer all three multiple-choice questions, then submit. Answers stay hidden until submission.
Discuss this chapter on GitHub
Sign in with GitHub to ask a question, share measurements, or compare implementations. Comments are stored in this course's GitHub Discussions.
The embedded comments need JavaScript. You can also open the GitHub discussion area directly: Open GitHub Discussions ↗
Further reading
Bridge to the next chapter
The 15-day route is complete. Start the next project from its target device and real workload: write safety and acceptance boundaries first, then select model and runtime, and leave reproducible evidence for every optimization.