Sub topic 7
Using GPUs and NPUs through delegates and execution providers
This chapter assumes you can export a model to TensorFlow Lite or ONNX and run it on the CPU. It also assumes you know why int8 quantization shrinks a model. You will learn how a runtime hands part of a model to a GPU or NPU, what you gain, and what can go wrong.
Why the CPU is not the only option
A phone system-on-chip (SoC) holds several processors. Each suits a different kind of work.
| Processor | Strength | Weakness |
|---|---|---|
| CPU | Runs every operator, predictable, easy to debug | Lower throughput per watt on large convolutions |
| GPU | Many parallel lanes, good for large float convolutions | Memory transfers, driver variation, power spikes |
| NPU / DSP / TPU | Highest efficiency for supported int8 or float16 operators | Narrow operator support, vendor-specific tools |
An NPU (neural processing unit) is a chip block built for tensor math. DSPs and Google's Edge TPU play a similar role. They can be several times faster and use less energy than the CPU. The exact gain depends on the model, the chip, and the driver, so measure it on your device.
The core idea: delegation
A runtime does not usually move a whole model to an accelerator. It uses a plug-in layer with two names:
- TensorFlow Lite calls the plug-in a delegate.
- ONNX Runtime calls it an execution provider (EP).
- Core ML and ExecuTorch use the same idea. Core ML chooses among CPU, GPU, and the Apple Neural Engine. ExecuTorch uses backends such as XNNPACK, Core ML, and Qualcomm QNN.
The process has three steps:
- The runtime loads the model graph.
- The delegate inspects the graph and claims the operators it can run.
- The runtime partitions the graph. Claimed groups of operators run on the accelerator. The rest run on the CPU.
Each boundary between processors costs a data transfer and a synchronization. A model split into many small partitions can run slower than the CPU alone. The goal is a small number of large partitions.
Delegates in TensorFlow Lite
Common TensorFlow Lite options:
- XNNPACK is a fast CPU path. Recent builds enable it by default for float models.
- GPU delegate uses OpenCL, OpenGL ES, or Metal. It works best with float16 or float32 models.
- NNAPI delegate is the Android neural network API. It forwards work to whatever vendor driver the device provides. Google has deprecated NNAPI since Android 15, so plan new work around vendor delegates or the LiteRT stack.
- Hexagon, Core ML, and Edge TPU delegates target specific hardware.
TensorFlow Lite is now part of Google's LiteRT. The interpreter API shown here still works, but check the current docs for the package names in your version.
The Python interpreter on a desktop mostly runs on the CPU. You normally attach accelerator delegates in the Android (Kotlin or Java) or iOS code, or in a native build. The following Python example loads an external delegate library, which is how vendor delegates such as the Edge TPU plug in on Linux boards. The library path is an example and must match your device.
import numpy as np
import tensorflow as tf
# Example path for an Edge TPU on Linux. Change it for your hardware.
delegate = tf.lite.experimental.load_delegate("libedgetpu.so.1")
interpreter = tf.lite.Interpreter(
model_path="mobilenet_v2_int8_edgetpu.tflite",
experimental_delegates=[delegate],
)
interpreter.allocate_tensors()
inp = interpreter.get_input_details()[0]
out = interpreter.get_output_details()[0]
image = np.zeros(inp["shape"], dtype=inp["dtype"])
interpreter.set_tensor(inp["index"], image)
interpreter.invoke()
print("top class:", int(interpreter.get_tensor(out["index"]).argmax()))The Edge TPU requires a model compiled with Google's edgetpu_compiler. Other delegates take the standard .tflite file.
On Android in Kotlin, the pattern is to create options, add a delegate, and pass the options to the interpreter. Close the delegate when you finish, because it holds native resources.
Execution providers in ONNX Runtime
ONNX Runtime takes an ordered list of providers. For each part of the graph it uses the first provider that supports it. The CPU provider is always the final fallback.
import numpy as np
import onnxruntime as ort
print("available:", ort.get_available_providers())
session = ort.InferenceSession(
"mobilenet_v3_small.onnx",
providers=["CoreMLExecutionProvider", "CPUExecutionProvider"],
)
print("active:", session.get_providers())
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
logits = session.run(["logits"], {"input": x})[0]
print("top class:", int(logits.argmax()))If you ask for a provider that is not in your build, current versions print a warning and fall back, so always check session.get_providers(). The list is the most common place to find out that your accelerator never ran. Common providers include:
- CoreML on Apple devices.
- NNAPI on Android, with the same deprecation caveat as above.
- QNN for Qualcomm NPUs.
- XNNPACK for optimized ARM CPU kernels.
- CUDA and TensorRT on NVIDIA edge boards such as Jetson.
The mobile builds of ONNX Runtime ship a limited set of providers, so you may need a custom build.
What decides whether an operator is accelerated
Four factors control how much of your model reaches the accelerator.
Operator support
Every delegate supports a fixed list of operators and versions. Standard convolutions, depthwise convolutions, pooling, and ReLU are widely supported. Newer or unusual operators are often not. Examples are custom activations, dynamic shapes, some resize modes, and non-maximum suppression in detection heads.
Data type
NPUs and DSPs often accept only int8 or uint8 models, as the Edge TPU does. Mobile GPUs prefer float16. Running the wrong type usually means a fallback or an error. This links directly to the quantization chapter: a quantization scheme chosen for accuracy may be one your NPU cannot run. Check the vendor's supported schemes, such as per-channel weights and symmetric versus asymmetric ranges.
Static shapes
Accelerators compile the graph ahead of time. Fixed input shapes, like the 1x3x224x224 export earlier, compile reliably. Dynamic batch or image sizes often force a fallback.
Driver and firmware version
The same model and delegate can behave differently across devices. A phone with an older vendor driver may reject operators that a newer one accepts. The result may also differ numerically by a small amount.
Cold-start cost and caching
Accelerators often compile the graph on first use. This can take hundreds of milliseconds to several seconds. Users see this as a slow first frame.
- Create the interpreter or session once, then reuse it.
- Run a warm-up inference on a background thread before the camera starts.
- Use compilation caches when the runtime offers them, for example the model caching options in TensorFlow Lite's GPU and NNAPI delegates or compiled-model caching in Core ML.
- Keep warm-up out of your benchmark numbers, as the earlier benchmarking code does.
Failure modes
Typical problems:
- Silent fallback. The delegate accepts the model but claims only a few operators. Latency barely improves. Log which nodes were delegated. TensorFlow Lite's benchmark tool and ONNX Runtime's verbose logging both report this.
- Too many partitions. One unsupported operator in the middle of the network splits it in two and adds transfers. Replace or remove that operator, or move it to preprocessing or postprocessing.
- Initialization failure. Some devices reject a delegate at load time. Wrap creation in error handling and fall back to the CPU so the app still works.
- Thermal and power effects. A GPU can be quick at first and then throttle under sustained load. NPUs usually sustain performance with less heat. The later chapter on battery and thermal behavior covers this.
- Device fragmentation. On Android, the same app runs on hundreds of chips. Test on a representative set, and decide by device class which delegate to enable.
A practical selection order
- Start with the CPU path (XNNPACK or the CPU provider) as your baseline and your safe fallback.
- Add the accelerator that matches your platform: Core ML on Apple, a vendor or GPU delegate on Android, TensorRT or CUDA on Jetson.
- Confirm how many operators were delegated.
- Compare outputs and accuracy with the CPU baseline.
- Benchmark median and p95 latency on the real device, after warm-up.
- Keep the accelerator only if it improves both latency (or energy) and accuracy within your limits.
- Ship a fallback path for devices where the delegate fails.
Exercise
Your quantized detector runs on a phone's NPU delegate at nearly the same speed as the CPU. The profiler shows that the model was split into 14 partitions. What is the most likely cause, and what would you try first?
Show answer
One or more unsupported operators, probably in the detection head such as non-maximum suppression or a custom activation, are scattered through the graph. Each one forces a fallback to the CPU and adds copies between processors. First list which nodes were not delegated. Then replace those operators with supported ones, or move them out of the model into postprocessing code, so the NPU gets one or two large partitions.
Exercise
An ONNX Runtime session is created with providers=["QNNExecutionProvider", "CPUExecutionProvider"]. Latency is the same as the CPU-only run. Which call do you use to check what is going on, and what do you expect to see if the NPU is not used?
Show answer
Call session.get_providers(). If the QNN provider could not be loaded, or the build does not include it, the list contains only CPUExecutionProvider. Verbose logging would also show which nodes were assigned to each provider.