wonnx
Library Archived
Wonnx is an ONNX runtime based on wgpu aimed at being a universal GPU runtime, written in Rust.
- Downloads
- 146
- Dependents
- 1
- Stars
- 1,753
- Forks
- 69
- Contributors
- 13
- Commits
- 721
- Latest release
- 0.5.1 ·
Why Archived
GitHub reports the repository as archived.
Exact rules: Instant archive. The check on applied thresholds version 9.
Every rule outcome, as the check records it
instant-archive: repository is archived
About
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: |
:white_check_mark: = 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):
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
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:
Read the full README
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
npm install @webonnx/wonnx-wasm
And then, on the client side:
import init, { Session, Input } from "@webonnx/wonnx-wasm";
// 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("x", [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();
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 withcargo run -- preparewhen inside this repo):
nnx prepare -i ./some-model.onnx ./some-model-prepared.onnx
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:
WGPU_ADAPTER_NAMEwith a substring of the name of the adapter you want to use (e.g.1080will matchNVIDIA GeForce 1080ti).WGPU_BACKENDwith a comma separated list of the backends you want to use (vulkan,metal,dx12,dx11, orgl).WGPU_POWER_PREFERENCEwith the power preference to choose when a specific adapter name isn't specified (highorlow)
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_attributefunction:
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
templatesfolder.
Available types are in
structs.wgslbut 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:
{{ i_lens[0] }}: the length of the input 0. This also work for output:{{ o_lens[0] }}and other input{{ i_lens[1] }}{{ i_shape[0] }}: the array of dimensions of input 0. To get the first dimension of the array, just use:{{ i_shape[0][0] }}{{ i_chunks[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:{{ i_chunks[0][0] }}.{{ op_type }}the op type as some op_type 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 test_matmul_square_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 = data_a.dot(&data_b);
input_data.insert("A".to_string(), data_a.as_slice().unwrap());
input_data.insert("B".to_string(), data_b.as_slice().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::block_on(wonnx::Session::from_model(model)).expect("Session did not create");
let result = pollster::block_on(session.run(input_data)).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.
assert_eq!((&result["C"]).try_into().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)
Known limitations
The
Clip,Resize,Reshape,Split,PadandReduceSumops 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
MatMulandGemm, 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 output tensors for each operation in order to generate shader code for executing it. ONNX models however do not always contain this information for intermediate values. Shape inference is the process of deducing the shape of intermediate values from the shape of inputs and outputs and the characteristics of each operation.
WONNX supports a limited form of shape inference (the process of determining what the shapes are of the various nodes in a model's graph). Shape inference is available programmatically as well as through the CLI. Before shape inference can be performed, all dynamic dimension parameters need to be replaced with static values. Shape inference only infers output shapes from input shapes for specific supported ops (see the table above). Inference cannot succeed if the shape for any input of a node is not known. Nodes that already have fully defined shapes for their outputs are left unchanged (and the outputs are used for shape inference on nodes that use these outputs as inputs).
To perform shape inference using the CLI, run a command similar to this (here batch_size and sequence_length are dynamic
dimension parameters; the -i flag enables shape inference):
nnx prepare model.onnx model-prepared.onnx --set batch_size=1 --set sequence_length=255 -i
To perform shape inference programmatically, use apply_dynamic_dimensions and infer_shapes from the
wonnx_preprocessing::shape_inference module.
Constant folding
Some models contain subgraphs whose output can be determined statically, as they do not depend on the specific inputs provided during inference. WONNX can replace such constant intermediate values with static values ('constant folding'). This is supported in the following cases:
- Output of nodes of the
Constantop type (these are replaced with initializers) - Output of nodes of the
Shapeop type where the shape of the input is known (up front or during inference) - Output of nodes of which all inputs are constant (possibly after folding), and for which the operator is supported by WONNX.
Constant folding is performed as part of shape inference, unless disabled (from the CLI pass --no-fold-constants to disable). This
is done in order to support models that dynamically calculate shapes using operators such as Shape/Squeeze/Unsqueeze depending
on dynamically set dimension parameters (e.g. batch size).
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT) at your option.
Except for the following files:
data/models:data/images:pelican.jpeg: source, (C) Rui Ornelas, CC-BY 2.0.bald_eagle.jpeg: source, (C) David R. Tribble, CC BY-SA 4.0
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions.
Compatibility
- Runs on
- WebGPU
What shows it
- WebGPU: wonnx dependency wgpu, wonnx-cli dependency wgpu, wonnx-preprocessing dependency wgpu
- Native code
- None found
- No native code found
- Python bindings
- No Python binding crate found
- License
- Apache-2.0 OR MIT
Compare with similar projects
Order: strongest tier first, then most downloads, then name, with unmeasured values last. A library counts downloads over 30 days. An app counts binary downloads per release. An app with none counts its crate downloads over 30 days. ML Rust runs this catalogue, so its closest project always gets a row.
| Project | Downloads | Dependents | Stars | Latest release | Runs on (GPU) | Native code | License |
|---|---|---|---|---|---|---|---|
|
Wonnx is an ONNX runtime based on wgpu aimed at being a universal GPU runtime, written in Rust. |
146 downloads over 30 days | 1 | 1,753 | 0.5.1 | WebGPU | No native code found | Apache-2.0 OR MIT |
|
ort Featured
A safe Rust wrapper for ONNX Runtime 1.31 - Optimize and accelerate machine learning inference & training |
3,902,768 downloads over 30 days | 694 | 2,611 | 2.0.0-rc.15 | CUDA, WebGPU, ROCm | Binds native code: onnxruntime, ort-sys. Build uses a native toolchain: pkg-config (feature pkg-config) | Apache-2.0 OR MIT |
|
rten Featured
Tensor library for the RTen machine learning runtime |
496,924 downloads over 30 days | 29 | 360 | 0.27.0 | GPU support unknown | No native code found | Apache-2.0 OR MIT |
|
orp Listed
Lightweight framework for building ONNX runtime pipelines with ort |
41,463 downloads over 30 days | 6 | 14 | 1.0.0 | CUDA, ROCm | Binds native code: ort-sys | Apache-2.0 |
|
Wrapper around Microsoft's ONNX Runtime |
802 downloads over 30 days | 3 | 332 | 0.0.14 | GPU support unknown | Binds native code: onnxruntime-sys. Build uses a native toolchain: bindgen (feature generate-bindings) | Apache-2.0 OR MIT |
|
oxionnx Listed
Pure Rust ONNX inference engine — zero C/C++ dependencies |
550 downloads over 30 days | 24 | 20 | 0.1.7 | CUDA, WebGPU | No native code found | Apache-2.0 |
|
Inference server for LLMs, speech and embeddings: OpenAI-compatible routes with streaming, plus speech synthesis (TTS) and transcription (ASR). Serves Llama, Mistral, Qwen, Mamba2, MLA+MoE and hybrid models from SafeTensors, AWQ, GPTQ and GGUF. |
8 binary downloads per release | Not applicable | 7 | 0.7.1 | CUDA, WebGPU | Binds native code: ring (feature distributed) | Apache-2.0 |
Crates3 crates
- wonnx Primary
- wonnx-cli
- wonnx-preprocessing
Measurements and sources
Each signal row shows the raw value, its source and the fetch date. The Sources list gathers every distinct source on this page. Movement needs more history.
Sources6 sources
- Description: the crates.io description
- crates.io database dump, fetched
- RustSec advisory database, fetched
- GitHub repository, fetched
- crates.io package, fetched
- GitHub contributors, fetched
Adoption0 active dependents, 0 new dependents in 365 days1 not measured
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| Active dependents | 0 | crates.io database dump | Yes | |
| New dependents (365 days) | 0 | crates.io database dump | Yes | |
| Peak active dependents | 1 | crates.io database dump | Yes | |
| Active dependents as a share of the peak | 1 | crates.io database dump | Yes | |
| Binary downloads per release | Not measured | Yes |
MaintenanceLatest human commit: 2 years ago3 not measured
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| Latest human commit | 2024-05-18 | GitHub repository | Yes | |
| Latest release | 2023-09-30 | crates.io database dump | Yes | |
| First release | 2021-08-30 | crates.io database dump | Yes | |
| Latest version | 0.5.1 | crates.io database dump | Yes | |
| Days the oldest outside issue waits for a reply | 1254 | GitHub repository | Yes | |
| Maintainer replies over 365 days | 0 | GitHub repository | Yes | |
| Repository archived | true | GitHub repository | Yes | |
| Repository gone | false | GitHub repository | Yes | |
| Release commit or manifest in the repo | true | crates.io package | Yes | |
| Published docs | true | crates.io database dump | Yes | |
| Latest release fails cargo check | Not measured | Yes | ||
| Build check date | Not measured | Yes | ||
| Build check toolchain | Not measured | Yes |
SecurityUnpatched vulnerabilities: none
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| Unpatched vulnerabilities past the grace window | none | RustSec advisory database | Yes | |
| RustSec unmaintained advisory | none | RustSec advisory database | Yes | |
| Deprecation notice | none | crates.io database dump | Yes | |
| Deprecated requirement | none | crates.io database dump | Yes |
Distribution9 releases, 146 downloads over 30 days5 not measured
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| Releases | 9 | crates.io database dump | Yes | |
| Downloads over 30 days | 146 | crates.io database dump | Yes | |
| Binary downloads over the last 3 releases | Not measured | Yes | ||
| Homebrew installs on request over 365 days | Not measured | Yes | ||
| Repology repository families | Not measured | Yes | ||
| Docker pull growth over 90 days | Not measured | Yes | ||
| Docker pulls at the growth baseline | Not measured | Yes | ||
| Every version a prerelease | false | crates.io database dump | Yes | |
| Every version 0.0.x | false | crates.io database dump | Yes | |
| Every version yanked | false | crates.io database dump | Yes | |
| Crate deleted from crates.io | false | crates.io database dump | Yes |
Repository1,753 stars, 69 forks, 13 contributors, 721 commits. Stars alone never qualify a project.
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| GitHub stars | 1753 | GitHub repository | Yes — one part of the repository route | |
| GitHub forks | 69 | GitHub repository | Yes — one part of the repository route | |
| Contributors with a GitHub account | 13 | GitHub contributors | Yes — one part of the repository route | |
| Commits on the default branch | 721 | GitHub repository | No | |
| Repository's main crate left out of the entry | none | crates.io database dump | Yes |
Facts that never count
| Signal | Value | Source | Fetched | Counts |
|---|---|---|---|---|
| License | Apache-2.0 OR MIT | crates.io database dump | No | |
| Runs on, from listed crates and their direct dependencies | WebGPU | crates.io database dump | No | |
| What shows each backend | WebGPU: wonnx dependency wgpu, wonnx-cli dependency wgpu, wonnx-preprocessing dependency wgpu | crates.io database dump | No | |
| Native code, from listed crates and their dependencies | No native code found | crates.io database dump | No | |
| Python bindings, from direct dependencies of listed crates | No Python binding crate found | crates.io database dump | No | |
| Crates that depend on a listed crate directly | 1 | crates.io database dump | No |
Corrections and review history
No correction applies to this entry.
Judgments
A judgment enters only through an approved issue and a merged pull request.
No judgment applies to this entry.