rustsy-engine 0.1.0

Task graph scheduling, residency planning and bounded streaming pipelines
Documentation
//! Cost-based placement for a linear chain with one live logical value.
//! Operations supply their own timings and declare unsupported placements as `None`.
use std::{num::NonZeroU64, time::Duration};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Location {
    Host,
    Device,
}

impl Location {
    const ALL: [Self; 2] = [Self::Host, Self::Device];

    fn index(self) -> usize {
        match self {
            Self::Host => 0,
            Self::Device => 1,
        }
    }
}

#[derive(Clone, Copy)]
pub struct Transfer {
    pub latency: Duration,
    pub bytes_per_second: NonZeroU64,
}

impl Transfer {
    fn cost(self, bytes: usize) -> Duration {
        if bytes == 0 {
            return Duration::ZERO;
        }
        let nanos = (bytes as u128 * 1_000_000_000).div_ceil(self.bytes_per_second.get() as u128);
        let seconds = nanos / 1_000_000_000;
        let duration = Duration::new(seconds as u64, (nanos % 1_000_000_000) as u32);
        self.latency.saturating_add(duration)
    }
}

pub struct Link {
    pub upload: Transfer,
    pub download: Transfer,
}

impl Link {
    fn cost(&self, from: Location, to: Location, bytes: usize) -> Duration {
        match (from, to) {
            (Location::Host, Location::Device) => self.upload.cost(bytes),
            (Location::Device, Location::Host) => self.download.cost(bytes),
            _ => Duration::ZERO,
        }
    }
}

pub struct Stage {
    pub output_bytes: usize,
    pub host: Option<Duration>,
    pub device: Option<Duration>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Step {
    Transfer { to: Location, bytes: usize },
    Run { stage: usize, at: Location },
}

#[derive(Debug)]
pub struct Placement {
    pub predicted: Duration,
    pub steps: Vec<Step>,
}

/// Minimize estimated time of sequential execution, including the final landing
/// location. A tie prefers fewer transfers and then host execution.
pub fn place(
    stages: &[Stage],
    link: &Link,
    input: Location,
    input_bytes: usize,
    output: Location,
) -> Option<Placement> {
    let mut costs = [None; 2];
    costs[input.index()] = Some((Duration::ZERO, 0usize));
    let mut previous = Vec::with_capacity(stages.len());
    let mut bytes = input_bytes;
    for stage in stages {
        let mut next = [None; 2];
        let mut parents = [None; 2];
        for (at, cost) in Location::ALL.into_iter().zip([stage.host, stage.device]) {
            let Some(cost) = cost else { continue };
            let best = Location::ALL
                .into_iter()
                .filter_map(|from| {
                    let (time, moves) = costs[from.index()]?;
                    let time = time
                        .saturating_add(link.cost(from, at, bytes))
                        .saturating_add(cost);
                    Some(((time, moves + usize::from(from != at)), from))
                })
                .min_by_key(|(score, _)| *score);
            if let Some((score, from)) = best {
                next[at.index()] = Some(score);
                parents[at.index()] = Some(from);
            }
        }
        previous.push((parents, bytes));
        costs = next;
        bytes = stage.output_bytes;
    }
    let ((predicted, _), mut at) = Location::ALL
        .into_iter()
        .filter_map(|from| {
            let (time, moves) = costs[from.index()]?;
            Some((
                (
                    time.saturating_add(link.cost(from, output, bytes)),
                    moves + usize::from(from != output),
                ),
                from,
            ))
        })
        .min_by_key(|(score, _)| *score)?;

    let mut steps = Vec::with_capacity(stages.len().saturating_mul(2).saturating_add(1));
    if at != output {
        steps.push(Step::Transfer { to: output, bytes });
    }
    for (stage, (parents, bytes)) in previous.into_iter().enumerate().rev() {
        steps.push(Step::Run { stage, at });
        let from = parents[at.index()]?;
        if from != at {
            steps.push(Step::Transfer { to: at, bytes });
        }
        at = from;
    }
    steps.reverse();
    Some(Placement { predicted, steps })
}

#[cfg(test)]
mod tests {
    use super::*;
    use Location::{Device, Host};

    fn setup() -> Link {
        let transfer = Transfer {
            latency: Duration::ZERO,
            bytes_per_second: NonZeroU64::new(1_000_000).unwrap(),
        };
        Link {
            upload: transfer,
            download: transfer,
        }
    }

    #[test]
    fn keeps_a_large_intermediate_at_the_device_until_it_shrinks() {
        let stages = [
            Stage {
                output_bytes: 8_000,
                host: None,
                device: Some(Duration::from_micros(10)),
            },
            Stage {
                output_bytes: 4,
                host: Some(Duration::ZERO),
                device: Some(Duration::from_micros(500)),
            },
        ];
        let plan = place(&stages, &setup(), Host, 1_000, Host).unwrap();
        assert_eq!(plan.predicted, Duration::from_micros(1514));
        assert_eq!(
            plan.steps,
            [
                Step::Transfer {
                    to: Device,
                    bytes: 1_000
                },
                Step::Run {
                    stage: 0,
                    at: Device
                },
                Step::Run {
                    stage: 1,
                    at: Device
                },
                Step::Transfer { to: Host, bytes: 4 }
            ]
        );
    }

    #[test]
    fn accounts_for_residency_and_missing_backends() {
        let stage = Stage {
            output_bytes: 4,
            host: Some(Duration::from_micros(20)),
            device: Some(Duration::from_micros(10)),
        };
        assert_eq!(
            place(std::slice::from_ref(&stage), &setup(), Host, 256, Host)
                .unwrap()
                .steps,
            [Step::Run { stage: 0, at: Host }]
        );
        assert_eq!(
            place(&[stage], &setup(), Device, 256, Host).unwrap().steps,
            [
                Step::Run {
                    stage: 0,
                    at: Device
                },
                Step::Transfer { to: Host, bytes: 4 }
            ]
        );
        assert!(
            place(
                &[Stage {
                    output_bytes: 0,
                    host: None,
                    device: None
                }],
                &setup(),
                Host,
                0,
                Host
            )
            .is_none()
        );
    }
}