Skip to main content

rustsy_engine/
residency.rs

1//! Cost-based placement for a linear chain with one live logical value.
2//! Operations supply their own timings and declare unsupported placements as `None`.
3use std::{num::NonZeroU64, time::Duration};
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub enum Location {
7    Host,
8    Device,
9}
10
11impl Location {
12    const ALL: [Self; 2] = [Self::Host, Self::Device];
13
14    fn index(self) -> usize {
15        match self {
16            Self::Host => 0,
17            Self::Device => 1,
18        }
19    }
20}
21
22#[derive(Clone, Copy)]
23pub struct Transfer {
24    pub latency: Duration,
25    pub bytes_per_second: NonZeroU64,
26}
27
28impl Transfer {
29    fn cost(self, bytes: usize) -> Duration {
30        if bytes == 0 {
31            return Duration::ZERO;
32        }
33        let nanos = (bytes as u128 * 1_000_000_000).div_ceil(self.bytes_per_second.get() as u128);
34        let seconds = nanos / 1_000_000_000;
35        let duration = Duration::new(seconds as u64, (nanos % 1_000_000_000) as u32);
36        self.latency.saturating_add(duration)
37    }
38}
39
40pub struct Link {
41    pub upload: Transfer,
42    pub download: Transfer,
43}
44
45impl Link {
46    fn cost(&self, from: Location, to: Location, bytes: usize) -> Duration {
47        match (from, to) {
48            (Location::Host, Location::Device) => self.upload.cost(bytes),
49            (Location::Device, Location::Host) => self.download.cost(bytes),
50            _ => Duration::ZERO,
51        }
52    }
53}
54
55pub struct Stage {
56    pub output_bytes: usize,
57    pub host: Option<Duration>,
58    pub device: Option<Duration>,
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub enum Step {
63    Transfer { to: Location, bytes: usize },
64    Run { stage: usize, at: Location },
65}
66
67#[derive(Debug)]
68pub struct Placement {
69    pub predicted: Duration,
70    pub steps: Vec<Step>,
71}
72
73/// Minimize estimated time of sequential execution, including the final landing
74/// location. A tie prefers fewer transfers and then host execution.
75pub fn place(
76    stages: &[Stage],
77    link: &Link,
78    input: Location,
79    input_bytes: usize,
80    output: Location,
81) -> Option<Placement> {
82    let mut costs = [None; 2];
83    costs[input.index()] = Some((Duration::ZERO, 0usize));
84    let mut previous = Vec::with_capacity(stages.len());
85    let mut bytes = input_bytes;
86    for stage in stages {
87        let mut next = [None; 2];
88        let mut parents = [None; 2];
89        for (at, cost) in Location::ALL.into_iter().zip([stage.host, stage.device]) {
90            let Some(cost) = cost else { continue };
91            let best = Location::ALL
92                .into_iter()
93                .filter_map(|from| {
94                    let (time, moves) = costs[from.index()]?;
95                    let time = time
96                        .saturating_add(link.cost(from, at, bytes))
97                        .saturating_add(cost);
98                    Some(((time, moves + usize::from(from != at)), from))
99                })
100                .min_by_key(|(score, _)| *score);
101            if let Some((score, from)) = best {
102                next[at.index()] = Some(score);
103                parents[at.index()] = Some(from);
104            }
105        }
106        previous.push((parents, bytes));
107        costs = next;
108        bytes = stage.output_bytes;
109    }
110    let ((predicted, _), mut at) = Location::ALL
111        .into_iter()
112        .filter_map(|from| {
113            let (time, moves) = costs[from.index()]?;
114            Some((
115                (
116                    time.saturating_add(link.cost(from, output, bytes)),
117                    moves + usize::from(from != output),
118                ),
119                from,
120            ))
121        })
122        .min_by_key(|(score, _)| *score)?;
123
124    let mut steps = Vec::with_capacity(stages.len().saturating_mul(2).saturating_add(1));
125    if at != output {
126        steps.push(Step::Transfer { to: output, bytes });
127    }
128    for (stage, (parents, bytes)) in previous.into_iter().enumerate().rev() {
129        steps.push(Step::Run { stage, at });
130        let from = parents[at.index()]?;
131        if from != at {
132            steps.push(Step::Transfer { to: at, bytes });
133        }
134        at = from;
135    }
136    steps.reverse();
137    Some(Placement { predicted, steps })
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    use Location::{Device, Host};
144
145    fn setup() -> Link {
146        let transfer = Transfer {
147            latency: Duration::ZERO,
148            bytes_per_second: NonZeroU64::new(1_000_000).unwrap(),
149        };
150        Link {
151            upload: transfer,
152            download: transfer,
153        }
154    }
155
156    #[test]
157    fn keeps_a_large_intermediate_at_the_device_until_it_shrinks() {
158        let stages = [
159            Stage {
160                output_bytes: 8_000,
161                host: None,
162                device: Some(Duration::from_micros(10)),
163            },
164            Stage {
165                output_bytes: 4,
166                host: Some(Duration::ZERO),
167                device: Some(Duration::from_micros(500)),
168            },
169        ];
170        let plan = place(&stages, &setup(), Host, 1_000, Host).unwrap();
171        assert_eq!(plan.predicted, Duration::from_micros(1514));
172        assert_eq!(
173            plan.steps,
174            [
175                Step::Transfer {
176                    to: Device,
177                    bytes: 1_000
178                },
179                Step::Run {
180                    stage: 0,
181                    at: Device
182                },
183                Step::Run {
184                    stage: 1,
185                    at: Device
186                },
187                Step::Transfer { to: Host, bytes: 4 }
188            ]
189        );
190    }
191
192    #[test]
193    fn accounts_for_residency_and_missing_backends() {
194        let stage = Stage {
195            output_bytes: 4,
196            host: Some(Duration::from_micros(20)),
197            device: Some(Duration::from_micros(10)),
198        };
199        assert_eq!(
200            place(std::slice::from_ref(&stage), &setup(), Host, 256, Host)
201                .unwrap()
202                .steps,
203            [Step::Run { stage: 0, at: Host }]
204        );
205        assert_eq!(
206            place(&[stage], &setup(), Device, 256, Host).unwrap().steps,
207            [
208                Step::Run {
209                    stage: 0,
210                    at: Device
211                },
212                Step::Transfer { to: Host, bytes: 4 }
213            ]
214        );
215        assert!(
216            place(
217                &[Stage {
218                    output_bytes: 0,
219                    host: None,
220                    device: None
221                }],
222                &setup(),
223                Host,
224                0,
225                Host
226            )
227            .is_none()
228        );
229    }
230}