ncnn_rust/net/mod.rs
1//! Network construction, configuration and model loading.
2
3mod blob;
4mod extractor;
5mod graph;
6mod output;
7
8pub use blob::{BlobId, Endpoint};
9pub use extractor::{Extractor, OutputGuard, TensorWidth};
10pub use graph::{BlobInfo, LayerInfo, ShapeInfo};
11pub use output::{FinalOutput, OutputRange};
12
13use crate::{
14 error::{status, status_at},
15 sys, Error, Mat, Options, Result,
16};
17use std::{
18 cell::{Cell, RefCell},
19 ffi::{CStr, CString},
20 marker::PhantomData,
21 path::Path,
22 rc::Rc,
23};
24
25use blob::BlobKind;
26
27/// One input of a request.
28///
29/// The variant decides what the call does with the storage. [`Input::Owned`] transfers a tensor the
30/// crate created or cloned, [`Input::Borrowed`] reads FP32 values where the caller keeps them, and
31/// [`Input::View`] reads a region of an existing tensor without copying it. A borrowed entry is
32/// only valid for the call that receives it, which is why [`Net::infer`] and
33/// [`Net::infer_into`] bound the borrow themselves.
34pub enum Input<'a> {
35 /// Tensor storage this request owns.
36 Owned(Mat),
37 /// Unpacked FP32 values and their extents, read where the caller keeps them.
38 Borrowed {
39 /// Values in channel-plane order.
40 values: &'a [f32],
41 /// Extents in ncnn order, without the batch dimension.
42 dimensions: &'a [usize],
43 },
44 /// A tensor sub view, which keeps no storage of its own.
45 View(&'a crate::MatView<'a>),
46}
47
48impl<'a> Input<'a> {
49 /// Reads FP32 values the caller keeps, without copying them.
50 pub fn borrowed(values: &'a [f32], dimensions: &'a [usize]) -> Self {
51 Self::Borrowed { values, dimensions }
52 }
53 /// Reads a tensor sub view, without copying it.
54 pub fn view(view: &'a crate::MatView<'a>) -> Self {
55 Self::View(view)
56 }
57}
58
59impl From<Mat> for Input<'_> {
60 fn from(mat: Mat) -> Self {
61 Self::Owned(mat)
62 }
63}
64
65impl<'a> From<(&'a [f32], &'a [usize])> for Input<'a> {
66 fn from((values, dimensions): (&'a [f32], &'a [usize])) -> Self {
67 Self::Borrowed { values, dimensions }
68 }
69}
70
71impl<'a, 'view: 'a> From<&'a crate::MatView<'view>> for Input<'a> {
72 fn from(view: &'a crate::MatView<'view>) -> Self {
73 Self::View(view)
74 }
75}
76
77/// Where a network reads its parameters from.
78///
79/// A text or binary source keeps the parameters in memory, a file source lets the native stdio
80/// loader read the path, and a reader source serves an archive or an embedded asset.
81pub enum ParamSource<'a> {
82 /// Text parameters, starting with the `7767517` magic line.
83 Text(&'a str),
84 /// Parameters in the binary form `ncnn2mem` writes, which needs no text parsing.
85 Binary(&'a [u8]),
86 /// A file the native stdio loader opens.
87 File(&'a Path),
88 /// A reader that owns its bytes or file.
89 Reader(&'a crate::DataReader),
90}
91
92impl<'a> ParamSource<'a> {
93 fn prepare(self) -> Result<PreparedParams<'a>> {
94 Ok(match self {
95 Self::Text(text) => PreparedParams::Text(CString::new(text)?),
96 Self::Binary(data) => PreparedParams::Binary(data),
97 Self::File(path) => PreparedParams::File(utf8_path(path)?),
98 Self::Reader(reader) => PreparedParams::Reader(reader),
99 })
100 }
101}
102
103impl<'a> From<&'a str> for ParamSource<'a> {
104 fn from(text: &'a str) -> Self {
105 Self::Text(text)
106 }
107}
108
109impl<'a> From<&'a [u8]> for ParamSource<'a> {
110 fn from(data: &'a [u8]) -> Self {
111 Self::Binary(data)
112 }
113}
114
115impl<'a> From<&'a Path> for ParamSource<'a> {
116 fn from(path: &'a Path) -> Self {
117 Self::File(path)
118 }
119}
120
121impl<'a> From<&'a std::path::PathBuf> for ParamSource<'a> {
122 fn from(path: &'a std::path::PathBuf) -> Self {
123 Self::File(path)
124 }
125}
126
127impl<'a> From<&'a crate::DataReader> for ParamSource<'a> {
128 fn from(reader: &'a crate::DataReader) -> Self {
129 Self::Reader(reader)
130 }
131}
132
133/// Where a network reads its weights from.
134///
135/// Weights have no text form, so a string source names a file.
136pub enum WeightSource<'a> {
137 /// Weight bytes in declaration order.
138 Bytes(&'a [u8]),
139 /// A file the native stdio loader opens.
140 File(&'a Path),
141 /// A reader that owns its bytes or file.
142 Reader(&'a crate::DataReader),
143}
144
145impl WeightSource<'_> {
146 /// No weights, which is what a graph whose layers need none loads.
147 pub const EMPTY: WeightSource<'static> = WeightSource::Bytes(&[]);
148}
149
150impl<'a> WeightSource<'a> {
151 fn prepare(self) -> Result<PreparedWeights<'a>> {
152 Ok(match self {
153 Self::Bytes(data) => PreparedWeights::Bytes(data),
154 Self::File(path) => PreparedWeights::File(utf8_path(path)?),
155 Self::Reader(reader) => PreparedWeights::Reader(reader),
156 })
157 }
158}
159
160impl<'a> From<&'a [u8]> for WeightSource<'a> {
161 fn from(data: &'a [u8]) -> Self {
162 Self::Bytes(data)
163 }
164}
165
166impl<'a> From<&'a Vec<u8>> for WeightSource<'a> {
167 fn from(data: &'a Vec<u8>) -> Self {
168 Self::Bytes(data)
169 }
170}
171
172impl<'a> From<&'a Path> for WeightSource<'a> {
173 fn from(path: &'a Path) -> Self {
174 Self::File(path)
175 }
176}
177
178impl<'a> From<&'a std::path::PathBuf> for WeightSource<'a> {
179 fn from(path: &'a std::path::PathBuf) -> Self {
180 Self::File(path)
181 }
182}
183
184impl<'a> From<&'a str> for WeightSource<'a> {
185 fn from(path: &'a str) -> Self {
186 Self::File(Path::new(path))
187 }
188}
189
190impl<'a> From<&'a crate::DataReader> for WeightSource<'a> {
191 fn from(reader: &'a crate::DataReader) -> Self {
192 Self::Reader(reader)
193 }
194}
195
196enum PreparedParams<'a> {
197 Text(CString),
198 Binary(&'a [u8]),
199 File(CString),
200 Reader(&'a crate::DataReader),
201}
202
203enum PreparedWeights<'a> {
204 Bytes(&'a [u8]),
205 File(CString),
206 Reader(&'a crate::DataReader),
207}
208
209/// Converts a filesystem path into the UTF-8 form the native loaders accept.
210fn utf8_path(path: &Path) -> Result<CString> {
211 let text = path
212 .to_str()
213 .ok_or_else(|| Error::invalid("The native loader needs a UTF-8 path"))?;
214 Ok(CString::new(text)?)
215}
216
217/// Refuses light mode for a graph that reads one blob from more than one layer.
218///
219/// Light mode releases a bottom blob after its first consumer, and the producing layer cannot refill
220/// it, so such a graph returns wrong values instead of failing. The check runs when a request starts,
221/// which is the first point that knows both the graph and the option.
222pub(crate) fn reject_light_mode(net: &Net) -> Result<()> {
223 let shared = net.shared_blobs()?;
224 let Some(blob) = shared.first() else {
225 return Ok(());
226 };
227 Err(Error::invalid(format!(
228 "Light mode cannot run this graph: blob `{blob}` feeds more than one layer, and light mode releases a bottom blob after its first consumer; keep light mode off or add an explicit Split layer"
229 )))
230}
231
232/// Low-copy eligibility shared by a network and the extractors created from it.
233pub(crate) struct GuardState {
234 pub(crate) low_copy: Cell<bool>,
235 pub(crate) extractors: Cell<usize>,
236 pub(crate) output_borrowed: Cell<bool>,
237}
238
239impl GuardState {
240 fn new() -> Self {
241 Self {
242 low_copy: Cell::new(true),
243 extractors: Cell::new(0),
244 output_borrowed: Cell::new(false),
245 }
246 }
247}
248
249/// A network configured before its first parameter load.
250///
251/// ```compile_fail
252/// let mut net = ncnn_rust::Net::new().unwrap();
253/// let mut ex = net.extractor().unwrap();
254/// net.clear();
255/// ex.extract("output", ncnn_rust::TensorWidth::Fp32).unwrap();
256/// ```
257///
258/// # Thread affinity
259///
260/// A network, its extractors and the tensors they exchange belong to one thread. Native blob and
261/// device state is thread-affine, so `Net` is neither `Send` nor `Sync`; parallel work creates one
262/// network per thread and shares only the input bytes. `Arc<Net>` therefore needs one network per
263/// worker rather than a shared one.
264pub struct Net {
265 pub(crate) raw: sys::ncnn_net_t,
266 loaded: bool,
267 pub(crate) ready: bool,
268 custom_names: Vec<CString>,
269 pub(crate) graph: Rc<()>,
270 pub(crate) guard: GuardState,
271 #[cfg(feature = "vulkan")]
272 device: Option<crate::gpu::Device>,
273 /// Blobs more than one layer reads, computed once per load.
274 ///
275 /// Light mode releases a bottom blob after its first consumer, so a graph that reads the same
276 /// blob twice cannot run that way. The list is filled on first use and dropped by `clear`.
277 shared_blobs: RefCell<Option<Vec<String>>>,
278 /// Pools the network installed through [`NetBuilder::reuse_blob_memory`].
279 ///
280 /// The native option block stores the allocator handles without owning them, and the native
281 /// network frees its blobs through them while it is destroyed, so these fields outlive `raw`:
282 /// the explicit `Drop` impl runs first and the fields drop afterwards.
283 pools: Option<NetPools>,
284 _thread: PhantomData<Rc<()>>,
285}
286/// Holds the pools a network installed through [`NetBuilder::reuse_blob_memory`].
287///
288/// The fields are read only by their destructors, which run after the native network is destroyed.
289#[allow(dead_code, reason = "held for its destructor order")]
290struct NetPools {
291 blob: crate::alloc::Pool,
292 workspace: crate::alloc::Pool,
293}
294/// Configures a network and loads its model in one expression.
295///
296/// Each method changes one field and returns the builder, so a rejected value surfaces before any
297/// model is read. [`load_files`](Self::load_files) and [`load_bytes`](Self::load_bytes) consume the
298/// builder and return a [`Net`] whose options were applied through [`Net::configure`].
299///
300/// [`Net::builder`] starts from [`Options::new`], which disables light mode. Use
301/// [`with_options`](Self::with_options) with [`Options::native_defaults`] to keep the native preset
302/// instead.
303pub struct NetBuilder {
304 options: Options,
305 #[cfg(feature = "vulkan")]
306 device: Option<crate::gpu::Device>,
307 pools: Option<NetPools>,
308}
309impl NetBuilder {
310 /// Selects Vulkan for the network this builder creates.
311 ///
312 /// The device is retained for the network's lifetime and has to be selected before parameters
313 /// load, which is why the builder offers it here. ncnn keeps per-layer CPU fallback, so this
314 /// selects a backend rather than guaranteeing GPU placement. FP32 output guards become
315 /// unavailable on a device network; [`Extractor::extract`](crate::Extractor::extract) with
316 /// [`TensorWidth::Stored`]
317 /// and [`Net::infer_stored`] still serve it.
318 #[cfg(feature = "vulkan")]
319 pub fn vulkan(mut self, device: crate::gpu::Device) -> Self {
320 self.device = Some(device);
321 self
322 }
323 fn configured_net(mut self) -> Result<Net> {
324 let mut net = Net::new()?;
325 net.configure(&self.options)?;
326 #[cfg(feature = "vulkan")]
327 if let Some(device) = self.device.take() {
328 net.set_vulkan_device(device)?;
329 }
330 net.pools = self.pools.take();
331 Ok(net)
332 }
333 /// Reuses the memory of intermediate tensors across requests.
334 ///
335 /// The builder creates one native pool allocator for intermediate blobs and one for layer
336 /// workspace, attaches both to the option block before parameters load, and hands them to the
337 /// network, which outlives them. Every extractor of the network then takes its scratch memory
338 /// from those pools, so a request stops allocating and freeing intermediate tensors through the
339 /// process heap. The pools keep the largest blocks they served for as long as the network
340 /// lives, which is the memory the retained set grows by.
341 ///
342 /// This is the lever for hosts whose heap is slow at the allocate-and-free of an output-sized
343 /// buffer; `docs/performance.md` records the measured effect. It is independent of
344 /// [`heap::retain_pages`](crate::heap::retain_pages), which is about the pages of a buffer the
345 /// caller allocates.
346 pub fn reuse_blob_memory(mut self) -> Result<Self> {
347 let blob = crate::alloc::Pool::new()?;
348 let workspace = crate::alloc::Pool::new()?;
349 // SAFETY: the two pools move into the network built from this option block, which is the
350 // only network that uses them, and they outlive its native handle. A fresh pair per builder
351 // keeps the pools exclusive to one network.
352 unsafe {
353 self.options.set_blob_allocator(&blob)?;
354 self.options.set_workspace_allocator(&workspace)?;
355 }
356 self.pools = Some(NetPools { blob, workspace });
357 Ok(self)
358 }
359 /// Starts from the supplied options; subsequent flags override only their field.
360 /// Use `Options::native_defaults()` explicitly for the native preset.
361 pub fn with_options(options: Options) -> Self {
362 Self {
363 options,
364 #[cfg(feature = "vulkan")]
365 device: None,
366 pools: None,
367 }
368 }
369 /// Overrides one boolean option and keeps every other field.
370 pub fn flag(mut self, flag: crate::OptionFlag, enabled: bool) -> Result<Self> {
371 self.options.set_flag(flag, enabled)?;
372 Ok(self)
373 }
374 /// Overrides one integer option after validating its range.
375 ///
376 /// [`CpuOption::Threads`](crate::CpuOption::Threads) must be positive,
377 /// [`CpuOption::FlushDenormals`](crate::CpuOption::FlushDenormals) stays within `0..=3`,
378 /// [`CpuOption::OpenmpBlocktime`](crate::CpuOption::OpenmpBlocktime) and
379 /// [`CpuOption::KvCacheSequenceHint`](crate::CpuOption::KvCacheSequenceHint) accept `0`, and
380 /// other keys accept `0` or `1`. Anything else returns [`Error::Invalid`].
381 pub fn option(mut self, key: crate::CpuOption, value: i32) -> Result<Self> {
382 self.options.set(key, value)?;
383 Ok(self)
384 }
385 /// Sets [`CpuOption::Threads`](crate::CpuOption::Threads), the native worker count.
386 ///
387 /// A count of zero returns [`Error::Invalid`]; one thread runs the graph without native
388 /// workers, which is the setting the conformance suite uses.
389 pub fn threads(self, count: usize) -> Result<Self> {
390 let count = i32::try_from(count)
391 .map_err(|_| Error::invalid("Thread count exceeds native range"))?;
392 self.option(crate::CpuOption::Threads, count)
393 }
394 /// Loads text parameters and weights from files.
395 ///
396 /// The parameter file is the text form that begins with the `7767517` magic line. ncnn reads
397 /// each layer's weights in declaration order, so the two files must come from the same model.
398 /// A graph without weight layers accepts an empty weights file.
399 pub fn load_files(
400 self,
401 parameters: impl AsRef<Path>,
402 weights: impl AsRef<Path>,
403 ) -> Result<Net> {
404 let mut net = self.configured_net()?;
405 net.load_param(ParamSource::File(parameters.as_ref()))?;
406 net.load_model(WeightSource::File(weights.as_ref()))?;
407 Ok(net)
408 }
409 /// Loads text parameters and weights from memory.
410 ///
411 /// `parameters` is the text form, not the binary form. Pass `&[]` for a graph whose layers
412 /// carry no weights. On an existing network, [`Net::load_param`] followed by
413 /// [`Net::load_model`] performs the same sequence.
414 pub fn load_bytes(self, parameters: &str, weights: &[u8]) -> Result<Net> {
415 let mut net = self.configured_net()?;
416 net.load_param(parameters)?;
417 net.load_model(weights)?;
418 Ok(net)
419 }
420}
421
422impl Net {
423 /// Selects a Vulkan device before loading, retaining native per-layer CPU fallback.
424 /// Guarded outputs are unavailable for this backend; validated buffer extraction is supported.
425 #[cfg(feature = "vulkan")]
426 pub fn set_vulkan_device(&mut self, device: crate::gpu::Device) -> Result<()> {
427 if self.loaded {
428 return Err(Error::invalid(
429 "Select the backend before loading parameters",
430 ));
431 }
432 unsafe {
433 status(sys::ncnn_rs_net_vulkan(self.raw, device.index()))?;
434 }
435 self.device = Some(device);
436 self.guard.low_copy.set(false);
437 Ok(())
438 }
439 /// Returns the selected device, not a guarantee that every layer executes on it.
440 #[cfg(feature = "vulkan")]
441 pub fn vulkan_device(&self) -> Option<&crate::gpu::Device> {
442 self.device.as_ref()
443 }
444 /// Reports whether a device was selected, independent of the enabled features.
445 pub(crate) fn has_device(&self) -> bool {
446 #[cfg(feature = "vulkan")]
447 {
448 self.device.is_some()
449 }
450 #[cfg(not(feature = "vulkan"))]
451 {
452 false
453 }
454 }
455 /// Starts a builder with default options.
456 pub fn builder() -> Result<NetBuilder> {
457 Ok(NetBuilder {
458 options: Options::new()?,
459 #[cfg(feature = "vulkan")]
460 device: None,
461 pools: None,
462 })
463 }
464 /// Reports whether the network takes intermediate-tensor memory from its own pools.
465 ///
466 /// [`NetBuilder::reuse_blob_memory`] installs the pools; a network built any other way reports
467 /// `false` and allocates that memory through the process heap.
468 pub fn reuses_blob_memory(&self) -> bool {
469 self.pools.is_some()
470 }
471 /// Borrows the layer the loaded graph holds at `index`.
472 ///
473 /// [`layers`](Self::layers) describes the same layer without handing out a handle. The returned
474 /// [`GraphLayer`](crate::GraphLayer) owns the C handle and lets the layer reach the raw module,
475 /// which is where the support flags, the userdata and the weight loading of a layer live. The
476 /// native layer itself belongs to this network and stays valid until the graph is cleared or
477 /// reloaded, so the borrow ends before either happens.
478 pub fn layer_handle(&self, index: usize) -> Result<crate::GraphLayer<'_>> {
479 let index =
480 i32::try_from(index).map_err(|_| Error::invalid("Layer index exceeds native range"))?;
481 // The adapter allocates a handle around the layer this network owns; the guard releases
482 // that handle and leaves the layer alone.
483 let raw = unsafe { sys::ncnn_rs_net_layer(self.raw, index) };
484 if raw.is_null() {
485 return Err(Error::invalid("Layer index is outside the loaded graph"));
486 }
487 Ok(crate::GraphLayer::borrowed(raw))
488 }
489 /// Runs one request and returns validated, independently owned final buffers.
490 ///
491 /// Each entry pairs a name with an [`Input`]: tensor storage this call owns, FP32 values the
492 /// caller keeps, or a tensor sub view. A borrowed entry is read where it lives, and the borrow
493 /// covers the whole call, which is what makes the zero-copy input path safe. Every output is
494 /// converted to FP32, so a network that returns quantized storage needs
495 /// [`infer_stored`](Self::infer_stored) instead.
496 ///
497 /// Every request allocates the output vector and frees it again, which is the largest cost of
498 /// this form on a host whose heap returns freed pages to the kernel.
499 /// [`infer_into`](Self::infer_into) writes into a caller buffer instead and allocates no data
500 /// buffer, and [`crate::heap::retain_pages`] keeps the freed pages mapped on glibc Linux.
501 ///
502 /// The native network allocates its intermediate tensors per request as well.
503 /// [`NetBuilder::reuse_blob_memory`] gives those tensors a pool the network owns, which removes
504 /// that allocation on every host.
505 ///
506 /// ```
507 /// let net = ncnn_rust::Net::builder()?.threads(1)?.load_bytes(
508 /// "7767517\n2 2\nInput input 0 1 input\nReLU relu 1 1 input output\n",
509 /// &[],
510 /// )?;
511 /// let outputs = net.infer(
512 /// [("input", ncnn_rust::Mat::from_f32(&[-1.0, 2.0], &[2])?)],
513 /// &["output"],
514 /// )?;
515 /// assert_eq!(outputs[0].values, [0.0, 2.0]);
516 /// # Ok::<(), ncnn_rust::Error>(())
517 /// ```
518 pub fn infer<'a>(
519 &self,
520 inputs: impl IntoIterator<Item = (impl AsRef<str>, impl Into<Input<'a>>)>,
521 outputs: &[&str],
522 ) -> Result<Vec<FinalOutput>> {
523 let mut extractor = self.extractor()?;
524 let _storage = self.submit_inputs(&mut extractor, inputs)?;
525 outputs
526 .iter()
527 .map(|name| extractor.extract_owned(Endpoint::Name(name)))
528 .collect()
529 }
530 /// Runs one request and returns stored storage with the metadata of each output.
531 ///
532 /// The element width of every output is preserved, so a quantized model is readable through
533 /// [`Mat::to_f32_typed`](crate::Mat::to_f32_typed) or [`Mat::to_i8`](crate::Mat::to_i8).
534 pub fn infer_stored<'a>(
535 &self,
536 inputs: impl IntoIterator<Item = (impl AsRef<str>, impl Into<Input<'a>>)>,
537 outputs: &[&str],
538 ) -> Result<Vec<(crate::TensorInfo, Mat)>> {
539 let mut extractor = self.extractor()?;
540 let _storage = self.submit_inputs(&mut extractor, inputs)?;
541 outputs
542 .iter()
543 .map(|name| {
544 let mat = extractor.extract_mat(Endpoint::Name(name), TensorWidth::Stored)?;
545 let info = mat.info();
546 Ok((info, mat))
547 })
548 .collect()
549 }
550 /// Replaces a caller-owned vector with concatenated outputs in name order.
551 ///
552 /// Returned metadata identifies every output range. Input failure preserves the vector;
553 /// extraction failure leaves only completed output values.
554 ///
555 /// A borrowed entry is read where the caller keeps it, so a steady-state loop allocates no data
556 /// buffer on either side: the input needs no copy and the output reuses this vector. Light mode
557 /// rejects a borrowed input, because the native forward path reads a storage refcount that an
558 /// external tensor does not carry.
559 pub fn infer_into<'a>(
560 &self,
561 inputs: impl IntoIterator<Item = (impl AsRef<str>, impl Into<Input<'a>>)>,
562 outputs: &[&str],
563 buffer: &mut Vec<f32>,
564 ) -> Result<Vec<OutputRange>> {
565 let mut extractor = self.extractor()?;
566 let _storage = self.submit_inputs(&mut extractor, inputs)?;
567 buffer.clear();
568 let mut ranges = Vec::with_capacity(outputs.len());
569 for name in outputs {
570 let start = buffer.len();
571 let info = extractor.extract_into(Endpoint::Name(name), buffer)?;
572 ranges.push(OutputRange {
573 name: (*name).to_owned(),
574 info,
575 values: start..buffer.len(),
576 });
577 }
578 Ok(ranges)
579 }
580 /// Submits every input and keeps the storage the extractions still read.
581 fn submit_inputs<'a>(
582 &self,
583 extractor: &mut Extractor<'_>,
584 inputs: impl IntoIterator<Item = (impl AsRef<str>, impl Into<Input<'a>>)>,
585 ) -> Result<Vec<Mat>> {
586 let mut storage = Vec::new();
587 for (name, input) in inputs {
588 let name = Endpoint::Name(name.as_ref());
589 match input.into() {
590 Input::Owned(mat) => extractor.input(name, mat)?,
591 Input::Borrowed { values, dimensions } => {
592 // SAFETY: `values` outlives this call, and the tensor joins `storage`, which
593 // the caller holds until every extraction has finished.
594 let mat = unsafe { Mat::from_external(values, dimensions)? };
595 // SAFETY: the tensor stays reachable through `storage` for the request.
596 unsafe { extractor.input_borrowed(name, &mat)? };
597 storage.push(mat);
598 }
599 Input::View(view) => {
600 // SAFETY: the view borrows its source for the whole call, and the extractor is
601 // dropped before this function returns.
602 unsafe { extractor.input_borrowed(name, view.as_mat())? };
603 }
604 }
605 }
606 Ok(storage)
607 }
608 /// Creates an empty network with default options.
609 ///
610 /// The network holds no graph until parameters load. [`Net::builder`] wraps this call and the
611 /// configuration steps, which keeps a failure in one expression.
612 pub fn new() -> Result<Self> {
613 let options = Options::new()?;
614 let raw = unsafe { sys::ncnn_net_create() };
615 if raw.is_null() {
616 return Err(Error::Native(-100));
617 }
618 unsafe {
619 sys::ncnn_net_set_option(raw, options.raw);
620 }
621 Ok(Self {
622 raw,
623 loaded: false,
624 ready: false,
625 custom_names: Vec::new(),
626 graph: Rc::new(()),
627 guard: GuardState::new(),
628 #[cfg(feature = "vulkan")]
629 device: None,
630 shared_blobs: RefCell::new(None),
631 pools: None,
632 _thread: PhantomData,
633 })
634 }
635 /// Applies an option set to a network that has not loaded parameters.
636 ///
637 /// The call copies the option block, so later writes to `options` do not reach this network.
638 /// Vulkan compute is forced off here because device selection goes through
639 /// `set_vulkan_device`, which retains the device object. A network that already selected a
640 /// device keeps it. Returns [`Error::Invalid`] once parameters have loaded.
641 pub fn configure(&mut self, options: &Options) -> Result<()> {
642 if self.loaded {
643 return Err(Error::invalid("Configure before loading parameters"));
644 }
645 unsafe {
646 sys::ncnn_net_set_option(self.raw, options.raw);
647 // Safe Vulkan selection always requires a retained Device below.
648 sys::ncnn_option_set_use_vulkan_compute(sys::ncnn_net_get_option(self.raw), 0);
649 }
650 #[cfg(feature = "vulkan")]
651 if let Some(device) = &self.device {
652 unsafe {
653 status(sys::ncnn_rs_net_vulkan(self.raw, device.index()))?;
654 }
655 }
656 self.guard
657 .low_copy
658 .set(self.guard.low_copy.get() && options.low_copy.get());
659 Ok(())
660 }
661 /// Replaces the graph from parameter data, a file or a reader.
662 ///
663 /// [`ParamSource::Text`] begins with the `7767517` magic line and [`ParamSource::Binary`] carries
664 /// the form `ncnn2mem` writes, which avoids parsing text at start-up. Loading releases the
665 /// previous layers, weights and cached blobs first, and a failure leaves the network empty
666 /// instead of partially loaded, so weights load again before the next extractor. Weights load
667 /// afterwards through [`load_model`](Self::load_model), or in the same call through
668 /// [`load`](Self::load).
669 ///
670 /// Loading needs mutable access, which keeps live extractors and resolved endpoints out of the
671 /// replaced graph.
672 pub fn load_param<'a>(&mut self, source: impl Into<ParamSource<'a>>) -> Result<()> {
673 // A source that cannot be prepared, such as text with an interior null, leaves the loaded
674 // graph alone.
675 let prepared = source.into().prepare()?;
676 self.clear();
677 let result = unsafe {
678 match prepared {
679 PreparedParams::Text(text) => status_at(
680 "load parameters",
681 sys::ncnn_net_load_param_memory(self.raw, text.as_ptr()),
682 ),
683 PreparedParams::Binary(data) => status_at(
684 "load parameters",
685 sys::ncnn_rs_load_bytes(self.raw, data.as_ptr(), data.len(), 0),
686 ),
687 PreparedParams::File(path) => status_at(
688 "load parameters",
689 sys::ncnn_rs_net_load_file(self.raw, path.as_ptr(), 0, 0),
690 ),
691 PreparedParams::Reader(reader) => status_at(
692 "load parameters",
693 sys::ncnn_net_load_param_datareader(self.raw, reader.as_raw()),
694 ),
695 }
696 };
697 self.loaded = result.is_ok();
698 if result.is_err() {
699 self.clear();
700 }
701 result
702 }
703 /// Loads weights for the current parameters, once.
704 ///
705 /// ncnn reads each layer's weights in declaration order, so the source has to match the loaded
706 /// parameters. Reload parameters before loading different weights. Detached outputs keep their
707 /// own storage after a later reload; borrowed ones do not, which the mutable borrow already
708 /// prevents.
709 ///
710 /// A file source keeps the weights out of Rust memory, so the peak allocation stays at the
711 /// per-layer copies ncnn keeps. [`load_model_file_native`](Self::load_model_file_native)
712 /// additionally maps the file instead of reading it.
713 pub fn load_model<'a>(&mut self, source: impl Into<WeightSource<'a>>) -> Result<()> {
714 if !self.loaded || self.ready {
715 return Err(Error::invalid(
716 "Load parameters before loading weights once",
717 ));
718 }
719 let prepared = source.into().prepare()?;
720 let result = unsafe {
721 match prepared {
722 PreparedWeights::Bytes(data) => status_at(
723 "load weights",
724 sys::ncnn_rs_load_bytes(self.raw, data.as_ptr(), data.len(), 1),
725 ),
726 PreparedWeights::File(path) => status_at(
727 "load weights",
728 sys::ncnn_rs_net_load_file(self.raw, path.as_ptr(), 1, 0),
729 ),
730 PreparedWeights::Reader(reader) => status_at(
731 "load weights",
732 sys::ncnn_net_load_model_datareader(self.raw, reader.as_raw()),
733 ),
734 }
735 };
736 self.ready = result.is_ok();
737 if result.is_err() {
738 self.clear();
739 }
740 result
741 }
742 /// Loads parameters and weights in one call.
743 ///
744 /// This is the two-stage pair above without the intermediate state: the call either leaves a
745 /// network that can extract or an empty one, and it is what [`NetBuilder`] uses.
746 pub fn load<'a>(
747 &mut self,
748 params: impl Into<ParamSource<'a>>,
749 weights: impl Into<WeightSource<'a>>,
750 ) -> Result<()> {
751 self.load_param(params)?;
752 self.load_model(weights)
753 }
754 /// Loads weights through the native path API, including configured memory mapping.
755 ///
756 /// # Safety
757 /// The model file's contents and length remain unchanged until the network is
758 /// cleared or destroyed when mapped loading is enabled. This advanced loading
759 /// path permanently disables low-copy output guards for the network.
760 pub unsafe fn load_model_file_native(&mut self, path: impl AsRef<Path>) -> Result<()> {
761 if !self.loaded || self.ready {
762 return Err(Error::invalid(
763 "Load parameters before loading weights once",
764 ));
765 }
766 self.guard.low_copy.set(false);
767 #[cfg(unix)]
768 let code = {
769 use std::os::unix::ffi::OsStrExt;
770 let path = CString::new(path.as_ref().as_os_str().as_bytes())?;
771 sys::ncnn_net_load_model(self.raw, path.as_ptr())
772 };
773 #[cfg(windows)]
774 let code = {
775 use std::os::windows::ffi::OsStrExt;
776 let mut path: Vec<u16> = path.as_ref().as_os_str().encode_wide().collect();
777 if path.contains(&0) {
778 return Err(Error::invalid("Path contains a null character"));
779 }
780 path.push(0);
781 sys::ncnn_net_load_model_w(self.raw, path.as_ptr())
782 };
783 let result = status(code);
784 self.ready = result.is_ok();
785 if result.is_err() {
786 self.clear();
787 }
788 result
789 }
790 /// Releases every layer, weight and cached blob.
791 ///
792 /// Options and the device selection survive; loading parameters again rebuilds the graph and
793 /// weights must load again before extraction. Existing extractors and resolved endpoints have
794 /// to be dropped first, which the mutable borrow enforces, and a token from the cleared graph
795 /// is rejected rather than resolving to a new blob.
796 pub fn clear(&mut self) {
797 self.graph = Rc::new(());
798 unsafe {
799 sys::ncnn_net_clear(self.raw);
800 }
801 self.loaded = false;
802 self.ready = false;
803 *self.shared_blobs.borrow_mut() = None;
804 }
805 /// Resolves an exposed graph input or output without retaining a CString.
806 ///
807 /// Resolution needs the loaded weights, because ncnn exposes its endpoint list only after the
808 /// graph is ready. Intermediate blobs are deliberately outside this boundary: extracting one
809 /// would depend on the layers between it and the outputs. The returned [`BlobId`] belongs to
810 /// this graph and stops resolving after a reload.
811 pub fn resolve_blob(&self, name: &str) -> Result<BlobId> {
812 if !self.ready {
813 return Err(Error::invalid(
814 "Load the graph and weights before resolving blobs",
815 ));
816 }
817 for output in [false, true] {
818 let count = unsafe {
819 if output {
820 sys::ncnn_net_get_output_count(self.raw)
821 } else {
822 sys::ncnn_net_get_input_count(self.raw)
823 }
824 };
825 for slot in 0..count {
826 let ptr = unsafe {
827 if output {
828 sys::ncnn_net_get_output_name(self.raw, slot)
829 } else {
830 sys::ncnn_net_get_input_name(self.raw, slot)
831 }
832 };
833 if !ptr.is_null() && unsafe { CStr::from_ptr(ptr) }.to_bytes() == name.as_bytes() {
834 let index = unsafe {
835 if output {
836 sys::ncnn_net_get_output_index(self.raw, slot)
837 } else {
838 sys::ncnn_net_get_input_index(self.raw, slot)
839 }
840 };
841 if index >= 0 {
842 let kind = if output {
843 BlobKind::Output
844 } else {
845 BlobKind::Input
846 };
847 return Ok(BlobId::new(self.graph.clone(), index, kind));
848 }
849 }
850 }
851 }
852 Err(Error::invalid("Unknown graph input or output"))
853 }
854 /// Returns the effective value of one option on this network.
855 ///
856 /// The read comes from the native option block the net actually uses, so it reflects what ncnn
857 /// applied rather than what a builder requested.
858 pub fn option(&self, key: crate::CpuOption) -> Result<i32> {
859 let option = unsafe { sys::ncnn_net_get_option(self.raw) };
860 let mut value = 0;
861 unsafe { status(sys::ncnn_rs_option_get(option, key as i32, &mut value))? };
862 Ok(value)
863 }
864 /// Registers a native custom-layer factory for a layer type index.
865 ///
866 /// Models produced by custom-layer tooling can carry the index instead of the type name, and
867 /// ncnn resolves those through this table. Registration must happen before parameters load, and
868 /// ncnn records the factory without validating the index: a model that requests the index
869 /// builds the layer, and no other model is affected.
870 ///
871 /// # Safety
872 ///
873 /// The creator must return a layer whose layout matches the index it is registered for, and
874 /// both callbacks keep the native lifecycle rules that
875 /// [`register_custom_layer`](Self::register_custom_layer) documents.
876 pub unsafe fn register_custom_layer_by_typeindex(
877 &mut self,
878 typeindex: i32,
879 creator: sys::ncnn_layer_creator_t,
880 destroyer: sys::ncnn_layer_destroyer_t,
881 userdata: *mut std::ffi::c_void,
882 ) -> Result<()> {
883 if self.loaded || creator.is_none() || destroyer.is_none() {
884 return Err(Error::invalid(
885 "Register complete factories before loading parameters",
886 ));
887 }
888 self.guard.low_copy.set(false);
889 sys::ncnn_net_register_custom_layer_by_typeindex(
890 self.raw, typeindex, creator, destroyer, userdata,
891 );
892 Ok(())
893 }
894 /// Returns the input blob names in graph order.
895 ///
896 /// An entry without a name is reported as an empty string.
897 pub fn input_names(&self) -> Vec<String> {
898 self.endpoint_names(false)
899 }
900 /// Returns the output blob names in graph order.
901 ///
902 /// An entry without a name is reported as an empty string.
903 pub fn output_names(&self) -> Vec<String> {
904 self.endpoint_names(true)
905 }
906 fn endpoint_names(&self, output: bool) -> Vec<String> {
907 unsafe {
908 let count = if output {
909 sys::ncnn_net_get_output_count(self.raw)
910 } else {
911 sys::ncnn_net_get_input_count(self.raw)
912 };
913 (0..count)
914 .map(|i| {
915 let p = if output {
916 sys::ncnn_net_get_output_name(self.raw, i)
917 } else {
918 sys::ncnn_net_get_input_name(self.raw, i)
919 };
920 if p.is_null() {
921 String::new()
922 } else {
923 CStr::from_ptr(p).to_string_lossy().into_owned()
924 }
925 })
926 .collect()
927 }
928 }
929 /// Creates a fresh native inference cache for one request path.
930 ///
931 /// The handle restarts itself when a request already ran, so one extractor serves repeated
932 /// requests without returning a cached answer. A changed input shape still needs a new
933 /// extractor when the graph was loaded for one shape. The call needs loaded weights, and a live
934 /// scoped output reserves the network, so create the next extractor after dropping the previous
935 /// guard. A network whose options enable light mode is refused while the graph reads one blob
936 /// from two layers, see [`shared_blobs`](Self::shared_blobs).
937 pub fn extractor(&self) -> Result<Extractor<'_>> {
938 if self.guard.output_borrowed.get() {
939 return Err(Error::invalid("A scoped output reserves this network"));
940 }
941 if !self.ready {
942 return Err(Error::invalid(
943 "Load parameters and weights before extraction",
944 ));
945 }
946 // Read the option before the handle exists, so a failed read leaves nothing to release.
947 let net_light_mode = self.option(crate::CpuOption::LightMode)? != 0;
948 if net_light_mode {
949 reject_light_mode(self)?;
950 }
951 let raw = unsafe { sys::ncnn_extractor_create(self.raw) };
952 if raw.is_null() {
953 return Err(Error::Native(-100));
954 }
955 self.guard.extractors.set(self.guard.extractors.get() + 1);
956 Ok(Extractor {
957 raw,
958 _net: self,
959 low_copy: Cell::new(true),
960 extracted: Cell::new(false),
961 continuation: Cell::new(false),
962 borrowed_input: Cell::new(false),
963 light_mode: None,
964 net_light_mode,
965 blob_allocator: None,
966 workspace_allocator: None,
967 kvcache_allocator: None,
968 kvcache_hint: None,
969 })
970 }
971 /// Registers an advanced native custom-layer factory before loading parameters.
972 ///
973 /// A factory registered for a built-in type index runs instead of that built-in
974 /// implementation, which is how a caller replaces one; ncnn consults custom factories before it
975 /// falls back to its own table.
976 ///
977 /// # Safety
978 /// Callbacks and userdata must remain valid until this network is destroyed.
979 /// Factories return valid owned layers; callbacks contain all Rust panics.
980 /// Callback outputs must initialize logical elements and preserve allocator lifetimes.
981 pub unsafe fn register_custom_layer(
982 &mut self,
983 name: &str,
984 creator: sys::ncnn_layer_creator_t,
985 destroyer: sys::ncnn_layer_destroyer_t,
986 userdata: *mut std::ffi::c_void,
987 ) -> Result<()> {
988 if self.loaded || creator.is_none() || destroyer.is_none() {
989 return Err(Error::invalid(
990 "Register complete factories before loading parameters",
991 ));
992 }
993 let name = CString::new(name)?;
994 self.guard.low_copy.set(false);
995 status(sys::ncnn_rs_register_layer(
996 self.raw,
997 name.as_ptr(),
998 0,
999 creator,
1000 destroyer,
1001 userdata,
1002 ))?;
1003 self.custom_names.push(name);
1004 Ok(())
1005 }
1006 /// Exposes advanced network access and permanently disables low-copy outputs
1007 /// from this network, including its existing extractors.
1008 ///
1009 /// # Safety
1010 /// The caller upholds native lifetime, allocator and synchronization rules and
1011 /// must not use the handle after this network is dropped or cleared.
1012 pub unsafe fn as_raw(&self) -> sys::ncnn_net_t {
1013 self.guard.low_copy.set(false);
1014 self.raw
1015 }
1016}
1017impl Drop for Net {
1018 fn drop(&mut self) {
1019 unsafe {
1020 sys::ncnn_net_destroy(self.raw);
1021 }
1022 }
1023}