Skip to main content

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    /// Step 3: 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        // Run inside `install` so par_iter picks up the correct pool.
166        self.install(|| (0..count).into_par_iter().for_each(f));
167    }
168
169    fn par_chunks_mut_dyn(
170        &self,
171        data: &mut [f32],
172        chunk_size: usize,
173        f: &(dyn Fn(usize, &mut [f32]) + Send + Sync),
174    ) {
175        if chunk_size == 0 || data.is_empty() {
176            return;
177        }
178        // Skip `self.install(...)` — rayon's par_iter uses the ambient
179        // pool via TLS, which the ONNX runner's outer `pool.install(...)`
180        // already installed. A nested `install` call per site adds real
181        // cost (measured ~4% regression at 6T on tracker) with no
182        // correctness benefit.
183        data.par_chunks_mut(chunk_size)
184            .enumerate()
185            .for_each(|(i, c)| f(i, c));
186    }
187
188    fn join_dyn(&self, a: &mut (dyn FnMut() + Send), b: &mut (dyn FnMut() + Send)) {
189        // Rely on ambient install (same reasoning as above).
190        rayon::join(a, b);
191    }
192
193    fn current_worker_index(&self) -> Option<usize> {
194        rayon::current_thread_index()
195    }
196
197    fn num_threads(&self) -> usize {
198        self.current_num_threads()
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205    use std::sync::Arc;
206    use std::sync::atomic::{AtomicUsize, Ordering};
207
208    fn sum_via_scope(scope: &dyn ParallelScope, count: usize) -> usize {
209        let total = Arc::new(AtomicUsize::new(0));
210        let t = Arc::clone(&total);
211        let f: Box<dyn Fn(usize) + Send + Sync> = Box::new(move |i| {
212            t.fetch_add(i, Ordering::Relaxed);
213        });
214        scope.par_for_each_index(count, f.as_ref());
215        total.load(Ordering::Relaxed)
216    }
217
218    #[test]
219    fn yscv_pool_scope_sums_correctly() {
220        let pool = YscvPool::new(4).unwrap();
221        assert_eq!(sum_via_scope(&pool, 1000), 499_500);
222    }
223
224    #[test]
225    fn rayon_pool_scope_sums_correctly() {
226        let pool = rayon::ThreadPoolBuilder::new()
227            .num_threads(4)
228            .build()
229            .unwrap();
230        assert_eq!(sum_via_scope(&pool, 1000), 499_500);
231    }
232
233    fn doubles_chunks_via_scope(scope: &dyn ParallelScope) -> Vec<f32> {
234        let mut data: Vec<f32> = (0..32).map(|i| i as f32).collect();
235        let f: Box<dyn Fn(usize, &mut [f32]) + Send + Sync> = Box::new(|_idx, chunk| {
236            for v in chunk {
237                *v *= 2.0;
238            }
239        });
240        scope.par_chunks_mut_dyn(&mut data, 4, f.as_ref());
241        data
242    }
243
244    #[test]
245    fn yscv_pool_par_chunks_mut_dyn_matches_rayon() {
246        let pool = YscvPool::new(4).unwrap();
247        let out = doubles_chunks_via_scope(&pool);
248        let expected: Vec<f32> = (0..32).map(|i| (i as f32) * 2.0).collect();
249        assert_eq!(out, expected);
250    }
251
252    #[test]
253    fn rayon_pool_par_chunks_mut_dyn_matches_rayon() {
254        let pool = rayon::ThreadPoolBuilder::new()
255            .num_threads(4)
256            .build()
257            .unwrap();
258        let out = doubles_chunks_via_scope(&pool);
259        let expected: Vec<f32> = (0..32).map(|i| (i as f32) * 2.0).collect();
260        assert_eq!(out, expected);
261    }
262
263    #[test]
264    fn par_chunks_mut_dyn_handles_uneven_last_chunk() {
265        let pool = YscvPool::new(2).unwrap();
266        let mut data: Vec<f32> = vec![1.0; 17];
267        let f: Box<dyn Fn(usize, &mut [f32]) + Send + Sync> = Box::new(|idx, chunk| {
268            for v in chunk {
269                *v += idx as f32;
270            }
271        });
272        pool.par_chunks_mut_dyn(&mut data, 5, f.as_ref());
273        // chunks: [0..5]=idx 0, [5..10]=idx 1, [10..15]=idx 2, [15..17]=idx 3
274        let expected = vec![
275            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,
276        ];
277        assert_eq!(data, expected);
278    }
279
280    #[test]
281    fn yscv_pool_current_worker_index_is_some_inside_install() {
282        let pool = YscvPool::new(2).unwrap();
283        let idx = pool.install(|| pool.current_worker_index());
284        assert!(idx.is_some(), "expected Some(worker_idx) inside install");
285    }
286
287    #[test]
288    fn yscv_pool_current_worker_index_is_none_on_main() {
289        let pool = YscvPool::new(2).unwrap();
290        assert_eq!(pool.current_worker_index(), None);
291    }
292}