Skip to main content

ncnn_rust/
heap.rs

1//! Process heap tuning for the request forms that allocate output storage.
2//!
3//! [`Net::infer`](crate::Net::infer), [`Extractor::extract_owned`](crate::Extractor::extract_owned)
4//! and their stored variants hand back independent storage, so every request allocates an
5//! output-sized buffer and frees it again. The cost of that cycle belongs to the process heap rather
6//! than to the wrapper: a C library that serves an output-sized request from a fresh mapping and
7//! returns the pages to the kernel on free makes the next request fault the same pages again.
8//!
9//! [`retain_pages`] keeps those pages mapped for the rest of the process. It is the in-library
10//! counterpart of the `MALLOC_MMAP_THRESHOLD_` and `MALLOC_TRIM_THRESHOLD_` environment variables
11//! that `docs/performance.md` records, and it exists because a service cannot always set the
12//! environment of its own process.
13//!
14//! The thresholds are glibc settings. The Windows heap serves the same pattern from committed pages
15//! and faults almost nothing, and its public API exposes no equivalent threshold, so every function
16//! here reports `false` on that target and leaves the heap alone. `crates/ncnn/tests/heap.rs`
17//! measures both hosts: it proves the faults and their removal on glibc, and asserts the absence of
18//! the faults and the `false` result on Windows.
19//!
20//! The setting is process-wide and holds for the rest of the run, like a global allocator, so an
21//! application calls it once at start-up. Two library-side forms remove the allocations instead and
22//! need no tuning: reusing a buffer through [`Net::infer_into`](crate::Net::infer_into) or
23//! [`Net::infer_into`](crate::Net::infer_into) removes the caller-side vector, and
24//! [`NetBuilder::reuse_blob_memory`](crate::NetBuilder::reuse_blob_memory) gives the network's own
25//! intermediate tensors a pool that outlives each request.
26
27/// The allocation size, in bytes, that `retain_pages` keeps on the heap.
28///
29/// Large enough for any pinned trained-model output, the biggest of which is about 2.9 MB, so an
30/// output buffer stays on the heap while a genuinely large allocation still takes its own mapping.
31pub const DEFAULT_RETAINED_LIMIT: usize = 64 * 1024 * 1024;
32
33const M_TRIM_THRESHOLD: i32 = -1;
34const M_MMAP_THRESHOLD: i32 = -3;
35
36#[cfg(all(target_os = "linux", target_env = "gnu"))]
37mod imp {
38    use core::ffi::c_int;
39
40    extern "C" {
41        fn mallopt(param: c_int, value: c_int) -> c_int;
42    }
43
44    pub(super) fn set(param: i32, value: i32) -> bool {
45        // SAFETY: `mallopt` only reads its two integer arguments and updates the process heap
46        // parameters; it neither keeps pointers nor depends on any Rust state.
47        unsafe { mallopt(param, value) != 0 }
48    }
49}
50
51#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
52mod imp {
53    pub(super) fn set(_param: i32, _value: i32) -> bool {
54        false
55    }
56}
57
58/// Keeps an output-sized buffer on the heap up to `mapping_limit` bytes.
59///
60/// The C library serves an allocation above this limit from a fresh mapping and returns it to the
61/// kernel on free, which is what makes a later request fault its pages again. Returns `false` when
62/// the platform heap has no such setting, which is every target outside glibc Linux.
63pub fn set_mapping_limit(mapping_limit: usize) -> bool {
64    let value = i32::try_from(mapping_limit).unwrap_or(i32::MAX);
65    imp::set(M_MMAP_THRESHOLD, value)
66}
67
68/// Stops the heap from returning freed pages to the kernel.
69///
70/// Returns `false` when the platform heap has no such setting, which is every target outside glibc
71/// Linux.
72pub fn disable_trimming() -> bool {
73    imp::set(M_TRIM_THRESHOLD, -1)
74}
75
76/// Keeps the pages of freed buffers mapped so the next request does not fault them again.
77///
78/// Sets the mapping limit to [`DEFAULT_RETAINED_LIMIT`] and disables trimming. The effect lasts for
79/// the rest of the process and grows its resident set by the buffers an application allocates and
80/// frees, because those pages stay charged to the process.
81///
82/// Returns `true` when the heap accepted both settings and `false` when the platform heap has no
83/// such setting, which is every target outside glibc Linux, so portable code can call it
84/// unconditionally.
85///
86/// ```
87/// let applied = ncnn_rust::heap::retain_pages();
88/// println!("retained pages: {applied}");
89/// ```
90pub fn retain_pages() -> bool {
91    retain_pages_up_to(DEFAULT_RETAINED_LIMIT)
92}
93
94/// [`retain_pages`] with an explicit mapping limit.
95///
96/// Returns `true` when the heap accepted both settings.
97pub fn retain_pages_up_to(mapping_limit: usize) -> bool {
98    let mapped = set_mapping_limit(mapping_limit);
99    let trimmed = disable_trimming();
100    mapped && trimmed
101}