Beyond the Transistor

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:

  1. Which layers run on the NPU, which run on the host, and which stay in PyTorch?
  2. How much data crosses the PCIe link in one forward pass?
  3. How far does the bfloat16 result drift from float32, overall and layer by layer?
Check and run an existing PyTorch model on the NPU8:29

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

  1. Install the toolkit. The CPU emulator is enough, so you don’t need hardware.

  2. 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'}.

  3. 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
  4. Install the example’s dependencies:

    pip install -r requirements.txt

    The file pins torch==2.11.0 and torchvision==0.26.0 from the PyTorch CPU index.

  5. 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:

FileWhat it is
npu_compat.pyThe converter. One module, no dependencies beyond the toolkit and PyTorch.
small_cnn.pyAn ordinary MNIST CNN, standing in for the model you already have.
model_compatibility.ipynbThe walkthrough this page follows.
test_model_compatibility.pyThe 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.

Where SmallCNN runs

interactive · real output
  • 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:

    AccuracySame prediction as float32
    float32 PyTorch97.6%-
    Toolkit, bfloat1697.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]))
    LayerRuns onAdded hereSo far
    conv1NPU0.38%0.38%
    bn1NPU0.44%0.56%
    reluHost, toolkit0.16%0.60%
    poolHost, toolkit0.16%0.54%
    conv2NPU0.36%0.70%
    bn2NPU0.47%0.94%
    relu_1Host, toolkit0.17%0.82%
    pool_1Host, toolkit0.17%0.73%
    fc1NPU0.25%0.42%
    relu_2Host, toolkit0.17%0.44%
    fc2NPU0.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 trainedBatch norm folded
    NPU calls per pass64
    Switches between NPU and host128
    Data to and from the card116.6 KB61.5 KB
    Output error0.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")
    OptionDefaultWhat it does
    fold_batchnormFalseFolds each BatchNorm2d into the convolution before it.
    weight_budget_gb17.0How 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_id0The 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

    1. Trace. torch.fx.symbolic_trace turns forward() into a graph of nodes, including functional calls, torch.flatten and residual adds. ShapeProp runs the example input through it to record every shape.
    2. 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.
    3. Upload once. Linear and convolution weights are converted to bfloat16 and uploaded with upload and upload_conv_weights, within the weight budget.
    4. Run. A torch.fx.Interpreter walks the graph. Planned nodes convert their input to bfloat16, call the toolkit, and convert back. Everything else runs in PyTorch.
    PyTorchRuns onToolkit function
    nn.LinearNPU, bias on hostlinear_fprop_preloaded_weights, add_bias_fprop
    nn.Conv2dNPU, after unfolding on hostconv_fprop_preloaded_weights
    nn.ConvTranspose2dNPUconv_transpose_fprop_preloaded_weights
    nn.BatchNorm2dScale on NPU, rest on hostbatchnorm2d_fprop
    ReLU, sigmoid, softmaxHostrelu_fprop, sigmoid_fprop, softmax_fprop
    Max, average and adaptive poolingHostmaxpool2d_fprop, avgpool2d_fprop, adaptive_*pool2d_fprop
    Flatten, view, reshape, dropout in evalNo arithmetic-
    Anything elseHost, PyTorch-

    Limits

    • The model has to be traceable with torch.fx. Data-dependent control flow in forward() 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