# Teflon

Use LiteRT (TensorFlow Lite) with the Open Inference Stack.


To use LiteRT (formerly known as TensorFlow Lite) with the Open Inference Stack,
you effectively use it just like you normally would, with minor adaptations to
use the Teflon delegate. Teflon is part of
[Mesa](https://docs.mesa3d.org/teflon.html) and works the same on every NPU Mesa
supports, so your application code does not change from one board to the next.

## What Teflon does

LiteRT can hand parts of a model to a *delegate*, a plugin that runs them on an
accelerator. Teflon is an external delegate that RTLite loads at runtime.

When the model is loaded, Teflon looks at each operation and asks Mesa whether
your NPU can run it. Supported operations such as convolutions are compiled for
the NPU. Everything else gets run on the CPU, and RTLite moves data between the
two automatically.

## Using Teflon

Because we are using LiteRT's standard external delegate system, there isn't
much to document here: you just use LiteRT in the normal way.

As an example, let's follow the
[LiteRT Getting Started guide](https://developers.google.com/edge/litert/overview)
on a system with the Open Inference Stack available. We'll highlight the two
points of deviation below.

### Setup

The first step is to install the package:

```sh
pip install ai-edge-litert
```

In the "Obtain a model" step, here instead of using the standard MobileNetV2
image suggested by the LiteRT guide, we use a quantized (int8) version instead.
The model used in the Getting Started guide uses float32 operations which are
typically not supported by our target NPUs.

The guide's "Obtain a model" step downloads a float32 MobileNetV2. Most NPUs
supported by the stack only run quantized (integer) operations, so a float32
model would run entirely on the CPU. Here we download a quantized (int8)
MobileNetV2 instead:

```sh
curl -L -o mobilenet_v2_quant.tgz \
  https://storage.googleapis.com/download.tensorflow.org/models/tflite_11_05_08/mobilenet_v2_1.0_224_quant.tgz
tar xzf mobilenet_v2_quant.tgz mobilenet_v2_1.0_224_quant.tflite
```

### Test LiteRT on CPU

In the following step, adjust the example app to use the int8 model filename
from the above download:

```python
# Platform: Linux, macOS, Windows • Accelerators: CPU / GPU / NPU
import numpy as np
from ai_edge_litert.compiled_model import CompiledModel, HardwareAccelerator

# 1. Load model and compile for target accelerator (CPU / GPU / NPU)
model = CompiledModel.from_file("mobilenet_v2_1.0_224_quant.tflite", HardwareAccelerator.CPU)

# 2. Preallocate input and output memory buffers
input_buffers = model.create_input_buffers(0)
output_buffers = model.create_output_buffers(0)

# 3. Populate input buffer with test tensor (1x3x224x224 float32 for MobileNetV2)
input_data = np.zeros((1, 3, 224, 224), dtype=np.float32)
input_buffers[0].write(input_data)

# 4. Execute on-device inference
model.run_by_index(0, input_buffers, output_buffers)

# 5. Read output tensor and inspect classification logits (1,000 ImageNet classes)
output = output_buffers[0].read(1000, np.float32)
top_class = np.argmax(output)
print("LiteRT Python inference completed successfully!")
print(f"Output shape: {output.shape}")
print(f"Top predicted class index: {top_class}, score: {output[top_class]:.4f}")
```

Run the above example app to confirm that LiteRT is operational running on the
CPU before you proceed further.

### Adapt example for NPU

The quick start switches backends by changing the accelerator passed to
`CompiledModel`. **That doesn't work for Teflon.**

To use Teflon, we need to adapt the example to use the `Interpreter` API, which
has been done for you below:

```python
import numpy as np
from ai_edge_litert.interpreter import Interpreter, load_delegate

# 1. Load the model and apply the Teflon delegate
model = Interpreter(model_path="mobilenet_v2_1.0_224_quant.tflite",
                    experimental_delegates=[load_delegate("/usr/lib/teflon/libteflon.so")])

# 2. Preallocate input and output memory buffers
model.allocate_tensors()
inp = model.get_input_details()[0]
out = model.get_output_details()[0]

# 3. Populate input buffer with test tensor (shape and type come from the model)
input_data = np.zeros(inp["shape"], dtype=inp["dtype"])
model.set_tensor(inp["index"], input_data)

# 4. Execute on-device inference
model.invoke()

# 5. Read output tensor and inspect classification logits (1,000 ImageNet classes)
output = model.get_tensor(out["index"]).reshape(-1)
top_class = np.argmax(output)
print("LiteRT Python inference completed successfully!")
print(f"Output shape: {output.shape}")
print(f"Top predicted class index: {top_class}, score: {output[top_class]}")
```

## Tips and Tricks

### Checking for accelerated operations

In the above example, if we had stuck with the float32 model suggested by the
Getting Started guide, the example would have run all the operations on the CPU
even though we made Teflon available.

To check on Teflon's behaviour here, run it against the float32 model with
Teflon's operation log turned on:

```sh
TEFLON_DEBUG=verbose python3 quickstart.py
```

The log shows that Teflon found the NPU, and that it rejected the model's
operations:

```text
Teflon delegate: loaded ethosu driver
idx type            ver support     inputs
================================================================================================
  0 TRANSPOSE       v1  unsupported in: 0(f32) 108(i32) out: 110(f32)
  1 PAD             v1  unsupported in: 110(f32) 107(i32) out: 111(f32)
  2 CONV            v1  unsupported in: 111(f32) 93(f32) 41(f32) out: 112(f32) ReLU6
```

Whereas when we run it with the int8 model, every operation is `supported`,
e.g.:

```text
  0 CONV            v1  supported   in: 171(u8) 2(u8) 0(i32) out: 1(u8)
  1 DWCONV          v1  supported   in: 1(u8) 13(u8) 12(i32) out: 11(u8)
```

### Quantizing a float TFLite model

Like the case we saw above, `.tflite` models that are in float format typically
need to be quantized before an NPU can run them.
[LiteRT Quantizer](https://github.com/google-ai-edge/LiteRT/tree/main/litert_quantizer)
can be used in this situation, which additionally requires a
*representative dataset* (a collection of typical inputs) as part of the
calibration process.

As an example, let's take the
[CustomCNN-5Blocks-PlantDiseaseDetection](https://huggingface.co/buildxsomnath/CustomCNN-5Blocks-PlantDiseaseDetection)
model, which classifies photos of leaves into 38 plant diseases. It ships a
float32 `.tflite` file and was trained on
[plantDiseaseDataset](https://huggingface.co/datasets/buildxsomnath/plantDiseaseDataset).

Here is the quantization script, knowing that the model was trained against
224x224 RGB images scaled from 0..255 to 0..1.

```python
import random
from pathlib import Path
import numpy as np
from huggingface_hub import HfApi, snapshot_download
from litert_quantizer import calibrator, quantizer
from PIL import Image

DATASET_REPO = "buildxsomnath/plantDiseaseDataset"

# Download a random selection of 200 images from the training dataset.
images = [f for f in HfApi().list_repo_files(DATASET_REPO, repo_type="dataset")
          if f.lower().endswith(".jpg")]
images = random.sample(images, 200)
dataset_dir = Path(snapshot_download(DATASET_REPO, repo_type="dataset",
                                     allow_patterns=images))

def preprocess(path):
    img = Image.open(path).convert("RGB").resize((224, 224))
    return np.asarray(img, dtype=np.float32)[np.newaxis] / 255

qt = quantizer.Quantizer("plant_disease_model_custom_cnn_5blocks.tflite")
qt.load_quantization_recipe("static_wi8_ai8")
calibration_data = {
    "serving_default": [{"input_1": preprocess(dataset_dir / f)} for f in images]
}
result = qt.calibrate(calibration_data,
                      mode=calibrator.CalibrationMode.CALIBRATION_PROFILER_BASED)
qt.quantize(result).export_model("plant_disease_int8.tflite")
```

The resultant model can now be used with Teflon:

```python
import sys
import numpy as np
from ai_edge_litert.interpreter import Interpreter, load_delegate
from PIL import Image

# The class names, in output order, are the first column of the report
report = open("classification_report_custom_cnn_5blocks.txt").read().splitlines()
labels = [line.rsplit(maxsplit=4)[0].strip() for line in report[2:40]]

interpreter = Interpreter(model_path="plant_disease_int8.tflite",
                          experimental_delegates=[load_delegate("/usr/lib/teflon/libteflon.so")])
interpreter.allocate_tensors()
inp = interpreter.get_input_details()[0]
out = interpreter.get_output_details()[0]

# Same preprocessing as for the representative dataset
img = Image.open(sys.argv[1]).convert("RGB").resize((224, 224))
x = np.asarray(img, dtype=np.float32)[np.newaxis] / 255

# Quantize the input to int8 using the scale and zero point from the model
scale, zero_point = inp["quantization"]
x = np.clip(np.round(x / scale + zero_point), -128, 127).astype(np.int8)
interpreter.set_tensor(inp["index"], x)
interpreter.invoke()

# Dequantize the output back to probabilities
scale, zero_point = out["quantization"]
probs = (interpreter.get_tensor(out["index"])[0].astype(np.float32) - zero_point) * scale
for i in np.argsort(probs)[::-1][:3]:
    print(f"{probs[i]:6.1%}  {labels[i]}")
```

Testing on
[this photo of bacterial leaf spot on a pepper plant](https://commons.wikimedia.org/wiki/File:Bacterial_leaf_spot_of_pepper_(Capsicum_sp.)_(43614805831).jpg)
(not part of the training data) yields a correct `Pepper,_bell___Bacterial_spot`
recognition with 95.7% confidence, with each inference taking 11.8ms on Arm
Ethos-U65 compared to 39ms when run on the CPU.

### Converting & quantizing TensorFlow models

If you want to use a
[TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model) with
Teflon, you first need to convert it to a `.tflite` float model using
[TFLiteConverter](https://www.tensorflow.org/api_docs/python/tf/lite/TFLiteConverter),
and then you can follow the quantization instructions above.

As an example, let's take the [HyzeACR](https://huggingface.co/HyzeAI/HyzeACR)
image classifier, which provides its `model.savedmodel` along with a published
[training dataset](https://huggingface.co/datasets/HyzeAI/HyzeACR-Dataset).

Convert the SavedModel to float32 with TensorFlow's converter:

```python
from pathlib import Path
import tensorflow as tf
converter = tf.lite.TFLiteConverter.from_saved_model("model.savedmodel")
Path("hyzeacr_fp32.tflite").write_bytes(converter.convert())
```

Now proceed to follow the above
[tflite quantization steps](#quantizing-a-float-tflite-model) to produce a model
suitable for NPU execution. For this model, set `DATASET_REPO` to
`HyzeAI/HyzeACR-Dataset`, adjust the `calibration_data` to refer to the model's
input as `sequential_1_input`, and preprocess the sample images as follows:

```python
def preprocess(path):
    img = Image.open(path).convert("RGB")
    img = ImageOps.fit(img, (224, 224), Image.Resampling.LANCZOS)
    return np.asarray(img, dtype=np.float32)[np.newaxis] / 127.5 - 1
```

After quantization, the model can be run on the device:

```python
import sys
import numpy as np
from ai_edge_litert.interpreter import Interpreter, load_delegate
from PIL import Image, ImageOps

labels = [line.split(" ", 1)[1] for line in open("labels.txt").read().splitlines()]

interpreter = Interpreter(model_path="hyzeacr_int8.tflite",
                          experimental_delegates=[load_delegate("/usr/lib/teflon/libteflon.so")])
interpreter.allocate_tensors()
inp = interpreter.get_input_details()[0]
out = interpreter.get_output_details()[0]

# Same preprocessing as for the representative dataset
img = Image.open(sys.argv[1]).convert("RGB")
img = ImageOps.fit(img, (224, 224), Image.Resampling.LANCZOS)
x = np.asarray(img, dtype=np.float32)[np.newaxis] / 127.5 - 1

# Quantize the input to int8 using the scale and zero point from the model
scale, zero_point = inp["quantization"]
x = np.clip(np.round(x / scale + zero_point), -128, 127).astype(np.int8)
interpreter.set_tensor(inp["index"], x)
interpreter.invoke()

# Dequantize the output back to probabilities
scale, zero_point = out["quantization"]
probs = (interpreter.get_tensor(out["index"])[0].astype(np.float32) - zero_point) * scale
for i in np.argsort(probs)[::-1][:3]:
    print(f"{probs[i]:6.1%}  {labels[i]}")
```

Testing on a
[Hubble image of the Veil Nebula](https://images.nasa.gov/details/GSFC_20171208_Archive_e000607)
(not part of the training data) yields a correct `Nebulae` recognition with
99.6% confidence. Each inference takes 1.9ms on Arm Ethos-U65 NPU compared to
7.0ms when run on the CPU.

### Converting & quantizing Keras models

If you want to use a Keras model with Teflon, you can convert it to `.tflite`
with
[TFLiteConverter](https://www.tensorflow.org/api_docs/python/tf/lite/TFLiteConverter),
which can also quantize the model to int8 in the same step when given a
representative dataset.

As an example, let's take the
[ball_models](https://huggingface.co/TaiHoag/ball_models) image classifier,
which recognises 7 types of sports ball. Its repository contains the Keras model
`convnet_ball_classification_model.keras` along with the `dataset.zip` it was
trained on. The
[author's application code](https://github.com/emberfox205/ballsports-rental)
shows that it expects 224x224 RGB images scaled from 0..255 to 0..1.

Convert and quantize the model as follows:

```python
import random
import zipfile
from pathlib import Path
import numpy as np
import tensorflow as tf
from huggingface_hub import hf_hub_download
from PIL import Image

REPO = "TaiHoag/ball_models"

model = tf.keras.models.load_model(
    hf_hub_download(REPO, "convnet_ball_classification_model.keras"))

# Extract the training dataset and pick 200 random images from it
with zipfile.ZipFile(hf_hub_download(REPO, "dataset.zip")) as z:
    z.extractall(".")
images = random.sample(sorted(Path("dataset/train").glob("*/*.jpg")), 200)

def preprocess(path):
    img = Image.open(path).convert("RGB").resize((224, 224))
    return np.asarray(img, dtype=np.float32)[np.newaxis] / 255

def representative_dataset():
    for path in images:
        yield [preprocess(path)]

# Convert to TFLite, quantizing weights, activations, input and output to int8
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_dataset
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8
converter.inference_output_type = tf.int8
Path("ball_int8.tflite").write_bytes(converter.convert())
```

The resultant model can now be run on the device:

```python
import sys
import numpy as np
from ai_edge_litert.interpreter import Interpreter, load_delegate
from PIL import Image

LABELS = ["american_football", "baseball", "basketball", "football",
          "table_tennis_ball", "tennis_ball", "volleyball"]

interpreter = Interpreter(model_path="ball_int8.tflite",
                          experimental_delegates=[load_delegate("/usr/lib/teflon/libteflon.so")])
interpreter.allocate_tensors()
inp = interpreter.get_input_details()[0]
out = interpreter.get_output_details()[0]

# Same preprocessing as for the representative dataset
img = Image.open(sys.argv[1]).convert("RGB").resize((224, 224))
x = np.asarray(img, dtype=np.float32)[np.newaxis] / 255

# Quantize the input to int8 using the scale and zero point from the model
scale, zero_point = inp["quantization"]
x = np.clip(np.round(x / scale + zero_point), -128, 127).astype(np.int8)
interpreter.set_tensor(inp["index"], x)
interpreter.invoke()

# Dequantize the output back to probabilities
scale, zero_point = out["quantization"]
probs = (interpreter.get_tensor(out["index"])[0].astype(np.float32) - zero_point) * scale
for i in np.argsort(probs)[::-1][:3]:
    print(f"{probs[i]:6.1%}  {LABELS[i]}")
```

Testing on
[this close-up photo of a tennis ball](https://commons.wikimedia.org/wiki/File:Closeup_of_a_tennis_ball_(2).jpg)
(not part of the training data) yields a correct `tennis_ball` recognition with
99.6% confidence. Each inference takes 9.6ms on Arm Ethos-U65 NPU compared to
30.5ms when run on the CPU.


---
Source: http://model-citizen.ai/getting-started/teflon/
