Skip to main content

cortiq_engine/
pool.rs

1//! Persistent worker pool for row-parallel matvecs.
2//!
3//! Threads are spawned once and spin-then-park between calls — vmfcore
4//! measured spawn-per-matvec at ~+27% decode cost versus a persistent
5//! pool. Parallelism is by disjoint row ranges, so results are
6//! bit-identical to the serial path (each row's dot product is computed
7//! the same way).
8//!
9//! Dispatch is a single shared job slot + atomic epoch (roadmap §3 P0):
10//! the caller publishes one pointer, bumps the epoch and JOINS THE WORK
11//! as the extra worker instead of blocking on a latch. The previous
12//! design allocated an `Arc<Latch>` and pushed a message into every
13//! worker's mpsc channel for every matvec (~200 dispatches/token) —
14//! with decode-grade matvecs that synchronization was its own budget.
15//! Workers spin for `CMF_POOL_SPIN` iterations before parking.
16//! Default 4000: at ~39 dispatches/token, park-immediately pays the
17//! unpark syscall on every worker for every dispatch — measured on an
18//! M4 (interleaved A/B, current epoch dispatch + parked-flag design):
19//! Qwen-0.5B q8 decode 101→115 tok/s, q4t 117→149, the 50M bench model
20//! 549→954 at spin=4000 vs spin=0. An early measurement that showed
21//! spinning LOSING (−25% on q8) predates the parked-flag skip and the
22//! multi-matrix dispatch cuts; it no longer reproduces. Over-spinning
23//! still hurts (200k: −15% vs 4k — spinners steal the caller's serial
24//! cycles), so the budget stays bounded. `CMF_POOL_SPIN=0` restores
25//! park-immediately for share-the-box serving.
26//!
27//! `CMF_THREADS` env: 0/1 = serial, N = worker count
28//! (default: available_parallelism − 1, capped at 8).
29
30use std::cell::UnsafeCell;
31use std::sync::Arc;
32use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
33
34/// Embedder override for the pool size (C ABI `cortiq_set_threads`):
35/// 0 = unset, consult CMF_THREADS / topology as before. Read once at
36/// pool construction, so set it before the load.
37pub static FORCED_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
38
39/// Kernel thread ids of the CURRENT pool's workers (Android/Linux) —
40/// what ADPF's PerformanceHintManager needs to attribute work to the
41/// governor. Refilled on every pool construction; empty elsewhere.
42pub static WORKER_TIDS: std::sync::Mutex<Vec<i32>> = std::sync::Mutex::new(Vec::new());
43
44
45/// A `*const dyn Fn` that may cross a thread boundary. Safety is
46/// provided by `Pool::run`: the caller blocks until every worker has
47/// finished, so the borrow outlives all uses.
48#[derive(Clone, Copy)]
49struct TaskPtr(*const (dyn Fn(usize, usize) + Sync));
50unsafe impl Send for TaskPtr {}
51
52struct Inner {
53    /// Bumped once per published job; workers watch it.
54    epoch: AtomicUsize,
55    /// Workers still running the current job (excludes the caller).
56    remaining: AtomicUsize,
57    /// The published job: closure pointer + total participant count.
58    /// Written by the caller BEFORE the epoch bump, read by workers
59    /// AFTER they observe the new epoch (acquire/release pairing).
60    slot: UnsafeCell<Option<(TaskPtr, usize)>>,
61    shutdown: AtomicBool,
62    /// Spin iterations before a worker parks (0 = park immediately).
63    spin_budget: usize,
64    /// Per-worker "I am parked" flags — lets the caller skip the unpark
65    /// syscall for workers that are still spinning.
66    parked: Box<[AtomicBool]>,
67}
68
69// SAFETY: `slot` is only written while no job is in flight (run()
70// returns after `remaining` hits 0) and only read after the epoch
71// publication that follows the write.
72unsafe impl Sync for Inner {}
73
74/// Process-wide dispatch counter (roadmap §3 P0 «измерения»): one tick
75/// per published job. `bench --json` reports dispatches/token from it.
76static DISPATCHES: AtomicUsize = AtomicUsize::new(0);
77
78/// Total pool jobs published since process start (all pools).
79pub fn dispatch_count() -> usize {
80    DISPATCHES.load(Ordering::Relaxed)
81}
82
83/// Persistent thread pool: shared job slot, epoch dispatch, caller
84/// participation.
85pub struct Pool {
86    inner: Arc<Inner>,
87    /// Thread handles for `unpark` (same order as `parked`).
88    threads: Vec<std::thread::Thread>,
89    joins: Vec<std::thread::JoinHandle<()>>,
90}
91
92fn spin_budget_from_env() -> usize {
93    std::env::var("CMF_POOL_SPIN")
94        .ok()
95        .and_then(|v| v.parse::<usize>().ok())
96        .unwrap_or(4000)
97}
98
99impl Pool {
100    pub fn new(n_workers: usize) -> Self {
101        Self::with_spin(n_workers, spin_budget_from_env())
102    }
103
104    /// Explicit spin budget (tests pin it without touching the env).
105    pub fn with_spin(n_workers: usize, spin_budget: usize) -> Self {
106        let inner = Arc::new(Inner {
107            epoch: AtomicUsize::new(0),
108            remaining: AtomicUsize::new(0),
109            slot: UnsafeCell::new(None),
110            shutdown: AtomicBool::new(false),
111            spin_budget,
112            parked: (0..n_workers).map(|_| AtomicBool::new(false)).collect(),
113        });
114        let mut joins = Vec::with_capacity(n_workers);
115        if let Ok(mut tids) = WORKER_TIDS.lock() {
116            tids.clear();
117        }
118        for w in 0..n_workers {
119            let inner = inner.clone();
120            let h = std::thread::Builder::new()
121                .name(format!("cmf-pool-{w}"))
122                .spawn(move || {
123                    #[cfg(any(target_os = "android", target_os = "linux"))]
124                    if let Ok(mut tids) = WORKER_TIDS.lock() {
125                        tids.push(unsafe { libc::gettid() } as i32);
126                    }
127                    worker_loop(&inner, w)
128                })
129                .expect("spawn pool worker");
130            joins.push(h);
131        }
132        // Registration barrier: `spawn` returns before the closure runs,
133        // and the embedder reads `cortiq_worker_tids` right after load —
134        // on a phone only the first worker had registered by then (the
135        // '· 1 threads' About line that misled the cmfmobile device
136        // investigation twice). Thread start is milliseconds; wait for
137        // every tid before construction returns.
138        #[cfg(any(target_os = "android", target_os = "linux"))]
139        while WORKER_TIDS.lock().map(|t| t.len()).unwrap_or(n_workers) < n_workers {
140            std::thread::yield_now();
141        }
142        let threads = joins.iter().map(|h| h.thread().clone()).collect();
143        Self {
144            inner,
145            threads,
146            joins,
147        }
148    }
149
150    /// Big-core count on heterogeneous ARM (big.LITTLE): the kernel
151    /// exposes per-core capacity on Android and most ARM Linux; efficiency
152    /// cores in the pool DRAG the big ones on our row-parallel jobs (the
153    /// same cliff llama.cpp hits at -t 10 on an M4: 163 → 112 tok/s).
154    /// None = capacities absent or homogeneous.
155    #[cfg(all(
156        target_arch = "aarch64",
157        any(target_os = "linux", target_os = "android")
158    ))]
159    fn big_cores() -> Option<usize> {
160        Self::cores_from_capacities(&core_capacities())
161    }
162
163    /// How many cores the pool should use, from the kernel's per-core
164    /// capacity values. Capacity folds µarch × clock into one number,
165    /// and the two need different treatment: cores of ANOTHER µarch
166    /// (A5xx efficiency cluster next to A7xx/X: capacity ratio ≥ ~2)
167    /// drag row-parallel work down and are excluded; cores of the SAME
168    /// µarch merely clock-binned (JLQ JR510: 8×A55 as 4×2.0 + 4×1.5 GHz,
169    /// ratio 1.33) pull their weight and must ALL be used. The 1.6
170    /// threshold splits the two regimes: on a Snapdragon 8-class part
171    /// it keeps X + A7xx mid cores and drops A5xx.
172    #[cfg_attr(
173        not(all(
174            target_arch = "aarch64",
175            any(target_os = "linux", target_os = "android")
176        )),
177        allow(dead_code)
178    )]
179    fn cores_from_capacities(caps: &[u64]) -> Option<usize> {
180        let max = *caps.iter().max()?;
181        let min = *caps.iter().min()?;
182        if caps.len() < 2 || max == min {
183            return None;
184        }
185        Some(caps.iter().filter(|&&c| c * 8 >= max * 5).count())
186    }
187
188    #[cfg(target_os = "macos")]
189    fn big_cores() -> Option<usize> {
190        unsafe extern "C" {
191            fn sysctlbyname(
192                name: *const std::ffi::c_char,
193                oldp: *mut std::ffi::c_void,
194                oldlenp: *mut usize,
195                newp: *mut std::ffi::c_void,
196                newlen: usize,
197            ) -> std::ffi::c_int;
198        }
199        unsafe {
200            let name = std::ffi::CString::new("hw.perflevel0.physicalcpu").ok()?;
201            let mut count: i32 = 0;
202            let mut size = std::mem::size_of::<i32>();
203            let ret = sysctlbyname(
204                name.as_ptr(),
205                &mut count as *mut i32 as *mut std::ffi::c_void,
206                &mut size,
207                std::ptr::null_mut(),
208                0,
209            );
210            if ret == 0 && count > 0 {
211                Some(count as usize)
212            } else {
213                None
214            }
215        }
216    }
217
218    #[cfg(not(any(
219        all(
220            target_arch = "aarch64",
221            any(target_os = "linux", target_os = "android")
222        ),
223        target_os = "macos"
224    )))]
225    fn big_cores() -> Option<usize> {
226        None
227    }
228
229    /// The thread count `from_env` would use RIGHT NOW: forced (C ABI)
230    /// > CMF_THREADS > big-core topology > available_parallelism−1.
231    /// ≤1 means the model runs serial (no pool). Introspection
232    /// (`execution_mode`, status endpoints) must report THIS, not
233    /// available_parallelism.
234    pub fn effective_threads() -> usize {
235        let forced = FORCED_THREADS.load(std::sync::atomic::Ordering::Relaxed);
236        if forced > 0 {
237            return forced;
238        }
239        match std::env::var("CMF_THREADS") {
240            Ok(v) => v.parse::<usize>().unwrap_or(0),
241            Err(_) => match Self::big_cores() {
242                Some(big) => big,
243                None => {
244                    let avail = std::thread::available_parallelism()
245                        .map(|n| n.get())
246                        .unwrap_or(1);
247                    avail.saturating_sub(1).min(8)
248                }
249            },
250        }
251    }
252
253    /// Pool sized from `CMF_THREADS` (see module docs). `None` = serial.
254    /// Without the env, heterogeneous ARM defaults to its BIG cores.
255    pub fn from_env() -> Option<Arc<Self>> {
256        let n = Self::effective_threads();
257        if n <= 1 {
258            None
259        } else {
260            Some(Arc::new(Self::new(n)))
261        }
262    }
263
264    /// Spawned worker threads (the caller joins each job on top).
265    pub fn n_workers(&self) -> usize {
266        self.threads.len()
267    }
268
269    /// Run `f(row_start, row_end)` over `0..rows`, self-balancing.
270    ///
271    /// One dispatch, but workers pull row-ranges from a shared cursor
272    /// instead of each taking a fixed 1/n slice. On a heterogeneous CPU
273    /// (Apple Silicon: 4 P-cores + 6 E-cores here) a static split makes
274    /// every matvec end at the SLOWEST core's pace while the fast ones
275    /// idle at the barrier; pulling by grain lets a P-core take several
276    /// chunks for each one an E-core takes, so skew collapses to a
277    /// single grain. Row ranges stay disjoint and each row's dot is
278    /// computed exactly as in the serial path → bit-identical output.
279    pub fn run_rows(&self, rows: usize, f: &(dyn Fn(usize, usize) + Sync)) {
280        // Enough chunks to balance, large enough to keep the SDOT inner
281        // loop and the hardware prefetcher in their stride.
282        let grain = (rows / ((self.threads.len() + 1) * 8)).max(32);
283        let next = AtomicUsize::new(0);
284        self.run(&|_w, _n| loop {
285            let start = next.fetch_add(grain, Ordering::Relaxed);
286            if start >= rows {
287                break;
288            }
289            f(start, (start + grain).min(rows));
290        });
291    }
292
293    /// Multi-matrix job: one dispatch serves SEVERAL row spaces
294    /// (roadmap §3 P0 — «одна внешняя публикация job на слой»). Parts
295    /// are laid out back-to-back in a virtual row space and pulled by
296    /// grain from one shared cursor, so QKV or gate+up cost a single
297    /// barrier instead of one each. Each part's `f(start, end)` sees its
298    /// OWN row indices — per-row math and outputs are bit-identical to
299    /// separate `run_rows` calls.
300    pub fn run_many(&self, parts: &[(usize, &(dyn Fn(usize, usize) + Sync))]) {
301        let total: usize = parts.iter().map(|p| p.0).sum();
302        if total == 0 {
303            return;
304        }
305        let grain = (total / ((self.threads.len() + 1) * 8)).max(32);
306        let next = AtomicUsize::new(0);
307        self.run(&|_w, _n| loop {
308            let s = next.fetch_add(grain, Ordering::Relaxed);
309            if s >= total {
310                break;
311            }
312            let e = (s + grain).min(total);
313            let mut base = 0usize;
314            for &(rows, f) in parts {
315                let a = s.max(base);
316                let b = e.min(base + rows);
317                if a < b {
318                    f(a - base, b - base);
319                }
320                base += rows;
321                if base >= e {
322                    break;
323                }
324            }
325        });
326    }
327
328    /// Run `f(worker_idx, n_participants)` on every worker AND the
329    /// calling thread (`worker_idx = n_workers()` for the caller);
330    /// returns when all participants have finished.
331    pub fn run(&self, f: &(dyn Fn(usize, usize) + Sync)) {
332        DISPATCHES.fetch_add(1, Ordering::Relaxed);
333        let nw = self.threads.len();
334        let n = nw + 1; // caller participates
335        // SAFETY: the wait loop below blocks until every worker is done,
336        // so extending the borrow to 'static never outlives the call.
337        let ptr: *const (dyn Fn(usize, usize) + Sync) = f;
338        let ptr: *const (dyn Fn(usize, usize) + Sync + 'static) =
339            unsafe { std::mem::transmute(ptr) };
340        // SAFETY: no job in flight (previous run() drained `remaining`),
341        // so the slot is not being read.
342        unsafe { *self.inner.slot.get() = Some((TaskPtr(ptr), n)) };
343        self.inner.remaining.store(nw, Ordering::Relaxed);
344        self.inner.epoch.fetch_add(1, Ordering::SeqCst);
345        for (i, t) in self.threads.iter().enumerate() {
346            if self.inner.parked[i].load(Ordering::SeqCst) {
347                t.unpark();
348            }
349        }
350
351        // The caller's share — the barrier costs nothing while there is
352        // real work to do.
353        f(nw, n);
354
355        // Wait for the stragglers (bounded by one worker's chunk).
356        let mut spins = 0usize;
357        while self.inner.remaining.load(Ordering::Acquire) != 0 {
358            spins += 1;
359            if spins < 10_000 {
360                std::hint::spin_loop();
361            } else {
362                std::thread::yield_now();
363            }
364        }
365    }
366}
367
368impl Drop for Pool {
369    fn drop(&mut self) {
370        self.inner.shutdown.store(true, Ordering::SeqCst);
371        for t in &self.threads {
372            t.unpark();
373        }
374        for h in self.joins.drain(..) {
375            let _ = h.join();
376        }
377    }
378}
379
380/// Per-core capacity: the kernel's `cpu_capacity` (µarch × clock) when
381/// EAS exposes it, else `cpufreq/cpuinfo_max_freq` — same cluster
382/// ordering, so the 62.5% big-core rule keeps working on EAS-less
383/// kernels (TUNING.md open item: pinning silently did nothing there).
384#[cfg(any(
385    target_os = "android",
386    all(target_arch = "aarch64", target_os = "linux")
387))]
388fn core_capacities() -> Vec<u64> {
389    let read_all = |leaf: &str| -> Vec<u64> {
390        let mut vals = Vec::new();
391        for cpu in 0.. {
392            let path = format!("/sys/devices/system/cpu/cpu{cpu}/{leaf}");
393            match std::fs::read_to_string(&path) {
394                Ok(v) => match v.trim().parse() {
395                    Ok(x) => vals.push(x),
396                    Err(_) => break,
397                },
398                Err(_) => break,
399            }
400        }
401        vals
402    };
403    let caps = read_all("cpu_capacity");
404    if caps.len() >= 2 {
405        return caps;
406    }
407    read_all("cpufreq/cpuinfo_max_freq")
408}
409
410#[cfg(target_os = "android")]
411fn pin_thread_to_big_cores() {
412    use std::mem;
413    let caps = core_capacities();
414    let max = caps.iter().copied().max().unwrap_or(0);
415    let min = caps.iter().copied().min().unwrap_or(0);
416
417    // Only pin if heterogeneous
418    if caps.len() < 2 || max == min {
419        return;
420    }
421
422    unsafe {
423        let mut set: libc::cpu_set_t = mem::zeroed();
424        for (i, &c) in caps.iter().enumerate() {
425            if c * 8 >= max * 5 {
426                libc::CPU_SET(i, &mut set);
427            }
428        }
429        libc::sched_setaffinity(0, mem::size_of::<libc::cpu_set_t>(), &set);
430    }
431}
432
433fn worker_loop(inner: &Inner, idx: usize) {
434    #[cfg(target_os = "android")]
435    pin_thread_to_big_cores();
436
437    // The pool is created at epoch 0; baseline MUST be 0, not a fresh
438    // epoch read — if the caller publishes a job before the OS actually
439    // starts this thread, reading the live epoch would adopt that job's
440    // epoch as "already seen", skip it, and deadlock the caller's wait.
441    let mut seen = 0usize;
442    loop {
443        // Wait for a new epoch: spin first (decode publishes the next
444        // matvec within microseconds), park only when idle for real.
445        let mut spins = 0usize;
446        loop {
447            let e = inner.epoch.load(Ordering::Acquire);
448            if e != seen {
449                seen = e;
450                break;
451            }
452            if inner.shutdown.load(Ordering::Relaxed) {
453                return;
454            }
455            if spins < inner.spin_budget {
456                spins += 1;
457                std::hint::spin_loop();
458            } else {
459                inner.parked[idx].store(true, Ordering::SeqCst);
460                // Re-check under SeqCst: the caller bumps the epoch
461                // BEFORE reading `parked`, so either it sees our flag
462                // (and unparks) or we see its epoch here — a missed
463                // wakeup is impossible. Spurious unparks just loop.
464                if inner.epoch.load(Ordering::SeqCst) == seen
465                    && !inner.shutdown.load(Ordering::Relaxed)
466                {
467                    std::thread::park();
468                }
469                inner.parked[idx].store(false, Ordering::SeqCst);
470            }
471        }
472        // SAFETY: the slot was written before the epoch bump we just
473        // observed (release/acquire), and stays valid until `remaining`
474        // drops to zero — which happens only after `f` returns below.
475        let (task, n) = unsafe { (*inner.slot.get()).expect("job published with epoch") };
476        let f = unsafe { &*task.0 };
477        f(idx, n);
478        inner.remaining.fetch_sub(1, Ordering::AcqRel);
479    }
480}
481
482/// Row-parallel dense matvec: `out[o] = Σ_j w[o·in + j]·x[j]`.
483/// Bit-identical to the serial loop (row order does not change math).
484pub fn matvec_rows(pool: Option<&Pool>, w: &[f32], x: &[f32], out: &mut [f32]) {
485    let in_dim = x.len();
486    let out_dim = out.len();
487    debug_assert!(w.len() >= out_dim * in_dim);
488
489    let row_dot = |o: usize| -> f32 {
490        let row = &w[o * in_dim..(o + 1) * in_dim];
491        let mut sum = 0.0f32;
492        for j in 0..in_dim {
493            sum += row[j] * x[j];
494        }
495        sum
496    };
497
498    match pool {
499        Some(pool) if out_dim >= 256 => {
500            let out_addr = SendMut(out.as_mut_ptr());
501            let run_range = move |start: usize, end: usize| {
502                for o in start..end {
503                    unsafe { *out_addr.at(o) = row_dot(o) };
504                }
505            };
506            pool.run_rows(out_dim, &run_range);
507        }
508        _ => {
509            for (o, dst) in out.iter_mut().enumerate() {
510                *dst = row_dot(o);
511            }
512        }
513    }
514}
515
516/// Two-input row matvec: one pass over the weight rows serves BOTH
517/// inputs — CPU decode is memory-bound, so the second position costs a
518/// fraction of the first (this is where MTP speculative verify wins).
519/// Per-output accumulation order matches the single-input path exactly
520/// → bit-identical results.
521pub fn matvec_rows2(
522    pool: Option<&Pool>,
523    w: &[f32],
524    x1: &[f32],
525    x2: &[f32],
526    out1: &mut [f32],
527    out2: &mut [f32],
528) {
529    let in_dim = x1.len();
530    debug_assert_eq!(x2.len(), in_dim);
531    let out_dim = out1.len();
532    debug_assert_eq!(out2.len(), out_dim);
533    debug_assert!(w.len() >= out_dim * in_dim);
534
535    let row_dots = |o: usize| -> (f32, f32) {
536        let row = &w[o * in_dim..(o + 1) * in_dim];
537        let (mut s1, mut s2) = (0.0f32, 0.0f32);
538        for j in 0..in_dim {
539            s1 += row[j] * x1[j];
540            s2 += row[j] * x2[j];
541        }
542        (s1, s2)
543    };
544
545    match pool {
546        Some(pool) if out_dim >= 256 => {
547            let o1 = SendMut(out1.as_mut_ptr());
548            let o2 = SendMut(out2.as_mut_ptr());
549            let run_range = move |start: usize, end: usize| {
550                for o in start..end {
551                    let (s1, s2) = row_dots(o);
552                    unsafe {
553                        *o1.at(o) = s1;
554                        *o2.at(o) = s2;
555                    }
556                }
557            };
558            pool.run_rows(out_dim, &run_range);
559        }
560        _ => {
561            for o in 0..out_dim {
562                let (s1, s2) = row_dots(o);
563                out1[o] = s1;
564                out2[o] = s2;
565            }
566        }
567    }
568}
569
570#[derive(Clone, Copy)]
571struct SendMut(*mut f32);
572unsafe impl Send for SendMut {}
573unsafe impl Sync for SendMut {}
574
575impl SendMut {
576    /// Method receiver forces the closure to capture the whole (Sync)
577    /// wrapper, not the bare `*mut f32` field (edition-2021 precise capture).
578    #[inline]
579    fn at(self, i: usize) -> *mut f32 {
580        unsafe { self.0.add(i) }
581    }
582}
583
584#[cfg(test)]
585mod tests {
586    #[test]
587    #[cfg(any(target_os = "android", target_os = "linux"))]
588    fn worker_tids_registered_before_new_returns() {
589        let _p = super::Pool::new(3);
590        assert_eq!(
591            super::WORKER_TIDS.lock().unwrap().len(),
592            3,
593            "all worker tids must be visible the moment the pool exists"
594        );
595    }
596
597    #[test]
598    fn forced_threads_overrides_env_and_topology() {
599        use std::sync::atomic::Ordering;
600        super::FORCED_THREADS.store(3, Ordering::Relaxed);
601        let pool = super::Pool::from_env().expect("forced 3 → pool");
602        assert_eq!(pool.n_workers(), 3);
603        super::FORCED_THREADS.store(1, Ordering::Relaxed);
604        assert!(super::Pool::from_env().is_none(), "forced 1 → serial");
605        super::FORCED_THREADS.store(0, Ordering::Relaxed);
606    }
607
608    #[test]
609    fn capacity_split_clock_bins_vs_microarch() {
610        type P = super::Pool;
611        // JR510: all-A55, two clock bins — use every core.
612        assert_eq!(
613            P::cores_from_capacities(&[1024, 1024, 1024, 1024, 768, 768, 768, 768]),
614            Some(8)
615        );
616        // Classic big.LITTLE (A78 + A55) — big only.
617        assert_eq!(
618            P::cores_from_capacities(&[1024, 1024, 1024, 1024, 350, 350, 350, 350]),
619            Some(4)
620        );
621        // Three-tier flagship: X + A7xx mids stay, A5xx littles go.
622        assert_eq!(
623            P::cores_from_capacities(&[1024, 800, 800, 800, 800, 300, 300, 300]),
624            Some(5)
625        );
626        // Uniform: no signal, caller falls back.
627        assert_eq!(P::cores_from_capacities(&[1024; 8]), None);
628        assert_eq!(P::cores_from_capacities(&[]), None);
629    }
630
631    use super::*;
632
633    #[test]
634    fn parallel_matvec_equals_serial_bitexact() {
635        let (out_dim, in_dim) = (512, 64);
636        let w: Vec<f32> = (0..out_dim * in_dim)
637            .map(|i| (i as f32 * 0.013).sin())
638            .collect();
639        let x: Vec<f32> = (0..in_dim).map(|i| (i as f32 * 0.07).cos()).collect();
640
641        let mut serial = vec![0.0f32; out_dim];
642        matvec_rows(None, &w, &x, &mut serial);
643
644        let pool = Pool::new(4);
645        let mut parallel = vec![0.0f32; out_dim];
646        matvec_rows(Some(&pool), &w, &x, &mut parallel);
647
648        assert_eq!(serial, parallel, "row-parallel must be bit-identical");
649    }
650
651    #[test]
652    fn fused_pair_equals_two_singles_bitexact() {
653        let (out_dim, in_dim) = (300, 48);
654        let w: Vec<f32> = (0..out_dim * in_dim)
655            .map(|i| (i as f32 * 0.011).sin())
656            .collect();
657        let x1: Vec<f32> = (0..in_dim).map(|i| (i as f32 * 0.03).cos()).collect();
658        let x2: Vec<f32> = (0..in_dim).map(|i| (i as f32 * 0.09).sin()).collect();
659
660        let mut a1 = vec![0.0f32; out_dim];
661        let mut a2 = vec![0.0f32; out_dim];
662        matvec_rows(None, &w, &x1, &mut a1);
663        matvec_rows(None, &w, &x2, &mut a2);
664
665        for pool in [None, Some(Pool::new(3))] {
666            let mut b1 = vec![0.0f32; out_dim];
667            let mut b2 = vec![0.0f32; out_dim];
668            matvec_rows2(pool.as_ref(), &w, &x1, &x2, &mut b1, &mut b2);
669            assert_eq!(a1, b1, "fused lane 1 must be bit-identical");
670            assert_eq!(a2, b2, "fused lane 2 must be bit-identical");
671        }
672    }
673
674    #[test]
675    fn pool_survives_many_runs() {
676        let pool = Pool::new(3);
677        let counter = AtomicUsize::new(0);
678        for _ in 0..100 {
679            pool.run(&|_, _| {
680                counter.fetch_add(1, Ordering::Relaxed);
681            });
682        }
683        // 3 workers + the participating caller = 4 executions per run.
684        assert_eq!(counter.load(Ordering::Relaxed), 400);
685    }
686
687    #[test]
688    fn pool_wakes_after_park() {
689        // Force immediate parking (no spin) — the epoch/parked handshake
690        // must still never miss a wakeup.
691        let pool = Pool::with_spin(2, 0);
692        let counter = AtomicUsize::new(0);
693        for _ in 0..50 {
694            pool.run(&|_, _| {
695                counter.fetch_add(1, Ordering::Relaxed);
696            });
697            // Give workers time to actually park between jobs.
698            std::thread::sleep(std::time::Duration::from_micros(200));
699        }
700        assert_eq!(counter.load(Ordering::Relaxed), 150);
701    }
702
703    #[test]
704    fn worker_indices_are_distinct_and_cover_range() {
705        let pool = Pool::new(3);
706        let hits: Vec<AtomicUsize> = (0..4).map(|_| AtomicUsize::new(0)).collect();
707        for _ in 0..20 {
708            pool.run(&|widx, n| {
709                assert_eq!(n, 4);
710                hits[widx].fetch_add(1, Ordering::Relaxed);
711            });
712        }
713        for (i, h) in hits.iter().enumerate() {
714            assert_eq!(h.load(Ordering::Relaxed), 20, "participant {i} missed runs");
715        }
716    }
717}