# Torx

Use PyTorch models through ExecuTorch with the Open Inference Stack.


To run PyTorch models on the Open Inference Stack, you use
[ExecuTorch](https://docs.pytorch.org/executorch/), PyTorch's framework for
on-device inference, just like you normally would, with minor adaptations to use
the **Torx** delegate. Torx is part of [Mesa](https://docs.mesa3d.org/torx.html)
since version 26.3.

> [!NOTE]
> Torx currently only supports Arm Ethos-U NPUs. Support for other NPUs will be
> added soon.

## What Torx does

ExecuTorch hands parts of a model to *backends* that run them on an accelerator.
Torx is the ExecuTorch backend for the NPUs supported by Mesa.

Unlike [Teflon](/getting-started/teflon/), which compiles a model for the NPU
when it is loaded, ExecuTorch backends do their work when you *export* the
model. Torx's partitioner asks Mesa which operations can be run on the target
NPU, and Mesa compiles those. The result is saved in the `.pte` file together
with the rest of the model, which runs on the CPU. On the device, ExecuTorch's
runtime then passes the NPU parts to Mesa to execute.

## Using Torx

As an example, let's follow the
[ExecuTorch Getting Started guide](https://docs.pytorch.org/executorch/stable/getting-started.html)
on a system with the Open Inference Stack available. We'll highlight the points
of deviation below.

### Setup

We assume Mesa 26.3 or later is installed with Torx enabled, built against
ExecuTorch 1.6.0. Mesa then provides `libtorx.so`, which the ExecuTorch runtime
uses to run models on the NPU, and the `torx` Python package used to export
models.

When installing ExecuTorch and PyTorch, you must match the versions which
Mesa/Torx was built against, and you must ensure that ExecuTorch can see the
`torx` package from your Mesa installation. If following the guide, this means
setting up the environment something like this:

```sh
python3 -m venv --system-site-packages venv
. venv/bin/activate
pip install executorch==1.6.0 torch==2.15.0 torchvision \
  --index-url https://download.pytorch.org/whl/cpu \
  --extra-index-url https://pypi.org/simple
```

### Test ExecuTorch on CPU

Follow the guide's
[Exporting](https://docs.pytorch.org/executorch/stable/getting-started.html#exporting)
and
[Testing the Model](https://docs.pytorch.org/executorch/stable/getting-started.html#testing-the-model)
steps without changes, to confirm that ExecuTorch is able to correctly run
models on your CPU.

### Adapt the export for the NPU

Two changes are needed to the export example from the guide:

1. The NPUs supported by the stack typically only run integer operations, so the
   export needs to *quantize* the model to int8. Quantization requires some
   representative inputs (i.e. sample images).
1. We need to tell ExecuTorch to use Torx to partition and compile the relevant
   parts of the model for a selected NPU.

First, download and extract
[imagenette2-160.tgz](https://s3.amazonaws.com/fast-ai-imageclas/imagenette2-160.tgz).
We'll provide the quantization with random images from this Imagenette
collection (a subset of the dataset that the model was originally trained on).

Next, we need to extend the guide's export example code to include this
quantization step, and we must also tell it to use Torx for partitioning and
compilation. The adapted export code is shown below:

```python
import glob, random
import torch
import torchvision.models as models
from PIL import Image
from torchvision.models.mobilenetv2 import MobileNet_V2_Weights
from torchao.quantization.pt2e.quantize_pt2e import prepare_pt2e, convert_pt2e
from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner
from executorch.exir import to_edge_transform_and_lower
from torx import TorxPartitioner, TorxQuantizer

weights = MobileNet_V2_Weights.DEFAULT
model = models.mobilenetv2.mobilenet_v2(weights=weights).eval()
sample_inputs = (torch.randn(1, 3, 224, 224), )

# Quantize the model to int8, calibrating with 100 sample images
model = prepare_pt2e(torch.export.export(model, sample_inputs).module(), TorxQuantizer())
preprocess = weights.transforms()
for path in random.sample(glob.glob("imagenette2-160/train/*/*.JPEG"), 100):
    model(preprocess(Image.open(path).convert("RGB")).unsqueeze(0))
model = convert_pt2e(model)

# Run what the NPU supports with Torx, and the rest with XNNPACK on the CPU
et_program = to_edge_transform_and_lower(
    torch.export.export(model, sample_inputs),
    partitioner=[TorxPartitioner(), XnnpackPartitioner()]
).to_executorch()

with open("model_npu.pte", "wb") as f:
    f.write(et_program.buffer)
```

Before we run this, we need to select the specific NPU target for compilation.
During partitioning/compilation, Torx does not look at the NPU (if any) on the
current system, since the expectation is that you'll be preparing the model on a
powerful machine before exporting it to your embedded device where the NPU is
present. We must select the target NPU via the `MESA_ML_DEVICE` environment
variable.

`MESA_ML_DEVICE` has the form `ethosu-<generation>-<MACs>-<SRAM bytes>`:

* **Generation**: `65` for an Ethos-U65, `85` for an Ethos-U85.
* **MACs**: the number of multiply-accumulate units. Mesa currently only
  supports the 256-MAC configuration.
* **SRAM bytes**: the size of the SRAM the NPU uses for intermediate data, in
  bytes. The Linux driver prints it when it loads:

  ```console
  $ dmesg | grep ethosu
  ethosu 4a900000.npu: Ethos-U NPU, [...], 256 MACs, 96KB SRAM
  ```

For the Ethos-U65 NPU on the [FRDM i.MX 93 board](/getting-started/frdm-imx93/),
here is the required value:

```sh
MESA_ML_DEVICE=ethosu-65-256-98304 python export_npu.py
```

The resultant `model_npu.pte` compiled model is now ready to be transferred to
the target device.

> [!TIP]
> If you're not sure which `MESA_ML_DEVICE` value to use, you can also compile a
> model for any NPU and then try to load it on the target device. The resultant
> error message will indicate the correct value to use. For example:
> `TorxBackend: Mismatched device id, expected ethosu-65-256-98304 got ethosu-65-256-0`.`

### Adapt the test for the NPU

Now you can run the model on the target device using ExecuTorch in the normal
way, using any of the available runtimes. Just one step is needed for Torx to be
used: `libtorx.so` must be loaded.

Here's an example using the Python runtime that loads Torx and feeds a given
image to the model:

```python
import ctypes
from PIL import Image
from executorch.runtime import Runtime
from torchvision.models.mobilenetv2 import MobileNet_V2_Weights

# Register the Torx backend with the ExecuTorch runtime
ctypes.CDLL("libtorx.so")

runtime = Runtime.get()
program = runtime.load_program("model_npu.pte")
method = program.load_method("forward")

# Same preprocessing as for the calibration images
weights = MobileNet_V2_Weights.DEFAULT
input_tensor = weights.transforms()(Image.open("dog.jpg")).unsqueeze(0)
output = method.execute([input_tensor])
print("Run successfully via executorch")

probabilities = output[0].softmax(-1)[0]
for p, i in zip(*probabilities.topk(3)):
    print(f"{p:.1%} {weights.meta['categories'][i]}")
```

Testing this on
[a photo of a Samoyed](https://commons.wikimedia.org/wiki/File:Samoyed_dog_two_year_old_female_dllu.jpg)
(not part of the training data) yields a correct classification of `Samoyed`. On
the FRDM i.MX 93 board, the NPU version takes about 8 ms per inference, against
about 76 ms for the guide's float32 model on the CPU.

## Tips and Tricks

### Checking which operations run on the NPU

In the example above, Torx runs most of the model on the NPU and XNNPACK runs
the rest on the CPU. To see how a model was split between them, keep the result
of `to_edge_transform_and_lower()` in the export script, and list the operations
each backend received before calling `to_executorch()`:

```python
from collections import Counter
from executorch.devtools.backend_debug import get_delegation_info
from executorch.exir.lowered_backend_module import get_lowered_submodules

edge = to_edge_transform_and_lower(
    torch.export.export(model, sample_inputs),
    partitioner=[TorxPartitioner(), XnnpackPartitioner()]
)

graph_module = edge.exported_program().graph_module
for _, module, _ in get_lowered_submodules(graph_module):
    print(module.backend_id)
    ops = Counter(n.target.__name__ for n in module.original_module.graph.nodes if n.op == "call_function")
    for op, count in ops.items():
        print(f"  {count:3d} {op}")
print(get_delegation_info(graph_module).get_summary())

et_program = edge.to_executorch()
```

For MobileNetV2, this prints:

```text
XnnpackBackend
    1 quantized_decomposed.quantize_per_tensor.default
TorxBackend
  104 quantized_decomposed.dequantize_per_channel.default
   72 quantized_decomposed.dequantize_per_tensor.default
   52 aten.convolution.default
   35 aten.hardtanh.default
   62 quantized_decomposed.quantize_per_tensor.default
   10 aten.add.Tensor
XnnpackBackend
    2 quantized_decomposed.dequantize_per_tensor.default
    1 aten.mean.dim
    1 aten.view_copy.default
    1 aten.permute_copy.default
    1 aten.addmm.default
    1 quantized_decomposed.quantize_per_tensor.default
Total delegated subgraphs: 3
Number of delegated nodes: 343
Number of non-delegated nodes: 3
```

This shows that the model is run in three parts:

1. XNNPACK converts the float input image to int8.
2. Torx runs all the convolutions, ReLU6 activations (`hardtanh`) and additions
   on the NPU.
3. XNNPACK runs the classifier at the end: average pooling (`mean`) and the
   final linear layer (`addmm`).

We can also see that there were 3 non-delegated nodes (operations that no
backend accepted). These run on ExecuTorch's slower CPU kernels. Refer to
[Debugging Delegation](https://docs.pytorch.org/executorch/stable/debug-backend-delegate.html)
for more info.

### Using a model from Hugging Face

Many models on [Hugging Face](https://huggingface.co/) are PyTorch models with
their weights stored in `.safetensors` files. These must be combined with some
application code that defines the model.

As an example, let's take
[resnet-50-finetuned-oxfordflowers](https://huggingface.co/anh-dangminh/resnet-50-finetuned-oxfordflowers),
a flower recognition model, which uses the `ResNetForImageClassification`
application code from the Transformers library. We'll use its
[training dataset](https://huggingface.co/datasets/dpdl-benchmark/oxford_flowers102)
for quantization.

First, install Transformers and Hugging Face's datasets library:

```sh
pip install transformers datasets
```

We adapt the export script to use those two libraries to download the model from
Hugging Face, hook it up to the appropriate ResNet code, and fetch and
preprocess sample images for quantization as specified by configuration files in
the model's repository:

```python
import torch
from datasets import load_dataset
from transformers import AutoImageProcessor, AutoModelForImageClassification
from torchao.quantization.pt2e.quantize_pt2e import prepare_pt2e, convert_pt2e
from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner
from executorch.exir import to_edge_transform_and_lower
from torx import TorxPartitioner, TorxQuantizer

model_id = "anh-dangminh/resnet-50-finetuned-oxfordflowers"
model = AutoModelForImageClassification.from_pretrained(model_id).eval()
processor = AutoImageProcessor.from_pretrained(model_id)
sample_inputs = (torch.randn(1, 3, 224, 224), )

# Quantize the model to int8, calibrating with 100 images from the training dataset
model = prepare_pt2e(torch.export.export(model, sample_inputs).module(), TorxQuantizer())
dataset = load_dataset("dpdl-benchmark/oxford_flowers102", split="train",
                       data_files={"train": "data/train-*.parquet"})
for example in dataset.shuffle().select(range(100)):
    model(processor(example["image"], return_tensors="pt")["pixel_values"])
model = convert_pt2e(model)

et_program = to_edge_transform_and_lower(
    torch.export.export(model, sample_inputs),
    partitioner=[TorxPartitioner(), XnnpackPartitioner()]
).to_executorch()

with open("flowers_npu.pte", "wb") as f:
    f.write(et_program.buffer)
```

Run it with `MESA_ML_DEVICE` set, as before:

```sh
MESA_ML_DEVICE=ethosu-65-256-98304 python export_flowers.py
```

The model can now be run on the device:

```python
import ctypes
from PIL import Image
from transformers import AutoConfig, AutoImageProcessor
from executorch.runtime import Runtime

ctypes.CDLL("libtorx.so")
runtime = Runtime.get()
program = runtime.load_program("flowers_npu.pte")
method = program.load_method("forward")

model_id = "anh-dangminh/resnet-50-finetuned-oxfordflowers"
processor = AutoImageProcessor.from_pretrained(model_id)
input_tensor = processor(Image.open("flower.jpg"), return_tensors="pt")["pixel_values"]
output = method.execute([input_tensor])

labels = AutoConfig.from_pretrained(model_id).id2label
probabilities = output[0].softmax(-1)[0]
for p, i in zip(*probabilities.topk(3)):
    print(f"{p:.1%} {labels[i.item()]}")
```

Testing this on
[a photo of a bird of paradise flower](https://commons.wikimedia.org/wiki/File:Strelitzia_reginae_kz05.jpg)
(not part of the training data) yields a correct `bird of paradise` recognition
with 99.8% confidence. Each inference takes 35 ms on the Arm Ethos-U65 NPU,
compared to 728 ms for the float32 model on the CPU.


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