Skip to main content

rustsy_engine/
dispatch.rs

1//! Runtime policy trained on complete CPU and GPU batch observations.
2//! Supply elapsed wall time including packing, transfers and synchronization.
3use std::time::Duration;
4#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
5pub struct WorkClass {
6    size_bin: u32,
7    entropy_bin: u8,
8    repetition_bin: u8,
9}
10impl WorkClass {
11    /// Sample up to sixteen 256-byte windows spread across an input.
12    pub fn bytes(input: &[u8]) -> Self {
13        let width = input.len().min(256);
14        let windows = input.len().div_ceil(256).clamp(1, 16);
15        let mut histogram = [0usize; 256];
16        let mut seen = [false; 4096];
17        let mut repeated = 0usize;
18        let mut words = 0usize;
19        for i in 0..windows {
20            let offset = (input.len() - width) / windows.saturating_sub(1).max(1) * i;
21            let sample = &input[offset..offset + width];
22            for &b in sample {
23                histogram[b as usize] += 1;
24            }
25            for chunk in sample.chunks_exact(4) {
26                let slot = (u32::from_le_bytes(chunk.try_into().unwrap()).wrapping_mul(2654435761)
27                    >> 20) as usize;
28                repeated += usize::from(seen[slot]);
29                seen[slot] = true;
30                words += 1;
31            }
32        }
33        let total = (width * windows) as f64;
34        let entropy = histogram
35            .iter()
36            .copied()
37            .filter(|&n| n > 0)
38            .map(|n| {
39                let p = n as f64 / total;
40                -p * p.log2()
41            })
42            .sum::<f64>();
43        Self {
44            size_bin: input.len().checked_ilog2().unwrap_or(0),
45            entropy_bin: (entropy * 2.) as u8,
46            repetition_bin: (4 * repeated / words.max(1)) as u8,
47        }
48    }
49}
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum Route {
52    Cpu,
53    Cuda,
54}
55#[derive(Clone, Copy)]
56pub struct Observation {
57    pub elapsed: Duration,
58    pub output_bytes: u64,
59}
60/// One instance per device, codec configuration and worker arrangement.
61/// Bucket medians describe only observations supplied by the caller.
62#[derive(Default)]
63pub struct DispatchHistory {
64    samples: std::collections::HashMap<
65        (WorkClass, usize),
66        std::collections::VecDeque<(Observation, Observation)>,
67    >,
68}
69impl DispatchHistory {
70    /// Execute an independently scheduled batch, reporting device failures even when CPU recovers.
71    pub fn execute<T, E>(
72        &self,
73        class: WorkClass,
74        count: usize,
75        max_extra_per_mille: u16,
76        cpu: impl FnOnce() -> Result<T, E>,
77        gpu: impl FnOnce() -> Result<T, E>,
78    ) -> Result<(T, Route, Option<E>), E> {
79        if self.choose(class, count, max_extra_per_mille) == Route::Cuda {
80            match gpu() {
81                Ok(result) => return Ok((result, Route::Cuda, None)),
82                Err(error) => return cpu().map(|v| (v, Route::Cpu, Some(error))),
83            }
84        }
85        cpu().map(|v| (v, Route::Cpu, None))
86    }
87
88    pub fn record(&mut self, class: WorkClass, count: usize, cpu: Observation, gpu: Observation) {
89        let v = self.samples.entry((class, count)).or_default();
90        if v.len() == 9 {
91            v.pop_front();
92        }
93        v.push_back((cpu, gpu));
94    }
95    /// Choose CUDA only after three paired samples, a positive median saving,
96    /// and a compressed-size ceiling respected in every retained pair.
97    pub fn choose(&self, class: WorkClass, count: usize, max_extra_per_mille: u16) -> Route {
98        let Some(v) = self.samples.get(&(class, count)) else {
99            return Route::Cpu;
100        };
101        if v.len() < 3
102            || v.iter().any(|(c, g)| {
103                g.output_bytes as u128 * 1000
104                    > c.output_bytes as u128 * (1000 + max_extra_per_mille as u128)
105            })
106        {
107            return Route::Cpu;
108        }
109        let mut differences = v
110            .iter()
111            .map(|(c, g)| c.elapsed.as_nanos() as i128 - g.elapsed.as_nanos() as i128)
112            .collect::<Vec<_>>();
113        differences.sort_unstable();
114        if differences[(differences.len() - 1) / 2] > 0 {
115            Route::Cuda
116        } else {
117            Route::Cpu
118        }
119    }
120}
121#[cfg(test)]
122mod tests {
123    use super::*;
124    #[test]
125    fn insufficient_or_expensive_profile_stays_on_cpu() {
126        let k = WorkClass::bytes(b"hello");
127        let c = Observation {
128            elapsed: Duration::from_millis(10),
129            output_bytes: 100,
130        };
131        let g = Observation {
132            elapsed: Duration::from_millis(2),
133            output_bytes: 101,
134        };
135        let mut h = DispatchHistory::default();
136        for _ in 0..2 {
137            h.record(k, 10, c, g);
138        }
139        assert_eq!(h.choose(k, 10, 10), Route::Cpu);
140        h.record(k, 10, c, g);
141        assert_eq!(h.choose(k, 10, 10), Route::Cuda);
142        assert_eq!(h.choose(k, 10, 0), Route::Cpu);
143        assert_eq!(h.choose(k, 11, 10), Route::Cpu);
144        assert_eq!(
145            h.execute(k, 10, 10, || Ok(3), || Err("device error")),
146            Ok((3, Route::Cpu, Some("device error")))
147        );
148        assert_eq!(
149            h.execute(k, 11, 10, || Ok::<_, &str>(4), || panic!()),
150            Ok((4, Route::Cpu, None))
151        );
152    }
153}