Sub topic 6
Inference runtimes: TensorFlow Lite, ONNX Runtime, Core ML, and ExecuTorch
This chapter covers what an on-device inference runtime does, how the four common runtimes differ, and how to pick one for a target platform. It assumes you can run a PyTorch or TensorFlow model in Python and that you know what float32 and int8 tensors are. You also need the export step from the previous chapter: a model file exists, and now something must execute it on the device.
What a runtime does
A training framework such as PyTorch or TensorFlow is built for flexibility. It carries autograd, a large operator library, and a Python front end. A phone app cannot afford any of that. An inference runtime is a small library that does four jobs:
- It loads a serialized model file (a graph of operators plus weights).
- It plans memory, so intermediate tensors reuse buffers instead of each getting its own allocation.
- It maps each operator to a kernel, which is the code that executes it. The kernel can run on the CPU, GPU, or NPU (neural processing unit).
- It executes the graph for each input and returns output tensors.
A runtime does not train, and it does not preprocess your images. Resizing, color conversion, and normalization remain your job (a later chapter covers them).
The four runtimes
TensorFlow Lite
TensorFlow Lite (TFLite) uses the .tflite format, which is a FlatBuffers file. FlatBuffers can be read directly from memory without a parsing step. This keeps load time short and lets the runtime memory-map the file.
TFLite runs on Android, iOS, embedded Linux, and microcontrollers (through a separate variant). Its strengths are mature integer quantization, a small binary, and a large set of ready-made models. Hardware access goes through delegates: GPU, NNAPI on Android, and Core ML on iOS. Google has been rebranding the project as LiteRT, and the file format and interpreter concepts stay the same.
Here is a minimal inference run with the Python interpreter. It reads the expected input shape and dtype from the model instead of hard-coding them.
import numpy as np
import tensorflow as tf
interpreter = tf.lite.Interpreter(model_path="mobilenet_v2_int8.tflite")
interpreter.allocate_tensors()
inp = interpreter.get_input_details()[0]
out = interpreter.get_output_details()[0]
image = np.zeros(inp["shape"], dtype=inp["dtype"]) # stand-in for a real image
interpreter.set_tensor(inp["index"], image)
interpreter.invoke()
scores = interpreter.get_tensor(out["index"])
print("top class:", int(scores.argmax()))allocate_tensors() is where the memory plan is built. Call it once after loading, never inside the per-frame loop.
ONNX Runtime
ONNX Runtime (ORT) executes models in the ONNX format, which PyTorch can export directly. ORT's main idea is the execution provider (EP). An EP is a plug-in that claims the part of the graph it can run and executes it on specific hardware. Examples are the CPU provider, XNNPACK, NNAPI on Android, Core ML on iOS, and vendor providers for Qualcomm and other chips.
ORT is a good choice when you want one model file and one API across Windows, Linux, Android, iOS, and the web. The ORT format (.ort) and a reduced-operator build can shrink the binary for mobile. Export from PyTorch looks like this:
import torch
import torchvision
model = torchvision.models.mobilenet_v3_small(weights="DEFAULT").eval()
dummy = torch.randn(1, 3, 224, 224)
torch.onnx.export(
model,
dummy,
"mobilenet_v3_small.onnx",
input_names=["input"],
output_names=["logits"],
opset_version=17,
)The exported file has a fixed 1x3x224x224 input. Note the layout: PyTorch exports use NCHW (batch, channels, height, width), while TFLite models usually expect NHWC. Feeding the wrong layout produces no error when the shapes happen to be compatible, only wrong predictions.
Core ML
Core ML is Apple's runtime for iOS, iPadOS, macOS, and other Apple platforms. Models use the .mlpackage format (or the older .mlmodel) and are produced with the coremltools converter. Core ML decides at run time whether to use the CPU, GPU, or Apple Neural Engine (ANE). You can restrict this choice with a compute-units setting, but you cannot name a specific core.
Its strength is tight integration with the platform. The Vision framework can feed camera frames straight into a model, and the ANE is often the most power-efficient option on an iPhone. The cost is portability: the format only runs on Apple devices. Teams that ship on both platforms often keep a Core ML model for iOS and a TFLite or ORT model for Android.
ExecuTorch
ExecuTorch is PyTorch's on-device runtime. Its path stays inside the PyTorch ecosystem. You capture the model with torch.export, lower it to an "edge" representation, optionally hand parts of it to a backend such as XNNPACK, Core ML, or Qualcomm's backend, and write a .pte file. The runtime is small and written in C++, and it plans memory ahead of time rather than at load.
Use ExecuTorch when your model is authored in PyTorch and you want to avoid a trip through ONNX, where operator support gaps can force rewrites. It is newer than the other three, so check that your operators and target backend are supported in the release you use.
Comparison
| Runtime | Model format | Platforms | Hardware access | Typical fit |
|---|---|---|---|---|
| TensorFlow Lite | `.tflite` | Android, iOS, Linux, microcontrollers | Delegates: GPU, NNAPI, Core ML | Android-first apps, full-integer quantized models |
| ONNX Runtime | `.onnx`, `.ort` | Android, iOS, desktop, web | Execution providers | One model across many platforms |
| Core ML | `.mlpackage` | Apple only | CPU, GPU, ANE (chosen by system) | iOS-first apps that want the ANE |
| ExecuTorch | `.pte` | Android, iOS, embedded | Backends: XNNPACK, Core ML, vendor | PyTorch-native models |
Partitioning: why one model can run on several processors
Most runtimes split a graph. The accelerator backend takes the operators it supports, and everything else stays on the CPU. Each boundary between the two costs time, because tensors must be copied or synchronized between processors. A model with one unsupported operator in the middle can end up as three pieces, and the copies may cost more than the accelerator saves.
This is why a later chapter spends time on unsupported operators. For now, remember that "the runtime supports my accelerator" does not mean "my whole model runs on it."
Choosing a runtime
Work through these questions in order.
- Which platforms must you ship on? Apple only points to Core ML. Android only points to TFLite or ORT. Both platforms point to TFLite, ORT, or ExecuTorch.
- Where was the model trained? PyTorch models can reach ORT through ONNX, TFLite through a converter, or ExecuTorch directly. Each conversion can lose or alter operators, so test the converted model.
- What precision do you need? If you need full-integer int8 for an NPU, TFLite has the most mature tooling. Check your target accelerator's documentation, since many NPUs only accept quantized models.
- What accelerator is on the device? Vendor NPUs usually ship an SDK with a TFLite delegate, an ORT execution provider, or an ExecuTorch backend. Pick the runtime that the vendor supports best.
- How much binary size can you afford? All four offer reduced builds. Measure the app size with your actual operator set.
Common errors
- Wrong input layout or type. NCHW versus NHWC, float32 versus uint8, and a 0 to 1 range versus 0 to 255 all give plausible but wrong output. Read the shape and dtype from the model, as the TFLite example does, and compare outputs against the original framework on the same image.
- Loading the model on every frame. Creating an interpreter or session is slow. Create it once and reuse it.
- Calling an interpreter from several threads. TFLite interpreters and ORT sessions have different threading rules. Do not share one TFLite interpreter across threads without locking.
- Assuming the accelerator ran. A delegate or EP that cannot take any operator usually fails silently and runs on the CPU. Enable the runtime's logging or profiler to confirm.
- Timing the first run. The first inference includes setup work such as kernel compilation, so exclude it.
A repeatable timing loop
The following code applies the warm-up and percentile pattern. Use it on the device, since desktop numbers do not transfer.
import time
import numpy as np
import tensorflow as tf
interpreter = tf.lite.Interpreter(model_path="mobilenet_v2_int8.tflite", num_threads=4)
interpreter.allocate_tensors()
inp = interpreter.get_input_details()[0]
image = np.zeros(inp["shape"], dtype=inp["dtype"])
for _ in range(10): # warm-up runs are excluded from timing
interpreter.set_tensor(inp["index"], image)
interpreter.invoke()
times = []
for _ in range(100):
start = time.perf_counter()
interpreter.set_tensor(inp["index"], image)
interpreter.invoke()
times.append((time.perf_counter() - start) * 1000)
print(f"median {np.median(times):.1f} ms, p95 {np.percentile(times, 95):.1f} ms")The median shows typical speed. The 95th percentile shows the slow frames that users notice as stutter.
Summary
A runtime loads the model file, plans memory, and dispatches operators to hardware. TFLite, ONNX Runtime, Core ML, and ExecuTorch differ in model format, platform reach, and how they attach accelerators. Choose by target platforms, the framework your model came from, the precision your hardware needs, and measured results on the real device.
Exercise
Your app must ship on Android and iOS, and the model is trained in PyTorch. An Android NPU only accepts int8 models. Name two runtime options you would evaluate and one risk of each.
Show answer
Two valid options are ONNX Runtime and ExecuTorch (TFLite is also acceptable). ONNX Runtime risk: the PyTorch-to-ONNX export may hit unsupported or changed operators, and the NPU execution provider may take only part of the graph, leaving CPU fallbacks. ExecuTorch risk: it is newer, so operator coverage and the vendor NPU backend must be checked for your release, and int8 support depends on that backend. For TFLite, the risk is the PyTorch-to-TFLite conversion path, which may need rewrites. In every case, test int8 accuracy and latency on the real device.
Exercise
A model runs at 40 ms per frame on the CPU. After enabling an NPU delegate it runs at 55 ms. Give two likely causes and one check for each.
Show answer
Cause 1: Several operators are unsupported, so the graph is split into many pieces and the copies between CPU and NPU outweigh the speedup. Check the delegate or profiler log for the number of partitions and which operators fell back. Cause 2: The timing includes first-run setup, such as kernel compilation, or the model is float and the NPU needs int8, so it converts or falls back. Check by adding warm-up runs and reporting the median, and confirm the model's quantization matches the NPU's requirements.