Skip to main content

Net

Struct Net 

Source
pub struct Net { /* private fields */ }
Expand description

A network configured before its first parameter load.

ⓘ
let mut net = ncnn_rust::Net::new().unwrap();
let mut ex = net.extractor().unwrap();
net.clear();
ex.extract("output", ncnn_rust::TensorWidth::Fp32).unwrap();

§Thread affinity

A network, its extractors and the tensors they exchange belong to one thread. Native blob and device state is thread-affine, so Net is neither Send nor Sync; parallel work creates one network per thread and shares only the input bytes. Arc<Net> therefore needs one network per worker rather than a shared one.

Implementations§

Source§

impl Net

Source

pub fn layers(&self) -> Result<Vec<LayerInfo>>

Describes every layer of the loaded network in graph order.

Use the support flags to see which layer types can run on a device before selecting one; the answer is a property of the layer type, and native per-layer fallback still applies. Names are copied, so the result outlives later loads.

Source

pub fn blobs(&self) -> Result<Vec<BlobInfo>>

Describes every blob of the loaded network in graph order.

producer and consumer are layer indices, so the pair of this call and layers describes the whole graph without running it.

Source

pub fn shared_blobs(&self) -> Result<Vec<String>>

Reports the blobs more than one layer reads.

Light mode releases a bottom blob once its first consumer ran, and the layer that produced it cannot refill it, so a graph that reads one blob twice returns wrong values under light mode. An explicit Split layer gives each consumer its own blob and keeps the graph compatible. Extractor::set_light_mode and Net::extractor reject enabling light mode while this list is not empty, and the result is cached until the graph is cleared or loaded again.

Source§

impl Net

Source

pub fn set_vulkan_device(&mut self, device: Device) -> Result<()>

Selects a Vulkan device before loading, retaining native per-layer CPU fallback. Guarded outputs are unavailable for this backend; validated buffer extraction is supported.

Source

pub fn vulkan_device(&self) -> Option<&Device>

Returns the selected device, not a guarantee that every layer executes on it.

Source

pub fn builder() -> Result<NetBuilder>

Starts a builder with default options.

Source

pub fn reuses_blob_memory(&self) -> bool

Reports whether the network takes intermediate-tensor memory from its own pools.

NetBuilder::reuse_blob_memory installs the pools; a network built any other way reports false and allocates that memory through the process heap.

Source

pub fn layer_handle(&self, index: usize) -> Result<GraphLayer<'_>>

Borrows the layer the loaded graph holds at index.

layers describes the same layer without handing out a handle. The returned GraphLayer owns the C handle and lets the layer reach the raw module, which is where the support flags, the userdata and the weight loading of a layer live. The native layer itself belongs to this network and stays valid until the graph is cleared or reloaded, so the borrow ends before either happens.

Source

pub fn infer<'a>( &self, inputs: impl IntoIterator<Item = (impl AsRef<str>, impl Into<Input<'a>>)>, outputs: &[&str], ) -> Result<Vec<FinalOutput>>

Runs one request and returns validated, independently owned final buffers.

Each entry pairs a name with an Input: tensor storage this call owns, FP32 values the caller keeps, or a tensor sub view. A borrowed entry is read where it lives, and the borrow covers the whole call, which is what makes the zero-copy input path safe. Every output is converted to FP32, so a network that returns quantized storage needs infer_stored instead.

Every request allocates the output vector and frees it again, which is the largest cost of this form on a host whose heap returns freed pages to the kernel. infer_into writes into a caller buffer instead and allocates no data buffer, and crate::heap::retain_pages keeps the freed pages mapped on glibc Linux.

The native network allocates its intermediate tensors per request as well. NetBuilder::reuse_blob_memory gives those tensors a pool the network owns, which removes that allocation on every host.

let net = ncnn_rust::Net::builder()?.threads(1)?.load_bytes(
    "7767517\n2 2\nInput input 0 1 input\nReLU relu 1 1 input output\n",
    &[],
)?;
let outputs = net.infer(
    [("input", ncnn_rust::Mat::from_f32(&[-1.0, 2.0], &[2])?)],
    &["output"],
)?;
assert_eq!(outputs[0].values, [0.0, 2.0]);
Source

pub fn infer_stored<'a>( &self, inputs: impl IntoIterator<Item = (impl AsRef<str>, impl Into<Input<'a>>)>, outputs: &[&str], ) -> Result<Vec<(TensorInfo, Mat)>>

Runs one request and returns stored storage with the metadata of each output.

The element width of every output is preserved, so a quantized model is readable through Mat::to_f32_typed or Mat::to_i8.

Source

pub fn infer_into<'a>( &self, inputs: impl IntoIterator<Item = (impl AsRef<str>, impl Into<Input<'a>>)>, outputs: &[&str], buffer: &mut Vec<f32>, ) -> Result<Vec<OutputRange>>

Replaces a caller-owned vector with concatenated outputs in name order.

Returned metadata identifies every output range. Input failure preserves the vector; extraction failure leaves only completed output values.

A borrowed entry is read where the caller keeps it, so a steady-state loop allocates no data buffer on either side: the input needs no copy and the output reuses this vector. Light mode rejects a borrowed input, because the native forward path reads a storage refcount that an external tensor does not carry.

Source

pub fn new() -> Result<Self>

Creates an empty network with default options.

The network holds no graph until parameters load. Net::builder wraps this call and the configuration steps, which keeps a failure in one expression.

Source

pub fn configure(&mut self, options: &Options) -> Result<()>

Applies an option set to a network that has not loaded parameters.

The call copies the option block, so later writes to options do not reach this network. Vulkan compute is forced off here because device selection goes through set_vulkan_device, which retains the device object. A network that already selected a device keeps it. Returns Error::Invalid once parameters have loaded.

Source

pub fn load_param<'a>( &mut self, source: impl Into<ParamSource<'a>>, ) -> Result<()>

Replaces the graph from parameter data, a file or a reader.

ParamSource::Text begins with the 7767517 magic line and ParamSource::Binary carries the form ncnn2mem writes, which avoids parsing text at start-up. Loading releases the previous layers, weights and cached blobs first, and a failure leaves the network empty instead of partially loaded, so weights load again before the next extractor. Weights load afterwards through load_model, or in the same call through load.

Loading needs mutable access, which keeps live extractors and resolved endpoints out of the replaced graph.

Source

pub fn load_model<'a>( &mut self, source: impl Into<WeightSource<'a>>, ) -> Result<()>

Loads weights for the current parameters, once.

ncnn reads each layer’s weights in declaration order, so the source has to match the loaded parameters. Reload parameters before loading different weights. Detached outputs keep their own storage after a later reload; borrowed ones do not, which the mutable borrow already prevents.

A file source keeps the weights out of Rust memory, so the peak allocation stays at the per-layer copies ncnn keeps. load_model_file_native additionally maps the file instead of reading it.

Source

pub fn load<'a>( &mut self, params: impl Into<ParamSource<'a>>, weights: impl Into<WeightSource<'a>>, ) -> Result<()>

Loads parameters and weights in one call.

This is the two-stage pair above without the intermediate state: the call either leaves a network that can extract or an empty one, and it is what NetBuilder uses.

Source

pub unsafe fn load_model_file_native( &mut self, path: impl AsRef<Path>, ) -> Result<()>

Loads weights through the native path API, including configured memory mapping.

§Safety

The model file’s contents and length remain unchanged until the network is cleared or destroyed when mapped loading is enabled. This advanced loading path permanently disables low-copy output guards for the network.

Source

pub fn clear(&mut self)

Releases every layer, weight and cached blob.

Options and the device selection survive; loading parameters again rebuilds the graph and weights must load again before extraction. Existing extractors and resolved endpoints have to be dropped first, which the mutable borrow enforces, and a token from the cleared graph is rejected rather than resolving to a new blob.

Source

pub fn resolve_blob(&self, name: &str) -> Result<BlobId>

Resolves an exposed graph input or output without retaining a CString.

Resolution needs the loaded weights, because ncnn exposes its endpoint list only after the graph is ready. Intermediate blobs are deliberately outside this boundary: extracting one would depend on the layers between it and the outputs. The returned BlobId belongs to this graph and stops resolving after a reload.

Source

pub fn option(&self, key: CpuOption) -> Result<i32>

Returns the effective value of one option on this network.

The read comes from the native option block the net actually uses, so it reflects what ncnn applied rather than what a builder requested.

Source

pub unsafe fn register_custom_layer_by_typeindex( &mut self, typeindex: i32, creator: ncnn_layer_creator_t, destroyer: ncnn_layer_destroyer_t, userdata: *mut c_void, ) -> Result<()>

Registers a native custom-layer factory for a layer type index.

Models produced by custom-layer tooling can carry the index instead of the type name, and ncnn resolves those through this table. Registration must happen before parameters load, and ncnn records the factory without validating the index: a model that requests the index builds the layer, and no other model is affected.

§Safety

The creator must return a layer whose layout matches the index it is registered for, and both callbacks keep the native lifecycle rules that register_custom_layer documents.

Source

pub fn input_names(&self) -> Vec<String>

Returns the input blob names in graph order.

An entry without a name is reported as an empty string.

Source

pub fn output_names(&self) -> Vec<String>

Returns the output blob names in graph order.

An entry without a name is reported as an empty string.

Source

pub fn extractor(&self) -> Result<Extractor<'_>>

Creates a fresh native inference cache for one request path.

The handle restarts itself when a request already ran, so one extractor serves repeated requests without returning a cached answer. A changed input shape still needs a new extractor when the graph was loaded for one shape. The call needs loaded weights, and a live scoped output reserves the network, so create the next extractor after dropping the previous guard. A network whose options enable light mode is refused while the graph reads one blob from two layers, see shared_blobs.

Source

pub unsafe fn register_custom_layer( &mut self, name: &str, creator: ncnn_layer_creator_t, destroyer: ncnn_layer_destroyer_t, userdata: *mut c_void, ) -> Result<()>

Registers an advanced native custom-layer factory before loading parameters.

A factory registered for a built-in type index runs instead of that built-in implementation, which is how a caller replaces one; ncnn consults custom factories before it falls back to its own table.

§Safety

Callbacks and userdata must remain valid until this network is destroyed. Factories return valid owned layers; callbacks contain all Rust panics. Callback outputs must initialize logical elements and preserve allocator lifetimes.

Source

pub unsafe fn as_raw(&self) -> ncnn_net_t

Exposes advanced network access and permanently disables low-copy outputs from this network, including its existing extractors.

§Safety

The caller upholds native lifetime, allocator and synchronization rules and must not use the handle after this network is dropped or cleared.

Trait Implementations§

Source§

impl Drop for Net

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

§

impl !Freeze for Net

§

impl !RefUnwindSafe for Net

§

impl !Send for Net

§

impl !Sync for Net

§

impl Unpin for Net

§

impl UnsafeUnpin for Net

§

impl UnwindSafe for Net

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.