webonnx
wonnx
Rust

A WebGPU-accelerated ONNX inference run-time written 100% in Rust, ready for native and the web

Last updated Jun 28, 2026
1.8k
Stars
71
Forks
40
Issues
0
Stars/day
Attention Score
53
Language breakdown
Rust 91.7%
WGSL 5.8%
Python 1.4%
HTML 0.8%
Makefile 0.2%
โ–ธ Files click to expand
README

WONNX

GitHub Workflow Status docs.rs Crates.io (latest) Crates.io

Wonnx is a GPU-accelerated ONNX inference run-time written 100% in Rust, ready for the web.

Supported Platforms (enabled by wgpu)

API | Windows | Linux & Android | macOS & iOS | ----- | ----------------------------- | ------------------ | ------------------ | Vulkan | โœ… | โœ… | | Metal | | | โœ… | DX12 | โœ… (W10 only) | | | DX11 | :construction: | | | GLES3 | | :ok: | |

:whitecheckmark: = First Class Support โ€” :ok: = Best Effort Support โ€” :construction: = Unsupported, but support in progress

Getting started

From the command line

Ensure your system supports either Vulkan, Metal or DX12 for access to the GPU. Then either download a binary release, or install Rust and run cargo install --git https://github.com/webonnx/wonnx.git wonnx-cli to install the CLI.

The CLI tool (nnx) provides a convenient interface for tinkering with models (see the README for more information):

bash
nnx info ./data/models/opt-squeeze.onnx
nnx infer ./data/models/opt-squeeze.onnx -i data=./data/images/pelican.jpeg --labels ./data/models/squeeze-labels.txt --top 3</code></pre>

From Rust

Add the wonnx crate as dependency (cargo add wonnx if you have cargo-add). Then, see the examples for usage examples, or browse the API docs.

From Python

pip install wonnx

And then, to use:

from wonnx import Session
session = Session.from_path(
    "../data/models/single_relu.onnx"
)
inputs = {"x": [-1.0, 2.0]}
assert session.run(inputs) == {"y": [0.0, 2.0]}

Then run python3 with the above Python code!

For more details on the Python package including build instructions, see wonnx-py.

In the browser, using WebGPU + WebAssembly

bash
npm install @webonnx/wonnx-wasm</code></pre>

And then, on the client side:

js
import init, { Session, Input } from &quot;@webonnx/wonnx-wasm&quot;;

// Check for WebGPU availability first: if(navigator.gpu) { .. } await init(); const session = await Session.fromBytes(modelBytes / Uint8Array containing the ONNX file /); const input = new Input(); input.insert(&quot;x&quot;, [13.0, -37.0]); const result = await session.run(input); // This will be an object where the keys are the names of the model outputs and the values are arrays of numbers. session.free(); input.free();</code></pre>

The package @webonnx/wonnx-wasm provides an interface to WONNX, which is included as WebAssembly module and will use the browser's WebGPU implementation. See wonnx-wasm-example for a more complete usage example involving a bundler.

For more details on the JS/WASM package including build instructions, see wonnx-wasm.

For development

To work on wonnx itself, follow the following steps:

  • Install Rust
  • Install Vulkan, Metal, or DX12 for the GPU API.
  • git clone this repo.
git clone https://github.com/webonnx/wonnx.git

Then, you're all set! You can run one of the included examples through cargo:

cargo run --example squeeze --release

Running other models

  • To run an onnx model, first simplify it with nnx prepare (substitute with cargo run -- prepare when inside this repo):
bash
nnx prepare -i ./some-model.onnx ./some-model-prepared.onnx</code></pre>

To specify dynamic dimension parameters, add e.g. --set batch_size=1.

You can also use an external tool, such as onnx-simplifier, with the command:

# pip install -U pip && pip install onnx-simplifier
python -m onnxsim mnist-8.onnx opt-mnist.onnx
  • Then you can run it using the CLI (see README or programmatically, following the
examples in the examples folder. To run an example:
cargo run --example mnist --release

Tested models

  • Squeezenet
  • MNIST
  • BERT

GPU selection

Except when running in WebAssembly, you may set the following environment variables to influence GPU selection by WGPU:

  • WGPUADAPTERNAME with a substring of the name of the adapter you want to use (e.g. 1080 will match NVIDIA GeForce 1080ti).
  • WGPU_BACKEND with a comma separated list of the backends you want to use (vulkan, metal, dx12, dx11, or gl).
  • WGPUPOWERPREFERENCE with the power preference to choose when a specific adapter name isn't specified (high or low)

Contribution: On implementing a new Operator

Contributions are very much welcomed even without large experience in DL, WGSL, or Rust. I hope that this project can be a sandbox for all of us to learn more about those technologies beyond this project's initial scope.

To implement an operator all you have to do is:

  • Add a new matching pattern in compiler.rs
  • Retrieve its attributes values using the get_attribute function:
let alpha = get_attribute("alpha", Some(1.0), node);     // or without default value     let alpha = get_attribute::<f32>("alpha", None, node);
  • Add any variable you want to use in the WGSL shader using context.
  • Write a new WGSL template in the templates folder.
Available types are in structs.wgsl but you can also generate new ones within your templates.
  • Respect the binding layout that each entry is incremented by 1 starting from 0, with input first and output last. If the number of binding is above 4. Increment the binding group. You can change the input within sequencer.rs
  • Write the logic.
There is default variables in the context:
  • {{ ilens[0] }}: the length of the input 0. This also work for output: {{ olens[0] }} and other input {{ i_lens[1] }}
  • {{ ishape[0] }}: the array of dimensions of input 0. To get the first dimension of the array, just use: {{ ishape[0][0] }}
  • {{ ichunks[0] }}: the size of the chunks of each dimensions of input 0. By default, each variable is represented as a long array of values where to get to specific values you have to move by chunks. Those chunks are represented within this variable. To get the size of the chunks of the first dimensions use: {{ ichunks[0][0] }}.
  • {{ optype }} the op type as some optype like activation are using the same template.
  • Test it using the utils function and place it in the tests folder. The test can look as follows:
#[test] fn testmatmulsquare_matrix() {     // USER INPUT

let n = 16; let mut input_data = HashMap::new();

let data_a = ndarray::Array2::eye(n); let mut data_b = ndarray::Array2::<f32>::zeros((n, n)); data_b[[0, 0]] = 0.2; data_b[[0, 1]] = 0.5;

let sum = dataa.dot(&datab);

inputdata.insert("A".tostring(), dataa.asslice().unwrap()); inputdata.insert("B".tostring(), datab.asslice().unwrap());

let n = n as i64; let model = model(graph( vec![tensor("A", &[n, n]), tensor("B", &[n, n])], vec![tensor("C", &[n, n])], vec![], vec![], vec![node(vec!["A", "B"], vec!["C"], "MatMul", "MatMul", vec![])], ));

let session = pollster::blockon(wonnx::Session::frommodel(model)).expect("Session did not create");

let result = pollster::blockon(session.run(inputdata)).unwrap();

// Note: it is better to use a method that compares floats with a tolerance to account for differences // between implementations; see wonnx/tests/common/mod.rs for an example. asserteq!((&result["C"]).tryinto().unwrap(),sum.as_slice().unwrap()); }

Check out tera documentation for other templating operation: https://tera.netlify.app/docs/

  • If at any point you want to do optimisation of several nodes you can do it within sequencer.rs.

Supported Operators (ref ONNX IR)

|Operator|Since version|Implemented|Shape inference supported| |-|-|-|-| |Abs|13, 6, 1|โœ…|โœ…| |Acos|7|โœ…|โœ…| |Acosh|9|โœ…|โœ…| |Add|14, 13, 7, 6, 1|โœ…|โœ…| |And|7, 1|โœ…| |ArgMax|13, 12, 11, 1| |ArgMin|13, 12, 11, 1| |Asin|7|โœ…|โœ…| |Asinh|9|โœ…|โœ…| |Atan|7|โœ…|โœ…| |Atanh|9|โœ…|โœ…| |AveragePool|11, 10, 7, 1|โœ…|โœ…| |BatchNormalization|15, 14, 9, 7, 6, 1|โœ…|โœ…| |BitShift|11| |Cast|13, 9, 6, 1|โœ…|โœ…| |Ceil|13, 6, 1|โœ…|โœ…| |Clip|13, 12, 11, 6, 1|โœ…|โœ…| |Compress|11, 9| |Concat|13, 11, 4, 1|โœ…|โœ…| |ConcatFromSequence|11| |Constant|13, 12, 11, 9, 1|โœ…|โœ…| |ConstantOfShape|9|โœ…|โœ…| |Conv|11, 1|โœ…| |ConvInteger|10| |ConvTranspose|11, 1| |Cos|7|โœ…|โœ…| |Cosh|9|โœ…|โœ…| |CumSum|14, 11| |DepthToSpace|13, 11, 1| |DequantizeLinear|13, 10| |Det|11| |Div|14, 13, 7, 6, 1|โœ…|โœ…| |Dropout|13, 12, 10, 7, 6, 1|โœ…|โœ…| |Einsum|12| |Elu|6, 1|โœ…|โœ…| |Equal|13, 11, 7, 1|โœ…| |Erf|13, 9|โœ…|โœ…| |Exp|13, 6, 1|โœ…|โœ…| |Expand|13, 8| |EyeLike|9| |Flatten|13, 11, 9, 1|โœ…|โœ…| |Floor|13, 6, 1|โœ…|โœ…| |GRU|14, 7, 3, 1| |Gather|13, 11, 1|โœ… (axis=0)|โœ…| |GatherElements|13, 11| |GatherND|13, 12, 11| |Gemm|13, 11, 9, 7, 6, 1|โœ…*| |GlobalAveragePool|1|โœ…|โœ…| |GlobalLpPool|2, 1| |GlobalMaxPool|1| |Greater|13, 9, 7, 1|โœ…| |GridSample|16| |HardSigmoid|6, 1|โœ…|โœ…| |Hardmax|13, 11, 1| |Identity|16, 14, 13, 1|โœ…|โœ…| |If|16, 13, 11, 1| |InstanceNormalization|6, 1| |IsInf|10| |IsNaN|13, 9| |LRN|13, 1|| |LSTM|14, 7, 1| |LeakyRelu|6, 1|โœ…|โœ…| |Less|13, 9, 7, 1|โœ…| |Log|13, 6, 1|โœ…|โœ…| |Loop|16, 13, 11, 1| |LpNormalization|1| |LpPool|11, 2, 1| |MatMul|13, 9, 1|โœ…| |MatMulInteger|10| |Max|13, 12, 8, 6, 1| |MaxPool|12, 11, 10, 8, 1|โœ…|โœ…| |MaxRoiPool|1| |MaxUnpool|11, 9| |Mean|13, 8, 6, 1| |Min|13, 12, 8, 6, 1|โœ…| |Mod|13, 10|โœ…|โœ…| |Mul|14, 13, 7, 6, 1|โœ…|โœ…| |Multinomial|7| |Neg|13, 6, 1|โœ…|โœ…| |NonMaxSuppression|11, 10| |NonZero|13, 9| |Not|1|โœ…| |OneHot|11, 9|โœ… (axis=-1)| |Optional|15| |OptionalGetElement|15| |OptionalHasElement|15| |Or|7, 1|โœ…| |PRelu|9, 7, 6, 1|โœ…| |Pad|13, 11, 2, 1|โœ… (mode=constant, pads>=0)| |Pow|15, 13, 12, 7, 1|โœ… (broadcast=0 and data type is f32)|โœ…| |QLinearConv|10| |QLinearMatMul|10| |QuantizeLinear|13, 10| |RNN|14, 7, 1| |RandomNormal|1| |RandomNormalLike|1| |RandomUniform|1| |RandomUniformLike|1| |Reciprocal|13, 6, 1|โœ…|โœ…| |ReduceL1|13, 11, 1|โœ…|โœ…| |ReduceL2|13, 11, 1|โœ…|โœ…| |ReduceLogSum|13, 11, 1|โœ…|โœ…| |ReduceLogSumExp|13, 11, 1|โœ…|โœ…| |ReduceMax|13, 12, 11, 1|โœ…|โœ…| |ReduceMean|13, 11, 1|โœ…|โœ…| |ReduceMin|13, 12, 11, 1|โœ…|โœ…| |ReduceProd|13, 11, 1|โœ…|โœ…| |ReduceSum|13, 11, 1|โœ…|โœ…| |ReduceSumSquare|13, 11, 1|โœ…|โœ…| |Relu|14, 13, 6, 1|โœ…|โœ…| |Reshape|14, 13, 5, 1|โœ…|โœ…| |Resize|13, 11, 10|โœ…| |ReverseSequence|10| |RoiAlign|16, 10| |Round|11| |Scan|11, 9, 8| |Scatter (deprecated)|11, 9| |ScatterElements|16, 13, 11| |ScatterND|16, 13, 11| |Selu|6, 1| |SequenceAt|11| |SequenceConstruct|11| |SequenceEmpty|11| |SequenceErase|11| |SequenceInsert|11| |SequenceLength|11| |Shape|15, 13, 1|โœ…|โœ…| |Shrink|9| |Sigmoid|13, 6, 1|โœ…| |Sign|13, 9|โœ…|โœ…| |Sin|7|โœ…|โœ…| |Sinh|9|โœ…|โœ…| |Size|13, 1|โœ…|โœ…| |Slice|13, 11, 10, 1||โœ…| |Softplus|1|โœ…| |Softsign|1|โœ…| |SpaceToDepth|13, 1| |Split|13, 11, 2, 1| |SplitToSequence|11| |Sqrt|13, 6, 1|โœ…|โœ…| |Squeeze|13, 11, 1|โœ…|โœ…| |StringNormalizer|10| |Sub|14, 13, 7, 6, 1|โœ…|โœ…| |Sum|13, 8, 6, 1| |Tan|7|โœ…|โœ…| |Tanh|13, 6, 1|โœ…|โœ…| |TfIdfVectorizer|9| |ThresholdedRelu|10| |Tile|13, 6, 1| |TopK|11, 10, 1| |Transpose|13, 1|โœ…|โœ…| |Trilu|14| |Unique|11| |Unsqueeze|13, 11, 1|โœ…|โœ…| |Upsample (deprecated)|10, 9, 7| |Where|16, 9| |Xor|7, 1| |Function|Since version| |Bernoulli|15| |CastLike|15| |Celu|12|โœ…|โœ…| |DynamicQuantizeLinear|11| |GreaterOrEqual|12|โœ…| |HardSwish|14| |LessOrEqual|12|โœ…| |LogSoftmax|13, 11, 1| |MeanVarianceNormalization|13, 9| |NegativeLogLikelihoodLoss|13, 12| |Range|11||โœ…| |Softmax|13, 11, 1|โœ… | |SoftmaxCrossEntropyLoss|13, 12|

Known limitations

  • The Clip, Resize, Reshape, Split, Pad and ReduceSum ops accept (typically optional) secondary inputs to set various
parameters (i.e. axis). These inputs are only supported if they are supplied as initializer tensors (i.e. do not depend on inputs and are not outputs of other ops), because wonnx pre-compiles all operations to shaders in advance (and must know these parameters up front).
  • Internally 64-bit integers are not supported (the reason is they are not supported in the current version of WGSL);
inputs and initializers with 64-bit scalars are converted to 32-bit values (possibly overflowing).
  • For MatMul and Gemm, the matrix dimensions must be divisible by 2, or the output matrix must be of size (1, N). Matrix
multiplication only supports floats, not integers (this is a WebGPU/WGSL limitation).

Shape inference

WONNX needs to know the shape of input and


README truncated. View on GitHub
๐Ÿ”— More in this category

ยฉ 2026 GitRepoTrend ยท webonnx/wonnx ยท Updated daily from GitHub