Check and run an existing PyTorch model
Trace any PyTorch model, see where every layer runs, run it through the toolkit, and find where bfloat16 rounding builds up, without rewriting the model.
Tested on the toolkit 2.4.0 CPU emulator with PyTorch 2.11.0 on 4 November 2026. The notebook ran in 24 seconds, including training. The model tests also passed on toolkit 2.5.0 with PyTorch 2.15 on 18 November 2026.
Most people who try the NPU already have a trained PyTorch model. Their first question isn’t how to build a network from toolkit calls. It’s this: which parts of my model can run on the NPU, and how much accuracy do I lose?
The official examples rebuild known networks by hand, and the small_lm community example designs a model around toolkit layers from the start. This example covers the step in between. It starts from an unmodified nn.Module and answers three questions:
- Which layers run on the NPU, which run on the host, and which stay in PyTorch?
- How much data crosses the PCIe link in one forward pass?
- How far does the bfloat16 result drift from float32, overall and layer by layer?
Objectives
- Trace a PyTorch model and see where each layer runs.
- Run the model through the toolkit and compare its predictions with float32.
- Find the layers where bfloat16 rounding error builds up.
- Cut NPU calls and PCIe traffic by folding batch norm into the convolutions.
- Use the same tool on your own model.
Before you begin
-
Install the toolkit. The CPU emulator is enough, so you don’t need hardware.
-
Check that Python can import the toolkit:
python -c "import qant_native_computing_toolkit as q; print(q.generic.get_available_npus())"On the 2.5.0 emulator this prints a list of six simulated devices, starting with
(0, 'cpu_backend_0'). Toolkit 2.4.0 and older print{0: 'cpu_backend'}. -
Get the example:
git clone -b model-compatibility https://github.com/alijnmerchant21/qant_native_computing_toolkit_examples.git cd qant_native_computing_toolkit_examples/community/python/model_compatibility -
Install the example’s dependencies:
pip install -r requirements.txtThe file pins
torch==2.11.0andtorchvision==0.26.0from the PyTorch CPU index. -
Make sure the machine can reach the internet. On first use, torchvision downloads MNIST to
/tmp/mnist_files/.
The folder has four files you’ll use:
| File | What it is |
|---|---|
npu_compat.py | The converter. One module, no dependencies beyond the toolkit and PyTorch. |
small_cnn.py | An ordinary MNIST CNN, standing in for the model you already have. |
model_compatibility.ipynb | The walkthrough this page follows. |
test_model_compatibility.py | The tests that run in CI. |
Run the example
Start Jupyter and open the notebook:
jupyter notebook model_compatibility.ipynb
Run all cells. The first run trains the CNN for one epoch on the CPU and saves small_cnn.pt. Later runs load the weights.
To run it without a browser:
jupyter nbconvert --to notebook --execute model_compatibility.ipynb --output executed.ipynb
Step 1: See where every layer runs
The model is a plain CNN. Its forward() uses functional calls, which a converter that only walks model.children() would miss:
def forward(self, x):
x = self.pool(F.relu(self.bn1(self.conv1(x)))) # 28x28 -> 14x14
x = self.pool(F.relu(self.bn2(self.conv2(x)))) # 14x14 -> 7x7
x = torch.flatten(x, 1)
x = F.relu(self.fc1(x))
return self.fc2(x)
convert() traces it with torch.fx, uploads the weights of the linear and convolution layers to the card once, and plans every node. report() prints the plan:
npu_model = npu_compat.convert(model, images[:1])
print(npu_model.report())
# layer op runs on MACs output note
1 conv1 Conv2d NPU 56,448 1x8x28x28
2 bn1 BatchNorm2d NPU 6,272 1x8x28x28 scale on NPU, normalize and shift on host, one image per call
3 relu relu host (toolkit) 1x8x28x28
4 pool MaxPool2d host (toolkit) 1x8x14x14 one image per call
5 conv2 Conv2d NPU 225,792 1x16x14x14
6 bn2 BatchNorm2d NPU 3,136 1x16x14x14 scale on NPU, normalize and shift on host, one image per call
7 relu_1 relu host (toolkit) 1x16x14x14
8 pool_1 MaxPool2d host (toolkit) 1x16x7x7 one image per call
9 flatten flatten - 1x784
10 fc1 Linear NPU 50,176 1x64
11 relu_2 relu host (toolkit) 1x64
12 fc2 Linear NPU 640 1x10
NPU share of multiply-accumulates 100.0%
NPU calls per forward pass 6
Switches between NPU and host 12
Data to and from the card per pass 116.6 KB
Weights resident on the card 101.6 KB of 17.0 GB budget
Left in PyTorch nothing
Explore the same report below. Switch to Batch norm folded to see Step 4.
- NPU
- Host, toolkit
- Host, PyTorch
- No arithmetic
Each block is one node that torch.fx found in forward(), in execution order. The lane below traces one forward pass: every step down to the NPU and back up is a trip over PCIe. Click a layer to see its share of the work, the data it moves and the bfloat16 error it adds. Measured on 32 MNIST test images with toolkit 2.4.0 on the CPU backend.
How to read the report:
- Runs on comes from the toolkit 2.4.0 source. Linear and convolution layers do their matrix multiplications on the NPU. Batch norm splits into three steps: normalize on the host, scale on the NPU, shift on the host. Bias, ReLU, pooling and softmax are toolkit functions that run on the host CPU.
- Switches between NPU and host counts every hand-over in one forward pass. Each one is a trip over PCIe, which the maintainers name as today’s bottleneck.
- Data to and from the card adds up the features sent and the results read back. Weights aren’t counted, because they were uploaded once. A convolution unfolds its input into patches on the host before uploading, so it moves more data than its input size suggests.
- Weights resident on the card is checked against a budget of about 17 GB. The driver enforces that limit on hardware. The CPU backend doesn’t, so the tool checks it for you.
Step 2: Run it through the toolkit
npu_model is callable like the original model. Supported layers run through the toolkit in bfloat16, and everything else runs in PyTorch:
npu_logits = npu_model(images)
On 1,000 MNIST test images:
| Accuracy | Same prediction as float32 | |
|---|---|---|
| float32 PyTorch | 97.6% | - |
| Toolkit, bfloat16 | 97.6% | 100% |
Step 3: Find where the error builds up
compare() runs both models side by side and measures the relative error of every layer’s output:
print(npu_model.compare(images[:32]))
| Layer | Runs on | Added here | So far |
|---|---|---|---|
| conv1 | NPU | 0.38% | 0.38% |
| bn1 | NPU | 0.44% | 0.56% |
| relu | Host, toolkit | 0.16% | 0.60% |
| pool | Host, toolkit | 0.16% | 0.54% |
| conv2 | NPU | 0.36% | 0.70% |
| bn2 | NPU | 0.47% | 0.94% |
| relu_1 | Host, toolkit | 0.17% | 0.82% |
| pool_1 | Host, toolkit | 0.17% | 0.73% |
| fc1 | NPU | 0.25% | 0.42% |
| relu_2 | Host, toolkit | 0.17% | 0.44% |
| fc2 | NPU | 0.32% | 0.57% |
- So far is the error of the layer’s output in the full toolkit run, so it includes everything upstream.
- Added here feeds the layer the exact float32 input and measures only its own rounding. The largest value points at the layer to look at first.
Every layer adds a fraction of a percent, which is what bfloat16’s 7-bit mantissa predicts. The two batch norm layers add the most, because the toolkit computes batch norm in three steps and rounds after each one.
Step 4: Fold batch norm into the convolutions
In inference, batch norm is a fixed scale and shift per channel, so it can be folded into the weights and bias of the convolution before it. Pass fold_batchnorm=True:
folded = npu_compat.convert(model, images[:1], fold_batchnorm=True)
| As trained | Batch norm folded | |
|---|---|---|
| NPU calls per pass | 6 | 4 |
| Switches between NPU and host | 12 | 8 |
| Data to and from the card | 116.6 KB | 61.5 KB |
| Output error | 0.57% | 0.42% |
The predictions stay the same, while the model makes a third fewer trips over PCIe, moves about half the data, and rounds less. You don’t need to know the toolkit’s internals to find a change like this. The report shows it.
Use it on your own model
import npu_compat
npu_model = npu_compat.convert(your_model, example_input)
print(npu_model.report()) # where every layer runs
y = npu_model(x) # forward pass through the toolkit
print(npu_model.compare(some_inputs)) # float32 vs bfloat16, layer by layer
npu_compat.export_json(npu_model, some_inputs, "report.json")
| Option | Default | What it does |
|---|---|---|
fold_batchnorm | False | Folds each BatchNorm2d into the convolution before it. |
weight_budget_gb | 17.0 | How many GB of weights to keep on the card. Layers past the budget send their weights with every call, and the report marks them. |
device_id | 0 | The NPU to use. On the emulator there is only 0. |
Layers the toolkit doesn’t cover stay in PyTorch, so any traceable model runs end to end. The notebook shows this on a small model with LayerNorm, GELU and residual adds:
2 blocks_0_norm LayerNorm host (PyTorch) 32 1x32 LayerNorm has no toolkit function
4 gelu gelu host (PyTorch) 1x64 gelu has no toolkit function
6 add add host (PyTorch) 1x32 add has no toolkit function
...
Left in PyTorch LayerNorm, add, gelu
That list is your to-do list if you want more of the model on the NPU.
How it works
- Trace.
torch.fx.symbolic_traceturnsforward()into a graph of nodes, including functional calls,torch.flattenand residual adds.ShapePropruns the example input through it to record every shape. - Plan. Each node maps to a toolkit function if its arguments are supported, for example a convolution with
groups=1. Otherwise it stays in PyTorch, and the report gives the reason. - Upload once. Linear and convolution weights are converted to bfloat16 and uploaded with
uploadandupload_conv_weights, within the weight budget. - Run. A
torch.fx.Interpreterwalks the graph. Planned nodes convert their input to bfloat16, call the toolkit, and convert back. Everything else runs in PyTorch.
| PyTorch | Runs on | Toolkit function |
|---|---|---|
nn.Linear | NPU, bias on host | linear_fprop_preloaded_weights, add_bias_fprop |
nn.Conv2d | NPU, after unfolding on host | conv_fprop_preloaded_weights |
nn.ConvTranspose2d | NPU | conv_transpose_fprop_preloaded_weights |
nn.BatchNorm2d | Scale on NPU, rest on host | batchnorm2d_fprop |
| ReLU, sigmoid, softmax | Host | relu_fprop, sigmoid_fprop, softmax_fprop |
| Max, average and adaptive pooling | Host | maxpool2d_fprop, avgpool2d_fprop, adaptive_*pool2d_fprop |
| Flatten, view, reshape, dropout in eval | No arithmetic | - |
| Anything else | Host, PyTorch | - |
Limits
- The model has to be traceable with
torch.fx. Data-dependent control flow inforward()isn’t. - Convolutions need
groups=1,dilation=1, and the same padding and stride in both directions. - In toolkit 2.4.0, transposed convolution, pooling, softmax and batch norm reject batched input, so the converter calls them one image at a time. Toolkit 2.4.1 and newer accept batches, so on 2.5.0 the per-image loop still works but is no longer needed.
- Byte counts are estimates from reading the toolkit source, not measurements. On hardware, measure with
get_perf_counter. - The CPU emulator reproduces the arithmetic, not the timing. This example checks compatibility and accuracy, not speed.
What’s next
- Run the converter on your own model and post the report in the forum.
- Read Emulator and hardware for what changes on a real card.
- See the image segmentation example for a UNet built from toolkit calls by hand.