Skip to main content

vyre_runtime/
scheduler.rs

1//! Multi-GPU work stealing scheduler (Innovation I.7).
2//!
3//! Partitions a large Program or batch of Programs across all
4//! registered physical devices.
5
6use std::ops::Range;
7use std::sync::atomic::{AtomicUsize, Ordering};
8use std::sync::Arc;
9use vyre_driver::{BackendError, VyreBackend};
10
11/// A unit of work assigned to one GPU.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Shard {
14    /// Stable backend identifier for the GPU backend receiving this shard.
15    pub backend_id: &'static str,
16    /// Half-open byte/item range assigned to the backend.
17    pub work_range: Range<usize>,
18}
19
20/// Dynamic work-stealing scheduler.
21pub struct WorkStealingScheduler {
22    backends: Vec<Arc<dyn VyreBackend>>,
23    /// Atomic work index used by dispatch loops to let fast backends
24    /// steal more fine-grained work units. Worker threads call
25    /// [`Self::claim_next_unit`] which atomically increments the index;
26    /// the returned value is the unit index they own. This is the
27    /// work-stealing primitive  -  fast backends pull more units, slow
28    /// backends pull fewer.
29    work_index: AtomicUsize,
30}
31
32impl WorkStealingScheduler {
33    /// Create a scheduler over the live runtime backends available to the process.
34    pub fn new(backends: Vec<Arc<dyn VyreBackend>>) -> Self {
35        Self {
36            backends,
37            work_index: AtomicUsize::new(0),
38        }
39    }
40
41    /// Partition a large haystack across available GPUs.
42    pub fn partition(&self, total_len: usize) -> Vec<Shard> {
43        match self.try_partition(total_len) {
44            Ok(shards) => shards,
45            Err(_error) => Vec::new(),
46        }
47    }
48
49    /// Partition a large haystack across available GPUs with explicit staging
50    /// allocation failure reporting.
51    pub fn try_partition(&self, total_len: usize) -> Result<Vec<Shard>, BackendError> {
52        let mut shards = Vec::new();
53        self.try_partition_into(total_len, &mut shards)?;
54        Ok(shards)
55    }
56
57    /// Atomically claim the next fine-grained work unit. Worker threads
58    /// call this in a loop; the returned value is the unit index they
59    /// own. When the returned index is `>= num_units`, the worker is
60    /// done. This is the work-stealing primitive: fast backends call
61    /// `claim_next_unit` more times in the same wall-clock window.
62    ///
63    /// # Examples
64    ///
65    /// ```
66    /// use vyre_runtime::scheduler::WorkStealingScheduler;
67    /// let scheduler = WorkStealingScheduler::new(Vec::new());
68    /// assert_eq!(scheduler.claim_next_unit(), 0);
69    /// assert_eq!(scheduler.claim_next_unit(), 1);
70    /// scheduler.reset_unit_cursor();
71    /// assert_eq!(scheduler.claim_next_unit(), 0);
72    /// ```
73    #[must_use]
74    pub fn claim_next_unit(&self) -> usize {
75        self.work_index.fetch_add(1, Ordering::AcqRel)
76    }
77
78    /// Reset the work-unit cursor to zero. Call between dispatches that
79    /// reuse the same scheduler.
80    pub fn reset_unit_cursor(&self) {
81        self.work_index.store(0, Ordering::Release);
82    }
83
84    /// Partition a large haystack into many fine-grained work units
85    /// assigned round-robin to backends. A caller-side dispatch loop
86    /// uses [`Self::claim_next_unit`] to let worker threads atomically
87    /// claim units so fast backends steal more work.
88    pub fn partition_into(&self, total_len: usize, out: &mut Vec<Shard>) {
89        // Clearing to empty on failure leaves NO work units — the dispatch loop
90        // then claims nothing and the scan silently processes nothing (Law 10
91        // recall loss). Fail loud; callers use try_partition_into.
92        if let Err(error) = self.try_partition_into(total_len, out) {
93            panic!("vyre-runtime work-unit partition failed: {error}");
94        }
95    }
96
97    /// Partition into caller-owned storage with explicit staging allocation
98    /// failure reporting.
99    pub fn try_partition_into(
100        &self,
101        total_len: usize,
102        out: &mut Vec<Shard>,
103    ) -> Result<(), BackendError> {
104        let n = self.backends.len();
105        out.clear();
106        if n == 0 || total_len == 0 {
107            return Ok(());
108        }
109        let work_unit_size = partition_work_unit_size(total_len, n);
110        let num_units = total_len.div_ceil(work_unit_size);
111        vyre_foundation::allocation::try_reserve_vec_to_capacity(out, num_units).map_err(
112            |error| BackendError::InvalidProgram {
113                fix: format!(
114                    "Fix: scheduler could not reserve {num_units} GPU work shard(s): {error}. Shard the workload before work-stealing partitioning."
115                ),
116            },
117        )?;
118        let mut start = 0;
119        for i in 0..num_units {
120            let end = (start + work_unit_size).min(total_len);
121            out.push(Shard {
122                backend_id: self.backends[i % n].id(),
123                work_range: start..end,
124            });
125            start = end;
126        }
127        Ok(())
128    }
129}
130
131fn partition_work_unit_size(total_len: usize, backend_count: usize) -> usize {
132    if total_len == 0 || backend_count == 0 {
133        return 1;
134    }
135    let denominator = backend_count.checked_mul(4).unwrap_or(usize::MAX);
136    (total_len / denominator.max(1)).max(1)
137}
138
139#[cfg(test)]
140fn partition_ranges(total_len: usize, backend_count: usize) -> Vec<Range<usize>> {
141    if backend_count == 0 || total_len == 0 {
142        return Vec::new();
143    }
144    let work_unit_size = partition_work_unit_size(total_len, backend_count);
145    let num_units = total_len.div_ceil(work_unit_size);
146    let mut ranges = Vec::with_capacity(num_units);
147    let mut start = 0;
148    for _ in 0..num_units {
149        let end = (start + work_unit_size).min(total_len);
150        ranges.push(start..end);
151        start = end;
152    }
153    ranges
154}
155
156#[cfg(test)]
157mod tests {
158    use super::{partition_ranges, WorkStealingScheduler};
159    use std::sync::Arc;
160    use vyre_driver::backend::{DispatchConfig, VyreBackend};
161    use vyre_foundation::ir::Program;
162
163    struct TestBackend(&'static str);
164
165    impl vyre_driver::backend::private::Sealed for TestBackend {}
166
167    impl VyreBackend for TestBackend {
168        fn id(&self) -> &'static str {
169            self.0
170        }
171
172        fn dispatch(
173            &self,
174            _program: &Program,
175            _inputs: &[Vec<u8>],
176            _config: &DispatchConfig,
177        ) -> Result<Vec<Vec<u8>>, vyre_driver::BackendError> {
178            Ok(Vec::new())
179        }
180    }
181
182    #[test]
183    fn partition_ranges_produces_fine_grained_units() {
184        let ranges = partition_ranges(10, 3);
185        assert_eq!(ranges.len(), 10);
186        assert_eq!(
187            ranges,
188            vec![0..1, 1..2, 2..3, 3..4, 4..5, 5..6, 6..7, 7..8, 8..9, 9..10]
189        );
190    }
191
192    #[test]
193    fn partition_ranges_never_emits_empty_shards() {
194        let ranges = partition_ranges(2, 8);
195        assert_eq!(ranges, vec![0..1, 1..2]);
196    }
197
198    #[test]
199    fn partition_ranges_uses_overflow_safe_work_unit_math() {
200        let ranges = partition_ranges(2, usize::MAX);
201        assert_eq!(ranges[0], 0..1);
202        assert_eq!(ranges[1], 1..2);
203        assert_eq!(
204            super::partition_work_unit_size(2, usize::MAX),
205            1,
206            "backend_count * 4 overflow must not panic or enlarge the work unit"
207        );
208    }
209
210    #[test]
211    fn scheduler_partition_into_reuses_output_storage() {
212        let scheduler = WorkStealingScheduler::new(vec![
213            Arc::new(TestBackend("a")),
214            Arc::new(TestBackend("b")),
215            Arc::new(TestBackend("c")),
216        ]);
217        let mut shards = Vec::with_capacity(10);
218
219        scheduler.partition_into(10, &mut shards);
220        let ptr = shards.as_ptr();
221        scheduler.partition_into(10, &mut shards);
222
223        assert_eq!(shards.as_ptr(), ptr);
224        assert_eq!(shards.len(), 10);
225        assert_eq!(shards[0].backend_id, "a");
226        assert_eq!(shards[0].work_range, 0..1);
227        assert_eq!(shards[1].backend_id, "b");
228        assert_eq!(shards[1].work_range, 1..2);
229        assert_eq!(shards[9].backend_id, "a");
230        assert_eq!(shards[9].work_range, 9..10);
231        assert_eq!(
232            scheduler
233                .work_index
234                .load(std::sync::atomic::Ordering::Relaxed),
235            0
236        );
237    }
238}