Skip to main content

ncnn_rust/net/
graph.rs

1//! Read-only description of a loaded network: its layers and its blobs.
2
3use super::Net;
4use crate::{sys, Error, Result};
5use std::ffi::CStr;
6
7/// One shape a layer recorded for one of its blobs.
8///
9/// A layer records the extents it resolved for its inputs and outputs when the graph carries shape
10/// information, which is how a caller sees a layer contract before running it. `dims` stays at zero
11/// when ncnn recorded no shape.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13pub struct ShapeInfo {
14    /// Shape rank.
15    pub dims: i32,
16    /// Width extent.
17    pub w: i32,
18    /// Height extent.
19    pub h: i32,
20    /// Depth extent.
21    pub d: i32,
22    /// Channel extent.
23    pub c: i32,
24}
25impl ShapeInfo {
26    /// Reports whether ncnn recorded a shape.
27    pub fn has_shape(&self) -> bool {
28        self.dims > 0
29    }
30}
31
32/// One layer of a loaded network.
33///
34/// The support flags are ncnn's declarations for that layer type, which is where the runtime
35/// fallback decision starts: a layer without `support_vulkan` runs on the CPU even when the network
36/// uses a device. They describe the layer type, not a promise about the selected kernel.
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct LayerInfo {
39    /// Layer name from the parameter text.
40    pub name: String,
41    /// Registered layer type, such as `Convolution`.
42    pub kind: String,
43    /// Registered type index.
44    pub typeindex: i32,
45    /// Shapes this layer recorded for its inputs, in bottom order.
46    pub bottom_shapes: Vec<ShapeInfo>,
47    /// Shapes this layer recorded for its outputs, in top order.
48    pub top_shapes: Vec<ShapeInfo>,
49    /// Number of bottom blobs the layer reads.
50    pub bottoms: usize,
51    /// Number of top blobs the layer writes.
52    pub tops: usize,
53    /// Declares a Vulkan implementation.
54    pub support_vulkan: bool,
55    /// Declares Vulkan support for packed layouts.
56    pub support_vulkan_packing: bool,
57    /// Declares support for packed CPU layouts.
58    pub support_packing: bool,
59    /// Declares support for FP16 storage.
60    pub support_fp16_storage: bool,
61    /// Declares support for BF16 storage.
62    pub support_bf16_storage: bool,
63    /// Reads exactly one bottom blob.
64    pub one_blob_only: bool,
65    /// Computes in place on its input blob.
66    pub support_inplace: bool,
67    /// Accepts a bottom blob whose layout has any element packing.
68    pub support_any_packing: bool,
69    /// Accepts any element packing on a device.
70    pub support_vulkan_any_packing: bool,
71    /// Accepts INT8 storage.
72    pub support_int8_storage: bool,
73    /// Accepts the shader tensor storage layout.
74    pub support_tensor_storage: bool,
75    /// Accepts a batch count above one.
76    pub support_batch: bool,
77}
78
79/// One blob of a loaded network.
80///
81/// A blob that ncnn could not infer keeps `dims` at zero and zero extents, which happens when the
82/// parameter text carries no shape hint and no layer produced a shape yet.
83#[derive(Clone, Debug, PartialEq, Eq)]
84pub struct BlobInfo {
85    /// Blob name from the parameter text.
86    pub name: String,
87    /// Shape hint rank.
88    pub dims: i32,
89    /// Width extent.
90    pub w: i32,
91    /// Height extent.
92    pub h: i32,
93    /// Depth extent.
94    pub d: i32,
95    /// Channel extent.
96    pub c: i32,
97    /// Index of the layer that produces this blob, or `-1` for a graph input.
98    pub producer: i32,
99    /// Index of the first layer that consumes this blob.
100    pub consumer: i32,
101}
102impl BlobInfo {
103    /// Reports whether ncnn recorded a shape for this blob.
104    pub fn has_shape(&self) -> bool {
105        self.dims > 0
106    }
107}
108
109impl Net {
110    /// Describes every layer of the loaded network in graph order.
111    ///
112    /// Use the support flags to see which layer types can run on a device before selecting one;
113    /// the answer is a property of the layer type, and native per-layer fallback still applies.
114    /// Names are copied, so the result outlives later loads.
115    pub fn layers(&self) -> Result<Vec<LayerInfo>> {
116        if !self.ready {
117            return Err(Error::invalid(
118                "Load parameters and weights before reading the graph",
119            ));
120        }
121        let count = unsafe { sys::ncnn_rs_net_layer_count(self.raw) };
122        if count < 0 {
123            return Err(Error::NativeAt("read the layer count", count));
124        }
125        let mut layers = Vec::with_capacity(count as usize);
126        for index in 0..count {
127            layers.push(self.layer_info(index)?);
128        }
129        Ok(layers)
130    }
131    fn layer_info(&self, index: i32) -> Result<LayerInfo> {
132        let mut name = std::ptr::null();
133        let mut kind = std::ptr::null();
134        let mut typeindex = 0;
135        let mut bottoms = 0;
136        let mut tops = 0;
137        let mut flags = 0;
138        let code = unsafe {
139            sys::ncnn_rs_net_layer_info(
140                self.raw,
141                index,
142                &mut name,
143                &mut kind,
144                &mut typeindex,
145                &mut bottoms,
146                &mut tops,
147                &mut flags,
148            )
149        };
150        if code != 0 || name.is_null() || kind.is_null() {
151            return Err(Error::NativeAt("read a layer", code));
152        }
153        let text = |pointer: *const std::os::raw::c_char| unsafe {
154            CStr::from_ptr(pointer).to_string_lossy().into_owned()
155        };
156        let shape = |top: bool, blob: usize| -> Result<ShapeInfo> {
157            let mut shape = ShapeInfo::default();
158            let code = unsafe {
159                sys::ncnn_rs_net_layer_shape(
160                    self.raw,
161                    index,
162                    i32::from(top),
163                    blob as i32,
164                    &mut shape.dims,
165                    &mut shape.w,
166                    &mut shape.h,
167                    &mut shape.d,
168                    &mut shape.c,
169                )
170            };
171            if code != 0 {
172                return Err(Error::NativeAt("read a layer shape", code));
173            }
174            Ok(shape)
175        };
176        let bottom_shapes = (0..bottoms.max(0) as usize)
177            .map(|blob| shape(false, blob))
178            .collect::<Result<Vec<_>>>()?;
179        let top_shapes = (0..tops.max(0) as usize)
180            .map(|blob| shape(true, blob))
181            .collect::<Result<Vec<_>>>()?;
182        Ok(LayerInfo {
183            name: text(name),
184            kind: text(kind),
185            typeindex,
186            bottom_shapes,
187            top_shapes,
188            bottoms: bottoms.max(0) as usize,
189            tops: tops.max(0) as usize,
190            support_vulkan: flags & (1 << 0) != 0,
191            support_vulkan_packing: flags & (1 << 1) != 0,
192            support_packing: flags & (1 << 2) != 0,
193            support_fp16_storage: flags & (1 << 3) != 0,
194            support_bf16_storage: flags & (1 << 4) != 0,
195            one_blob_only: flags & (1 << 5) != 0,
196            support_inplace: flags & (1 << 6) != 0,
197            support_any_packing: flags & (1 << 7) != 0,
198            support_vulkan_any_packing: flags & (1 << 8) != 0,
199            support_int8_storage: flags & (1 << 9) != 0,
200            support_tensor_storage: flags & (1 << 10) != 0,
201            support_batch: flags & (1 << 11) != 0,
202        })
203    }
204    /// Describes every blob of the loaded network in graph order.
205    ///
206    /// `producer` and `consumer` are layer indices, so the pair of this call and
207    /// [`layers`](Self::layers) describes the whole graph without running it.
208    pub fn blobs(&self) -> Result<Vec<BlobInfo>> {
209        if !self.ready {
210            return Err(Error::invalid(
211                "Load parameters and weights before reading the graph",
212            ));
213        }
214        let count = unsafe { sys::ncnn_rs_net_blob_count(self.raw) };
215        if count < 0 {
216            return Err(Error::NativeAt("read the blob count", count));
217        }
218        let mut blobs = Vec::with_capacity(count as usize);
219        for index in 0..count {
220            let mut name = std::ptr::null();
221            let mut dims = 0;
222            let mut w = 0;
223            let mut h = 0;
224            let mut d = 0;
225            let mut c = 0;
226            let mut producer = 0;
227            let mut consumer = 0;
228            let code = unsafe {
229                sys::ncnn_rs_net_blob_info(
230                    self.raw,
231                    index,
232                    &mut name,
233                    &mut dims,
234                    &mut w,
235                    &mut h,
236                    &mut d,
237                    &mut c,
238                    &mut producer,
239                    &mut consumer,
240                )
241            };
242            if code != 0 || name.is_null() {
243                return Err(Error::NativeAt("read a blob", code));
244            }
245            blobs.push(BlobInfo {
246                name: unsafe { CStr::from_ptr(name) }
247                    .to_string_lossy()
248                    .into_owned(),
249                dims,
250                w,
251                h,
252                d,
253                c,
254                producer,
255                consumer,
256            });
257        }
258        Ok(blobs)
259    }
260    /// Reports the blobs more than one layer reads.
261    ///
262    /// Light mode releases a bottom blob once its first consumer ran, and the layer that produced it
263    /// cannot refill it, so a graph that reads one blob twice returns wrong values under light mode.
264    /// An explicit `Split` layer gives each consumer its own blob and keeps the graph compatible.
265    /// [`Extractor::set_light_mode`](crate::Extractor::set_light_mode) and
266    /// [`Net::extractor`](Self::extractor) reject enabling light mode while this list is not empty,
267    /// and the result is cached until the graph is cleared or loaded again.
268    pub fn shared_blobs(&self) -> Result<Vec<String>> {
269        if !self.ready {
270            return Err(Error::invalid(
271                "Load parameters and weights before reading the graph",
272            ));
273        }
274        if let Some(cached) = self.shared_blobs.borrow().clone() {
275            return Ok(cached);
276        }
277        let mut counts =
278            vec![0u32; unsafe { sys::ncnn_rs_net_blob_count(self.raw) }.max(0) as usize];
279        let layers = unsafe { sys::ncnn_rs_net_layer_count(self.raw) };
280        for index in 0..layers.max(0) {
281            let mut bottoms = 0;
282            let mut tops = 0;
283            let mut name = std::ptr::null();
284            let mut kind = std::ptr::null();
285            let mut typeindex = 0;
286            let mut flags = 0;
287            let code = unsafe {
288                sys::ncnn_rs_net_layer_info(
289                    self.raw,
290                    index,
291                    &mut name,
292                    &mut kind,
293                    &mut typeindex,
294                    &mut bottoms,
295                    &mut tops,
296                    &mut flags,
297                )
298            };
299            if code != 0 {
300                continue;
301            }
302            for bottom in 0..bottoms {
303                let blob = unsafe { sys::ncnn_rs_net_layer_bottom(self.raw, index, bottom) };
304                if blob < 0 {
305                    continue;
306                }
307                if let Some(slot) = counts.get_mut(blob as usize) {
308                    *slot += 1;
309                }
310            }
311        }
312        let mut shared = Vec::new();
313        for (index, count) in counts.iter().enumerate() {
314            if *count < 2 {
315                continue;
316            }
317            let mut name = std::ptr::null();
318            let mut dims = 0;
319            let mut w = 0;
320            let mut h = 0;
321            let mut d = 0;
322            let mut c = 0;
323            let mut producer = 0;
324            let mut consumer = 0;
325            let code = unsafe {
326                sys::ncnn_rs_net_blob_info(
327                    self.raw,
328                    index as i32,
329                    &mut name,
330                    &mut dims,
331                    &mut w,
332                    &mut h,
333                    &mut d,
334                    &mut c,
335                    &mut producer,
336                    &mut consumer,
337                )
338            };
339            if code == 0 && !name.is_null() {
340                shared.push(
341                    unsafe { CStr::from_ptr(name) }
342                        .to_string_lossy()
343                        .into_owned(),
344                );
345            }
346        }
347        *self.shared_blobs.borrow_mut() = Some(shared.clone());
348        Ok(shared)
349    }
350}