Skip to content

Using the NPU with the Mainline Stack#

The i.MX93 and the i.MX8M Plus contain a Neural Processing Unit (NPU) that accelerates the inference of neural networks. This guide shows how to use it with upstream components only, in a custom layer on top of the meta-ked-bsp Yocto BSP (v8, Wrynose).

SoC NPU Kernel driver Mesa driver
i.MX93 Arm Ethos-U65, 256 MACs ethosu (/dev/accel/accel0) ethosu
i.MX8M Plus VeriSilicon VIPNano-SI+ etnaviv, together with the GPU etnaviv

On both SoCs, the software stack is the same:

Component Provided by
Kernel driver upstream Linux
Userspace NPU driver and TensorFlow Lite delegate (libteflon.so) Mesa, from openembedded-core
TensorFlow Lite runtime (tflite_runtime for Python) meta-tensorflow-lite

No NXP components are involved: Mesa compiles the model for the NPU itself, and Linux drives the NPU directly. On the i.MX93, no Vela compiler or Cortex-M33 firmware is needed. On the i.MX8M Plus, no galcore driver or VX delegate is needed.

Proof of Concept

This setup has been tested with a quantized MobileNet V1 on the BL i.MX93 and the BL i.MX8M Plus. The mainline NPU stack is young: expect gaps in operator support and performance, and test your own models carefully.

Prerequisites#

  • A custom repository and layer set up as described in the BSP documentation, chapter "Customization". This guide uses meta-custom and custom.yaml from there.
  • A quantized (uint8 or int8) TensorFlow Lite model. Float models do not run on the NPU.

Build Configuration#

Extend custom.yaml with meta-tensorflow-lite and the packages for the image. On the i.MX93, also include the BSP's Stable Kernel option, which provides the upstream kernel with the NPU driver.

custom.yaml
header:
  version: 15
  includes:
    - repo: meta-ked-bsp
      file: kas/ked-mx93.yml
    - repo: meta-ked-bsp
      file: kas/inc/kernel-stable.yml

repos:
  meta-ked-bsp:
    url: https://git.kontron-electronics.de/sw/ked/meta-ked-bsp.git
    branch: main
    path: layers/meta-ked-bsp
  meta-tensorflow-lite:
    url: https://github.com/NobuoTsukamoto/meta-tensorflow-lite
    path: layers/meta-tensorflow-lite
    # The layer has no Wrynose branch. This is the last revision that
    # supports Wrynose.
    branch: main
    commit: 1fc5d5d68763ded53b11feac20fd65fbc6700f3b
  meta-custom:
    layers:
      layers/meta-custom:

local_conf_header:
  npu: |
    PREFERRED_VERSION_linux-stable = "7.2%"
    IMAGE_INSTALL:append = " npu-demo"

Kernel Version

The NPU driver is upstream since Linux 6.19, but the i.MX93 device tree only describes the NPU since Linux 7.1, so 7.1 is the minimum. The PREFERRED_VERSION line pins the series this guide was tested with. Without it, the build takes the newest stable kernel that the BSP's locked meta-linux-mainline revision provides.

The BSP's default kernel already contains everything the NPU needs: the etnaviv driver supports it since Linux 6.6, and the i.MX8M Plus device tree describes it since Linux 6.8.

custom.yaml
header:
  version: 15
  includes:
    - repo: meta-ked-bsp
      file: kas/ked-mx8mp.yml

repos:
  meta-ked-bsp:
    url: https://git.kontron-electronics.de/sw/ked/meta-ked-bsp.git
    branch: main
    path: layers/meta-ked-bsp
  meta-tensorflow-lite:
    url: https://github.com/NobuoTsukamoto/meta-tensorflow-lite
    path: layers/meta-tensorflow-lite
    # The layer has no Wrynose branch. This is the last revision that
    # supports Wrynose.
    branch: main
    commit: 1fc5d5d68763ded53b11feac20fd65fbc6700f3b
  meta-custom:
    layers:
      layers/meta-custom:

local_conf_header:
  npu: |
    IMAGE_INSTALL:append = " npu-demo"

Network Access during the Build

The meta-tensorflow-lite recipes download additional sources in their do_configure task (CMake FetchContent). They cannot be built offline from a download mirror.

Kernel Configuration#

Enable the NPU driver and the Contiguous Memory Allocator (CMA). The i.MX93 has no IOMMU, so the NPU needs physically contiguous buffers. Already for MobileNet V1, these are larger than the kernel can allocate without CMA.

layers/meta-custom/recipes-kernel/linux/files/npu.cfg
CONFIG_DRM_ACCEL=y
CONFIG_DRM_ACCEL_ARM_ETHOSU=m
CONFIG_CMA=y
CONFIG_DMA_CMA=y
CONFIG_CMA_SIZE_MBYTES=64
layers/meta-custom/recipes-kernel/linux/linux-stable_%.bbappend
FILESEXTRAPATHS:prepend := "${THISDIR}/files:"

KERNEL_CFG_FRAGMENTS_EXTRA:append:mx93 = " file://npu.cfg"

Increase CONFIG_CMA_SIZE_MBYTES for larger models, or when a display also needs contiguous memory.

Nothing to do: the default kernel configuration already enables etnaviv, and the NPU does not need contiguous memory because it has its own MMU.

Layers used for both SoCs

linux-stable only exists in builds with the Stable Kernel option. If meta-custom is also used for builds without it, like the i.MX8M Plus build above, BitBake stops with an error because the append has no recipe. In this case, move the recipes-kernel directory to layers/meta-custom/dynamic-layers/meta-linux-mainline/ and add this to the layer configuration, so that the append is only used when meta-linux-mainline is part of the build:

layers/meta-custom/conf/layer.conf
BBFILES_DYNAMIC += " \
    meta-linux-mainline:${LAYERDIR}/dynamic-layers/meta-linux-mainline/*/*/*.bbappend \
"

Mesa#

Enable Mesa's TensorFlow Lite delegate (teflon) and add the patch below. On the i.MX93, also enable Mesa's NPU driver (ethosu). On the i.MX8M Plus, the NPU is driven by Mesa's etnaviv driver, which the BSP already enables for the GPU.

layers/meta-custom/recipes-graphics/mesa/mesa.bbappend
FILESEXTRAPATHS:prepend := "${THISDIR}/files:"

PACKAGECONFIG:append:mx93 = " ethosu teflon"
PACKAGECONFIG:append:mx8mp = " teflon"

SRC_URI:append:mx93 = " file://0001-teflon-Match-TfLiteRegistration-to-the-TFLite-runtime.patch"
SRC_URI:append:mx8mp = " file://0001-teflon-Match-TfLiteRegistration-to-the-TFLite-runtime.patch"

File Name of the Append

The Mesa recipe in Wrynose is mesa.bb without a version, so the append has to be named mesa.bbappend. A mesa_%.bbappend matches no recipe.

Mesa 26.0 builds the delegate against TensorFlow Lite 2.13 headers. Its TfLiteRegistration structure is smaller than the one of the TensorFlow Lite 2.21 runtime, and part of it is not initialized. The result is a segmentation fault on the first inference on the NPU. The following patch fixes this. Mesa 26.2 and later already contain the tfl_device.c part.

0001-teflon-Match-TfLiteRegistration-to-the-TFLite-runtime.patch
layers/meta-custom/recipes-graphics/mesa/files/0001-teflon-Match-TfLiteRegistration-to-the-TFLite-runtime.patch
From: Frieder Schrempf <frieder.schrempf@kontron.de>
Subject: [PATCH] teflon: Match TfLiteRegistration to the TFLite runtime

TfLiteRegistration is handed to ReplaceNodeSubsetsWithDelegateKernels() by
value, so its layout must match the runtime's. The vendored headers are from
TensorFlow 2.13, but TFLite 2.14+ appends 'inplace_operator', which the arena
planner reads to decide whether a node's input and output may share memory.
The runtime therefore read 8 bytes past Teflon's struct, and 'async_kernel'
was never initialized at all.

Zero the struct (backport of upstream 924ccc2f6c8e, in Mesa 26.2) and add the
missing field to the vendored header so the runtime reads 0
(kTfLiteInplaceOpNone).

Upstream-Status: Pending [tfl_device.c part is upstream as 924ccc2f6c8e]
Signed-off-by: Frieder Schrempf <frieder.schrempf@kontron.de>
---
diff -ru a/include/tensorflow/lite/core/c/common.h b/include/tensorflow/lite/core/c/common.h
--- a/include/tensorflow/lite/core/c/common.h
+++ b/include/tensorflow/lite/core/c/common.h
@@ -976,6 +976,10 @@
   // does not support asynchronous execution for this `node`.
   struct TfLiteAsyncKernel* (*async_kernel)(TfLiteContext* context,
                                             TfLiteNode* node);
+
+  // Indicates if an operator's output may safely overwrite its inputs.
+  // See the comments in `TfLiteInPlaceOp`.
+  uint64_t inplace_operator;
 } TfLiteRegistration;

 /// \private
diff -ru a/src/gallium/frontends/teflon/tfl_device.c b/src/gallium/frontends/teflon/tfl_device.c
--- a/src/gallium/frontends/teflon/tfl_device.c
+++ b/src/gallium/frontends/teflon/tfl_device.c
@@ -813,17 +813,15 @@
    }
    supported_nodes->size = node_count;

-   TfLiteRegistration registration;
+   TfLiteRegistration registration = {};

    registration.init = partition_init;
    registration.free = partition_free;
    registration.prepare = partition_prepare;
    registration.invoke = partition_invoke;

-   registration.profiling_string = NULL;
    registration.builtin_code = kTfLiteBuiltinDelegate;
    registration.version = 1;
-   registration.registration_external = NULL;
    registration.custom_name = "Teflon Delegate";

    // Replace supported subgraphs.

Demo Application#

The demo classifies an image with a quantized MobileNet V1, first on the CPU and then on the NPU, and prints the top five results and the inference times of both.

layers/meta-custom/recipes-demo/npu-demo/npu-demo_1.0.bb
SUMMARY = "Image classification demo on the NPU via the mainline stack"
LICENSE = "MIT & Apache-2.0"
LIC_FILES_CHKSUM = " \
    file://${COREBASE}/meta/files/common-licenses/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302 \
    file://${COREBASE}/meta/files/common-licenses/Apache-2.0;md5=89aea4e17d99a7cacdbeed46a0096b10 \
"

SRC_URI = " \
    file://npu-demo.py \
    https://storage.googleapis.com/download.tensorflow.org/models/tflite/mobilenet_v1_1.0_224_quant_and_labels.zip;name=model;subdir=model \
    https://raw.githubusercontent.com/tensorflow/tensorflow/a481b10260dfdf833a1b16007eead49c1d7febf3/tensorflow/lite/examples/label_image/testdata/grace_hopper.bmp;name=image \
"
SRC_URI[model.sha256sum] = "2f8054076cf655e1a73778a49bd8fd0306d32b290b7e576dda9574f00f186c0f"
SRC_URI[image.sha256sum] = "8c1165a143b3ac5c37fba13a918101133d549d3419c7fc474ae70a2f29263b80"

S = "${UNPACKDIR}"

PACKAGE_ARCH = "${MACHINE_ARCH}"

do_install() {
    install -D -m 0755 ${UNPACKDIR}/npu-demo.py ${D}${bindir}/npu-demo
    install -d ${D}${datadir}/npu-demo
    install -m 0644 ${UNPACKDIR}/model/mobilenet_v1_1.0_224_quant.tflite \
        ${UNPACKDIR}/model/labels_mobilenet_quant_v1_224.txt \
        ${UNPACKDIR}/grace_hopper.bmp \
        ${D}${datadir}/npu-demo/
}

RDEPENDS:${PN} = " \
    libteflon \
    python3-core \
    python3-numpy \
    python3-pillow \
    python3-tensorflow-lite \
"
# The etnaviv driver of the i.MX8M Plus is built into the kernel.
RRECOMMENDS:${PN}:mx93 = "kernel-module-ethosu"
npu-demo.py
layers/meta-custom/recipes-demo/npu-demo/files/npu-demo.py
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT

"""Classify an image with MobileNet V1, on the CPU and on the NPU."""

import argparse
import time

import numpy as np
from PIL import Image
import tflite_runtime.interpreter as tflite

DATADIR = "/usr/share/npu-demo"


def classify(model, image, labels, delegate, runs):
    delegates = [tflite.load_delegate(delegate)] if delegate else None
    interpreter = tflite.Interpreter(model_path=model,
                                     experimental_delegates=delegates)
    interpreter.allocate_tensors()

    inp = interpreter.get_input_details()[0]
    out = interpreter.get_output_details()[0]
    _, height, width, _ = inp["shape"]
    img = Image.open(image).convert("RGB").resize((width, height))
    interpreter.set_tensor(inp["index"],
                           np.expand_dims(np.asarray(img, dtype=inp["dtype"]), 0))

    # The NPU graph is compiled in allocate_tensors(), so time a warm-up
    # run separately.
    start = time.monotonic()
    interpreter.invoke()
    first = time.monotonic() - start

    start = time.monotonic()
    for _ in range(runs):
        interpreter.invoke()
    average = (time.monotonic() - start) / runs

    scale, zero_point = out["quantization"]
    scores = (np.squeeze(interpreter.get_tensor(out["index"])).astype(np.float32)
              - zero_point) * scale
    top = scores.argsort()[-5:][::-1]
    return [(scores[i], labels[i]) for i in top], first, average


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("-i", "--image", default=f"{DATADIR}/grace_hopper.bmp")
    parser.add_argument("-m", "--model",
                        default=f"{DATADIR}/mobilenet_v1_1.0_224_quant.tflite")
    parser.add_argument("-l", "--labels",
                        default=f"{DATADIR}/labels_mobilenet_quant_v1_224.txt")
    parser.add_argument("-e", "--delegate", default="/usr/lib/libteflon.so",
                        help="external delegate for the NPU run")
    parser.add_argument("-n", "--runs", type=int, default=20,
                        help="timed invocations per backend")
    parser.add_argument("--npu-only", action="store_true",
                        help="skip the CPU reference run")
    args = parser.parse_args()

    with open(args.labels) as f:
        labels = [line.strip() for line in f]

    backends = [("NPU", args.delegate)]
    if not args.npu_only:
        backends.insert(0, ("CPU", None))

    for name, delegate in backends:
        results, first, average = classify(args.model, args.image, labels,
                                           delegate, args.runs)
        print(f"== {name}: first run {first * 1000:.1f} ms, "
              f"average {average * 1000:.2f} ms over {args.runs} runs")
        for score, label in results:
            print(f"   {score:.3f}  {label}")


if __name__ == "__main__":
    main()

Build the image with kas-container build custom.yaml and flash it as described in Getting Started for the i.MX93 or the i.MX8M Plus.

Running the Demo#

Check the NPU Driver#

Check that the ethosu driver is loaded and that CMA memory is available:

root@kontron-mx93:~# dmesg | grep ethosu
[    7.546741] ethosu 4a900000.npu: Ethos-U NPU, arch v1.0.6, rev r0p0, cmd stream ver0, 256 MACs, 96KB SRAM
[    7.600678] [drm] Initialized ethosu 1.0.0 for 4a900000.npu on minor 0
root@kontron-mx93:~# grep CmaTotal /proc/meminfo

CmaTotal should show the size configured in npu.cfg.

Check that etnaviv has bound the NPU (38500000.npu) next to the two GPU cores:

root@kontron-mx8mp:~# dmesg | grep etnaviv
[    2.049471] etnaviv etnaviv: bound 38000000.gpu (ops 0xffff800080e4e830)
[    2.056373] etnaviv etnaviv: bound 38008000.gpu (ops 0xffff800080e4e830)
[    2.063230] etnaviv etnaviv: bound 38500000.npu (ops 0xffff800080e4e830)
[    2.070030] etnaviv-gpu 38000000.gpu: model: GC7000, revision: 6204
[    2.076428] etnaviv-gpu 38008000.gpu: model: GC520, revision: 5341
[    2.082729] etnaviv-gpu 38500000.npu: model: GC8000, revision: 8002
[    2.089051] etnaviv-gpu 38500000.npu: etnaviv has been instantiated on a NPU, for which the UAPI is still experimental
[    2.100107] [drm] Initialized etnaviv 1.4.0 for etnaviv on minor 0

The warning about the experimental UAPI is expected.

Run the Demo#

root@kontron-mx93:~# npu-demo
INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
== CPU: first run 133.6 ms, average 124.10 ms over 20 runs
   0.855  military uniform
   0.035  Windsor tie
   0.016  mortarboard
   0.008  academic gown
   0.008  bulletproof vest
== NPU: first run 6.3 ms, average 5.01 ms over 20 runs
   0.852  military uniform
   0.035  Windsor tie
   0.016  mortarboard
   0.012  bulletproof vest
   0.008  bow tie
root@kontron-mx8mp:~# npu-demo
INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
== CPU: first run 136.9 ms, average 132.32 ms over 20 runs
   0.855  military uniform
   0.035  Windsor tie
   0.016  mortarboard
   0.008  academic gown
   0.008  bulletproof vest
== NPU: first run 8.2 ms, average 7.54 ms over 20 runs
   0.867  military uniform
   0.031  Windsor tie
   0.012  mortarboard
   0.008  bow tie
   0.008  bulletproof vest
SoC CPU (XNNPACK) NPU Speed-up
i.MX93 124 ms 5.0 ms about 25 ×
i.MX8M Plus 132 ms 7.5 ms about 17 ×

The NPU returns the same classes with nearly the same scores as the CPU. The scores differ slightly because the NPU computes with its own integer arithmetic.

Before the first inference, Mesa compiles the model for the NPU. This takes about 3 seconds for MobileNet V1, while the interpreter is being set up (allocate_tensors()), so it does not show up in the timings. Create the interpreter once and reuse it for all inferences.

The runtime prints a warning that tf.lite.Interpreter is deprecated in favour of LiteRT. It can be ignored.

Running your own Application#

An application uses the NPU by loading libteflon.so as a TensorFlow Lite external delegate. In Python:

import tflite_runtime.interpreter as tflite

delegate = tflite.load_delegate("/usr/lib/libteflon.so")
interpreter = tflite.Interpreter(model_path="model.tflite",
                                 experimental_delegates=[delegate])

In C++, the TensorFlow Lite label_image and benchmark_model tools do the same with --external_delegate_path=/usr/lib/libteflon.so. Your own C++ application uses TfLiteExternalDelegateCreate() from tensorflow/lite/delegates/external/external_delegate.h.

For the recipe of your application, take the demo recipe as a template:

  • RDEPENDS on libteflon, plus python3-tensorflow-lite for Python, or DEPENDS on libtensorflow-lite for C++,
  • on the i.MX93, RRECOMMENDS on kernel-module-ethosu,
  • add it to IMAGE_INSTALL in custom.yaml.

Operations that the NPU does not support stay on the CPU. To see which operations of a model run on the NPU, set TEFLON_DEBUG=verbose:

root@kontron-mx93:~# TEFLON_DEBUG=verbose npu-demo --npu-only

The first table lists each operation of the model with supported or unsupported. For MobileNet V1, 29 of 31 operations run on the NPU on both SoCs, but not the same ones:

The final RESHAPE and SOFTMAX stay on the CPU:

 28 CONV            v1  supported   in: 0(u8) 3(u8) 2(i32) out: 1(u8)
 29 RESHAPE         v1  unsupported in: 1(u8) 5(i32) out: 4(u8)
 30 SOFTMAX         v1  unsupported in: 4(u8) out: 87(u8)

AVGPOOL and the final SOFTMAX stay on the CPU:

 26 CONV            v1  supported   in: 27(u8) 32(u8) 30(i32) out: 31(u8)
 27 AVGPOOL         v1  unsupported in: 31(u8) out: 0(u8)
 28 CONV            v1  supported   in: 0(u8) 3(u8) 2(i32) out: 1(u8)
 29 RESHAPE         v1  supported   in: 1(u8) 5(i32) out: 4(u8)
 30 SOFTMAX         v1  unsupported in: 4(u8) out: 87(u8)

Because AVGPOOL sits in the middle of the model, Mesa compiles two NPU graphs, one before and one after it. Each inference hands over between NPU and CPU three times instead of once. The log shows one teflon: invoked graph line per graph.

Each switch between NPU and CPU costs time. Models whose unsupported operations are only at the beginning or end benefit most.

Troubleshooting#

Symptom Cause
Failed to load delegate from /usr/lib/libteflon.so No NPU device. On the i.MX93, check that ethosu is loaded and /dev/accel/accel0 exists. On the i.MX8M Plus, check that etnaviv has bound 38500000.npu.
Segmentation fault on the first inference on the NPU, dmesg shows nothing The Mesa patch is missing. On the i.MX93, also check for missing CMA (CmaTotal absent or too small).
The NPU result is no faster than the CPU result The model is not quantized, or most of its operations are unsupported. Check with TEFLON_DEBUG=verbose.