Skip to main content

ncnn_rust/
cpu.rs

1//! Native CPU capabilities, legacy worker masks, and OS processor-group affinity.
2use crate::{error::status, sys, Error, Result};
3use std::{ffi::c_void, marker::PhantomData, rc::Rc};
4
5#[derive(Clone, Copy, Debug)]
6#[repr(i32)]
7#[non_exhaustive]
8/// Identifies one native CPU capability query.
9pub enum CpuQuery {
10    /// Counts logical processors.
11    LogicalCount,
12    /// Counts processors in the little cluster.
13    LittleCount,
14    /// Counts processors in the big cluster.
15    BigCount,
16    /// Counts physical cores.
17    PhysicalCount,
18    /// Counts physical little-cluster cores.
19    PhysicalLittleCount,
20    /// Counts physical big-cluster cores.
21    PhysicalBigCount,
22    /// Reports the L2 cache size in bytes.
23    L2Bytes,
24    /// Reports the L3 cache size in bytes.
25    L3Bytes,
26    /// Reports AVX support.
27    Avx,
28    /// Reports FMA support.
29    Fma,
30    /// Reports FMA4 support.
31    Fma4,
32    /// Reports XOP support.
33    Xop,
34    /// Reports F16C support.
35    F16c,
36    /// Reports AVX2 support.
37    Avx2,
38    /// Reports AVX-VNNI support.
39    AvxVnni,
40    /// Reports AVX-VNNI-INT8 support.
41    AvxVnniInt8,
42    /// Reports AVX-VNNI-INT16 support.
43    AvxVnniInt16,
44    /// Reports AVX-NE-CONVERT support.
45    AvxNeConvert,
46    /// Reports AVX-512 support.
47    Avx512,
48    /// Reports AVX-512 VNNI support.
49    Avx512Vnni,
50    /// Reports AVX-512 BF16 support.
51    Avx512Bf16,
52    /// Reports AVX-512 FP16 support.
53    Avx512Fp16,
54    /// Reports ARM EDSP support.
55    ArmEdsp,
56    /// Reports ARM NEON support.
57    ArmNeon,
58    /// Reports ARM VFPv4 support.
59    ArmVfpv4,
60    /// Reports ARM FP16 support.
61    ArmFp16,
62    /// Reports whether ARM CPUID queries are available.
63    ArmCpuid,
64    /// Reports ARM dot-product support.
65    ArmDotProduct,
66    /// Reports ARM FP16 multiply-accumulate support.
67    ArmFp16Fma,
68    /// Reports ARM BF16 support.
69    ArmBf16,
70    /// Reports ARM INT8 matrix-multiply support.
71    ArmI8mm,
72    /// Reports ARM SVE support.
73    ArmSve,
74    /// Reports ARM SVE2 support.
75    ArmSve2,
76    /// Reports ARM SVE BF16 support.
77    ArmSveBf16,
78    /// Reports ARM SVE INT8 matrix-multiply support.
79    ArmSveI8mm,
80    /// Reports ARM SVE FP32 matrix-multiply support.
81    ArmSveF32mm,
82}
83
84/// Returns the native answer for one query, zero when the feature is unsupported.
85///
86/// The value is a native capability report rather than a Rust-side guess: counts and cache sizes
87/// come back as numbers, and a feature test returns `1` when the current CPU has it and `0`
88/// otherwise. Nothing here gates behavior; ncnn performs its own dispatch at run time.
89pub fn query(key: CpuQuery) -> i32 {
90    unsafe { sys::ncnn_rs_cpu_query(key as i32) }
91}
92
93/// An OS processor identity. Linux uses group zero and the kernel CPU index.
94#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
95pub struct ProcessorId {
96    /// Windows processor group; Linux reports zero.
97    pub group: u32,
98    /// Processor index inside the group.
99    pub index: u32,
100}
101
102/// Reports support for exact OS processor identities and affinity masks.
103pub fn supports_thread_affinity() -> bool {
104    unsafe { sys::ncnn_rs_os_affinity_supported() != 0 }
105}
106
107fn processors(current_thread: bool) -> Result<Vec<ProcessorId>> {
108    if !supports_thread_affinity() {
109        return Err(Error::Unsupported(
110            "exact processor identities and affinity",
111        ));
112    }
113    for _ in 0..3 {
114        let count =
115            unsafe { sys::ncnn_rs_os_processors(current_thread as i32, std::ptr::null_mut(), 0) };
116        if count == usize::MAX {
117            return Err(Error::Native(-1));
118        }
119        let mut ids = vec![0u64; count];
120        let actual = unsafe {
121            sys::ncnn_rs_os_processors(current_thread as i32, ids.as_mut_ptr(), ids.len())
122        };
123        if actual == usize::MAX {
124            return Err(Error::Native(-1));
125        }
126        if actual > ids.len() {
127            continue;
128        }
129        ids.truncate(actual);
130        return Ok(ids
131            .into_iter()
132            .map(|id| ProcessorId {
133                group: (id >> 32) as u32,
134                index: id as u32,
135            })
136            .collect());
137    }
138    Err(Error::invalid("CPU topology changed during enumeration"))
139}
140
141/// Enumerates online processors across Windows groups or Linux kernel CPU IDs.
142pub fn online_processors() -> Result<Vec<ProcessorId>> {
143    processors(false)
144}
145
146/// Reads the calling thread's OS mask; Windows reports its current processor group.
147pub fn current_thread_affinity() -> Result<Vec<ProcessorId>> {
148    processors(true)
149}
150
151/// Counts physical cores from OS topology records independently of ncnn's legacy masks.
152pub fn physical_core_count() -> Result<usize> {
153    let count = unsafe { sys::ncnn_rs_os_physical_count() };
154    if count < 0 {
155        return Err(Error::Native(count));
156    }
157    Ok(count as usize)
158}
159
160/// Sets and verifies the calling thread's affinity. Windows accepts one group per call.
161/// Native OpenMP worker assignment remains a separate runtime operation.
162pub fn set_current_thread_affinity(processors: &[ProcessorId]) -> Result<()> {
163    if !supports_thread_affinity() {
164        return Err(Error::Unsupported("exact current-thread affinity"));
165    }
166    let ids: Vec<_> = processors
167        .iter()
168        .map(|id| ((id.group as u64) << 32) | id.index as u64)
169        .collect();
170    unsafe { status(sys::ncnn_rs_thread_affinity_set(ids.as_ptr(), ids.len())) }
171}
172
173/// An owned native CPU mask. Applying it is an explicit runtime operation.
174pub struct CpuSet {
175    raw: *mut c_void,
176    _thread: PhantomData<Rc<()>>,
177}
178impl CpuSet {
179    /// Returns the native mask capacity in CPUs.
180    pub fn capacity() -> usize {
181        unsafe { sys::ncnn_rs_cpuset_capacity() as usize }
182    }
183    /// Builds the native power-save mask for the given mode.
184    pub fn for_powersave(mode: u8) -> Result<Self> {
185        let mask = Self::new()?;
186        unsafe {
187            status(sys::ncnn_rs_cpuset_affinity(mask.raw, mode as i32))?;
188        }
189        Ok(mask)
190    }
191    /// Creates an empty mask.
192    pub fn new() -> Result<Self> {
193        let raw = unsafe { sys::ncnn_rs_cpuset_create() };
194        if raw.is_null() {
195            return Err(Error::Native(-100));
196        }
197        Ok(Self {
198            raw,
199            _thread: PhantomData,
200        })
201    }
202    /// Enables or disables one CPU index.
203    pub fn set(&mut self, cpu: usize, enabled: bool) -> Result<()> {
204        let cpu =
205            i32::try_from(cpu).map_err(|_| Error::invalid("CPU index exceeds native range"))?;
206        unsafe { status(sys::ncnn_rs_cpuset_update(self.raw, cpu, enabled as i32)) }
207    }
208    /// Reports whether one CPU index is enabled.
209    pub fn contains(&self, cpu: usize) -> Result<bool> {
210        let cpu =
211            i32::try_from(cpu).map_err(|_| Error::invalid("CPU index exceeds native range"))?;
212        let result = unsafe { sys::ncnn_rs_cpuset_contains(self.raw, cpu) };
213        if result < 0 {
214            return Err(Error::invalid("CPU index exceeds native mask capacity"));
215        }
216        Ok(result != 0)
217    }
218    /// Counts enabled CPU indices.
219    pub fn count(&self) -> usize {
220        unsafe { sys::ncnn_rs_cpuset_count(self.raw) as usize }
221    }
222    /// Applies the mask to native workers.
223    ///
224    /// # Safety
225    /// Serialize changes with native inference and other users of global thread settings.
226    pub unsafe fn apply(&self) -> Result<()> {
227        if !supports_thread_affinity() {
228            return Err(Error::Unsupported("exact native worker affinity"));
229        }
230        status(sys::ncnn_rs_cpuset_apply(self.raw))
231    }
232}
233impl Drop for CpuSet {
234    fn drop(&mut self) {
235        unsafe {
236            sys::ncnn_rs_cpuset_destroy(self.raw);
237        }
238    }
239}