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