Skip to main content

EXPERIMENTAL: Python implementation of the W3C WebNN API with ONNX and CoreML conversion support (NOT for production use)

Project description

rustnn / PyWebNN

A Rust implementation of WebNN graph handling with Python bindings that implement the W3C WebNN API specification.


โš ๏ธ EXPERIMENTAL - DO NOT USE IN PRODUCTION

This project is a proof-of-concept and experimental implementation. It is NOT ready for production use.

This is an early-stage experiment to explore WebNN graph handling and format conversion. Many features are incomplete, untested, or may change significantly. Use at your own risk for research and experimentation only.


Features:

  • ๐Ÿฆ€ Rust Library: Validates WebNN graphs and converts to ONNX/CoreML formats
  • ๐Ÿ Python API: Complete W3C WebNN API implementation via PyO3 bindings
  • ๐Ÿ“Š Format Conversion: Export graphs to ONNX (cross-platform) and CoreML (macOS)
  • ๐Ÿš€ Model Execution: Run converted models on CPU, GPU, and Neural Engine (macOS)
  • ๐Ÿ” Graph Visualization: Generate Graphviz diagrams of your neural networks
  • โœ… Validation: Comprehensive graph validation matching Chromium's WebNN implementation

๐Ÿ“ฆ Installation

Python Package (PyWebNN)

Install from PyPI:

pip install pywebnn

Or install from source with maturin:

# Clone the repository
git clone https://github.com/tarekziade/rustnn.git
cd rustnn

# Install in development mode
pip install maturin
maturin develop --features python

Requirements: Python 3.12+, NumPy 1.20+

Rust Library

Add to your Cargo.toml:

[dependencies]
rustnn = "0.1"

Or use directly from this repository.


๐Ÿš€ Quick Start

Python API

import webnn
import numpy as np

# Create ML context
ml = webnn.ML()
context = ml.create_context(device_type="cpu")
builder = context.create_graph_builder()

# Build a simple neural network: output = relu(matmul(input, weights) + bias)
input_tensor = builder.input("input", [1, 4], "float32")

# Define weights and bias as constants
weights = np.array([[0.1, 0.2, 0.3],
                    [0.4, 0.5, 0.6],
                    [0.7, 0.8, 0.9],
                    [1.0, 1.1, 1.2]], dtype=np.float32)
bias = np.array([0.1, 0.2, 0.3], dtype=np.float32)

weights_const = builder.constant(weights)
bias_const = builder.constant(bias)

# Build computation graph
matmul_result = builder.matmul(input_tensor, weights_const)
add_result = builder.add(matmul_result, bias_const)
output = builder.relu(add_result)

# Compile the graph
graph = builder.build({"output": output})

# Convert to ONNX
context.convert_to_onnx(graph, "model.onnx")
print(f"โœ“ ONNX model saved: model.onnx")

# Convert to CoreML (macOS only)
context.convert_to_coreml(graph, "model.mlmodel")
print(f"โœ“ CoreML model saved: model.mlmodel")

Rust Library

use rustnn::{GraphInfo, GraphValidator, ContextProperties};
use rustnn::converters::{ConverterRegistry, OnnxConverter};

// Load graph from JSON
let graph_info: GraphInfo = serde_json::from_str(&json_data)?;

// Validate the graph
let validator = GraphValidator::new(&graph_info, ContextProperties::default());
let artifacts = validator.validate()?;

// Convert to ONNX
let mut registry = ConverterRegistry::new();
registry.register(Box::new(OnnxConverter));
let converted = registry.convert("onnx", &graph_info)?;

// Save to file
std::fs::write("model.onnx", &converted.data)?;

๐Ÿ“š Documentation


๐ŸŽฏ Python API Overview

The Python API implements the W3C WebNN specification:

Core Classes

  • webnn.ML - Entry point for creating ML contexts
  • webnn.MLContext - Manages graph builders and model conversion
  • webnn.MLGraphBuilder - Builds computational graphs with operations
  • webnn.MLGraph - Compiled graph ready for execution or conversion
  • webnn.MLOperand - Represents tensors in the computation graph

Supported Operations

Binary Operations: add, sub, mul, div, matmul

Activations: relu, sigmoid, tanh, softmax

Shape Operations: reshape

Constants: Define weights and biases from NumPy arrays

Format Support

Format Status Platform Features
ONNX โœ… Full All All operations, cross-platform
CoreML โš ๏ธ Basic macOS Basic ops (add, matmul) - activations coming soon

See TODO.txt for planned features and improvements.


๐Ÿฆ€ Rust CLI Usage

The Rust library includes a powerful CLI tool for working with WebNN graphs.

Validate a Graph

cargo run -- examples/sample_graph.json

Visualize a Graph

# Generate DOT file
cargo run -- examples/sample_graph.json --export-dot graph.dot

# Convert to PNG (requires graphviz)
dot -Tpng graph.dot -o graph.png

# Or use the Makefile shortcut (macOS)
make viz

Convert to ONNX

cargo run -- examples/sample_graph.json \
    --convert onnx \
    --convert-output model.onnx

Convert to CoreML

cargo run -- examples/sample_graph.json \
    --convert coreml \
    --convert-output model.mlmodel

Execute Models

ONNX Runtime (cross-platform):

cargo run --features onnx-runtime -- \
    examples/sample_graph.json \
    --convert onnx \
    --run-onnx

CoreML Runtime (macOS only):

cargo run --features coreml-runtime -- \
    examples/sample_graph.json \
    --convert coreml \
    --run-coreml \
    --device gpu  # or 'cpu', 'ane' for Neural Engine

Makefile Targets

make help              # Show all available targets
make build             # Build Rust project
make test              # Run Rust tests
make python-dev        # Install Python package in dev mode
make python-test       # Run Python tests
make docs-serve        # Serve documentation locally
make validate-all-env  # Run full test pipeline

๐Ÿ—๏ธ Project Structure

rustnn/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ lib.rs              # Public Rust API
โ”‚   โ”œโ”€โ”€ main.rs             # CLI tool
โ”‚   โ”œโ”€โ”€ graph.rs            # WebNN graph data structures
โ”‚   โ”œโ”€โ”€ validator.rs        # Graph validation logic
โ”‚   โ”œโ”€โ”€ converters/         # ONNX and CoreML converters
โ”‚   โ”œโ”€โ”€ executors/          # Runtime execution
โ”‚   โ””โ”€โ”€ python/             # Python bindings (PyO3)
โ”‚       โ”œโ”€โ”€ context.rs      # ML and MLContext classes
โ”‚       โ”œโ”€โ”€ graph_builder.rs # MLGraphBuilder class
โ”‚       โ”œโ”€โ”€ graph.rs        # MLGraph class
โ”‚       โ””โ”€โ”€ operand.rs      # MLOperand class
โ”‚
โ”œโ”€โ”€ python/webnn/           # Python package
โ”‚   โ”œโ”€โ”€ __init__.py         # Public API exports
โ”‚   โ””โ”€โ”€ __init__.pyi        # Type stubs for IDEs
โ”‚
โ”œโ”€โ”€ docs/                   # Documentation (MkDocs)
โ”‚   โ”œโ”€โ”€ index.md
โ”‚   โ”œโ”€โ”€ getting-started.md
โ”‚   โ”œโ”€โ”€ api-reference.md
โ”‚   โ”œโ”€โ”€ examples.md
โ”‚   โ””โ”€โ”€ advanced.md
โ”‚
โ”œโ”€โ”€ tests/                  # Python tests
โ”‚   โ”œโ”€โ”€ test_python_api.py
โ”‚   โ”œโ”€โ”€ test_integration.py
โ”‚   โ””โ”€โ”€ test_coreml_basic.py
โ”‚
โ”œโ”€โ”€ examples/               # Example code and graphs
โ”‚   โ”œโ”€โ”€ sample_graph.json
โ”‚   โ”œโ”€โ”€ python_simple.py
โ”‚   โ””โ”€โ”€ python_matmul.py
โ”‚
โ”œโ”€โ”€ pyproject.toml          # Python package configuration
โ”œโ”€โ”€ Cargo.toml              # Rust package configuration
โ””โ”€โ”€ Makefile                # Build automation

๐Ÿ”ง Development

Prerequisites

  • Rust: 1.70+ (install from rustup.rs)
  • Python: 3.12+ with pip
  • Maturin: pip install maturin
  • Optional: Graphviz for visualization (brew install graphviz on macOS)

Building from Source

# Clone repository
git clone https://github.com/tarekziade/rustnn.git
cd rustnn

# Build Rust library
cargo build --release

# Build Python package
maturin develop --features python

# Run tests
cargo test                    # Rust tests
python -m pytest tests/       # Python tests

# Build documentation
mkdocs serve                  # Live preview at http://127.0.0.1:8000
mkdocs build                  # Build static site

Running Examples

Python:

# Install package first
maturin develop --features python

# Run examples
python examples/python_simple.py
python examples/python_matmul.py

# Run integration tests
python tests/test_integration.py
python tests/test_coreml_basic.py --cleanup

Rust:

cargo run -- examples/sample_graph.json --export-dot graph.dot

๐Ÿงช Testing

Python Tests

# Install test dependencies
pip install -e ".[dev]"

# Run all tests
pytest tests/ -v

# Run specific test file
pytest tests/test_python_api.py -v

# Run integration tests with cleanup
python tests/test_integration.py --cleanup

Rust Tests

# All tests
cargo test

# Specific module
cargo test converters

# With features
cargo test --features onnx-runtime,coreml-runtime

๐Ÿ“‹ Roadmap

See TODO.txt for a comprehensive list of planned features.

High Priority:

  • โœ… Python WebNN API implementation
  • โœ… ONNX conversion with full operation support
  • โœ… Comprehensive documentation
  • โฌœ CoreML support for activation functions (relu, sigmoid, tanh, softmax)
  • โฌœ Actual tensor execution in MLContext.compute()
  • โฌœ PyPI package publishing automation

Medium Priority:

  • โฌœ More operations (conv2d, pooling, normalization)
  • โฌœ Graph optimization passes
  • โฌœ Multi-platform wheel building (manylinux, Windows)
  • โฌœ Performance benchmarks

๐Ÿค Contributing

Contributions are welcome! Please see:

Quick Contribution Guide

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Make your changes
  4. Run tests: cargo test && pytest tests/
  5. Format code: cargo fmt
  6. Commit: git commit -m "Add my feature"
  7. Push and create a pull request

๐Ÿ“„ License

Licensed under the Apache License, Version 2.0. See LICENSE for details.


๐Ÿ”— Links


๐Ÿ™ Acknowledgments

  • W3C WebNN Community Group for the specification
  • Chromium WebNN implementation for reference
  • PyO3 project for excellent Python-Rust bindings
  • Maturin for seamless Python package building

Made with โค๏ธ by Tarek Ziade

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pywebnn-0.1.0.tar.gz (195.2 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

pywebnn-0.1.0-cp312-cp312-win_amd64.whl (225.0 kB view details)

Uploaded CPython 3.12Windows x86-64

pywebnn-0.1.0-cp312-cp312-win32.whl (211.8 kB view details)

Uploaded CPython 3.12Windows x86

pywebnn-0.1.0-cp312-cp312-manylinux_2_28_x86_64.whl (378.8 kB view details)

Uploaded CPython 3.12manylinux: glibc 2.28+ x86-64

pywebnn-0.1.0-cp312-cp312-manylinux_2_28_aarch64.whl (367.6 kB view details)

Uploaded CPython 3.12manylinux: glibc 2.28+ ARM64

pywebnn-0.1.0-cp312-cp312-macosx_11_0_arm64.whl (480.0 kB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

pywebnn-0.1.0-cp312-cp312-macosx_10_12_x86_64.whl (478.1 kB view details)

Uploaded CPython 3.12macOS 10.12+ x86-64

File details

Details for the file pywebnn-0.1.0.tar.gz.

File metadata

  • Download URL: pywebnn-0.1.0.tar.gz
  • Upload date:
  • Size: 195.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pywebnn-0.1.0.tar.gz
Algorithm Hash digest
SHA256 1af94cc76877d0cf2646bd7680a2456ac1e3a08be2b6737f1eb4a502b0fb0a4e
MD5 ea62cef3d0d3b1f7465f90f4e6924724
BLAKE2b-256 467662b06ef1e814599e135d97b4a7b28ffb83ce5145fd9fc83247bcabf94856

See more details on using hashes here.

Provenance

The following attestation bundles were made for pywebnn-0.1.0.tar.gz:

Publisher: publish-pypi.yml on tarekziade/rustnn

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pywebnn-0.1.0-cp312-cp312-win_amd64.whl.

File metadata

  • Download URL: pywebnn-0.1.0-cp312-cp312-win_amd64.whl
  • Upload date:
  • Size: 225.0 kB
  • Tags: CPython 3.12, Windows x86-64
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pywebnn-0.1.0-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 36f461274c0fd5576bab9bf18e1cd394a913a1ae98e3efe694d1563b6a8cd0a6
MD5 18c38563d2912155e0ed59b9526d530a
BLAKE2b-256 88b1af8fa034b0e0f053da88251992d569c394b92604b98d0ced9c1c3d578563

See more details on using hashes here.

Provenance

The following attestation bundles were made for pywebnn-0.1.0-cp312-cp312-win_amd64.whl:

Publisher: publish-pypi.yml on tarekziade/rustnn

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pywebnn-0.1.0-cp312-cp312-win32.whl.

File metadata

  • Download URL: pywebnn-0.1.0-cp312-cp312-win32.whl
  • Upload date:
  • Size: 211.8 kB
  • Tags: CPython 3.12, Windows x86
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for pywebnn-0.1.0-cp312-cp312-win32.whl
Algorithm Hash digest
SHA256 ca0084570341911945f5d902b3df319f3226ca0c645c77aef8a5e7bd862422b6
MD5 2bbc91c7f1073781faf736f5e172e357
BLAKE2b-256 37b8772e1e2965e6ffaa2ec2c9631cbb6125e700c6417bfdeef7f9c5818de9ba

See more details on using hashes here.

Provenance

The following attestation bundles were made for pywebnn-0.1.0-cp312-cp312-win32.whl:

Publisher: publish-pypi.yml on tarekziade/rustnn

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pywebnn-0.1.0-cp312-cp312-manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for pywebnn-0.1.0-cp312-cp312-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 54226e4f8817126927a5c705908004aa3b0cc0583cef129ec87e3de361aabb1d
MD5 ad26fd8be6262f8b21c61025db7f7b69
BLAKE2b-256 945d9cc202193952672aee4c49b3aeff43c937c4d1ba7ada6a82171b672c8cbc

See more details on using hashes here.

Provenance

The following attestation bundles were made for pywebnn-0.1.0-cp312-cp312-manylinux_2_28_x86_64.whl:

Publisher: publish-pypi.yml on tarekziade/rustnn

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pywebnn-0.1.0-cp312-cp312-manylinux_2_28_aarch64.whl.

File metadata

File hashes

Hashes for pywebnn-0.1.0-cp312-cp312-manylinux_2_28_aarch64.whl
Algorithm Hash digest
SHA256 ecef6212b0b61536db7928b98dea23b00e7f13c29afb13930523197a7b366eeb
MD5 8733fedff1b2d3351cc6ee4bbfa74b15
BLAKE2b-256 662b45261da3a99c31c1a16e8d15f5b3620912113d5d97ebf9b71441eb296876

See more details on using hashes here.

Provenance

The following attestation bundles were made for pywebnn-0.1.0-cp312-cp312-manylinux_2_28_aarch64.whl:

Publisher: publish-pypi.yml on tarekziade/rustnn

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pywebnn-0.1.0-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for pywebnn-0.1.0-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 564741209ff01d50f81290c95429ee80094259f982a8249ae469348cb79bdd82
MD5 f6539b3b05a9fc5c6ba848737856c015
BLAKE2b-256 de52b63ae941bed25ffacb9df115ac06e9ce1107a05be926efaa631cdf020495

See more details on using hashes here.

Provenance

The following attestation bundles were made for pywebnn-0.1.0-cp312-cp312-macosx_11_0_arm64.whl:

Publisher: publish-pypi.yml on tarekziade/rustnn

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pywebnn-0.1.0-cp312-cp312-macosx_10_12_x86_64.whl.

File metadata

File hashes

Hashes for pywebnn-0.1.0-cp312-cp312-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 2f70daf3e2c31bb8e5c03eec277f035d940d8fd90802811c3a264c98a5e1aef8
MD5 b9aa00d62f508e58d7b81c238f8d5758
BLAKE2b-256 ad659c922bae25ab47fcedcec8e5741935f59fcacde43ee8c7c22a0902c49fe1

See more details on using hashes here.

Provenance

The following attestation bundles were made for pywebnn-0.1.0-cp312-cp312-macosx_10_12_x86_64.whl:

Publisher: publish-pypi.yml on tarekziade/rustnn

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page