Skip to main content

Crate ncnn_rust

Crate ncnn_rust 

Source
Expand description

The crate documentation is the package README, so the page crates.io renders and the page rustdoc builds cannot drift apart: one file answers both.

§ncnn-rust

Rust CPU and optional Vulkan inference interfaces for an externally installed ncnn 20261020 SDK. The companion ncnn-rust-sys package provides raw bindings and C ABI adapters; the raw feature re-exports them as ncnn_rust::sys, and the default build publishes no generated bindings.

§Install

cargo add ncnn-rust

The crate ships Rust code only. Building it compiles the C ABI adapters against an ncnn 20261020 SDK that the build environment supplies.

§Build environment

Set NCNN_INSTALL_DIR to a matching SDK with include/ncnn and lib or lib64. NCNN_LINK_KIND selects static (default) or dylib. A shared SDK also needs the directory that holds the shared library on the runtime loader path: lib on Unix, and the bin directory that CMake installs ncnn.dll into on Windows, where a static and an import library share the ncnn.lib name. NCNN_EXTRA_LIBS supplies comma-separated native runtime dependencies in link order, optionally using static= or dylib= prefixes, such as gomp for a GCC OpenMP static SDK. NCNN_EXTRA_LIB_DIRS supplies existing dependency library directories separated by the platform path separator. Cargo compiles the adapters and generates bindings with a target-compatible C++ compiler and host-loadable libclang.

The SDK enables the C API, stdio, strings, pixel helpers, batch, INT8, BF16 and validation. Default builds use Vulkan disabled; --features vulkan requires a Vulkan-enabled SDK. Static Vulkan SDKs additionally require an explicit nonempty NCNN_EXTRA_LIBS dependency closure matching their exported CMake targets. Headers and libraries come from the same build and match the Rust target, C++ ABI and CRT. The build accepts Linux GNU, Windows MSVC and macOS on x86-64 or ARM64.

§Inference

use ncnn_rust::{Mat, Net};

fn main() -> ncnn_rust::Result<()> {
    let net = Net::builder()?.threads(2)?.load_files("model.param", "model.bin")?;
    let input = Mat::from_f32(&vec![0.; 224 * 224 * 3], &[224, 224, 3])?;
    let outputs = net.infer([("input", input)], &["output"])?;
    println!("{:?} {}", outputs[0].info, outputs[0].values.len());
    Ok(())
}

A request has one storage decision per side. On an extractor, TensorWidth selects FP32 conversion or the width the layer wrote:

FormStorage
extract(endpoint, width)borrowed read-only guard, which reserves the network until it drops
extract_mat(endpoint, width)owned native tensor, without a second copy on the default pool
extract_into(endpoint, buffer)appended to a caller vector that keeps its capacity
extract_owned(endpoint)independent FP32 values

Net::infer, infer_stored and infer_into take an Input, which carries the same choice on the input side: owned storage, borrowed FP32 values or a tensor sub view.

PixelImage checks color formats, stride and ROI before conversion or resizing. Read-only tensor views borrow their tensor and expose logical initialized data: Mat::channel, channel_range, depth, depth_range, column_range, row_range, batch and batch_range return a MatView that aliases the source storage, so the slice readers borrow it and the copying readers, like to_f32, copy out of it; Extractor::input copies a view as well. Input::view reads the region where it lives and Net::infer_into appends the outputs to a caller buffer, which is the zero-copy form for a model that takes a crop, a channel or one batch item. input transfers crate-owned storage; raw-adopted inputs are copied so external storage dependencies stay with the caller.

Batched storage is built with Mat::from_f32_batch, and TensorInfo::n reports the batch count. Mat::into_normalized and Mat::into_reshape consume a tensor the caller no longer needs, which lets the native call run on that storage instead of on a duplicate; the &self forms keep returning independent storage. Net::layers and Net::blobs describe a loaded graph without running it.

A fresh input can transfer storage and borrow an output while its extractor remains exclusively borrowed:

use ncnn_rust::TensorWidth;

let mut ex = net.extractor()?;
ex.input("input", ncnn_rust::Mat::from_f32(&[1., 2., 3.], &[3])?)?;
let output = ex.extract("output", TensorWidth::Fp32)?;
println!("{:?}", output.channel_f32(0)?);

Several inputs and outputs are the same two calls in a loop: submit each input with input and read each output with extract, extract_mat or extract_into. The caller therefore owns the error policy, and a failure names the endpoint it happened at. Mat::from_f32 copies the source slice into owned storage, input adds no wrapper tensor copy for that storage, and to_f32 explicitly copies logical values.

OutputGuard exposes checked immutable views and explicit FP32 vector copying; it exposes no raw or owned tensor handle. Drop the guard, or end its scope, before reusing its extractor, including when the guard is otherwise unused. Endpoint::Index selects a blob by index. Native unpacking, precision conversion and local-pool detachment still apply, and the caller selects FP32 interpretation according to the model. Raw-handle export, options whose raw handle was exported before configuration, native path model loading and custom-layer registration disable guard extraction. extract_mat and OutputGuard::into_mat are the owned forms: they keep the buffer the native extractor already detached, and copy only when the storage cannot be owned, which is a pooled network or an input the caller still owns.

For repeated inference, resolve endpoints once and fill one reusable vector:

let input_id = net.resolve_blob("input")?;
let output_id = net.resolve_blob("output")?;
let mut ex = net.extractor()?;
ex.input(&input_id, ncnn_rust::Mat::from_f32(&values, &[3])?)?;
let mut buffer = Vec::new();
ex.extract_into(&output_id, &mut buffer)?;

Forms that return independent storage, such as Net::infer and Extractor::extract_owned, allocate and free an output-sized vector per request, and the native network allocates its intermediate tensors per request as well. NetBuilder::reuse_blob_memory gives those tensors a pool the network owns, which is the half no process allocator setting reaches, and the reuse form above removes the output vector: together they leave no per-request allocation. A glibc host that still allocates has heap::retain_pages for the pages of a caller-allocated buffer.

Exact affinity is an OS capability. Linux and Windows expose processor IDs and thread masks; macOS reports Error::Unsupported for exact mask operations while core inference and physical-core queries remain separate.

An extractor serves repeated requests: input and input_borrowed restart the native handle once a request extracted, so a second inference recomputes rather than returning the cached blobs of the first. Extractor::clear performs that restart explicitly, and Extractor::continue_session keeps the cached state for the next input, which is what token-by-token decoding needs. The per-extractor settings set_light_mode, set_blob_allocator, set_workspace_allocator, set_kvcache_allocator and set_kvcache_max_seqlen_hint override the network options for one request path and survive a restart. Light mode releases each intermediate after its consumer, so set_light_mode(true) returns Error::Invalid while Net::shared_blobs lists a blob that feeds two layers, such as a residual connection; an explicit Split layer keeps such a graph compatible. A network and its extractor stay on the thread that created them, which makes one pair per worker the scaling unit; crates/ncnn/examples/threads.rs measures that against a single network over every core.

Quantized and half-precision outputs keep the width the producing layer wrote. Net::infer_stored returns TensorInfo and Mat, and Extractor::extract or extract_mat with TensorWidth::Stored reads one without FP32 conversion; both are readable through Mat::to_f32_typed(kind) or Mat::to_i8(). Mat::from_typed and Mat::from_i8 build the same storage for an input side, and ElementKind names each format. infer converts to FP32 and stays the form for models that end in FP32.

§Thread affinity

A network, its extractor and its tensors stay on the thread that created them: the handles are not Send or Sync because native allocation, packing and the allocator a tensor came from are thread-affine. One network and extractor pair per worker is therefore the scaling unit, and crates/ncnn/examples/threads.rs measures that against a single network over every core.

ⓘ
let net = ncnn_rust::Net::new().unwrap();
std::thread::spawn(move || drop(net));
ⓘ
let ex;
{
    let net = ncnn_rust::Net::new().unwrap();
    ex = net.extractor().unwrap();
}
drop(ex);
ⓘ
let layer;
{
    let net = ncnn_rust::Net::new().unwrap();
    layer = net.layer_handle(0).unwrap();
}
drop(layer);

§Optional Vulkan

The vulkan feature needs a matching Vulkan-enabled SDK, either shared or an explicitly configured static SDK with nonempty NCNN_EXTRA_LIBS matching its exported dependency closure. Device selection is explicit through Net::builder()?.vulkan(device), and CPU stays the default. cargo run -p ncnn-rust --features vulkan --example add -- --vulkan demonstrates synchronous CPU-Mat inference on the selected device. Native per-layer CPU fallback remains possible.

Resident gpu::Tensor, Allocator, blocking-completion Command, completed TensorGuard, cache persistence and unsafe same-device buffer imports are available. FP32 extractor guards reject device networks, while stored extraction serves them because the download copy is detached from the pool allocator. Nonblocking submission and arbitrary external device adoption are unavailable in the pinned native API.

§Performance

The benchmark compares against the native C API from the same SDK in one process, so it isolates the binding from the engine. Median milliseconds per request, one thread:

ModelDevicenativencnn-rustDelta
NanoDet-m, 6 outputsCPU23.01123.379+1.6%
PP-OCRv5 recognitionCPU57.56658.842+2.2%
NanoDet-m, 6 outputsVulkan4.4894.702+4.7%
PP-OCRv5 recognitionVulkan10.86310.210within spread

The ncnn-rust column resolves endpoints once and reuses a caller vector, which allocates nothing after warm-up. Single-layer graphs stay at native timing: ReLU and AbsVal both measure 0.002 ms on CPU. Returning an owned vector per request instead costs one output copy, which is where the NanoDet Vulkan gap of 18% comes from. extract_mat and OutputGuard::into_mat return an owned tensor without that copy: the native extractor already detaches its output from the network’s blob pool, and these forms keep that buffer.

§Versions

MSRV: Rust 1.85.1. License: BSD-3-Clause. Native ncnn retains its upstream license.

Re-exports§

pub use ncnn_sys as sys;

Modules§

alloc
CPU-side allocators.
cpu
Native CPU capabilities, legacy worker masks, and OS processor-group affinity.
gpu
Process-lifetime Vulkan initialization and explicit device selection.
heap
Process heap tuning for the request forms that allocate output storage.
image
Checked CPU image views, color conversion, resizing, orientation, and affine warping.

Structs§

BlobId
A graph-specific blob index resolved once before repeated inference. The token remains invalid after graph replacement, including address reuse.
BlobInfo
One blob of a loaded network.
Borders
Border sizes for the padding and crop helpers.
DataReader
An owned, bounded binary reader for advanced native loading.
Extractor
Runs one request against a borrowed network.
FinalOutput
One requested output with independent storage.
GraphLayer
A layer a loaded graph owns, borrowed for native calls.
Layer
A single CPU layer with automatic pipeline cleanup.
LayerInfo
One layer of a loaded network.
Mat
An owned tensor handle released through the native allocator.
MatView
A read-only alias of part of a tensor.
ModelBin
A ModelBin backed by owned, deep-copied tensors.
Net
A network configured before its first parameter load.
NetBuilder
Configures a network and loads its model in one expression.
Options
Native CPU option storage. Net::configure applies it to an unloaded network.
OutputGuard
A read-only output that borrows its extractor and reserves the network.
OutputRange
Shape and boundary of one named output in a concatenated final buffer.
ParamDict
Owns a native parameter dictionary for standalone layers.
ReshapeView
A read-only reshape retaining its source and allocator provenance. It cannot be transferred into an extractor or exported as a native handle.
ShapeInfo
One shape a layer recorded for one of its blobs.
TensorInfo
Native tensor metadata for one extracted output.

Enums§

BorderMode
Edge treatment of Mat::copy_make_border.
CpuOption
Identifies one native integer option.
ElementKind
Scalar format of a native tensor.
Endpoint
Selects a graph endpoint by name, exposed index or resolved token.
Error
Failure from the native layer or from a validated Rust check.
Input
One input of a request.
OptionFlag
Independent native boolean preferences. Native capability dispatch remains authoritative.
ParamKind
Storage form of one parameter dictionary entry.
ParamSource
Where a network reads its parameters from.
PixelFormat
Source and destination pixel layout for image conversion.
TensorWidth
Element width an extraction asks the native extractor for.
WeightSource
Where a network reads its weights from.

Functions§

cpu_count
Returns the native logical CPU count.
layer_type_index
Returns the registered type index of a layer type.
version
Returns the pinned native version.
version_number
Returns the pinned native version as the integer ncnn encodes, which is the release date.

Type Aliases§

Result
Result of a fallible wrapper operation.