onnx-extractor

Library Listed

Minimal ONNX model loader for extracting weights, tensors, operations, and graph structure

Checked · Sources

Downloads
3,975
Dependents
4
Stars
6
Forks
0
Contributors
1
Commits
169
Latest release
0.5.2 ·

About

From the project README ·

A minimal ONNX model loader designed for extracting weights, tensor data, operations, and graph structure. Built for zero-copy access with memory mapping (mmap) and lazy external data support.

Model Loading

use onnx_extractor::Model;

// Load from file (uses mmap)
let model = Model::load_from_file("model.onnx")?;

// Load from bytes (e.g. Vec<u8>, Bytes, &'static [u8])
let bytes = std::fs::read("model.onnx")?;
let model = Model::load_from_bytes(bytes)?;

// Load from bytes with a directory path for external data files
let bytes = std::fs::read("path/to/model.onnx")?;
let model = Model::load_from_bytes_with_path(bytes, "path/to")?;

Model and Graph Functions

Global metadata is accessed from the Model container, while graph structure and state is accessed via model.graph().

Read the full README
// Model summary
println!("{}", model);

// Get individual metadata items
let opset = model.default_opset_version(); // Option<i64>
let metadata = model.metadata(); // &HashMap<String, String>
let ir_ver = model.ir_version(); // i64

// Graph access
let graph = model.graph();

// Tensor access
let tensor = graph.tensors().get("input_name"); // Option<&Tensor>
let tensor_names = graph.tensors().keys(); // Iterator<Item = &String>
let inputs = graph.get_input_tensors(); // Iterator<Item = &Tensor>
let outputs = graph.get_output_tensors(); // Iterator<Item = &Tensor>
let weights = graph.get_weight_tensors(); // Iterator<Item = &Tensor>

// Operation access
let operation = graph.get_operation("op_name"); // Option<&Operation>
let conv_ops = graph.get_operations_by_type("Conv"); // Iterator<Item = &Operation>
let op_types = graph.operation_types(); // HashSet<&str>
let op_counts = graph.count_operations_by_type(); // HashMap<&str, usize>

// Topological order
let topo_order = graph.topological_order()?; // Vec<&Operation>

// Extracting a tensor (moves out of graph so data can outlive it)
// (Note: `model` must be declared as `mut model`)
let owned_tensor = model.graph_mut().tensors_mut().remove("weight"); // Option<Tensor>

Tensor Functions

use onnx_extractor::TensorDataRef;

let tensor = model.graph().tensors().get("weight").unwrap();

// Name, shape and data type
println!("Name: {:?}", tensor.name());
println!("Shape: {:?}", tensor.shape());
println!("Data type: {:?}", tensor.data_type());

// Check if tensor contains data (does not trigger external file loading or mmap)
let has_data = tensor.has_data(); // bool

// Borrow tensor data
let data_ref = tensor.data()?; // TensorDataRef<'_>
println!("Data size: {} bytes", data_ref.len());

// Get data as contiguous byte slice
// Returns Some(&[u8]) for Raw and Numeric variants; returns None for Strings as they are not contiguous in memory
if let Some(bytes) = data_ref.as_slice() {
    println!("Byte slice length: {}", bytes.len());
}

// Access string elements for String tensors
if let Some(strings) = data_ref.strings() {
    for s in strings {
        println!("String element: {:?}", s);
    }
}

// Access Raw data
if let TensorDataRef::Raw(bytes) = &data_ref {
    println!("Bytes length: {}", bytes.len());
}

// Consume tensor and get owned data
// This allows the data to outlive the model itself
// (Note: `model` must be declared as `mut model`)
if let Some(owned_tensor) = model.graph_mut().tensors_mut().remove("weight") {
    let owned_data = owned_tensor.into_data()?; // TensorData
}
Tensor Data Enums

The data() method returns a TensorDataRef which borrows from the model:

pub enum TensorDataRef<'a> {
    /// Contiguous buffer (mmap-backed or loaded)
    Raw(Bytes),
    /// String tensor elements (shared Bytes)
    Strings(&'a [Bytes]),
    /// Typed numeric data
    F32(&'a [f32]),
    F64(&'a [f64]),
    I32(&'a [i32]),
    I64(&'a [i64]),
    U64(&'a [u64]),
}

The into_data() method returns an owned TensorData (using Bytes or Vec storage from the protobuf):

pub enum TensorData {
    /// Contiguous buffer (mmap-backed or loaded)
    Raw(Bytes),
    /// String tensor elements (shared Bytes)
    Strings(Vec<Bytes>),
    /// Typed numeric data
    F32(Vec<f32>),
    F64(Vec<f64>),
    I32(Vec<i32>),
    I64(Vec<i64>),
    U64(Vec<u64>),
}

Operation Functions

let op = model.graph().get_operation("conv1").unwrap();

// Basic info
println!("Type: {}", op.op_type());
println!("Inputs: {:?}", op.inputs());
println!("Outputs: {:?}", op.outputs());

// Attribute access
let attributes = op.attributes();
if let Some(attr) = attributes.get("kernel_shape") {
    let kernel_size = attr.as_ints(); // Option<&[i64]>
}

let stride = attributes.get("stride").and_then(|a| a.as_int()); // Option<i64>
let activation = attributes.get("activation").and_then(|a| a.as_string()); // Option<&Bytes>
// Or for validated UTF-8:
let activation_str = attributes.get("activation").and_then(|a| a.as_string_validated().ok()); // Option<&str>

// Subgraph access (Control Flow subgraphs)
if let Some(subgraph) = attributes.get("then_branch").and_then(|a| a.as_graph()) {
    println!("Subgraph name: {:?}", subgraph.graph_name());
}

Data Types

Access the DataType enum for type checking:

use onnx_extractor::DataType;

let tensor = model.graph().tensors().get("input").unwrap();
match tensor.data_type() {
    DataType::Float => println!("32-bit float"),
    DataType::Double => println!("64-bit float"),
    DataType::Int32 => println!("32-bit int"),
    _ => println!("Other type"),
}

// Type properties
let size = tensor.data_type().size_in_bytes(); // Option<usize>
let is_float = tensor.data_type().is_float();
let is_int = tensor.data_type().is_integer();

External Data Support

ONNX models can store large tensor data in external files. This crate supports lazy loading of external data with automatic caching:

// Load model with external data files
let model = Model::load_from_file("large_model.onnx")?;

// External data files (e.g., "large_model.onnx.data") are automatically discovered
// from the model directory and loaded lazily when tensor data is accessed

let tensor = model.graph().tensors().get("large_weight").unwrap();

// Data is loaded from external file on first access and cached for subsequent use
let data = tensor.data()?;
println!("Loaded {} bytes from external file", data.len());

// Multiple tensors can share the same external file efficiently
// The file is only loaded once and cached
External Data Features
  • Lazy Loading: External files are only loaded when tensor data is accessed
  • Shared Caching: Multiple tensors sharing the same external file benefit from caching
  • Offset & Length: Supports reading specific ranges from large external files

About the protobuf (onnx.proto)

This crate generates Rust types from the ONNX protobuf at build time using prost-build.

Platform Notes

  • Endianness: Raw tensor data uses little-endian byte order as defined in the ONNX specification. Typed fields use native host representation.

License

MIT

Runs on
GPU support unknown
What shows it
  • no dependency or feature matches a backend row
Native code
None found
  • No native code found
Python bindings
No Python binding crate found
License
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.

onnx-extractor beside the projects that share a topic with it
ProjectDownloadsDependentsStarsLatest releaseRuns on (GPU)Native codeLicense
onnx-extractor This page Listed

Minimal ONNX model loader for extracting weights, tensors, operations, and graph structure

3,975 downloads over 30 days 4 6 0.5.2 GPU support unknown No native code found MIT
safetensors Featured

Provides functions to read and write safetensors which aim to be safer than their PyTorch counterpart.

5,486,837 downloads over 30 days 531 3,943 0.8.0 GPU support unknown No native code found Apache-2.0
gguf Listed

GGUF file parser

2,472 downloads over 30 days 4 25 0.1.8 GPU support unknown No native code found MIT
onnx-rs Listed

Zero-dependency ONNX model parser in Rust

453 downloads over 30 days 5 6 0.1.3 GPU support unknown No native code found MIT
cmf App Listed

One backbone, many specialists. CMF is a self-describing, memory-mappable single-file format and a dependency-free runtime for quantized LLMs — zero-copy execution on CPU or GPU (Vulkan · Metal · DX12) that overlays task-specialized skills onto one shared model, with no per-model duplication.

24 binary downloads per release Not applicable 52 Not measured Not measured Apache-2.0
compressr App New

Model conversion and quantization with no Python: reads SafeTensors, GGUF, TCF and PyTorch state dicts, writes SafeTensors, GGUF and TCF, and quantizes to Q2_K through Q8_0 and IQ4 formats, including Q4_K_M mixes. GPTQ, AWQ, NF4, FP8, EXL2 and ONNX input are not implemented.

Python bindings

23 downloads over 30 days Not applicable 0 0.2.1 GPU support unknown No native code found Apache-2.0
Why ListedNo archive, New or Featured rule places it, so it is Listed.

What it lacks for Featured

  • It has 3 active dependents and 3 new dependents in 365 days. Featured needs 11 active dependents or 9 new dependents in 365 days. The repository route reads 6 stars, 0 forks and 1 contributor. It needs 4,539 stars, 434 forks and 79 contributors together.

What else the check found

  • The last activity is on 30 Oct 2026, 10 days ago. The rules expect an update within 365 days. Dormancy rule

Exact rules: Listed, Featured library. The check on applied thresholds version 9.

Every rule outcome, as the check records it
  • expected-interval: version 0.5.2 base 300, raised to the 365-day floor: E = 365 days
  • dormancy: last activity 2026-10-30, 10 days ago, E = 365: active
  • featured: not featured: active_users 3 < 11 and new_adopters 3 < 9 and repository route stars 6 (needs 4539), forks 0 (needs 434), contributors 1 (needs 79)
  • listed: listed: no archive, new or featured rule applies

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
Adoption3 active dependents, 3 new dependents in 365 days1 not measured
Adoption measurements
SignalValueSourceFetchedCounts
Active dependents3crates.io database dumpYes
New dependents (365 days)3crates.io database dumpYes
Peak active dependents3crates.io database dumpYes
Active dependents as a share of the peak1crates.io database dumpYes
Binary downloads per releaseNot measuredYes
MaintenanceLatest human commit: 10 days ago3 not measured
Maintenance measurements
SignalValueSourceFetchedCounts
Latest human commit2026-10-30GitHub repositoryYes
Latest release2026-10-30crates.io database dumpYes
First release2025-08-18crates.io database dumpYes
Latest version0.5.2crates.io database dumpYes
Days the oldest outside issue waits for a reply0GitHub repositoryYes
Maintainer replies over 365 days0GitHub repositoryYes
Repository archivedfalseGitHub repositoryYes
Repository gonefalseGitHub repositoryYes
Release commit or manifest in the repotruecrates.io packageYes
Published docstruecrates.io database dumpYes
Latest release fails cargo checkNot measuredYes
Build check dateNot measuredYes
Build check toolchainNot measuredYes
SecurityUnpatched vulnerabilities: none
Security measurements
SignalValueSourceFetchedCounts
Unpatched vulnerabilities past the grace windownoneRustSec advisory databaseYes
RustSec unmaintained advisorynoneRustSec advisory databaseYes
Deprecation noticenonecrates.io database dumpYes
Deprecated requirementnonecrates.io database dumpYes
Distribution26 releases, 3,975 downloads over 30 days5 not measured
Distribution measurements
SignalValueSourceFetchedCounts
Releases26crates.io database dumpYes
Downloads over 30 days3975crates.io database dumpYes
Binary downloads over the last 3 releasesNot measuredYes
Homebrew installs on request over 365 daysNot measuredYes
Repology repository familiesNot measuredYes
Docker pull growth over 90 daysNot measuredYes
Docker pulls at the growth baselineNot measuredYes
Every version a prereleasefalsecrates.io database dumpYes
Every version 0.0.xfalsecrates.io database dumpYes
Every version yankedfalsecrates.io database dumpYes
Crate deleted from crates.iofalsecrates.io database dumpYes
Repository6 stars, 0 forks, 1 contributors, 169 commits. Stars alone never qualify a project.
Repository measurements
SignalValueSourceFetchedCounts
GitHub stars6GitHub repositoryYes — one part of the repository route
GitHub forks0GitHub repositoryYes — one part of the repository route
Contributors with a GitHub account1GitHub contributorsYes — one part of the repository route
Commits on the default branch169GitHub repositoryNo
Repository's main crate left out of the entrynonecrates.io database dumpYes
Facts that never count
Facts that never count measurements
SignalValueSourceFetchedCounts
LicenseMITcrates.io database dumpNo
Runs on, from listed crates and their direct dependenciesGPU support unknowncrates.io database dumpNo
What shows each backendno dependency or feature matches a backend rowcrates.io database dumpNo
Native code, from listed crates and their dependenciesNo native code foundcrates.io database dumpNo
Python bindings, from direct dependencies of listed cratesNo Python binding crate foundcrates.io database dumpNo
Crates that depend on a listed crate directly4crates.io database dumpNo

Corrections and review history

Report a correction

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.