yscv_threadpool/scope.rs
1//! `ParallelScope` — uniform parallelism trait over `YscvPool` and
2//! `rayon::ThreadPool`. Lets the rest of the yscv stack be pool-agnostic
3//! and switch backends at runtime via `YSCV_POOL=rayon|yscv`.
4//!
5//! Surface grew during the Part 2A full-rayon-replacement refactor to cover
6//! every parallel call site in yscv-kernels / yscv-onnx:
7//! - `par_for_each_index(n, f)` — mirrors `(0..n).into_par_iter().for_each(f)`.
8//! - `par_chunks_mut_dyn(data, chunk, f)` — mirrors `data.par_chunks_mut(chunk).enumerate().for_each(f)`.
9//! The enumeration form is chosen because most kernel sites need the
10//! chunk index to compute row/tile offsets into co-owned inputs.
11//! - `join_dyn(a, b)` — mirrors `rayon::join(a, b)` over `FnMut`.
12//! - `current_worker_index()` — mirrors `rayon::current_thread_index()`,
13//! used by matmul.rs to avoid re-entrant pool dispatch.
14//! - `num_threads()` — same as both pools' existing method.
15//!
16//! More complex rayon patterns (`scope` with arbitrary spawn trees, `par_sort`,
17//! data-parallel reductions over borrowed structures) aren't used by the
18//! inference hot path, so they're not in the trait.
19
20use rayon::prelude::*;
21
22use crate::YscvPool;
23
24/// Trait abstracting over thread-pool backends for the inference hot path.
25pub trait ParallelScope: Send + Sync {
26 /// enter a session-scoped parallel region. On backends that
27 /// support persistent sections (currently [`YscvPool`]), all pool
28 /// workers enter a tight-poll loop, and parallel dispatch inside
29 /// `f` routes through the section's single-atomic-pointer
30 /// mechanism instead of rayon's fork-join. On rayon, this is a
31 /// pass-through that just invokes `f`.
32 ///
33 /// The downstream dispatch hook (`yscv-kernels`'s
34 /// `par_chunks_mut_dispatch`) reads the thread-local section
35 /// pointer via [`crate::current_section`] and picks the session
36 /// path when present.
37 ///
38 /// Uses a `&mut dyn FnMut()` rather than generic `FnOnce` so the
39 /// trait stays dyn-compatible (the runner holds a
40 /// `Arc<dyn ParallelScope>`).
41 fn install_session(&self, f: &mut dyn FnMut());
42
43 /// Runs `f(i)` for each `i` in `0..count`, in parallel. Blocks until
44 /// every iteration completes. Equivalent to rayon's
45 /// `(0..count).into_par_iter().for_each(f)`.
46 fn par_for_each_index(&self, count: usize, f: &(dyn Fn(usize) + Send + Sync));
47
48 /// Runs `f(chunk_idx, chunk)` for each `chunk_size`-wide slice of `data`,
49 /// in parallel. The last chunk may be short when `data.len()` is not a
50 /// multiple of `chunk_size`. Blocks until every chunk completes.
51 /// Equivalent to `data.par_chunks_mut(chunk_size).enumerate().for_each(…)`.
52 fn par_chunks_mut_dyn(
53 &self,
54 data: &mut [f32],
55 chunk_size: usize,
56 f: &(dyn Fn(usize, &mut [f32]) + Send + Sync),
57 );
58
59 /// Runs `a` and `b` in parallel, returns both results. Equivalent
60 /// to `rayon::join(a, b)`.
61 fn join_dyn(&self, a: &mut (dyn FnMut() + Send), b: &mut (dyn FnMut() + Send));
62
63 /// The caller's worker index, 0..num_threads, if running on one of this
64 /// pool's workers. `None` when called from outside the pool (e.g. from
65 /// the main thread before `install`). Used by matmul.rs at 538/684 to
66 /// decide whether to further parallelise — we don't want nested pool
67 /// dispatch on an already-parallel worker.
68 fn current_worker_index(&self) -> Option<usize>;
69
70 /// Number of worker threads.
71 fn num_threads(&self) -> usize;
72}
73
74impl ParallelScope for YscvPool {
75 fn install_session(&self, f: &mut dyn FnMut()) {
76 // Create section + hold workers in `section_worker_loop` for
77 // the closure's lifetime. Install TLS so downstream dispatch
78 // routes through the section's parallel_for.
79 self.enter_section(|section| {
80 let _guard = section.install_tls();
81 f();
82 });
83 }
84
85 fn par_for_each_index(&self, count: usize, f: &(dyn Fn(usize) + Send + Sync)) {
86 // Bridge the dyn reference into the generic API. Closure captures
87 // `f` by reference — `par_for_each_index` blocks so lifetime is OK.
88 self.par_for_each_index(count, f);
89 }
90
91 fn par_chunks_mut_dyn(
92 &self,
93 data: &mut [f32],
94 chunk_size: usize,
95 f: &(dyn Fn(usize, &mut [f32]) + Send + Sync),
96 ) {
97 if chunk_size == 0 || data.is_empty() {
98 return;
99 }
100 let len = data.len();
101 let n_chunks = len.div_ceil(chunk_size);
102 // Share the slice across workers via its raw pointer + length.
103 // Disjoint chunk ranges give non-overlapping `&mut [f32]` slices,
104 // which is exactly the rayon `par_chunks_mut` safety invariant.
105 //
106 // SAFETY: (1) `par_for_each_index` blocks until every chunk
107 // finishes, so `data` outlives all task accesses. (2) Chunk ranges
108 // `[i*chunk_size .. min((i+1)*chunk_size, len)]` are pairwise
109 // disjoint and in-bounds, so no two tasks alias the same byte.
110 // (3) `f: Fn` is `Send + Sync`, required by the trait bound.
111 // (4) PtrWrap's Send/Sync are safe to assert because the pointer
112 // is only used to derive the disjoint chunk slices described
113 // in (1)-(3); we never share or read raw memory beyond them.
114 // The `as_ptr()` accessor routes through `&self`, which forces
115 // the closure to capture the whole `PtrWrap` struct rather than
116 // the bare `*mut f32` field — Rust 2021 disjoint captures would
117 // otherwise strip the Send/Sync impls off and leave us with a
118 // raw pointer capture the compiler rejects.
119 struct PtrWrap(*mut f32);
120 impl PtrWrap {
121 #[inline]
122 fn as_ptr(&self) -> *mut f32 {
123 self.0
124 }
125 }
126 #[allow(unsafe_code)]
127 unsafe impl Send for PtrWrap {}
128 #[allow(unsafe_code)]
129 unsafe impl Sync for PtrWrap {}
130 let wrap = PtrWrap(data.as_mut_ptr());
131 self.par_for_each_index(n_chunks, move |i| {
132 let start = i * chunk_size;
133 let end = (start + chunk_size).min(len);
134 #[allow(unsafe_code)]
135 let chunk =
136 unsafe { std::slice::from_raw_parts_mut(wrap.as_ptr().add(start), end - start) };
137 f(i, chunk);
138 });
139 }
140
141 fn join_dyn(&self, a: &mut (dyn FnMut() + Send), b: &mut (dyn FnMut() + Send)) {
142 // Wrap the &mut dyn FnMut in closures that take ownership of the
143 // reference. Uses a single call each — FnMut → FnOnce semantically.
144 self.join(a, b);
145 }
146
147 fn current_worker_index(&self) -> Option<usize> {
148 self.current_worker_index()
149 }
150
151 fn num_threads(&self) -> usize {
152 YscvPool::num_threads(self)
153 }
154}
155
156impl ParallelScope for rayon::ThreadPool {
157 fn install_session(&self, f: &mut dyn FnMut()) {
158 // rayon has no persistent section — just invoke the closure.
159 // CURRENT_SECTION_TLS stays null; downstream dispatch falls
160 // through to rayon's normal fork-join path.
161 f();
162 }
163
164 fn par_for_each_index(&self, count: usize, f: &(dyn Fn(usize) + Send + Sync)) {
165 // Use ambient pool (same as par_chunks_mut_dyn) — avoids nested install.
166 // When called from within pool_A.install(), the ambient pool IS pool_A;
167 // pool_A's workers (idle after join) steal the tasks directly. The nested
168 // `self.install()` would activate a separate pool_B while pool_A workers
169 // spin-idle, causing 12-thread oversubscription on 12-SMT and a measured
170 // ~0× speedup on merge-branch ops. See June 2026 performance investigation.
171 (0..count).into_par_iter().for_each(f);
172 }
173
174 fn par_chunks_mut_dyn(
175 &self,
176 data: &mut [f32],
177 chunk_size: usize,
178 f: &(dyn Fn(usize, &mut [f32]) + Send + Sync),
179 ) {
180 if chunk_size == 0 || data.is_empty() {
181 return;
182 }
183 // Skip `self.install(...)` — rayon's par_iter uses the ambient
184 // pool via TLS, which the ONNX runner's outer `pool.install(...)`
185 // already installed. A nested `install` call per site adds real
186 // cost (measured ~4% regression at 6T on tracker) with no
187 // correctness benefit.
188 data.par_chunks_mut(chunk_size)
189 .enumerate()
190 .for_each(|(i, c)| f(i, c));
191 }
192
193 fn join_dyn(&self, a: &mut (dyn FnMut() + Send), b: &mut (dyn FnMut() + Send)) {
194 // Rely on ambient install (same reasoning as above).
195 rayon::join(a, b);
196 }
197
198 fn current_worker_index(&self) -> Option<usize> {
199 rayon::current_thread_index()
200 }
201
202 fn num_threads(&self) -> usize {
203 self.current_num_threads()
204 }
205}
206
207/// Zero-thread parallel scope for the rayon inference path.
208///
209/// `rayon::ThreadPool`-backed runners already install their pool via
210/// `pool.install(|| run_onnx_model_inner(...))`. Every `par_iter` call
211/// inside that closure automatically uses pool's workers — no separate
212/// scope pool is needed. Maintaining a second static rayon pool (the old
213/// `build_parallel_scope` RAYON_SCOPES approach) added N scope-pool threads
214/// that would spin-idle alongside N pool threads = 2N threads on an N-core
215/// machine: pure oversubscription that regresses multi-thread latency.
216///
217/// `AmbientRayonScope` fixes this by delegating all dispatch to the ambient
218/// rayon pool with zero extra threads. `num_threads` is reported as the
219/// logical count so downstream threshold checks (`blocked_blocks >= nthreads`)
220/// remain accurate.
221pub struct AmbientRayonScope {
222 num_threads: usize,
223}
224
225impl AmbientRayonScope {
226 pub fn new(num_threads: usize) -> Self {
227 Self {
228 num_threads: num_threads.max(1),
229 }
230 }
231}
232
233impl ParallelScope for AmbientRayonScope {
234 fn install_session(&self, f: &mut dyn FnMut()) {
235 f();
236 }
237
238 fn par_for_each_index(&self, count: usize, f: &(dyn Fn(usize) + Send + Sync)) {
239 (0..count).into_par_iter().for_each(f);
240 }
241
242 fn par_chunks_mut_dyn(
243 &self,
244 data: &mut [f32],
245 chunk_size: usize,
246 f: &(dyn Fn(usize, &mut [f32]) + Send + Sync),
247 ) {
248 if chunk_size == 0 || data.is_empty() {
249 return;
250 }
251 data.par_chunks_mut(chunk_size)
252 .enumerate()
253 .for_each(|(i, c)| f(i, c));
254 }
255
256 fn join_dyn(&self, a: &mut (dyn FnMut() + Send), b: &mut (dyn FnMut() + Send)) {
257 rayon::join(a, b);
258 }
259
260 fn current_worker_index(&self) -> Option<usize> {
261 rayon::current_thread_index()
262 }
263
264 fn num_threads(&self) -> usize {
265 self.num_threads
266 }
267}
268
269#[cfg(test)]
270mod tests {
271 use super::*;
272 use std::sync::Arc;
273 use std::sync::atomic::{AtomicUsize, Ordering};
274
275 fn sum_via_scope(scope: &dyn ParallelScope, count: usize) -> usize {
276 let total = Arc::new(AtomicUsize::new(0));
277 let t = Arc::clone(&total);
278 let f: Box<dyn Fn(usize) + Send + Sync> = Box::new(move |i| {
279 t.fetch_add(i, Ordering::Relaxed);
280 });
281 scope.par_for_each_index(count, f.as_ref());
282 total.load(Ordering::Relaxed)
283 }
284
285 #[test]
286 fn yscv_pool_scope_sums_correctly() {
287 let pool = YscvPool::new(4).unwrap();
288 assert_eq!(sum_via_scope(&pool, 1000), 499_500);
289 }
290
291 #[test]
292 fn rayon_pool_scope_sums_correctly() {
293 let pool = rayon::ThreadPoolBuilder::new()
294 .num_threads(4)
295 .build()
296 .unwrap();
297 assert_eq!(sum_via_scope(&pool, 1000), 499_500);
298 }
299
300 fn doubles_chunks_via_scope(scope: &dyn ParallelScope) -> Vec<f32> {
301 let mut data: Vec<f32> = (0..32).map(|i| i as f32).collect();
302 let f: Box<dyn Fn(usize, &mut [f32]) + Send + Sync> = Box::new(|_idx, chunk| {
303 for v in chunk {
304 *v *= 2.0;
305 }
306 });
307 scope.par_chunks_mut_dyn(&mut data, 4, f.as_ref());
308 data
309 }
310
311 #[test]
312 fn yscv_pool_par_chunks_mut_dyn_matches_rayon() {
313 let pool = YscvPool::new(4).unwrap();
314 let out = doubles_chunks_via_scope(&pool);
315 let expected: Vec<f32> = (0..32).map(|i| (i as f32) * 2.0).collect();
316 assert_eq!(out, expected);
317 }
318
319 #[test]
320 fn rayon_pool_par_chunks_mut_dyn_matches_rayon() {
321 let pool = rayon::ThreadPoolBuilder::new()
322 .num_threads(4)
323 .build()
324 .unwrap();
325 let out = doubles_chunks_via_scope(&pool);
326 let expected: Vec<f32> = (0..32).map(|i| (i as f32) * 2.0).collect();
327 assert_eq!(out, expected);
328 }
329
330 #[test]
331 fn par_chunks_mut_dyn_handles_uneven_last_chunk() {
332 let pool = YscvPool::new(2).unwrap();
333 let mut data: Vec<f32> = vec![1.0; 17];
334 let f: Box<dyn Fn(usize, &mut [f32]) + Send + Sync> = Box::new(|idx, chunk| {
335 for v in chunk {
336 *v += idx as f32;
337 }
338 });
339 pool.par_chunks_mut_dyn(&mut data, 5, f.as_ref());
340 // chunks: [0..5]=idx 0, [5..10]=idx 1, [10..15]=idx 2, [15..17]=idx 3
341 let expected = vec![
342 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0,
343 ];
344 assert_eq!(data, expected);
345 }
346
347 #[test]
348 fn yscv_pool_current_worker_index_is_some_inside_install() {
349 let pool = YscvPool::new(2).unwrap();
350 let idx = pool.install(|| pool.current_worker_index());
351 assert!(idx.is_some(), "expected Some(worker_idx) inside install");
352 }
353
354 #[test]
355 fn yscv_pool_current_worker_index_is_none_on_main() {
356 let pool = YscvPool::new(2).unwrap();
357 assert_eq!(pool.current_worker_index(), None);
358 }
359}