ncnn_rust/net/extractor.rs
1//! Extractor operations, scoped outputs and guard lifetime rules.
2
3use crate::{error::status_at, sys, Error, Mat, Result};
4
5use super::{BlobId, Endpoint, FinalOutput, Net};
6use crate::net::blob::BlobKind;
7use std::{cell::Cell, ffi::CString, marker::PhantomData};
8
9/// Runs one request against a borrowed network.
10///
11/// # Thread affinity
12///
13/// An extractor borrows its network, so it stays on the thread that created both. A worker thread
14/// builds its own network and extractor instead of sharing them.
15///
16/// # Reuse
17///
18/// The native extractor caches the blobs a request produced, so submitting a second input to the
19/// same handle would answer from that cache. [`input`](Self::input) therefore restarts the handle
20/// first, which makes one extractor safe to reuse: the second extraction recomputes instead of
21/// returning the first answer. A restart creates a new native handle, because ncnn's
22/// `Extractor::clear` empties the blob table and leaves the handle unable to accept input; the
23/// per-request settings below are re-applied to the new handle. [`clear`](Self::clear) performs the
24/// restart explicitly, and [`continue_session`](Self::continue_session) keeps the cache for the next
25/// input, which is what token-by-token decoding needs.
26pub struct Extractor<'net> {
27 pub(crate) raw: sys::ncnn_extractor_t,
28 pub(crate) _net: &'net Net,
29 pub(crate) low_copy: Cell<bool>,
30 pub(crate) extracted: Cell<bool>,
31 pub(crate) continuation: Cell<bool>,
32 pub(crate) borrowed_input: Cell<bool>,
33 pub(crate) light_mode: Option<bool>,
34 pub(crate) net_light_mode: bool,
35 pub(crate) blob_allocator: Option<sys::ncnn_allocator_t>,
36 pub(crate) workspace_allocator: Option<sys::ncnn_allocator_t>,
37 pub(crate) kvcache_allocator: Option<sys::ncnn_allocator_t>,
38 pub(crate) kvcache_hint: Option<i32>,
39}
40
41/// Element width an extraction asks the native extractor for.
42///
43/// Native extraction converts packed, half-precision, bfloat16 and INT8 storage to FP32 unless the
44/// caller asks for stored storage, so the width decides both the native conversion and which reader
45/// applies to the result. [`TensorWidth::Fp32`] returns `elemsize` 4 values that
46/// [`OutputGuard::as_f32_slice`] reads directly; [`TensorWidth::Stored`] keeps the width the
47/// producing layer wrote, which [Mat::to_i8](crate::Mat::to_i8) and
48/// [Mat::to_f32_typed](crate::Mat::to_f32_typed) read.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50#[non_exhaustive]
51pub enum TensorWidth {
52 /// Convert to unpacked FP32 inside the native extractor.
53 Fp32,
54 /// Keep the element width the producing layer wrote.
55 Stored,
56}
57
58enum Target {
59 Named(CString),
60 Indexed(i32),
61}
62
63impl Extractor<'_> {
64 fn resolve(&self, endpoint: Endpoint<'_>, output: bool) -> Result<Target> {
65 match endpoint {
66 Endpoint::Name(name) => Ok(Target::Named(CString::new(name)?)),
67 Endpoint::Index(index) => {
68 self.ensure_exposed_index(index, !output)?;
69 Ok(Target::Indexed(index))
70 }
71 Endpoint::Blob(blob) => {
72 let kind = if output {
73 BlobKind::Output
74 } else {
75 BlobKind::Input
76 };
77 Ok(Target::Indexed(self.validate_token(blob, kind)?))
78 }
79 }
80 }
81 fn validate_token(&self, blob: &BlobId, kind: BlobKind) -> Result<i32> {
82 if !blob.belongs_to(&self._net.graph) {
83 return Err(Error::invalid(
84 "Blob identifier belongs to another graph or an earlier load",
85 ));
86 }
87 if blob.kind() != kind {
88 return Err(Error::invalid(
89 "Blob identifier was resolved for the other endpoint kind",
90 ));
91 }
92 Ok(blob.index())
93 }
94 fn ensure_exposed_index(&self, index: i32, input: bool) -> Result<()> {
95 if !self._net.ready {
96 return Err(Error::invalid(
97 "Load the graph and weights before using blob indices",
98 ));
99 }
100 let kind_inputs = unsafe { sys::ncnn_net_get_input_count(self._net.raw) };
101 for slot in 0..kind_inputs {
102 if index >= 0 && unsafe { sys::ncnn_net_get_input_index(self._net.raw, slot) } == index
103 {
104 return Ok(());
105 }
106 }
107 if input {
108 return Err(Error::invalid("Index is not an exposed input"));
109 }
110 let outputs = unsafe { sys::ncnn_net_get_output_count(self._net.raw) };
111 for slot in 0..outputs {
112 if index >= 0 && unsafe { sys::ncnn_net_get_output_index(self._net.raw, slot) } == index
113 {
114 return Ok(());
115 }
116 }
117 Err(Error::invalid("Index is not an exposed output"))
118 }
119 fn ensure_not_reserved(&self) -> Result<()> {
120 if self._net.guard.output_borrowed.get() {
121 return Err(Error::invalid("A scoped output reserves this network"));
122 }
123 Ok(())
124 }
125 fn ensure_borrowable(&self, stored: bool) -> Result<()> {
126 if self._net.guard.extractors.get() != 1 || self._net.guard.output_borrowed.get() {
127 return Err(Error::invalid(
128 "Scoped output requires the network's only live extractor",
129 ));
130 }
131 if !self.low_copy.get() || !self._net.guard.low_copy.get() {
132 // A device network downloads into its own CPU blob storage and detaches that copy
133 // from the pool allocator, so a stored borrow is as safe there as on the host while
134 // the FP32-converting guard path stays CPU-only.
135 let device_stored = stored && self.low_copy.get() && self._net.has_device();
136 if !device_stored {
137 return Err(Error::invalid(
138 "Guarded outputs need the low-copy path: configure safe options before loading, avoid layer types that export raw handles, and keep one extractor per network; use extract_owned, extract_mat or infer for independent storage instead",
139 ));
140 }
141 }
142 Ok(())
143 }
144 /// Restarts this handle so the next request starts from an empty cache.
145 ///
146 /// The handle stays usable: a restart creates a new native extractor and re-applies the
147 /// per-request settings. [`input`](Self::input) performs this restart itself once the handle has
148 /// extracted, so an explicit call is only needed to release a cached request early or after a
149 /// failure.
150 pub fn clear(&mut self) -> Result<()> {
151 self.restart(true)
152 }
153 /// Enables or disables light mode for this extractor.
154 ///
155 /// Light mode releases each intermediate tensor after its consumer ran, which lowers what a
156 /// request holds in memory. Native ncnn releases the bottom blob after its first consumer and
157 /// refills it from its producer, so a graph whose blob feeds several layers, such as a residual
158 /// connection or an input consumed twice, returns wrong values instead of failing:
159 /// [`Net::shared_blobs`](crate::Net::shared_blobs) lists those blobs, and enabling light mode
160 /// while the list is not empty returns [`Error::Invalid`]. The network option stays unchanged;
161 /// [`light_mode`](Self::light_mode) reports the value this handle uses.
162 pub fn set_light_mode(&mut self, enable: bool) -> Result<()> {
163 if enable {
164 super::reject_light_mode(self._net)?;
165 }
166 unsafe { sys::ncnn_rs_extractor_lightmode(self.raw, i32::from(enable)) };
167 self.light_mode = Some(enable);
168 Ok(())
169 }
170 /// Reports the light mode this extractor uses.
171 ///
172 /// The value is the per-extractor override when one was set, and the value the network option
173 /// held when this extractor was created otherwise.
174 pub fn light_mode(&self) -> bool {
175 self.light_mode.unwrap_or(self.net_light_mode)
176 }
177 /// Takes intermediate tensor storage from a caller pool for this extractor.
178 ///
179 /// # Safety
180 ///
181 /// The allocator stays alive and usable until this extractor is dropped, and no other extractor
182 /// or network claims the same pool at the same time. The native extractor stores the handle
183 /// without taking ownership.
184 pub unsafe fn set_blob_allocator(&mut self, allocator: &crate::alloc::Pool) {
185 unsafe { sys::ncnn_rs_extractor_allocator(self.raw, 0, allocator.as_raw()) };
186 self.blob_allocator = Some(allocator.as_raw());
187 }
188 /// Takes layer workspace from a caller pool for this extractor.
189 ///
190 /// # Safety
191 ///
192 /// The same lifetime and exclusivity rules as
193 /// [`set_blob_allocator`](Self::set_blob_allocator) apply.
194 pub unsafe fn set_workspace_allocator(&mut self, allocator: &crate::alloc::Pool) {
195 unsafe { sys::ncnn_rs_extractor_allocator(self.raw, 1, allocator.as_raw()) };
196 self.workspace_allocator = Some(allocator.as_raw());
197 }
198 /// Takes key-value cache storage from a caller pool for this extractor.
199 ///
200 /// # Safety
201 ///
202 /// The same lifetime and exclusivity rules as
203 /// [`set_blob_allocator`](Self::set_blob_allocator) apply.
204 pub unsafe fn set_kvcache_allocator(&mut self, allocator: &crate::alloc::Pool) {
205 unsafe { sys::ncnn_rs_extractor_allocator(self.raw, 2, allocator.as_raw()) };
206 self.kvcache_allocator = Some(allocator.as_raw());
207 }
208 /// Sets the key-value cache sequence length hint for this extractor.
209 ///
210 /// The hint sizes the cache a long-context graph reserves; zero clears it.
211 pub fn set_kvcache_max_seqlen_hint(&mut self, hint: usize) -> Result<()> {
212 let hint = i32::try_from(hint)
213 .map_err(|_| Error::invalid("Sequence hint exceeds native range"))?;
214 unsafe { sys::ncnn_rs_extractor_cache_hint(self.raw, hint) };
215 self.kvcache_hint = Some(hint);
216 Ok(())
217 }
218 /// Replaces the native handle when a request already ran, and re-applies the settings.
219 fn restart(&mut self, force: bool) -> Result<()> {
220 if !force && !self.extracted.get() {
221 return Ok(());
222 }
223 let raw = unsafe { sys::ncnn_extractor_create(self._net.raw) };
224 if raw.is_null() {
225 // The previous handle stays, and it still reports that it extracted, so a later call
226 // retries the restart instead of reading its cache.
227 return Err(Error::Native(-100));
228 }
229 self.extracted.set(false);
230 self.borrowed_input.set(false);
231 let stale = std::mem::replace(&mut self.raw, raw);
232 unsafe { sys::ncnn_extractor_destroy(stale) };
233 unsafe {
234 if let Some(enabled) = self.light_mode {
235 sys::ncnn_rs_extractor_lightmode(self.raw, i32::from(enabled));
236 }
237 for (kind, allocator) in [
238 (0, self.blob_allocator),
239 (1, self.workspace_allocator),
240 (2, self.kvcache_allocator),
241 ] {
242 if let Some(allocator) = allocator {
243 sys::ncnn_rs_extractor_allocator(self.raw, kind, allocator);
244 }
245 }
246 if let Some(hint) = self.kvcache_hint {
247 sys::ncnn_rs_extractor_cache_hint(self.raw, hint);
248 }
249 }
250 Ok(())
251 }
252 /// Drops the blobs a completed request cached, so a new input starts from the beginning.
253 fn reset_after_extraction(&mut self) -> Result<()> {
254 self.restart(false)
255 }
256 /// Starts the next input from the cached state this handle already holds.
257 ///
258 /// The default boundary between requests restarts the handle, which is what an independent
259 /// request needs. A graph that carries state across inputs, such as an attention layer that
260 /// keeps a key/value cache for token-by-token decoding, continues instead: this call applies to
261 /// the next input only, leaves the blobs the previous request produced in place, and skips the
262 /// restart that input would otherwise perform. The caller keeps the cache valid, so the graph
263 /// and the input both have to belong to one session.
264 ///
265 /// A graph without a cache reads the values the previous request left, because a layer runs
266 /// only while its output blob is empty.
267 pub fn continue_session(&mut self) {
268 self.continuation.set(true);
269 }
270 /// Ends the request boundary: a continuation keeps the cache, anything else restarts.
271 fn begin_request(&mut self) -> Result<()> {
272 if self.continuation.replace(false) {
273 return Ok(());
274 }
275 self.reset_after_extraction()
276 }
277
278 fn extract_native(&self, target: &Target, stored: bool) -> Result<Mat> {
279 self.ensure_not_reserved()?;
280 let mut raw = std::ptr::null_mut();
281 let extraction_type = i32::from(stored);
282 let code = unsafe {
283 match target {
284 Target::Named(name) => {
285 if stored {
286 sys::ncnn_rs_extractor_extract_stored(
287 self.raw,
288 name.as_ptr(),
289 extraction_type,
290 &mut raw,
291 )
292 } else {
293 sys::ncnn_extractor_extract(self.raw, name.as_ptr(), &mut raw)
294 }
295 }
296 Target::Indexed(index) => {
297 if stored {
298 sys::ncnn_rs_extractor_extract_stored_index(
299 self.raw,
300 *index,
301 extraction_type,
302 &mut raw,
303 )
304 } else {
305 sys::ncnn_extractor_extract_index(self.raw, *index, &mut raw)
306 }
307 }
308 }
309 };
310 if code != 0 {
311 if !raw.is_null() {
312 unsafe {
313 sys::ncnn_mat_destroy(raw);
314 }
315 }
316 return Err(Error::NativeAt("extract output", code));
317 }
318 self.extracted.set(true);
319 unsafe { Mat::owned(raw, false) }
320 }
321
322 /// Reports whether an extracted tensor can keep the storage ncnn handed out.
323 ///
324 /// The native extractor detaches an output from its own pool allocator before it returns the
325 /// handle, so the buffer belongs to the tensor and survives the extractor and the network. Two
326 /// configurations return storage that this crate cannot own: a network built with
327 /// [`NetBuilder::reuse_blob_memory`](crate::NetBuilder::reuse_blob_memory) hands back a tensor
328 /// inside the network's pools, and a borrowed input hands back storage the caller manages.
329 fn keeps_extracted_storage(&self) -> bool {
330 !self._net.reuses_blob_memory() && !self.borrowed_input.get()
331 }
332 /// Returns the storage ncnn handed out, or a copy when this extractor cannot keep it.
333 fn own_extracted(&self, mat: Mat) -> Result<Mat> {
334 if self.keeps_extracted_storage() {
335 Ok(mat)
336 } else {
337 mat.deep_clone()
338 }
339 }
340
341 /// Consumes an owned input, copying raw-adopted storage.
342 ///
343 /// The tensor's storage is transferred when the crate created or independently cloned it, and
344 /// copied when it came from a raw handle, because the caller keeps managing that storage. The
345 /// endpoint resolves to a graph input; a reserved network rejects the call until its scoped
346 /// output drops.
347 pub fn input<'a>(&mut self, endpoint: impl Into<Endpoint<'a>>, mat: Mat) -> Result<()> {
348 let target = self.resolve(endpoint.into(), false)?;
349 self.ensure_not_reserved()?;
350 self.begin_request()?;
351 let mat = if mat.is_transferable() {
352 mat
353 } else {
354 mat.deep_clone()?
355 };
356 unsafe {
357 status_at(
358 "submit input",
359 match &target {
360 Target::Named(name) => {
361 sys::ncnn_extractor_input(self.raw, name.as_ptr(), mat.raw)
362 }
363 Target::Indexed(index) => {
364 sys::ncnn_extractor_input_index(self.raw, *index, mat.raw)
365 }
366 },
367 )
368 }
369 }
370 /// Submits a borrowed tensor without copying its storage.
371 ///
372 /// This is the zero-copy form of [`input`](Self::input): native input keeps a shallow handle,
373 /// so the tensor's buffer is read in place. The tensor must already hold unpacked FP32 storage,
374 /// and the network must run without light mode, because the native forward path reads a storage
375 /// refcount that an external tensor does not carry. Upstream tracks that defect as
376 /// [Tencent/ncnn#1543](https://github.com/Tencent/ncnn/issues/1543) and has a fix under review in
377 /// [Tencent/ncnn#7270](https://github.com/Tencent/ncnn/pull/7270); the rejection here can be
378 /// relaxed once a release carries it.
379 ///
380 /// # Safety
381 ///
382 /// The tensor and the storage behind it must stay alive and unmodified until every extraction
383 /// that reads this input has finished and the extractor is dropped. [`input`](Self::input)
384 /// copies instead, which is why it is safe. [`Input::borrowed`](crate::Input::borrowed)
385 /// bounds the borrow to one request.
386 pub unsafe fn input_borrowed<'a>(
387 &mut self,
388 endpoint: impl Into<Endpoint<'a>>,
389 mat: &Mat,
390 ) -> Result<()> {
391 let target = self.resolve(endpoint.into(), false)?;
392 self.ensure_not_reserved()?;
393 // An external tensor carries no storage refcount, and the light-mode forward path reads that
394 // counter before it decides whether an in-place layer may write. Rejecting the combination
395 // keeps a safe request from reaching that native read.
396 if self.light_mode() {
397 return Err(Error::invalid(
398 "A borrowed input needs light mode off, because the native forward path reads the storage refcount that an external tensor does not have",
399 ));
400 }
401 self.begin_request()?;
402 let info = mat.info();
403 if !mat.f32_known || info.elemsize != 4 || info.elempack != 1 {
404 return Err(Error::invalid(
405 "A borrowed input needs unpacked FP32 storage",
406 ));
407 }
408 status_at(
409 "submit input",
410 match &target {
411 Target::Named(name) => sys::ncnn_extractor_input(self.raw, name.as_ptr(), mat.raw),
412 Target::Indexed(index) => {
413 sys::ncnn_extractor_input_index(self.raw, *index, mat.raw)
414 }
415 },
416 )?;
417 // An owned extraction of this storage would outlive the borrow the caller promised.
418 self.borrowed_input.set(true);
419 Ok(())
420 }
421 /// Borrows eligible CPU output through a scoped guard.
422 ///
423 /// The guard reserves the network for its lifetime, so no other extractor starts and no input
424 /// replacement happens until it drops. Eligibility needs the low-copy path: safe options before
425 /// loading, no raw handle exports, and one live extractor. [`TensorWidth::Stored`] keeps the
426 /// width the producing layer wrote, which is what a device network can borrow; networks that
427 /// miss the requirements use [`extract_owned`](Self::extract_owned).
428 pub fn extract<'a>(
429 &mut self,
430 endpoint: impl Into<Endpoint<'a>>,
431 width: TensorWidth,
432 ) -> Result<OutputGuard<'_>> {
433 self.ensure_borrowable(width == TensorWidth::Stored)?;
434 let target = self.resolve(endpoint.into(), true)?;
435 let mat = self.extract_native(&target, width == TensorWidth::Stored)?;
436 let keeps_storage = self.keeps_extracted_storage();
437 self._net.guard.output_borrowed.set(true);
438 Ok(OutputGuard {
439 mat,
440 keeps_storage,
441 network_borrowed: &self._net.guard.output_borrowed,
442 _extractor: PhantomData,
443 })
444 }
445 /// Returns one output as an independently owned tensor without copying it.
446 ///
447 /// The native extractor detaches the output from its own pool allocator before it returns the
448 /// handle, so the buffer already belongs to the tensor: this form takes that buffer instead of
449 /// duplicating it. The tensor stays valid after the extractor and the network are dropped, and
450 /// after later requests run.
451 ///
452 /// A network built with
453 /// [`NetBuilder::reuse_blob_memory`](crate::NetBuilder::reuse_blob_memory) returns tensors
454 /// inside its pools, which have to outlive them, and an extractor that submitted a borrowed
455 /// input returns caller storage; both cases copy instead, so the tensor is independent either
456 /// way. Use [`extract`](Self::extract) while the output is consumed in place, and
457 /// [`extract_owned`](Self::extract_owned) for FP32 values in a caller-owned vector.
458 ///
459 /// ```
460 /// let net = ncnn_rust::Net::builder()?.threads(1)?.load_bytes(
461 /// "7767517\n2 2\nInput input 0 1 input\nReLU relu 1 1 input output\n",
462 /// &[],
463 /// )?;
464 /// let mut extractor = net.extractor()?;
465 /// extractor.input("input", ncnn_rust::Mat::from_f32(&[-1.0, 2.0], &[2])?)?;
466 /// let output = extractor.extract_mat("output", ncnn_rust::TensorWidth::Fp32)?;
467 /// assert_eq!(output.to_f32()?, [0.0, 2.0]);
468 /// # Ok::<(), ncnn_rust::Error>(())
469 /// ```
470 pub fn extract_mat<'a>(
471 &mut self,
472 endpoint: impl Into<Endpoint<'a>>,
473 width: TensorWidth,
474 ) -> Result<Mat> {
475 let target = self.resolve(endpoint.into(), true)?;
476 let mat = self.extract_native(&target, width == TensorWidth::Stored)?;
477 self.own_extracted(mat)
478 }
479 /// Returns validated values with independent owned storage.
480 ///
481 /// This is the form that works for every network, including device networks, networks with
482 /// exported raw handles and networks with more than one live extractor. It converts the output
483 /// to FP32 and copies it, so a quantized model needs
484 /// [`extract_mat`](Self::extract_mat) with [`TensorWidth::Stored`].
485 ///
486 /// Each call allocates the value vector and frees it again. [`extract_into`](Self::extract_into)
487 /// appends to a caller buffer instead and allocates no data buffer,
488 /// [`extract_mat`](Self::extract_mat) returns the tensor the extractor already detached without
489 /// copying it, and [`crate::heap::retain_pages`] keeps the freed pages mapped on glibc Linux.
490 pub fn extract_owned<'a>(&mut self, endpoint: impl Into<Endpoint<'a>>) -> Result<FinalOutput> {
491 let mut values = Vec::new();
492 let info = self.extract_into(endpoint, &mut values)?;
493 Ok(FinalOutput { info, values })
494 }
495 /// Appends the output to a caller vector and returns its shape metadata.
496 ///
497 /// The vector keeps its capacity across calls, which is what makes the steady-state path
498 /// allocation-free, and existing values stay in place so several outputs concatenate in call
499 /// order. A failure leaves the vector exactly as it was, which is why
500 /// [`Net::infer_into`](crate::Net::infer_into) builds its ranges on this form. A caller that
501 /// wants the output alone clears the vector first.
502 pub fn extract_into<'a>(
503 &mut self,
504 endpoint: impl Into<Endpoint<'a>>,
505 buffer: &mut Vec<f32>,
506 ) -> Result<crate::TensorInfo> {
507 let target = self.resolve(endpoint.into(), true)?;
508 let mat = self.extract_native(&target, false)?;
509 let info = mat.info();
510 mat.to_f32_into(buffer)?;
511 Ok(info)
512 }
513 /// Exposes advanced access and permanently disables this extractor's guards.
514 ///
515 /// # Safety
516 /// The caller upholds native input/output rules and must not use the handle
517 /// after this extractor is dropped.
518 pub unsafe fn as_raw(&self) -> sys::ncnn_extractor_t {
519 self.low_copy.set(false);
520 self.raw
521 }
522}
523
524/// A read-only output that borrows its extractor and reserves the network.
525///
526/// ```compile_fail
527/// fn reuse(ex: &mut ncnn_rust::Extractor<'_>) {
528/// let output = ex.extract("output", ncnn_rust::TensorWidth::Fp32).unwrap();
529/// ex.extract("output", ncnn_rust::TensorWidth::Fp32).unwrap();
530/// println!("{:?}", output.as_f32_slice());
531/// }
532/// ```
533/// ```compile_fail
534/// fn escape(net: &ncnn_rust::Net) -> ncnn_rust::OutputGuard<'_> {
535/// let mut ex = net.extractor().unwrap();
536/// ex.extract("output", ncnn_rust::TensorWidth::Fp32).unwrap()
537/// }
538/// ```
539/// ```compile_fail
540/// fn escape_slice(ex: &mut ncnn_rust::Extractor<'_>) {
541/// let output = ex.extract("output", ncnn_rust::TensorWidth::Fp32).unwrap();
542/// let values = output.as_f32_slice().unwrap();
543/// drop(output);
544/// println!("{}", values[0]);
545/// }
546/// ```
547/// ```compile_fail
548/// fn escape_handle(output: ncnn_rust::OutputGuard<'_>) -> ncnn_rust::Mat {
549/// output.into_raw()
550/// }
551/// ```
552/// ```compile_fail
553/// fn destroy_extractor(net: &ncnn_rust::Net) {
554/// let mut ex = net.extractor().unwrap();
555/// let _output = ex.extract("output", ncnn_rust::TensorWidth::Fp32).unwrap();
556/// drop(ex); // The unused guard must still release its handle first.
557/// }
558/// ```
559pub struct OutputGuard<'extractor> {
560 mat: Mat,
561 keeps_storage: bool,
562 network_borrowed: &'extractor Cell<bool>,
563 _extractor: PhantomData<&'extractor mut ()>,
564}
565
566impl OutputGuard<'_> {
567 /// Returns the borrowed tensor metadata.
568 ///
569 /// The metadata describes the layout the native extractor produced: extents, `elemsize`,
570 /// `elempack` and the channel stride. `elemsize` decides which reader applies.
571 pub fn info(&self) -> crate::TensorInfo {
572 self.mat.info()
573 }
574 /// Borrows contiguous unpacked storage with an FP32 interpretation.
575 ///
576 /// The borrow needs aligned, unpacked, single-batch storage whose channels are adjacent, so a
577 /// 16-bit or packed output returns [`Error::Invalid`](crate::Error::Invalid) with the stored
578 /// width in the message. A multi-channel output with padded planes needs
579 /// [`channel_f32`](Self::channel_f32) or [`to_f32`](Self::to_f32).
580 pub fn as_f32_slice(&self) -> Result<&[f32]> {
581 self.mat.as_f32_slice()
582 }
583 /// Borrows one channel, skipping inter-channel padding.
584 ///
585 /// ncnn pads each channel plane, so this returns the logical elements of `channel` without the
586 /// padding a whole-tensor slice would include. An index outside the channel count returns
587 /// [`Error::Invalid`](crate::Error::Invalid).
588 pub fn channel_f32(&self, channel: usize) -> Result<&[f32]> {
589 self.mat.channel_f32(channel)
590 }
591 /// Consumes the guard and keeps the extracted tensor without copying it.
592 ///
593 /// The guard hands out the buffer the native extractor detached when this extractor can keep
594 /// it, and copies in the two cases where it cannot: a network built with
595 /// [`NetBuilder::reuse_blob_memory`](crate::NetBuilder::reuse_blob_memory) returns storage
596 /// inside its pools, and an extractor that submitted a borrowed input returns caller storage.
597 /// Either way the tensor is independent of the guard, extractor and network once this returns,
598 /// and the network stops being reserved.
599 pub fn into_mat(self) -> Result<Mat> {
600 if !self.keeps_storage {
601 return self.mat.deep_clone();
602 }
603 let guard = std::mem::ManuallyDrop::new(self);
604 // SAFETY: `guard` is never dropped, so the tensor is read exactly once, and the borrow flag
605 // is cleared here instead of in `Drop`.
606 let mat = unsafe { std::ptr::read(&guard.mat) };
607 guard.network_borrowed.set(false);
608 Ok(mat)
609 }
610 /// Copies logical FP32 elements into a new vector.
611 ///
612 /// Native padding is excluded, so the length is the product of the reported extents. Quantized
613 /// and half-precision outputs convert here; use [`to_f32_typed`](Self::to_f32_typed) to name a
614 /// 16-bit format.
615 pub fn to_f32(&self) -> Result<Vec<f32>> {
616 self.mat.to_f32()
617 }
618 /// Copies any scalar format into FP32 values, including quantized outputs.
619 ///
620 /// The tensor records an element width without a format tag, so a 16-bit output needs the
621 /// caller to say whether it holds IEEE half or bfloat16. A width that disagrees with `kind`
622 /// returns [`Error::Invalid`](crate::Error::Invalid).
623 pub fn to_f32_typed(&self, kind: crate::ElementKind) -> Result<Vec<f32>> {
624 self.mat.to_f32_typed(kind)
625 }
626 /// Copies signed 8-bit quantized values.
627 pub fn to_i8(&self) -> Result<Vec<i8>> {
628 self.mat.to_i8()
629 }
630}
631
632impl Drop for OutputGuard<'_> {
633 fn drop(&mut self) {
634 self.network_borrowed.set(false);
635 }
636}
637
638impl Drop for Extractor<'_> {
639 fn drop(&mut self) {
640 unsafe {
641 sys::ncnn_extractor_destroy(self.raw);
642 }
643 let live = self._net.guard.extractors.get();
644 self._net.guard.extractors.set(live - 1);
645 }
646}