Module 13 · Lesson 66 of 98

TFLite and its GPU delegates

Explain how TFLite executes a model, identify the delegate paths available on different targets, and locate CPU work in a mixed execution plan.

  • Beginner to advanced
  • 7 min read
  • 13 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM for the written exercises. No model, GPU, or runtime installation is required.

Your place in the module
By the end you can 3 objectives
  • Trace inference from a FlatBuffers model through the interpreter to output tensors.
  • Distinguish the direct GPU delegate from the Android NNAPI delegate.
  • Identify CPU and GPU execution boundaries from tensor dependencies in a delegated plan.
Video coming soonTFLite and its GPU delegates
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The TensorRT C++ runtime
  • IRuntime deserializes a plan into an ICudaEngine, which creates an IExecutionContext.
  • enqueueV2 receives device addresses indexed by binding for the device-resident execution tensors in the example.
  • Successful submission and successful stream completion are separate checks.
01

How the interpreter runs a model

3 min read

You have TensorRT's native path. Other runtimes reach the same hardware, and this lesson answers how TFLite runs models and what its GPU delegates do.

On embedded Linux, a program can read its model successfully and still fail to initialize GPU execution. Opening a readable model file and getting access to a usable device are separate operations. On systems with a DRM render node, for example, the process needs permission to open that node before it can use the rendering interface it exposes. The kernel documentation describes how these device permissions apply. DRM userspace API

Google now ships this runtime as LiteRT (formerly TensorFlow Lite). This lesson keeps the TFLite name, the .tflite extension and the tflite:: C++ API names. A .tflite file contains a model serialized with FlatBuffers. It records subgraphs, operators, tensor descriptions and buffers for constant data such as weights. An operator record specifies the operation and identifies its input and output tensors. A tensor description includes its element type and shape information. The runtime reads these records to work out which computations produce the values needed by other computations. Your program supplies the actual input values for each inference.

In the native C++ API, tflite::FlatBufferModel::BuildFromFile loads a model, and tflite::InterpreterBuilder constructs an interpreter with an operator resolver. The resolver connects operator codes in the file to runtime implementations. Keep the model alive for as long as the interpreter uses it. A runtime can map model bytes from a file on Linux. Such a mapping makes the file bytes available in the process address space. Tensor storage for inference still has to be prepared by the interpreter. mmap(2)

Once you have an interpreter, read the input tensor descriptions so your program knows what shape and element type to supply. When the model supports resizing and needs a different input shape, call ResizeInputTensor() before preparing tensor storage with AllocateTensors(). Check the result before accessing the input buffers. Fill each input with data in the layout and value range expected by the model. Then call Invoke(), check its result and read the output tensors. With a fixed input shape, you can generally prepare the interpreter once and reuse it for successive inputs. After resizing and reallocating, obtain fresh tensor pointers before using them again.

Think of a camera program that calls inference for each frame. The program converts the image into the form expected by the model before writing the input tensor. The interpreter executes the operators encoded in the model. The program then interprets the returned values, such as class scores. If you change the execution backend, the application still needs to supply the expected input and interpret the same output contract. This division lets you change how operators execute without redesigning the surrounding camera program.

TFLite interpreter lifecycleLoad modelReadFlatBuffersrecordsBuildinterpreterAllocatetensorsFill inputsInvokegraphReadoutputsLoad modelReadFlatBuffersrecordsBuildinterpreterAllocatetensorsFill inputsInvokegraphReadoutputs
The application prepares the interpreter, supplies input values, invokes the graph and reads its outputs.
02

How delegates reach an accelerator

3 min read

The interpreter can run models with CPU kernels. A CPU delegate such as XNNPACK can also supply optimised CPU implementations for operations it supports. Some runtime builds or packages apply CPU delegation by default. For a CPU-only configuration, the important distinction is that execution stays on the CPU, whether individual operators use the interpreter's CPU kernels or a CPU delegate.

A In a native integration that applies an explicit delegate, configure the input shape and apply the delegate before allocating tensors for inference. The C++ interpreter exposes ModifyGraphWithDelegate() for applying it. Check the result of that call, then check allocation and invocation separately. Once set up, the application still calls Invoke() through the interpreter. The delegate handles backend preparation and submits the computation it accepted.

The classic TFLite mobile GPU delegate has Android backends using OpenCL or OpenGL ES compute. OpenCL submits compute kernels, and the OpenGL ES backend uses compute shaders. The backend available to an application depends on the delegate build and the driver on the device. A Vulkan compute path requires a delegate implementation built to target Vulkan. Vulkan support on a board does not add a Vulkan backend to the classic OpenCL or OpenGL ES delegate. On iOS, the direct TFLite GPU delegate uses Metal.

Android's NNAPI delegate uses a different route. It submits supported computation to Android's Neural Networks API, which can dispatch it through a device implementation. Depending on the Android device, its drivers and the configuration, execution can use hardware such as a GPU or a neural accelerator, and a CPU path can also be involved. Selecting NNAPI alone therefore tells you less about which hardware executes the computation than selecting a specific direct GPU backend. Android has deprecated NNAPI since Android 15, so new Android code is steered toward the direct delegates and vendor delegates instead. Android and iOS delegate support describe those platform integrations. For Ubuntu on a Raspberry Pi 4 or 5, start with the capabilities of the Linux runtime build and the APIs provided by the installed driver.

Before enabling GPU execution on a Linux board, identify the delegate included in the runtime you will deploy and the API that delegate actually uses. Then verify that the application can initialize that backend on the target. A GPU capability listed for the board, a backend compiled into the runtime and a backend successfully initialized by your process are three separate facts. The model filename provides none of them.

Mobile delegate pathsAndroiddirect GPUAndroid NNAPIiOS directGPUInterfaceOpenCL orOpenGL ESNNAPIMetalPossiblehardwareGPUGPU,acceleratoror CPUGPURuntimecomponentGPU delegateNNAPIdelegateMetal GPUdelegate
Direct GPU adapters target specific compute APIs, while the Android NNAPI delegate submits to a system interface.
03

Where execution crosses between CPU and GPU

3 min read

GPU operator coverage depends on the delegate and the specific operator instance. The operator name is a useful starting point. The version, tensor types and shapes, or operator parameters can also affect whether the delegate accepts it. When the delegate applies successfully to only some of the graph, the unsupported operators keep their CPU execution path if compatible CPU kernels are registered and no other delegate claims them. This fallback can be silent from the application's point of view. Invoke() can succeed and return normal output even when some operators ran on the CPU. Runtime diagnostics may still report the delegation details. A failure to apply the delegate is a separate setup outcome, and your program should handle the returned error explicitly.

A Consider a straight-line graph with a supported convolution, a CPU-only operation and a second supported convolution. If both convolutions are delegated, the first GPU group produces a tensor the CPU operation must read. The CPU then produces a tensor the second GPU group must read. These two dependencies mark the partition boundaries. For a graph with branches, follow the tensor dependencies. Adjacent operators in a model listing may belong to separate branches and exchange no data.

Mixed execution planGPU groupGPU to CPUFirsttensordependencyCPUoperatorCPU to GPUSecondtensordependencyGPU groupGPU groupGPU to CPUFirsttensordependencyCPUoperatorCPU to GPUSecondtensordependencyGPU group
In this illustrative graph, a CPU operator consumes the first GPU result and supplies an input to the second GPU group.

Depending on the backend and buffer arrangement, a boundary can require waiting for a producer, copying a tensor or converting its layout. Shared physical memory can reduce some copying costs. The consumer still needs the producer's writes to be complete and visible. A CPU operation with very little computation can therefore increase latency if it separates two GPU groups that exchange large tensors with it. A summary showing that most operators were delegated gives no information about the sizes of those tensors or the cost of crossing the boundaries.

To locate partition points, start with the original operator list and record each operator's input and output tensor identifiers. Then inspect the plan after delegate application. In native C++ diagnostics, execution_plan() gives the scheduled node indices, and node_and_registration() lets you inspect the node and its registration at each index. Identify the delegate nodes and the remaining CPU nodes. Inspect their input and output tensor lists and match a producer's output identifier to its consumer's input identifier. Each tensor passed between a delegate node and a CPU node identifies a boundary. A delegate log that reports only the number of replaced nodes or partitions can confirm partial delegation, while the tensor lists tell you where it occurs.

Keep the diagnosis tied to the observed plan. A successful initialization tells you the delegate applied. The plan identifies the operators or groups scheduled for execution. If the graph contains a CPU operation between two GPU groups, use the tensors at its inputs and outputs to explain what must complete before each consumer can proceed. The plan identifies those dependencies even when it carries no information about the time they take.

The next lesson, Quantised TFLite and ONNX Runtime providers, considers how quantised models affect TFLite execution and how ONNX Runtime selects hardware through execution providers. The distinction between loading a model and assigning its operators to a backend carries over to both topics.

Key takeaways

  • A .tflite file describes a model, while the interpreter prepares tensors and executes the graph.
  • The direct GPU delegate needs a compatible backend in the runtime build and a working driver on the target.
  • Android NNAPI can dispatch to different kinds of hardware, while the direct iOS GPU delegate uses Metal.
  • A successful inference can contain CPU operators between GPU partitions.
Reflect
  1. Explain to a colleague, in two sentences: trace inference from a FlatBuffers model through the interpreter to output tensors.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close