Skip to main content

yscv_threadpool/
affinity.rs

1//! CPU affinity pinning for workers.
2//!
3//! Why: on SMT-enabled CPUs (Zen 4 is 6 physical × 2 SMT = 12 logical),
4//! unpinned workers can land on SMT siblings of the main submitter thread
5//! and steal its cycles. That's exactly how the previous `InferencePool`
6//! attempt regressed on 6T. Pinning each worker to a distinct physical
7//! core eliminates SMT contention.
8//!
9//! Policies (env `YSCV_POOL_AFFINITY`):
10//! - `none`      — no pinning, workers float (previous behavior).
11//! - `big`       — big / performance cores only (ARM big.LITTLE,
12//!   Intel P-cores). Fallback to `physical` on symmetric CPUs.
13//! - `physical`  — one worker per physical core, one SMT sibling per
14//!   core left idle for the submitter. Default on Zen 4
15//!   and other symmetric SMT CPUs.
16//!
17//! Linux uses `sched_setaffinity`; macOS uses `thread_policy_set` with
18//! `THREAD_AFFINITY_POLICY`. Other OSes fall through as a no-op.
19
20#[cfg(target_os = "linux")]
21use std::fs;
22
23/// Returns a list of CPU IDs to pin `nthreads` workers to, sized exactly
24/// `nthreads`. If topology info is unavailable or policy is `none`,
25/// returns an empty vec (caller should skip pinning).
26pub fn resolve_pinning(policy: AffinityPolicy, nthreads: usize) -> Vec<usize> {
27    match policy {
28        AffinityPolicy::None => Vec::new(),
29        AffinityPolicy::Big => resolve_big(nthreads).unwrap_or_else(|| resolve_physical(nthreads)),
30        AffinityPolicy::Physical => resolve_physical(nthreads),
31    }
32}
33
34/// Parses `YSCV_POOL_AFFINITY` env; default is `physical`.
35pub fn policy_from_env() -> AffinityPolicy {
36    match std::env::var("YSCV_POOL_AFFINITY").as_deref() {
37        Ok("none") => AffinityPolicy::None,
38        Ok("big") => AffinityPolicy::Big,
39        // Default (including unset, "physical", or any other value) is
40        // physical-core pinning — explicitly spelled out so clippy sees
41        // the `"physical"` arm as intentional rather than redundant.
42        _ => AffinityPolicy::Physical,
43    }
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum AffinityPolicy {
48    None,
49    Big,
50    Physical,
51}
52
53/// Pin the current thread to `cpu_id`. No-op on unsupported platforms.
54pub fn pin_current_thread(cpu_id: usize) {
55    #[cfg(target_os = "linux")]
56    {
57        pin_linux(cpu_id);
58    }
59    #[cfg(target_os = "macos")]
60    {
61        pin_darwin(cpu_id);
62    }
63    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
64    {
65        let _ = cpu_id;
66    }
67}
68
69#[cfg(target_os = "linux")]
70fn pin_linux(cpu_id: usize) {
71    // SAFETY: zero-initialized cpu_set_t is valid; CPU_SET on it is safe;
72    // sched_setaffinity takes a pointer to a cpu_set_t with correct size.
73    // libc is the standard Rust FFI shim for exactly this pattern.
74    #[allow(unsafe_code)]
75    unsafe {
76        let mut set: libc::cpu_set_t = std::mem::zeroed();
77        libc::CPU_SET(cpu_id, &mut set);
78        let _ = libc::sched_setaffinity(
79            0, // 0 = current thread
80            std::mem::size_of::<libc::cpu_set_t>(),
81            &set,
82        );
83    }
84}
85
86#[cfg(target_os = "macos")]
87fn pin_darwin(cpu_id: usize) {
88    // macOS doesn't expose hard pinning — `thread_policy_set` with
89    // THREAD_AFFINITY_POLICY is a hint the scheduler may ignore. We apply
90    // the hint anyway (matches what ORT / Eigen do on Darwin). Tag derived
91    // from cpu_id % 256 so workers on different CPUs get different tags.
92    //
93    // SAFETY: `mach_thread_self` returns a valid thread port; the policy
94    // struct is stack-local with the documented layout (affinity_tag: i32).
95    #[allow(unsafe_code)]
96    unsafe {
97        #[repr(C)]
98        struct ThreadAffinityPolicy {
99            affinity_tag: i32,
100        }
101        const THREAD_AFFINITY_POLICY: i32 = 4;
102        const THREAD_AFFINITY_POLICY_COUNT: u32 = 1;
103
104        unsafe extern "C" {
105            fn mach_thread_self() -> u32;
106            fn thread_policy_set(
107                thread: u32,
108                flavor: i32,
109                policy_info: *const i32,
110                policy_count: u32,
111            ) -> i32;
112            fn mach_port_deallocate(task: u32, port: u32) -> i32;
113            fn mach_task_self() -> u32;
114        }
115
116        let policy = ThreadAffinityPolicy {
117            affinity_tag: (cpu_id as i32) + 1, // 0 = null tag
118        };
119        let thread = mach_thread_self();
120        let _ = thread_policy_set(
121            thread,
122            THREAD_AFFINITY_POLICY,
123            &policy as *const _ as *const i32,
124            THREAD_AFFINITY_POLICY_COUNT,
125        );
126        let _ = mach_port_deallocate(mach_task_self(), thread);
127    }
128}
129
130/// Big-core detection: ARM big.LITTLE exposes capacity via
131/// `/sys/devices/system/cpu/cpuN/cpu_capacity`; Intel P-cores on hybrid
132/// CPUs via the same sysfs. Returns `None` if unavailable OR if all cores
133/// have the same capacity (symmetric CPU — caller falls back to
134/// `physical`).
135#[cfg(target_os = "linux")]
136fn resolve_big(nthreads: usize) -> Option<Vec<usize>> {
137    let mut caps: Vec<(usize, u32)> = Vec::new();
138    for id in 0..1024usize {
139        let path = format!("/sys/devices/system/cpu/cpu{id}/cpu_capacity");
140        match fs::read_to_string(&path) {
141            Ok(s) => {
142                if let Ok(cap) = s.trim().parse::<u32>() {
143                    caps.push((id, cap));
144                }
145            }
146            Err(_) => {
147                let cpu_dir = format!("/sys/devices/system/cpu/cpu{id}");
148                if !std::path::Path::new(&cpu_dir).exists() {
149                    break;
150                }
151            }
152        }
153    }
154    if caps.is_empty() {
155        return None;
156    }
157    let max_cap = caps.iter().map(|&(_, c)| c).max()?;
158    let min_cap = caps.iter().map(|&(_, c)| c).min()?;
159    if max_cap == min_cap {
160        return None; // symmetric
161    }
162    let big: Vec<usize> = caps
163        .into_iter()
164        .filter(|&(_, c)| c == max_cap)
165        .map(|(id, _)| id)
166        .collect();
167    Some(take_first_n(big, nthreads))
168}
169
170#[cfg(not(target_os = "linux"))]
171fn resolve_big(nthreads: usize) -> Option<Vec<usize>> {
172    // macOS: sysctl hw.perflevel0.logicalcpu_max gives P-core count.
173    // First N logical CPUs are always P-cores on Apple Silicon.
174    #[cfg(target_os = "macos")]
175    {
176        if let Ok(out) = std::process::Command::new("sysctl")
177            .args(["-n", "hw.perflevel0.logicalcpu_max"])
178            .output()
179            && out.status.success()
180            && let Ok(s) = String::from_utf8(out.stdout)
181            && let Ok(n) = s.trim().parse::<usize>()
182            && n > 0
183        {
184            let big: Vec<usize> = (0..n).collect();
185            return Some(take_first_n(big, nthreads));
186        }
187    }
188    let _ = nthreads;
189    None
190}
191
192/// Physical-core detection: parse `/sys/devices/system/cpu/cpuN/topology/
193/// thread_siblings_list` to identify SMT groups. Take the lowest-numbered
194/// sibling from each group as "the physical core representative".
195///
196/// On a 6C/12T Zen 4: returns [0, 1, 2, 3, 4, 5] (or similar — depending on
197/// how the kernel enumerates) — one logical CPU per physical, avoiding
198/// SMT siblings.
199#[cfg(target_os = "linux")]
200fn resolve_physical(nthreads: usize) -> Vec<usize> {
201    use std::collections::BTreeSet;
202    let mut seen: BTreeSet<usize> = BTreeSet::new();
203    let mut reps: Vec<usize> = Vec::new();
204
205    for id in 0..1024usize {
206        let path = format!("/sys/devices/system/cpu/cpu{id}/topology/thread_siblings_list");
207        let s = match fs::read_to_string(&path) {
208            Ok(s) => s,
209            Err(_) => {
210                let cpu_dir = format!("/sys/devices/system/cpu/cpu{id}");
211                if !std::path::Path::new(&cpu_dir).exists() {
212                    break;
213                }
214                continue;
215            }
216        };
217        // Format: "0,6" or "0-1" — list of sibling CPU IDs. Take the
218        // minimum as the physical-core representative.
219        let sibling_min = parse_cpu_list_min(&s);
220        let Some(rep) = sibling_min else { continue };
221        if seen.insert(rep) {
222            reps.push(rep);
223        }
224    }
225    if reps.is_empty() {
226        // Sysfs missing (container?) — fall back to first `nthreads` logical CPUs.
227        return (0..nthreads).collect();
228    }
229    take_first_n(reps, nthreads)
230}
231
232#[cfg(not(target_os = "linux"))]
233fn resolve_physical(nthreads: usize) -> Vec<usize> {
234    // Darwin / Windows: fall back to first N logical CPUs. Darwin's
235    // `thread_policy_set` hint gives some affinity anyway.
236    (0..nthreads).collect()
237}
238
239/// Parses a cpuset list like "0,6" or "0-1,4-5" and returns the smallest ID.
240#[cfg(target_os = "linux")]
241fn parse_cpu_list_min(s: &str) -> Option<usize> {
242    let s = s.trim();
243    let mut min: Option<usize> = None;
244    for part in s.split(',') {
245        let part = part.trim();
246        if part.is_empty() {
247            continue;
248        }
249        if let Some((a, _b)) = part.split_once('-') {
250            if let Ok(v) = a.trim().parse::<usize>() {
251                min = Some(min.map_or(v, |m| m.min(v)));
252            }
253        } else if let Ok(v) = part.parse::<usize>() {
254            min = Some(min.map_or(v, |m| m.min(v)));
255        }
256    }
257    min
258}
259
260#[cfg(any(target_os = "linux", target_os = "macos"))]
261fn take_first_n(mut v: Vec<usize>, n: usize) -> Vec<usize> {
262    if v.len() > n {
263        v.truncate(n);
264    }
265    v
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    #[test]
273    fn none_policy_returns_empty() {
274        assert!(resolve_pinning(AffinityPolicy::None, 6).is_empty());
275    }
276
277    #[test]
278    fn physical_returns_at_most_nthreads() {
279        let v = resolve_pinning(AffinityPolicy::Physical, 4);
280        assert!(v.len() <= 4, "got {} ids for 4 threads", v.len());
281    }
282
283    #[cfg(target_os = "linux")]
284    #[test]
285    fn cpu_list_min_parses() {
286        assert_eq!(parse_cpu_list_min("0,6"), Some(0));
287        assert_eq!(parse_cpu_list_min("3,9"), Some(3));
288        assert_eq!(parse_cpu_list_min("2-3,5"), Some(2));
289        assert_eq!(parse_cpu_list_min(""), None);
290    }
291
292    #[test]
293    fn policy_from_env_defaults_to_physical() {
294        // We can't mutate env safely inside a test; just verify the
295        // default branch when the var is unset in CI.
296        let _p = policy_from_env();
297    }
298
299    #[test]
300    fn pin_current_thread_is_noop_safe() {
301        // Just ensure it doesn't crash on any supported target.
302        pin_current_thread(0);
303    }
304}