rustsy-engine 0.1.0

Task graph scheduling, residency planning and bounded streaming pipelines
Documentation
//! Runtime policy trained on complete CPU and GPU batch observations.
//! Supply elapsed wall time including packing, transfers and synchronization.
use std::time::Duration;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct WorkClass {
    size_bin: u32,
    entropy_bin: u8,
    repetition_bin: u8,
}
impl WorkClass {
    /// Sample up to sixteen 256-byte windows spread across an input.
    pub fn bytes(input: &[u8]) -> Self {
        let width = input.len().min(256);
        let windows = input.len().div_ceil(256).clamp(1, 16);
        let mut histogram = [0usize; 256];
        let mut seen = [false; 4096];
        let mut repeated = 0usize;
        let mut words = 0usize;
        for i in 0..windows {
            let offset = (input.len() - width) / windows.saturating_sub(1).max(1) * i;
            let sample = &input[offset..offset + width];
            for &b in sample {
                histogram[b as usize] += 1;
            }
            for chunk in sample.chunks_exact(4) {
                let slot = (u32::from_le_bytes(chunk.try_into().unwrap()).wrapping_mul(2654435761)
                    >> 20) as usize;
                repeated += usize::from(seen[slot]);
                seen[slot] = true;
                words += 1;
            }
        }
        let total = (width * windows) as f64;
        let entropy = histogram
            .iter()
            .copied()
            .filter(|&n| n > 0)
            .map(|n| {
                let p = n as f64 / total;
                -p * p.log2()
            })
            .sum::<f64>();
        Self {
            size_bin: input.len().checked_ilog2().unwrap_or(0),
            entropy_bin: (entropy * 2.) as u8,
            repetition_bin: (4 * repeated / words.max(1)) as u8,
        }
    }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Route {
    Cpu,
    Cuda,
}
#[derive(Clone, Copy)]
pub struct Observation {
    pub elapsed: Duration,
    pub output_bytes: u64,
}
/// One instance per device, codec configuration and worker arrangement.
/// Bucket medians describe only observations supplied by the caller.
#[derive(Default)]
pub struct DispatchHistory {
    samples: std::collections::HashMap<
        (WorkClass, usize),
        std::collections::VecDeque<(Observation, Observation)>,
    >,
}
impl DispatchHistory {
    /// Execute an independently scheduled batch, reporting device failures even when CPU recovers.
    pub fn execute<T, E>(
        &self,
        class: WorkClass,
        count: usize,
        max_extra_per_mille: u16,
        cpu: impl FnOnce() -> Result<T, E>,
        gpu: impl FnOnce() -> Result<T, E>,
    ) -> Result<(T, Route, Option<E>), E> {
        if self.choose(class, count, max_extra_per_mille) == Route::Cuda {
            match gpu() {
                Ok(result) => return Ok((result, Route::Cuda, None)),
                Err(error) => return cpu().map(|v| (v, Route::Cpu, Some(error))),
            }
        }
        cpu().map(|v| (v, Route::Cpu, None))
    }

    pub fn record(&mut self, class: WorkClass, count: usize, cpu: Observation, gpu: Observation) {
        let v = self.samples.entry((class, count)).or_default();
        if v.len() == 9 {
            v.pop_front();
        }
        v.push_back((cpu, gpu));
    }
    /// Choose CUDA only after three paired samples, a positive median saving,
    /// and a compressed-size ceiling respected in every retained pair.
    pub fn choose(&self, class: WorkClass, count: usize, max_extra_per_mille: u16) -> Route {
        let Some(v) = self.samples.get(&(class, count)) else {
            return Route::Cpu;
        };
        if v.len() < 3
            || v.iter().any(|(c, g)| {
                g.output_bytes as u128 * 1000
                    > c.output_bytes as u128 * (1000 + max_extra_per_mille as u128)
            })
        {
            return Route::Cpu;
        }
        let mut differences = v
            .iter()
            .map(|(c, g)| c.elapsed.as_nanos() as i128 - g.elapsed.as_nanos() as i128)
            .collect::<Vec<_>>();
        differences.sort_unstable();
        if differences[(differences.len() - 1) / 2] > 0 {
            Route::Cuda
        } else {
            Route::Cpu
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn insufficient_or_expensive_profile_stays_on_cpu() {
        let k = WorkClass::bytes(b"hello");
        let c = Observation {
            elapsed: Duration::from_millis(10),
            output_bytes: 100,
        };
        let g = Observation {
            elapsed: Duration::from_millis(2),
            output_bytes: 101,
        };
        let mut h = DispatchHistory::default();
        for _ in 0..2 {
            h.record(k, 10, c, g);
        }
        assert_eq!(h.choose(k, 10, 10), Route::Cpu);
        h.record(k, 10, c, g);
        assert_eq!(h.choose(k, 10, 10), Route::Cuda);
        assert_eq!(h.choose(k, 10, 0), Route::Cpu);
        assert_eq!(h.choose(k, 11, 10), Route::Cpu);
        assert_eq!(
            h.execute(k, 10, 10, || Ok(3), || Err("device error")),
            Ok((3, Route::Cpu, Some("device error")))
        );
        assert_eq!(
            h.execute(k, 11, 10, || Ok::<_, &str>(4), || panic!()),
            Ok((4, Route::Cpu, None))
        );
    }
}