ncnn_rust/options.rs
1use crate::{error::status, sys, Error, Result};
2use std::{cell::Cell, marker::PhantomData, rc::Rc};
3
4/// Identifies one native integer option.
5///
6/// Each variant maps to one field of the native option block;
7/// [`Options::set`](crate::Options::set) documents the accepted range per variant.
8#[derive(Clone, Copy, Debug)]
9#[repr(i32)]
10#[non_exhaustive]
11pub enum CpuOption {
12 /// Native worker count.
13 Threads = 0,
14 /// Releases cached intermediate blobs after use.
15 LightMode,
16 /// Enables Winograd convolution.
17 Winograd,
18 /// Enables single-precision matrix multiplication.
19 Sgemm,
20 /// Enables INT8 inference paths.
21 Int8Inference,
22 /// Enables packed element layouts.
23 Packing,
24 /// Enables packed FP16 storage.
25 Fp16Packed,
26 /// Stores activations as FP16.
27 Fp16Storage,
28 /// Uses FP16 arithmetic where available.
29 Fp16Arithmetic,
30 /// Stores activations as BF16.
31 Bf16Storage,
32 /// Uses the per-network blob pool.
33 LocalPool,
34 /// Sets the OpenMP spin block time.
35 OpenmpBlocktime,
36 /// Flushes denormal results to zero.
37 FlushDenormals,
38 /// Enables 3x3 Winograd kernels.
39 Winograd23,
40 /// Enables 5x5 Winograd kernels.
41 Winograd43,
42 /// Enables 7x7 Winograd kernels.
43 Winograd63,
44 /// Maps model files instead of copying them.
45 MappedModelLoading,
46 /// Hints the sequence length of an LLM KV cache.
47 KvCacheSequenceHint,
48 /// Allows Vulkan subgroup operations.
49 SubgroupOps,
50 /// Enables packed INT8 storage.
51 Int8Packed,
52 /// Stores activations as INT8.
53 Int8Storage,
54 /// Uses INT8 arithmetic where available.
55 Int8Arithmetic,
56 /// Enables packed BF16 storage.
57 Bf16Packed,
58 /// Uses tensor storage for Vulkan buffers.
59 TensorStorage,
60 /// Keeps Vulkan weights in host memory.
61 WeightsInHostMemory,
62 /// Prefers shader local memory.
63 ShaderLocalMemory,
64 /// Allows cooperative matrix instructions.
65 CooperativeMatrix,
66 /// Selects kernels tuned for Cortex-A53 and A55.
67 A53A55OptimizedKernel,
68 /// Uses FP16 uniform buffers.
69 Fp16Uniform,
70 /// Uses INT8 uniform buffers.
71 Int8Uniform,
72 /// Enables packed INT16 storage.
73 Int16Packed,
74 /// Stores activations as INT16.
75 Int16Storage,
76}
77
78/// Independent native boolean preferences. Native capability dispatch remains authoritative.
79#[derive(Clone, Copy, Debug)]
80#[non_exhaustive]
81pub enum OptionFlag {
82 /// Releases cached intermediate blobs after use.
83 LightMode,
84 /// Enables Winograd convolution.
85 Winograd,
86 /// Enables single-precision matrix multiplication.
87 Sgemm,
88 /// Enables INT8 inference paths.
89 Int8Inference,
90 /// Enables packed element layouts.
91 Packing,
92 /// Enables packed FP16 storage.
93 Fp16Packed,
94 /// Stores activations as FP16.
95 Fp16Storage,
96 /// Uses FP16 arithmetic where available.
97 Fp16Arithmetic,
98 /// Stores activations as BF16.
99 Bf16Storage,
100 /// Uses the per-network blob pool.
101 LocalPool,
102 /// Enables 3x3 Winograd kernels.
103 Winograd23,
104 /// Enables 5x5 Winograd kernels.
105 Winograd43,
106 /// Enables 7x7 Winograd kernels.
107 Winograd63,
108 /// Maps model files instead of copying them.
109 MappedModelLoading,
110 /// Allows Vulkan subgroup operations.
111 SubgroupOps,
112 /// Enables packed INT8 storage.
113 Int8Packed,
114 /// Stores activations as INT8.
115 Int8Storage,
116 /// Uses INT8 arithmetic where available.
117 Int8Arithmetic,
118 /// Enables packed BF16 storage.
119 Bf16Packed,
120 /// Uses tensor storage for Vulkan buffers.
121 TensorStorage,
122 /// Keeps Vulkan weights in host memory.
123 WeightsInHostMemory,
124 /// Prefers shader local memory.
125 ShaderLocalMemory,
126 /// Allows cooperative matrix instructions.
127 CooperativeMatrix,
128 /// Selects kernels tuned for Cortex-A53 and A55.
129 A53A55OptimizedKernel,
130 /// Uses FP16 uniform buffers.
131 Fp16Uniform,
132 /// Uses INT8 uniform buffers.
133 Int8Uniform,
134 /// Enables packed INT16 storage.
135 Int16Packed,
136 /// Stores activations as INT16.
137 Int16Storage,
138}
139impl OptionFlag {
140 fn key(self) -> CpuOption {
141 match self {
142 Self::LightMode => CpuOption::LightMode,
143 Self::Winograd => CpuOption::Winograd,
144 Self::Sgemm => CpuOption::Sgemm,
145 Self::Int8Inference => CpuOption::Int8Inference,
146 Self::Packing => CpuOption::Packing,
147 Self::Fp16Packed => CpuOption::Fp16Packed,
148 Self::Fp16Storage => CpuOption::Fp16Storage,
149 Self::Fp16Arithmetic => CpuOption::Fp16Arithmetic,
150 Self::Bf16Storage => CpuOption::Bf16Storage,
151 Self::LocalPool => CpuOption::LocalPool,
152 Self::Winograd23 => CpuOption::Winograd23,
153 Self::Winograd43 => CpuOption::Winograd43,
154 Self::Winograd63 => CpuOption::Winograd63,
155 Self::MappedModelLoading => CpuOption::MappedModelLoading,
156 Self::SubgroupOps => CpuOption::SubgroupOps,
157 Self::Int8Packed => CpuOption::Int8Packed,
158 Self::Int8Storage => CpuOption::Int8Storage,
159 Self::Int8Arithmetic => CpuOption::Int8Arithmetic,
160 Self::Bf16Packed => CpuOption::Bf16Packed,
161 Self::TensorStorage => CpuOption::TensorStorage,
162 Self::WeightsInHostMemory => CpuOption::WeightsInHostMemory,
163 Self::ShaderLocalMemory => CpuOption::ShaderLocalMemory,
164 Self::CooperativeMatrix => CpuOption::CooperativeMatrix,
165 Self::A53A55OptimizedKernel => CpuOption::A53A55OptimizedKernel,
166 Self::Fp16Uniform => CpuOption::Fp16Uniform,
167 Self::Int8Uniform => CpuOption::Int8Uniform,
168 Self::Int16Packed => CpuOption::Int16Packed,
169 Self::Int16Storage => CpuOption::Int16Storage,
170 }
171 }
172}
173
174/// Native CPU option storage. `Net::configure` applies it to an unloaded network.
175///
176/// # Choosing between `Options` and `NetBuilder`
177///
178/// Both reach the same native option block. Use [`Net::builder`](crate::Net::builder) with
179/// `threads`, `flag` and `option` while a network is being created: those calls consume the
180/// builder and report a configuration failure before any model is read. Use [`Options`] when an
181/// option set is shared or prepared elsewhere, then hand it to
182/// [`Net::configure`](crate::Net::configure) once, before loading parameters.
183pub struct Options {
184 pub(crate) raw: sys::ncnn_option_t,
185 pub(crate) low_copy: Cell<bool>,
186 _thread: PhantomData<Rc<()>>,
187}
188impl Options {
189 /// Applies a convenience preset, not a hardware capability restriction.
190 ///
191 /// FP16 toggles packed, storage, and arithmetic together; FP32 clears all
192 /// three. Both presets clear BF16 storage. Later `set_flag` overrides win,
193 /// so mixed precision preferences remain independently configurable. Native
194 /// ncnn selects supported kernels and performs runtime capability dispatch.
195 #[cfg(feature = "vulkan")]
196 pub fn vulkan_precision(&mut self, precision: crate::gpu::Precision) -> Result<&mut Self> {
197 let enabled = i32::from(matches!(precision, crate::gpu::Precision::Fp16));
198 self.set(CpuOption::Fp16Packed, enabled)?;
199 self.set(CpuOption::Fp16Storage, enabled)?;
200 self.set(CpuOption::Fp16Arithmetic, enabled)?;
201 self.set(CpuOption::Bf16Storage, 0)
202 }
203 /// Retains the backward-compatible CPU, non-lightmode convenience preset.
204 pub fn new() -> Result<Self> {
205 let mut options = Self::native_defaults()?;
206 unsafe { sys::ncnn_option_set_use_vulkan_compute(options.raw, 0) };
207 options.set_flag(OptionFlag::LightMode, false)?;
208 Ok(options)
209 }
210 /// Allocates unchanged native defaults. Safe networks select CPU unless a
211 /// tracked Vulkan device is explicitly attached, independently of these flags.
212 pub fn native_defaults() -> Result<Self> {
213 let raw = unsafe { sys::ncnn_option_create() };
214 if raw.is_null() {
215 return Err(Error::Native(-100));
216 }
217 Ok(Self {
218 raw,
219 low_copy: Cell::new(true),
220 _thread: PhantomData,
221 })
222 }
223 /// Overrides one independent native boolean without changing other preferences.
224 ///
225 /// The flag maps to the same native field as the matching
226 /// [`CpuOption`](crate::CpuOption), so mixing the two forms for one field is allowed and the
227 /// later write wins.
228 pub fn set_flag(&mut self, flag: OptionFlag, enabled: bool) -> Result<&mut Self> {
229 self.set(flag.key(), i32::from(enabled))
230 }
231 /// Reads one boolean option.
232 pub fn flag(&self, flag: OptionFlag) -> Result<bool> {
233 self.get(flag.key()).map(|value| value != 0)
234 }
235 /// Writes one integer option after validating its range.
236 ///
237 /// [`CpuOption::Threads`](crate::CpuOption::Threads) must be positive,
238 /// [`CpuOption::FlushDenormals`](crate::CpuOption::FlushDenormals) stays within `0..=3`,
239 /// [`CpuOption::OpenmpBlocktime`](crate::CpuOption::OpenmpBlocktime) and
240 /// [`CpuOption::KvCacheSequenceHint`](crate::CpuOption::KvCacheSequenceHint) accept zero, and
241 /// the remaining keys accept `0` or `1`. The value reaches the native option block only after
242 /// those checks, so a rejected write leaves the block unchanged.
243 pub fn set(&mut self, key: CpuOption, value: i32) -> Result<&mut Self> {
244 match key {
245 CpuOption::Threads if value < 1 => {
246 return Err(Error::invalid("Thread count must be positive"))
247 }
248 CpuOption::OpenmpBlocktime | CpuOption::KvCacheSequenceHint if value < 0 => {
249 return Err(Error::invalid("Value must be nonnegative"))
250 }
251 CpuOption::FlushDenormals if !(0..=3).contains(&value) => {
252 return Err(Error::invalid("Denormal mode must be 0..=3"))
253 }
254 CpuOption::Threads
255 | CpuOption::OpenmpBlocktime
256 | CpuOption::KvCacheSequenceHint
257 | CpuOption::FlushDenormals => {}
258 _ if value != 0 && value != 1 => {
259 return Err(Error::invalid("Boolean option must be 0 or 1"))
260 }
261 _ => {}
262 }
263 unsafe {
264 status(sys::ncnn_rs_option_set(self.raw, key as i32, value))?;
265 }
266 Ok(self)
267 }
268 /// Attaches a pool allocator for intermediate blobs.
269 ///
270 /// # Safety
271 ///
272 /// The allocator stays alive and usable until every network configured from this option block
273 /// is dropped, and no other network may claim the same pool at the same time. The native option
274 /// block stores the handle without taking ownership.
275 pub unsafe fn set_blob_allocator(&mut self, allocator: &crate::alloc::Pool) -> Result<()> {
276 sys::ncnn_option_set_blob_allocator(self.raw, allocator.as_raw());
277 Ok(())
278 }
279 /// Attaches a pool allocator for layer workspace.
280 ///
281 /// # Safety
282 ///
283 /// The same lifetime and exclusivity rules as
284 /// [`set_blob_allocator`](Self::set_blob_allocator) apply.
285 pub unsafe fn set_workspace_allocator(&mut self, allocator: &crate::alloc::Pool) -> Result<()> {
286 sys::ncnn_option_set_workspace_allocator(self.raw, allocator.as_raw());
287 Ok(())
288 }
289 /// Attaches the allocator that keeps an attention KV cache.
290 ///
291 /// The cache allocator must differ from the blob allocator, and
292 /// [`CpuOption::KvCacheSequenceHint`] sizes the cache for the longest sequence.
293 ///
294 /// # Safety
295 ///
296 /// The same lifetime and exclusivity rules as
297 /// [`set_blob_allocator`](Self::set_blob_allocator) apply.
298 pub unsafe fn set_kvcache_allocator(&mut self, allocator: &crate::alloc::Pool) -> Result<()> {
299 sys::ncnn_option_set_kvcache_allocator(self.raw, allocator.as_raw());
300 Ok(())
301 }
302 /// Reads one integer option.
303 ///
304 /// Reads come from the native block, so a value written through a raw handle is visible here.
305 pub fn get(&self, key: CpuOption) -> Result<i32> {
306 let mut value = 0;
307 unsafe {
308 status(sys::ncnn_rs_option_get(self.raw, key as i32, &mut value))?;
309 }
310 Ok(value)
311 }
312 /// Exposes advanced configuration and disables low-copy output eligibility
313 /// for networks subsequently configured with these options.
314 ///
315 /// # Safety
316 /// The caller keeps these options alive while any network uses them and
317 /// restores fields the adapter does not model.
318 pub unsafe fn as_raw(&self) -> sys::ncnn_option_t {
319 self.low_copy.set(false);
320 self.raw
321 }
322}
323impl Drop for Options {
324 fn drop(&mut self) {
325 unsafe {
326 sys::ncnn_option_destroy(self.raw);
327 }
328 }
329}