Path: blob/master/site/en-snapshot/lite/guide/inference.md
25118 views
TensorFlow Lite inference
The term inference refers to the process of executing a TensorFlow Lite model on-device in order to make predictions based on input data. To perform an inference with a TensorFlow Lite model, you must run it through an interpreter. The TensorFlow Lite interpreter is designed to be lean and fast. The interpreter uses a static graph ordering and a custom (less-dynamic) memory allocator to ensure minimal load, initialization, and execution latency.
This page describes how to access to the TensorFlow Lite interpreter and perform an inference using C++, Java, and Python, plus links to other resources for each supported platform.
[TOC]
Important concepts
TensorFlow Lite inference typically follows the following steps:
Loading a model
You must load the
.tflite
model into memory, which contains the model's execution graph.Transforming data
Raw input data for the model generally does not match the input data format expected by the model. For example, you might need to resize an image or change the image format to be compatible with the model.
Running inference
This step involves using the TensorFlow Lite API to execute the model. It involves a few steps such as building the interpreter, and allocating tensors, as described in the following sections.
Interpreting output
When you receive results from the model inference, you must interpret the tensors in a meaningful way that's useful in your application.
For example, a model might return only a list of probabilities. It's up to you to map the probabilities to relevant categories and present it to your end-user.
Supported platforms
TensorFlow inference APIs are provided for most common mobile/embedded platforms such as Android, iOS and Linux, in multiple programming languages.
In most cases, the API design reflects a preference for performance over ease of use. TensorFlow Lite is designed for fast inference on small devices, so it should be no surprise that the APIs try to avoid unnecessary copies at the expense of convenience. Similarly, consistency with TensorFlow APIs was not an explicit goal and some variance between languages is to be expected.
Across all libraries, the TensorFlow Lite API enables you to load models, feed inputs, and retrieve inference outputs.
Android Platform
On Android, TensorFlow Lite inference can be performed using either Java or C++ APIs. The Java APIs provide convenience and can be used directly within your Android Activity classes. The C++ APIs offer more flexibility and speed, but may require writing JNI wrappers to move data between Java and C++ layers.
See below for details about using C++ and Java, or follow the Android quickstart for a tutorial and example code.
TensorFlow Lite Android wrapper code generator
Note: TensorFlow Lite wrapper code generator is in experimental (beta) phase and it currently only supports Android.
For TensorFlow Lite model enhanced with metadata, developers can use the TensorFlow Lite Android wrapper code generator to create platform specific wrapper code. The wrapper code removes the need to interact directly with ByteBuffer
on Android. Instead, developers can interact with the TensorFlow Lite model with typed objects such as Bitmap
and Rect
. For more information, please refer to the TensorFlow Lite Android wrapper code generator.
iOS Platform
On iOS, TensorFlow Lite is available with native iOS libraries written in Swift and Objective-C. You can also use C API directly in Objective-C codes.
See below for details about using Swift, Objective-C and the C API, or follow the iOS quickstart for a tutorial and example code.
Linux Platform
On Linux platforms (including Raspberry Pi), you can run inferences using TensorFlow Lite APIs available in C++ and Python, as shown in the following sections.
Running a model
Running a TensorFlow Lite model involves a few simple steps:
Load the model into memory.
Build an
Interpreter
based on an existing model.Set input tensor values. (Optionally resize input tensors if the predefined sizes are not desired.)
Invoke inference.
Read output tensor values.
Following sections describe how these steps can be done in each language.
Load and run a model in Java
Platform: Android
The Java API for running an inference with TensorFlow Lite is primarily designed for use with Android, so it's available as an Android library dependency: org.tensorflow:tensorflow-lite
.
In Java, you'll use the Interpreter
class to load a model and drive model inference. In many cases, this may be the only API you need.
You can initialize an Interpreter
using a .tflite
file:
Or with a MappedByteBuffer
:
In both cases, you must provide a valid TensorFlow Lite model or the API throws IllegalArgumentException
. If you use MappedByteBuffer
to initialize an Interpreter
, it must remain unchanged for the whole lifetime of the Interpreter
.
The preferred way to run inference on a model is to use signatures - Available for models converted starting Tensorflow 2.5
The runSignature
method takes three arguments:
Inputs : map for inputs from input name in the signature to an input object.
Outputs : map for output mapping from output name in signature to output data.
Signature Name [optional]: Signature name (Can be left empty if the model has single signature).
Another way to run an inference when the model doesn't have a defined signatures. Simply call Interpreter.run()
. For example:
The run()
method takes only one input and returns only one output. So if your model has multiple inputs or multiple outputs, instead use:
In this case, each entry in inputs
corresponds to an input tensor and map_of_indices_to_outputs
maps indices of output tensors to the corresponding output data.
In both cases, the tensor indices should correspond to the values you gave to the TensorFlow Lite Converter when you created the model. Be aware that the order of tensors in input
must match the order given to the TensorFlow Lite Converter.
The Interpreter
class also provides convenient functions for you to get the index of any model input or output using an operation name:
If opName
is not a valid operation in the model, it throws an IllegalArgumentException
.
Also beware that Interpreter
owns resources. To avoid memory leak, the resources must be released after use by:
For an example project with Java, see the Android image classification sample.
Supported data types (in Java)
To use TensorFlow Lite, the data types of the input and output tensors must be one of the following primitive types:
float
int
long
byte
String
types are also supported, but they are encoded differently than the primitive types. In particular, the shape of a string Tensor dictates the number and arrangement of strings in the Tensor, with each element itself being a variable length string. In this sense, the (byte) size of the Tensor cannot be computed from the shape and type alone, and consequently strings cannot be provided as a single, flat ByteBuffer
argument. You can see some examples in this page.
If other data types, including boxed types like Integer
and Float
, are used, an IllegalArgumentException
will be thrown.
Inputs
Each input should be an array or multi-dimensional array of the supported primitive types, or a raw ByteBuffer
of the appropriate size. If the input is an array or multi-dimensional array, the associated input tensor will be implicitly resized to the array's dimensions at inference time. If the input is a ByteBuffer, the caller should first manually resize the associated input tensor (via Interpreter.resizeInput()
) before running inference.
When using ByteBuffer
, prefer using direct byte buffers, as this allows the Interpreter
to avoid unnecessary copies. If the ByteBuffer
is a direct byte buffer, its order must be ByteOrder.nativeOrder()
. After it is used for a model inference, it must remain unchanged until the model inference is finished.
Outputs
Each output should be an array or multi-dimensional array of the supported primitive types, or a ByteBuffer of the appropriate size. Note that some models have dynamic outputs, where the shape of output tensors can vary depending on the input. There's no straightforward way of handling this with the existing Java inference API, but planned extensions will make this possible.
Load and run a model in Swift
Platform: iOS
The Swift API is available in TensorFlowLiteSwift
Pod from Cocoapods.
First, you need to import TensorFlowLite
module.
Load and run a model in Objective-C
Platform: iOS
The Objective-C API is available in TensorFlowLiteObjC
Pod from Cocoapods.
First, you need to import TensorFlowLite
module.
Using C API in Objective-C code
Currently Objective-C API does not support delegates. In order to use delegates with Objective-C code, you need to directly call underlying C API.
Load and run a model in C++
Platforms: Android, iOS, and Linux
Note: C++ API on iOS is only available when using bazel.
In C++, the model is stored in FlatBufferModel
class. It encapsulates a TensorFlow Lite model and you can build it in a couple of different ways, depending on where the model is stored:
Note: If TensorFlow Lite detects the presence of the Android NNAPI, it will automatically try to use shared memory to store the FlatBufferModel
.
Now that you have the model as a FlatBufferModel
object, you can execute it with an Interpreter
. A single FlatBufferModel
can be used simultaneously by more than one Interpreter
.
Caution: The FlatBufferModel
object must remain valid until all instances of Interpreter
using it have been destroyed.
The important parts of the Interpreter
API are shown in the code snippet below. It should be noted that:
Tensors are represented by integers, in order to avoid string comparisons (and any fixed dependency on string libraries).
An interpreter must not be accessed from concurrent threads.
Memory allocation for input and output tensors must be triggered by calling
AllocateTensors()
right after resizing tensors.
The simplest usage of TensorFlow Lite with C++ looks like this:
For more example code, see minimal.cc
and label_image.cc
.
Load and run a model in Python
Platform: Linux
The Python API for running an inference is provided in the tf.lite
module. From which, you mostly need only tf.lite.Interpreter
to load a model and run an inference.
The following example shows how to use the Python interpreter to load a .tflite
file and run inference with random input data:
This example is recommended if you're converting from SavedModel with a defined SignatureDef. Available starting from TensorFlow 2.5
Another example if the model doesn't have SignatureDefs defined.
As an alternative to loading the model as a pre-converted .tflite
file, you can combine your code with the TensorFlow Lite Converter Python API (tf.lite.TFLiteConverter
), allowing you to convert your Keras model into the TensorFlow Lite format and then run inference:
For more Python sample code, see label_image.py
.
Tip: Run help(tf.lite.Interpreter)
in the Python terminal to get detailed documentation about the interpreter.
Run inference with dynamic shape model
If you want to run a model with dynamic input shape, resize the input shape before running inference. Otherwise, the None
shape in Tensorflow models will be replaced by a placeholder of 1
in TFLite models.
The following examples show how to resize the input shape before running inference in different languages. All the examples assume that the input shape is defined as [1/None, 10]
, and need to be resized to [3, 10]
.
C++ example:
Python example:
Supported operations
TensorFlow Lite supports a subset of TensorFlow operations with some limitations. For full list of operations and limitations see TF Lite Ops page.