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<'_>
impl Extractor<'_>
Sourcepub fn clear(&mut self) -> Result<()>
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.
Sourcepub fn set_light_mode(&mut self, enable: bool) -> Result<()>
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.
Sourcepub fn light_mode(&self) -> bool
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.
Sourcepub unsafe fn set_blob_allocator(&mut self, allocator: &Pool)
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.
Sourcepub unsafe fn set_workspace_allocator(&mut self, allocator: &Pool)
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.
Sourcepub unsafe fn set_kvcache_allocator(&mut self, allocator: &Pool)
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.
Sourcepub fn set_kvcache_max_seqlen_hint(&mut self, hint: usize) -> Result<()>
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.
Sourcepub fn continue_session(&mut self)
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.
Sourcepub fn input<'a>(
&mut self,
endpoint: impl Into<Endpoint<'a>>,
mat: Mat,
) -> Result<()>
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.
Sourcepub unsafe fn input_borrowed<'a>(
&mut self,
endpoint: impl Into<Endpoint<'a>>,
mat: &Mat,
) -> Result<()>
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.
Sourcepub fn extract<'a>(
&mut self,
endpoint: impl Into<Endpoint<'a>>,
width: TensorWidth,
) -> Result<OutputGuard<'_>>
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.
Sourcepub fn extract_mat<'a>(
&mut self,
endpoint: impl Into<Endpoint<'a>>,
width: TensorWidth,
) -> Result<Mat>
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]);Sourcepub fn extract_owned<'a>(
&mut self,
endpoint: impl Into<Endpoint<'a>>,
) -> Result<FinalOutput>
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.
Sourcepub fn extract_into<'a>(
&mut self,
endpoint: impl Into<Endpoint<'a>>,
buffer: &mut Vec<f32>,
) -> Result<TensorInfo>
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.