webnn-onnx-utils
Shared ONNX/WebNN conversion utilities used by:
rust-webnn-graph(WebNN → ONNX)webnn-wg(ONNX → WebNN)
This crate is intentionally small and modular. It provides:
- Data type mapping - Bidirectional conversion between WebNN and ONNX data types (Float32, Float16, Int32, Int64, etc.)
- Operation name mapping - 90+ operation mappings between WebNN and ONNX (matmul↔MatMul, conv2d↔Conv, etc.)
- Attribute parsing/building - Type-safe attribute handling for ONNX NodeProto (int, float, string, arrays)
- Tensor data handling - Conversion between ONNX TensorProto and typed data (with all data type support)
- Identifier sanitization - WebNN DSL-compatible identifier generation
- Shape inference - Comprehensive shape inference for common operations (matmul, transpose, reduce, concat, etc.)
Features
Data Types
All common ONNX and WebNN data types are supported:
- Float32, Float16
- Int8, Int32, Int64
- Uint8, Uint32, Uint64
Operations
90+ operations mapped including:
- Matrix operations (MatMul, Gemm)
- Convolutions (Conv, ConvTranspose)
- Pooling (AveragePool, MaxPool, GlobalAveragePool)
- Activations (Relu, Sigmoid, Tanh, Softmax, Gelu)
- Elementwise (Add, Sub, Mul, Div)
- Reductions (ReduceSum, ReduceMean, ReduceMax, etc.)
- Tensor manipulation (Concat, Reshape, Transpose, Squeeze, Unsqueeze)
- And many more...
Shape Inference
Shape inference context with support for:
- Unary and binary operations with broadcasting
- Matrix multiplication (2D and batched)
- Transpose with permutation
- Reduction operations (with keepdims support)
- Concat along any axis
- Reshape (with -1 inference)
- Squeeze and Unsqueeze
- Dynamic dimensions with overrides
Usage
use ;
// Data type conversion
let onnx_type = webnn_to_onnx;
let webnn_type = onnx_to_webnn.unwrap; // 1 = FLOAT
// Operation mapping
let m = mapper;
assert_eq!;
assert_eq!;
// Attribute building
let attrs = new
.add_int
.add_float
.add_ints
.build;
// Tensor data
let data = scalar;
let proto = data.to_tensor_proto;
// Shape inference
let mut ctx = new;
ctx.set_shape;
ctx.set_shape;
let result = ctx.infer_matmul.unwrap;
// result shape: [2, 3, 5]
Testing
Comprehensive test coverage with 57+ tests:
All tests pass covering:
- Data type round-trip conversions
- Operation name mappings (case-insensitive)
- Attribute parsing and building (all types)
- Tensor data operations
- Shape inference for all supported operations
- Broadcasting rules
- Identifier sanitization
Protobufs
ONNX protobufs are compiled with prost-build from protos/onnx/onnx.proto3.
License
Apache-2.0