Pidoku

Mobile Runtimes: ExecuTorch, LiteRT, ONNX Runtime GenAI

Module 29 Lesson 29.d 1h 15m Difficulty 4/5

Prerequisites 29.a, 29.b, 15.d, 13.m


Before you start: words you need#

WordPlain meaning
RuntimeThe library inside an app that loads a model file and runs it. On phones it must be small, fast to start and free of Python.
ExportTurning a model written in a training framework (PyTorch, JAX) into a fixed graph that a runtime can run without the framework.
Delegate / execution provider / backendA plug-in that runs part of the graph on specific hardware (GPU, NPU, DSP). Each runtime has its own word for it.
PartitioningSplitting the graph into pieces the accelerator supports and pieces that fall back to the CPU.
Ahead-of-time (AOT) compilationCompiling the model for a specific chip before shipping it, instead of on the device at first launch.
LLM runnerThe code around the model that a chatbot needs: tokenizer, KV cache, sampling loop, chat template, stop conditions.
AICoreAndroid’s system service that holds Gemini Nano and runs it for apps.
WebGPUThe browser’s modern GPU interface, which lets web pages run models on the user’s GPU.

1. What is it?#

A mobile runtime is the engine an app embeds to run a model on a phone, tablet, laptop, browser or embedded board. In 2026 three open runtimes cover most of the field, plus the operating-system models:

RuntimeFromFile formatStrength
ExecuTorch v1.6.0 (November 2026)PyTorch (Meta and partners).ptePyTorch-native export; the widest range of targets, from phones to microcontrollers
LiteRT v2.3 (October 2026) and LiteRT-LM v0.19 (November 2026)Google AI Edge (the successor of TensorFlow Lite).tflite, .litertlmGoogle’s production path for Gemma and Gemini Nano-class models on Android, iOS, web and desktop
ONNX Runtime GenAI v0.19.0 (3 November 2026)MicrosoftONNX + genai_config.jsonWindows and cross-vendor PCs; powers Windows ML and Foundry Local
OS modelsApple, Google, Microsoftnone: the OS ships itApple Foundation Models (29.c), Gemini Nano through AICore, Phi Silica on Copilot+ PCs

llama.cpp (29.b) and MLX (29.c) are also used on devices; this lesson covers the runtimes built for shipping inside mobile and desktop apps. Facts checked on 13 November 2026.


2. Why does it matter?#

  • A server stack cannot ship in an app. PyTorch with CUDA is gigabytes; a phone app’s runtime must be a few megabytes, start in milliseconds and run without Python.
  • Every device has different accelerators. The runtime’s delegates are what turn a generic graph into something that uses the GPU or NPU. Coverage decides speed.
  • The LLM loop is more than the model. Tokenizer, KV cache, sampling, constrained decoding, chat templates and multimodal encoders must all run on the device. A runtime with a good LLM runner saves months.
  • The choice is sticky. The export path, file format and delegate set shape the whole release process. Picking the wrong runtime is expensive to undo.

3. Simple analogy#

Training a model in PyTorch is writing a recipe in a busy restaurant kitchen with every tool at hand. A mobile runtime is a meal kit: the recipe is fixed in advance (export), the ingredients are measured and packed for one specific stove (AOT compilation for one chip), and the instructions say which steps use the oven and which the hob (partitioning). If the kit asks for a tool your kitchen lacks, that step is done by hand (CPU fallback), slowly.


4. Tiny example: one Gemma 4 model, many devices#

Google publishes LiteRT-LM measurements for Gemma 4 E2B (a 2,583 MB file):

DeviceBackendPrefill (tok/s)Decode (tok/s)Time to first token
Samsung S26 UltraCPU557471.8 s
Samsung S26 UltraGPU3,808520.3 s
iPhone 17 ProCPU532251.9 s
iPhone 17 ProGPU2,878560.3 s
MacBook Pro M4 MaxGPU7,8351600.1 s
Raspberry Pi 5 (16 GB)CPU13387.8 s

These are vendor figures (prompt length and settings as on Google’s page). Read them with 29.a in mind: moving from CPU to GPU multiplies prefill by 5–7x (compute-bound) but barely changes decode on the Samsung (bandwidth-bound). On the iPhone the GPU also doubles decode, a sign that its CPU path was not using the full memory bandwidth.


5. Technical explanation#

The common pipeline#

All three runtimes follow the same five steps:

  1. Capture the model as a graph: torch.export (ExecuTorch, Core AI, LiteRT Torch), or an ONNX export or builder (ORT GenAI).
  2. Transform and quantize: fuse operations, fold constants, apply quantization (4-bit weights, 8-bit activations or KV, 29.f). Most quantization is done here, ahead of time.
  3. Partition and lower: hand supported subgraphs to delegates (XNNPACK for CPU, Vulkan/OpenCL/ Metal for GPU, QNN, MediaTek, Samsung, Core ML/Core AI for NPUs), keep the rest on portable CPU kernels.
  4. Serialize into a file the runtime loads with little parsing, ideally memory-mapped.
  5. Run with an LLM runner around it: tokenizer, KV cache, sampler, constrained decoding.

ExecuTorch#

ExecuTorch is PyTorch’s on-device runtime (1.0 in October 2025; v1.6.0 in November 2026). Meta reports it in production in Instagram, WhatsApp, Facebook and Messenger, and on Quest and Ray-Ban Meta devices.

The minimal export, from the project’s README:

Python
import torch
from executorch.exir import to_edge_transform_and_lower
from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner

class Add(torch.nn.Module):
    def forward(self, x, y):
        return x + y

model = Add().eval()
sample_inputs = (torch.ones(1), torch.ones(1))
et_program = to_edge_transform_and_lower(
    torch.export.export(model, sample_inputs),
    partitioner=[XnnpackPartitioner()],
).to_executorch()
with open("add.pte", "wb") as f:
    f.write(et_program.buffer)

What matters for production:

  • A .pte is specialised for its backend. A file lowered for Qualcomm will not run on MediaTek. Plan one export per target family.
  • Backends: XNNPACK (CPU, with Arm KleidiAI kernels), Vulkan, Core ML, MLX (experimental), Metal, Qualcomm QNN, MediaTek, Samsung Exynos, Arm Ethos-U and VGF, NXP Neutron (production-ready in 1.6), Cadence DSPs, OpenVINO, CUDA, WebGPU. v1.6.0 notes MediaTek as temporarily unsupported while its converter moves to Python 3.11+, a reminder that delegate support moves.
  • Selective build links only the operators a model uses, keeping the binary small; this is how it reaches microcontrollers.
  • A compatibility contract: a .pte built with stable APIs is guaranteed to load in at least the next non-patch runtime release. Do not assume more.
  • LLMs: export_llm and Optimum ExecuTorch export Hugging Face models with tested recipes; the runner provides KV cache, sampling and multimodal inputs. Version 1.6 added batched serving, prefix caching and DFlash speculative decoding on its CUDA and MLX paths, and Qualcomm improvements such as 8-bit KV-cache I/O and one artifact for several Snapdragon chips (“flexible context binary”).

LiteRT and LiteRT-LM#

LiteRT is TensorFlow Lite’s successor. Version 2 introduced the CompiledModel API: the runtime selects the accelerator itself, runs asynchronously, and handles I/O buffers without copies. GPU execution uses Google’s ML Drift engine; NPUs from Qualcomm, MediaTek, Google Tensor, Samsung System LSI, Intel and Broadcom are reached through one API; and vendors can ship their own NPU backend outside the LiteRT repository. Models arrive from PyTorch through LiteRT Torch (formerly AI Edge Torch) and are compressed with the AI Edge Quantizer.

LiteRT-LM is the LLM layer on top: model loading, KV cache, sampling, multimodal inputs (image and audio), tool calling, and multi-token-prediction speculative decoding for Gemma 4. Its .litertlm file bundles the model sections, tokenizer and metadata. Google says LiteRT-LM powers on-device generative AI in Chrome, Chromebook Plus and Pixel Watch. Version 0.19 (November 2026) added accelerated logit masking for constrained decoding on GPUs, a web SDK that defaults to the GPU, speech models, and a C API 1.0 with breaking changes. Try it from a terminal:

Shell
uv tool install litert-lm
litert-lm run --from-huggingface-repo=litert-community/gemma-4-E4B-it-litert-lm \
  gemma-4-E4B-it.litertlm --backend=gpu --speculative-decoding=on \
  --prompt="What is the capital of France?"

APIs exist for Kotlin, C++ and Python (stable) and Swift, JavaScript and Flutter (preview).

ONNX Runtime GenAI#

ORT GenAI adds the generative loop to ONNX Runtime: pre- and post-processing, KV cache management, search and sampling, multi-LoRA, constrained decoding for tool calls, and, from 0.17, a dynamic engine with paged KV cache and automatic prefix caching, plus DFlash speculative decoding. Microsoft says it powers Foundry Local, Windows ML and the VS Code AI Toolkit.

Models are produced by the model builder, which exports and quantizes a Hugging Face model for one execution provider:

Shell
python -m onnxruntime_genai.models.builder -m Qwen/Qwen3-8B -o qwen3-8b-int4 -p int4 -e cpu

Execution providers include CPU, CUDA, DirectML, NvTensorRtRtx (TensorRT for RTX), OpenVINO (Intel CPUs, GPUs and NPUs), QNN (Qualcomm NPUs) and WebGPU. On Windows, Windows ML ships ONNX Runtime with vendor providers (QNN, VitisAI for AMD, OpenVINO for Intel) that it downloads per device, so an app ships one ONNX model and the OS supplies the right accelerator plug-in.

The generation loop, from the ORT GenAI README:

Python
import onnxruntime_genai as og

model = og.Model("qwen3-8b-int4")
tokenizer = og.Tokenizer(model)
stream = tokenizer.create_stream()
params = og.GeneratorParams(model)
params.set_search_options(max_length=2048)
generator = og.Generator(model, params)
generator.append_tokens(tokenizer.encode(prompt))
while not generator.is_done():
    generator.generate_next_token()
    print(stream.decode(generator.get_next_tokens()[0]), end="", flush=True)

The OS models#

  • Gemini Nano (Android) runs inside AICore, so all apps share one copy. Apps reach it through the ML Kit GenAI APIs: task APIs (summarization, proofreading, rewriting, image description, speech) and direct prompting. Device support depends on the Nano version (Nano 2, 3 or 4) the device has; Google’s examples are Xiaomi 15 (Nano 2), Pixel 9 (Nano 3) and Galaxy S25 (Nano 4). Firebase’s documentation describes preview models Gemini Nano 4 Full (based on Gemma 4 E4B) and Nano 4 Fast (based on Gemma 4 E2B). AICore enforces a per-app inference quota (an error such as BUSY when you send too much too fast, a battery-use quota over longer periods) and runs inference only for the foreground app: background use, even from a foreground service, is blocked.
  • Chrome’s built-in AI: the Prompt API (LanguageModel.create(), session.prompt(), promptStreaming()) is available to web pages from Chrome 148 on desktop (Windows, macOS, Linux, Chromebook Plus), and to extensions since Chrome 138. It needs 22 GB of free disk for the model and a GPU with more than 4 GB of VRAM, or 16 GB of RAM and 4 CPU cores. It is not on Android or iOS yet.
  • Apple Foundation Models (29.c) and Phi Silica on Windows Copilot+ PCs play the same role.

OS models trade control for reach: no download and no memory of your own, but you cannot choose the model, its version or its quantization, and the OS can throttle you.

Browsers beyond Chrome’s model#

WebLLM (MLC, v0.2.88) compiles models with TVM to WebGPU; LiteRT.js, the LiteRT-LM web SDK and ExecuTorch’s WebGPU backend (experimental) run your own models in the page. Expect GPU-memory limits set by the browser and a first-load download of hundreds of megabytes to gigabytes, cached afterwards.


6. Under the hood: the cost of partial delegation#

When an accelerator’s compiler does not support one operation, the runtime splits the graph and runs that operation on the CPU. Each split costs a hand-off: synchronise, flush caches, maybe copy or convert the tensor, then start the accelerator again. This program models one decode step of a 28-layer model with illustrative timings (not measurements of any chip).

Go
// partition.go — what a few unsupported ops do to a delegated model.
// Times are illustrative assumptions for one decode step of a 28-layer 3B model.
package main

import "fmt"

type op struct {
	name      string
	cpuMicros float64 // time on the CPU kernels
	npuMicros float64 // time on the accelerator
	npuOK     bool    // does the accelerator's compiler support it?
}

func main() {
	const layers = 28
	const handoffMicros = 150.0 // cost of each CPU<->accelerator switch: sync, cache flush, copy (assumed)

	layer := []op{
		{"rmsnorm", 15, 5, true},
		{"qkv matmul", 900, 260, true},
		{"rope", 20, 6, true},
		{"attention", 250, 80, true},
		{"o_proj matmul", 300, 90, true},
		{"rmsnorm", 15, 5, true},
		{"ffn matmuls", 2700, 780, true},
	}

	run := func(label string, unsupported map[string]bool) {
		total, handoffs := 0.0, 0
		onNPU := false // the token's data starts on the CPU
		for l := 0; l < layers; l++ {
			for _, o := range layer {
				useNPU := o.npuOK && !unsupported[o.name]
				if useNPU != onNPU {
					handoffs++
				}
				onNPU = useNPU
				if useNPU {
					total += o.npuMicros
				} else {
					total += o.cpuMicros
				}
			}
		}
		if onNPU {
			handoffs++ // logits go back to the CPU for sampling
		}
		total += float64(handoffs) * handoffMicros
		fmt.Printf("%-34s %3d hand-offs  %6.1f ms/token  %5.1f tok/s\n", label, handoffs, total/1000, 1e6/total)
	}

	run("all ops on CPU", map[string]bool{"rmsnorm": true, "qkv matmul": true, "rope": true,
		"attention": true, "o_proj matmul": true, "ffn matmuls": true})
	run("whole graph on the accelerator", nil)
	run("rope unsupported (falls back)", map[string]bool{"rope": true})
	run("rope + rmsnorm unsupported", map[string]bool{"rope": true, "rmsnorm": true})
}

Output:

all ops on CPU                       0 hand-offs   117.6 ms/token    8.5 tok/s
whole graph on the accelerator       2 hand-offs    34.6 ms/token   28.9 tok/s
rope unsupported (falls back)       58 hand-offs    43.4 ms/token   23.0 tok/s
rope + rmsnorm unsupported         168 hand-offs    60.5 ms/token   16.5 tok/s

How to read it:

  • One tiny unsupported op per layer (RoPE takes 20 µs) costs 20% of the speed, purely in hand-offs. Two such ops cost almost half.
  • This is why runtime release notes are full of “fully delegated transformer blocks”, “SDPA decomposition” and new operators: coverage, not peak TOPS, decides accelerated speed.
  • Before shipping, inspect the partition: ExecuTorch prints delegation summaries and has ETRecord and ETDump for profiling; LiteRT and ORT log which nodes ran where. Rewrite the model (a different RoPE formulation, a fused norm) so the accelerator takes the whole layer.

7. Performance implications#

  • GPU and NPU paths mostly help prefill and power; decode stays bandwidth-bound (29.a). Judge a backend on time to first token, sustained decode and energy, not one number.
  • Static shapes. Many NPU compilers need fixed tensor shapes. Runtimes compile a few variants (for example a prefill graph for 128-token chunks and a decode graph for one token) and pad inputs. Padding wastes work; chunk sizes are a tuning knob.
  • First-run compilation. Some GPU and NPU delegates compile or tune kernels on first launch, adding seconds. Prefer AOT-compiled artifacts or cache the compiled result.
  • Memory-mapped weights start faster and let the OS reclaim pages; avoid runtimes or settings that copy the whole model into the heap.
  • Speculative decoding (MTP drafters in LiteRT-LM, DFlash in ExecuTorch and ORT GenAI) is one of the few ways to speed up bandwidth-bound decode on a device (12.n).

8. Production implications#

  • Pick by platform first. Android-first with Gemma-class models: LiteRT-LM or ML Kit’s Gemini Nano. iOS-first: Foundation Models, Core AI or ExecuTorch with Core ML/MLX. Windows PCs: ORT GenAI through Windows ML or Foundry Local. Many platforms from one PyTorch codebase: ExecuTorch. Many platforms from one GGUF: llama.cpp.
  • Build a device matrix. Test every export on representative devices per accelerator family (Qualcomm, MediaTek, Samsung, Tensor, Apple), with numerical checks against the reference model (28.b). Delegates have numerical bugs; ExecuTorch 1.6 alone lists fixes for silently wrong outputs in two backends.
  • Plan for fallback at every level: NPU to GPU to CPU to cloud. Log which path each request took.
  • Respect OS quotas. With Gemini Nano, background jobs are blocked and per-app quotas apply; design batch features (summarising a mailbox overnight) for the cloud or for foreground use.
  • Version everything together: runtime, delegate SDK (for example QNN SDK 2.51 in ExecuTorch 1.6), model file, tokenizer and prompt template. A delegate SDK update can change numerics.

9. Common mistakes#

  1. Treating a delegated model file as portable. It was compiled for one accelerator family.
  2. Counting “supported” operators instead of measuring hand-offs. One fallback per layer can undo most of the gain.
  3. Benchmarking only on a flagship. Mid-range phones often lack the NPU path entirely.
  4. Running Gemini Nano from a background service. AICore blocks it.
  5. Assuming the OS model is fixed. It updates with AICore or the OS, and outputs differ across Nano versions.
  6. Shipping without a numerical check per backend. A GPU or NPU delegate can produce plausible but wrong text.

10. Hands-on exercise#

  1. Run partition.go. Set handoffMicros to 30 (a tightly integrated accelerator) and to 500 (a slow driver). How does the value of full delegation change?
  2. Add a “custom attention” op that the accelerator does not support. What is the fastest plan: fall back per layer, or run whole layers on the CPU?
  3. Install executorch, export a small Hugging Face model with the XNNPACK recipe, and run it with the Python runtime. Read the delegation summary: which operators stayed on the portable kernels?
  4. Run Gemma 4 E2B with litert-lm on CPU and on GPU on your laptop. Compare time to first token and decode speed with Google’s table.
  5. Build an int4 CPU model with the ORT GenAI model builder and compare its speed and outputs with the same model as Q4_K_M in llama.cpp.

11. Interview questions#

  1. Describe the export → partition → serialize → run pipeline and where quantization happens.
  2. Why is a .pte or a compiled .tflite tied to one accelerator family, and how do you ship to thousands of phone models?
  3. How can an NPU-delegated model be slower than the CPU?
  4. What do OS models such as Gemini Nano and Apple Foundation Models give you, and what do you give up?
  5. You must ship one summarisation feature on Android, iOS and Windows. Which runtimes do you choose, and what is your fallback plan?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in