Skip to main content

Extractor

Struct Extractor 

Source
pub struct Extractor<'net> { /* private fields */ }
Expand description

Runs one request against a borrowed network.

§Thread affinity

An extractor borrows its network, so it stays on the thread that created both. A worker thread builds its own network and extractor instead of sharing them.

§Reuse

The native extractor caches the blobs a request produced, so submitting a second input to the same handle would answer from that cache. input therefore restarts the handle first, which makes one extractor safe to reuse: the second extraction recomputes instead of returning the first answer. A restart creates a new native handle, because ncnn’s Extractor::clear empties the blob table and leaves the handle unable to accept input; the per-request settings below are re-applied to the new handle. clear performs the restart explicitly, and continue_session keeps the cache for the next input, which is what token-by-token decoding needs.

Implementations§

Source§

impl Extractor<'_>

Source

pub fn clear(&mut self) -> Result<()>

Restarts this handle so the next request starts from an empty cache.

The handle stays usable: a restart creates a new native extractor and re-applies the per-request settings. input performs this restart itself once the handle has extracted, so an explicit call is only needed to release a cached request early or after a failure.

Source

pub fn set_light_mode(&mut self, enable: bool) -> Result<()>

Enables or disables light mode for this extractor.

Light mode releases each intermediate tensor after its consumer ran, which lowers what a request holds in memory. Native ncnn releases the bottom blob after its first consumer and refills it from its producer, so a graph whose blob feeds several layers, such as a residual connection or an input consumed twice, returns wrong values instead of failing: Net::shared_blobs lists those blobs, and enabling light mode while the list is not empty returns Error::Invalid. The network option stays unchanged; light_mode reports the value this handle uses.

Source

pub fn light_mode(&self) -> bool

Reports the light mode this extractor uses.

The value is the per-extractor override when one was set, and the value the network option held when this extractor was created otherwise.

Source

pub unsafe fn set_blob_allocator(&mut self, allocator: &Pool)

Takes intermediate tensor storage from a caller pool for this extractor.

§Safety

The allocator stays alive and usable until this extractor is dropped, and no other extractor or network claims the same pool at the same time. The native extractor stores the handle without taking ownership.

Source

pub unsafe fn set_workspace_allocator(&mut self, allocator: &Pool)

Takes layer workspace from a caller pool for this extractor.

§Safety

The same lifetime and exclusivity rules as set_blob_allocator apply.

Source

pub unsafe fn set_kvcache_allocator(&mut self, allocator: &Pool)

Takes key-value cache storage from a caller pool for this extractor.

§Safety

The same lifetime and exclusivity rules as set_blob_allocator apply.

Source

pub fn set_kvcache_max_seqlen_hint(&mut self, hint: usize) -> Result<()>

Sets the key-value cache sequence length hint for this extractor.

The hint sizes the cache a long-context graph reserves; zero clears it.

Source

pub fn continue_session(&mut self)

Starts the next input from the cached state this handle already holds.

The default boundary between requests restarts the handle, which is what an independent request needs. A graph that carries state across inputs, such as an attention layer that keeps a key/value cache for token-by-token decoding, continues instead: this call applies to the next input only, leaves the blobs the previous request produced in place, and skips the restart that input would otherwise perform. The caller keeps the cache valid, so the graph and the input both have to belong to one session.

A graph without a cache reads the values the previous request left, because a layer runs only while its output blob is empty.

Source

pub fn input<'a>( &mut self, endpoint: impl Into<Endpoint<'a>>, mat: Mat, ) -> Result<()>

Consumes an owned input, copying raw-adopted storage.

The tensor’s storage is transferred when the crate created or independently cloned it, and copied when it came from a raw handle, because the caller keeps managing that storage. The endpoint resolves to a graph input; a reserved network rejects the call until its scoped output drops.

Source

pub unsafe fn input_borrowed<'a>( &mut self, endpoint: impl Into<Endpoint<'a>>, mat: &Mat, ) -> Result<()>

Submits a borrowed tensor without copying its storage.

This is the zero-copy form of input: native input keeps a shallow handle, so the tensor’s buffer is read in place. The tensor must already hold unpacked FP32 storage, and the network must run without light mode, because the native forward path reads a storage refcount that an external tensor does not carry. Upstream tracks that defect as Tencent/ncnn#1543 and has a fix under review in Tencent/ncnn#7270; the rejection here can be relaxed once a release carries it.

§Safety

The tensor and the storage behind it must stay alive and unmodified until every extraction that reads this input has finished and the extractor is dropped. input copies instead, which is why it is safe. Input::borrowed bounds the borrow to one request.

Source

pub fn extract<'a>( &mut self, endpoint: impl Into<Endpoint<'a>>, width: TensorWidth, ) -> Result<OutputGuard<'_>>

Borrows eligible CPU output through a scoped guard.

The guard reserves the network for its lifetime, so no other extractor starts and no input replacement happens until it drops. Eligibility needs the low-copy path: safe options before loading, no raw handle exports, and one live extractor. TensorWidth::Stored keeps the width the producing layer wrote, which is what a device network can borrow; networks that miss the requirements use extract_owned.

Source

pub fn extract_mat<'a>( &mut self, endpoint: impl Into<Endpoint<'a>>, width: TensorWidth, ) -> Result<Mat>

Returns one output as an independently owned tensor without copying it.

The native extractor detaches the output from its own pool allocator before it returns the handle, so the buffer already belongs to the tensor: this form takes that buffer instead of duplicating it. The tensor stays valid after the extractor and the network are dropped, and after later requests run.

A network built with NetBuilder::reuse_blob_memory returns tensors inside its pools, which have to outlive them, and an extractor that submitted a borrowed input returns caller storage; both cases copy instead, so the tensor is independent either way. Use extract while the output is consumed in place, and extract_owned for FP32 values in a caller-owned vector.

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 mut extractor = net.extractor()?;
extractor.input("input", ncnn_rust::Mat::from_f32(&[-1.0, 2.0], &[2])?)?;
let output = extractor.extract_mat("output", ncnn_rust::TensorWidth::Fp32)?;
assert_eq!(output.to_f32()?, [0.0, 2.0]);
Source

pub fn extract_owned<'a>( &mut self, endpoint: impl Into<Endpoint<'a>>, ) -> Result<FinalOutput>

Returns validated values with independent owned storage.

This is the form that works for every network, including device networks, networks with exported raw handles and networks with more than one live extractor. It converts the output to FP32 and copies it, so a quantized model needs extract_mat with TensorWidth::Stored.

Each call allocates the value vector and frees it again. extract_into appends to a caller buffer instead and allocates no data buffer, extract_mat returns the tensor the extractor already detached without copying it, and crate::heap::retain_pages keeps the freed pages mapped on glibc Linux.

Source

pub fn extract_into<'a>( &mut self, endpoint: impl Into<Endpoint<'a>>, buffer: &mut Vec<f32>, ) -> Result<TensorInfo>

Appends the output to a caller vector and returns its shape metadata.

The vector keeps its capacity across calls, which is what makes the steady-state path allocation-free, and existing values stay in place so several outputs concatenate in call order. A failure leaves the vector exactly as it was, which is why Net::infer_into builds its ranges on this form. A caller that wants the output alone clears the vector first.

Source

pub unsafe fn as_raw(&self) -> ncnn_extractor_t

Exposes advanced access and permanently disables this extractor’s guards.

§Safety

The caller upholds native input/output rules and must not use the handle after this extractor is dropped.

Trait Implementations§

Source§

impl Drop for Extractor<'_>

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<'net> !Freeze for Extractor<'net>

§

impl<'net> !RefUnwindSafe for Extractor<'net>

§

impl<'net> !Send for Extractor<'net>

§

impl<'net> !Sync for Extractor<'net>

§

impl<'net> !UnwindSafe for Extractor<'net>

§

impl<'net> Unpin for Extractor<'net>

§

impl<'net> UnsafeUnpin for Extractor<'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.