Skip to main content

psync_graph/
predict.rs

1//! What psync's schedule would make of a measured run: a what-if prediction.
2//!
3//! The input is a [`Report`] and a trace of one sequential run: every measured call, with the
4//! source line it was made from and what it cost (in any unit: milliseconds, polls). The trace
5//! already says which path the run took, because a call on a branch that was not taken has no
6//! sample. The prediction replays psync's schedule for that path:
7//!
8//! - in a region, every level costs its slowest chain, and a chain costs the sum of its nodes;
9//! - in a prefetched loop, the prefixes of all items run first, at most `bound` at once, each
10//!   starting when a slot frees; the rest of each body then runs in order;
11//! - every other call costs what it cost.
12//!
13//! The levels' slowest chains are the critical path. The model is psync's own: a level waits for
14//! all of its chains (see [Levels](https://psync.used.rs/internals/schedule#levels)), so it
15//! predicts what psync does, not what a dataflow schedule could do.
16//!
17//! A sample belongs to the statement whose lines contain it. A loop's items are told apart by
18//! where its prefix starts again, and its runs (one per iteration of an enclosing loop) by the
19//! samples between them.
20
21use crate::{LoopReport, RegionReport, Report};
22use std::cmp::Reverse;
23use std::collections::BinaryHeap;
24
25/// One measured call: the line it was made from, and its cost.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct Sample {
28    pub line: usize,
29    pub cost: u64,
30}
31
32/// The prediction for one region.
33#[derive(Clone, Debug, Default, PartialEq, Eq)]
34pub struct RegionTiming {
35    pub sequential: u64,
36    pub predicted: u64,
37    /// For each level, its cost and the chain (an index into the region's `chains`) that sets it.
38    pub levels: Vec<(u64, usize)>,
39}
40
41/// The prediction for one prefetched loop.
42#[derive(Clone, Debug, Default, PartialEq, Eq)]
43pub struct LoopTiming {
44    pub label: String,
45    pub items: usize,
46    pub sequential: u64,
47    pub predicted: u64,
48}
49
50/// The prediction for one run of a function.
51#[derive(Clone, Debug, Default, PartialEq, Eq)]
52pub struct Prediction {
53    /// The run as measured: the sum of every sample.
54    pub sequential: u64,
55    /// The same path under psync's schedule.
56    pub predicted: u64,
57    pub regions: Vec<RegionTiming>,
58    pub loops: Vec<LoopTiming>,
59}
60
61/// Predict the time of the run that produced `trace`, under the schedule `report` describes.
62pub fn predict(report: &Report, trace: &[Sample]) -> Prediction {
63    let sequential: u64 = trace.iter().map(|s| s.cost).sum();
64    let mut used = vec![false; trace.len()];
65    let mut out = Prediction {
66        sequential,
67        ..Default::default()
68    };
69    let mut saved: u64 = 0;
70    for l in report.loops.iter().filter(|l| l.changed) {
71        let t = predict_loop(l, trace, &mut used);
72        saved += t.sequential - t.predicted;
73        out.loops.push(t);
74    }
75    for r in &report.regions {
76        let t = predict_region(r, trace, &mut used);
77        saved += t.sequential - t.predicted;
78        out.regions.push(t);
79    }
80    out.predicted = sequential - saved;
81    out
82}
83
84/// The runs that took one path through a function, and their predictions.
85#[derive(Clone, Debug, Default, PartialEq)]
86pub struct PathTiming {
87    /// The path: the distinct source lines of its samples, in order. A call on a branch the runs
88    /// did not take has no sample, so two paths differ in the lines they contain.
89    pub lines: Vec<usize>,
90    /// Indices of the runs (in the order given) that took it.
91    pub runs: Vec<usize>,
92    /// Mean measured and predicted time of those runs.
93    pub sequential: f64,
94    pub predicted: f64,
95    /// The prediction of its slowest measured run, whose levels name the critical path.
96    pub slowest: Prediction,
97}
98
99/// Predict many runs and group them by path, most frequent path first (ties: the order the paths
100/// first appear). Each path gets its own critical path; the runs' share of each path is the
101/// condition under which that critical path is the one that matters.
102pub fn predict_paths(report: &Report, runs: &[Vec<Sample>]) -> Vec<PathTiming> {
103    let mut paths: Vec<PathTiming> = Vec::new();
104    let mut slowest: Vec<u64> = Vec::new();
105    for (k, run) in runs.iter().enumerate() {
106        let mut lines: Vec<usize> = run.iter().map(|s| s.line).collect();
107        lines.sort_unstable();
108        lines.dedup();
109        let p = predict(report, run);
110        let i = match paths.iter().position(|q| q.lines == lines) {
111            Some(i) => i,
112            None => {
113                paths.push(PathTiming {
114                    lines,
115                    ..Default::default()
116                });
117                slowest.push(0);
118                paths.len() - 1
119            }
120        };
121        let path = &mut paths[i];
122        path.runs.push(k);
123        path.sequential += p.sequential as f64;
124        path.predicted += p.predicted as f64;
125        if path.runs.len() == 1 || p.sequential > slowest[i] {
126            slowest[i] = p.sequential;
127            path.slowest = p;
128        }
129    }
130    for p in &mut paths {
131        let n = p.runs.len() as f64;
132        p.sequential /= n;
133        p.predicted /= n;
134    }
135    // Stable: equal counts keep the order of first appearance.
136    paths.sort_by_key(|p| std::cmp::Reverse(p.runs.len()));
137    paths
138}
139
140/// Whether `line` falls in the lines `first..=last` of a statement (never for unknown lines).
141fn within(line: usize, (first, last): (usize, usize)) -> bool {
142    first != 0 && first <= line && line <= last.max(first)
143}
144
145fn predict_region(r: &RegionReport, trace: &[Sample], used: &mut [bool]) -> RegionTiming {
146    let mut cost = vec![0u64; r.nodes.len()];
147    for (i, s) in trace.iter().enumerate() {
148        if used[i] {
149            continue;
150        }
151        // A sample belongs to the node whose statement contains its line: a profiled statement may
152        // sit inside the node's `if` or block.
153        if let Some(n) = r
154            .nodes
155            .iter()
156            .position(|n| within(s.line, (n.line, n.end_line)))
157        {
158            cost[n] += s.cost;
159            used[i] = true;
160        }
161    }
162    let sequential = cost.iter().sum();
163    let chain_cost = |c: &[usize]| c.iter().map(|&n| cost[n]).sum::<u64>();
164    let levels: Vec<(u64, usize)> = r
165        .levels
166        .iter()
167        .map(|level| {
168            level
169                .iter()
170                .map(|&c| (chain_cost(&r.chains[c]), c))
171                // The slowest chain; among equals, the first.
172                .max_by_key(|&(t, c)| (t, Reverse(c)))
173                .unwrap_or((0, 0))
174        })
175        .collect();
176    RegionTiming {
177        sequential,
178        predicted: levels.iter().map(|l| l.0).sum(),
179        levels,
180    }
181}
182
183/// A loop's samples are split into runs of the loop (a sample outside it ends a run: an outer
184/// loop's next iteration), and each run into items: an item starts with a prefix sample that comes
185/// after the rest of the body, or after a sample of the same or a later prefix statement.
186fn predict_loop(l: &LoopReport, trace: &[Sample], used: &mut [bool]) -> LoopTiming {
187    let prefix_of = |line| {
188        l.prefetched_lines
189            .iter()
190            .position(|&range| within(line, range))
191    };
192    let mut runs: Vec<Vec<u64>> = Vec::new();
193    let mut rest: u64 = 0;
194    let mut in_run = false;
195    // The current item's last prefix statement, and whether its body has gone past the prefix.
196    let mut at: Option<usize> = None;
197    let mut past = false;
198    for (i, s) in trace.iter().enumerate() {
199        if !within(s.line, (l.line, l.end_line)) {
200            in_run = false;
201            continue;
202        }
203        if used[i] {
204            continue;
205        }
206        used[i] = true;
207        if !in_run {
208            runs.push(Vec::new());
209            (in_run, at, past) = (true, None, false);
210        }
211        let items = runs.last_mut().expect("in a run");
212        match prefix_of(s.line) {
213            Some(k) if !past && at.is_some_and(|a| k > a) => {
214                *items.last_mut().expect("an item") += s.cost;
215                at = Some(k);
216            }
217            Some(k) => {
218                items.push(s.cost);
219                (at, past) = (Some(k), false);
220            }
221            None => {
222                rest += s.cost;
223                past = true;
224            }
225        }
226    }
227    let prefixes: u64 = runs.iter().flatten().sum();
228    let slots = l.bound.max(1);
229    LoopTiming {
230        label: l.label.clone(),
231        items: runs.iter().map(Vec::len).sum(),
232        sequential: prefixes + rest,
233        predicted: runs.iter().map(|r| makespan(r, slots)).sum::<u64>() + rest,
234    }
235}
236
237/// When the last of `jobs` ends, if they start in order, each as soon as one of `slots` frees.
238pub fn makespan(jobs: &[u64], slots: usize) -> u64 {
239    let mut free: BinaryHeap<Reverse<u64>> = (0..slots.max(1)).map(|_| Reverse(0)).collect();
240    let mut end = 0;
241    for &j in jobs {
242        let Reverse(at) = free.pop().expect("at least one slot");
243        end = end.max(at + j);
244        free.push(Reverse(at + j));
245    }
246    end
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn makespan_fills_slots_in_order() {
255        assert_eq!(makespan(&[], 4), 0);
256        assert_eq!(makespan(&[10, 10, 10], 16), 10);
257        assert_eq!(makespan(&[10; 6], 4), 20);
258        // The long job starts first and holds its slot; the short ones share the other.
259        assert_eq!(makespan(&[30, 10, 10, 10], 2), 30);
260        // The long job starts last, when the first two end.
261        assert_eq!(makespan(&[10, 10, 10, 30], 2), 40);
262    }
263
264    #[test]
265    fn runs_group_by_path() {
266        // n0 (line 3) and n1 (line 4) run together; line 5 is a branch some runs take.
267        let node = |line| crate::NodeReport {
268            line,
269            awaits: true,
270            ..Default::default()
271        };
272        let report = Report {
273            regions: vec![RegionReport {
274                nodes: vec![node(3), node(4)],
275                chains: vec![vec![0], vec![1]],
276                levels: vec![vec![0, 1]],
277                ..Default::default()
278            }],
279            ..Default::default()
280        };
281        let run = |v: &[(usize, u64)]| {
282            v.iter()
283                .map(|&(line, cost)| Sample { line, cost })
284                .collect()
285        };
286        let runs: Vec<Vec<Sample>> = vec![
287            run(&[(3, 10), (4, 20)]),
288            run(&[(3, 10), (4, 20), (5, 50)]),
289            run(&[(3, 30), (4, 20)]),
290        ];
291        let paths = predict_paths(&report, &runs);
292        assert_eq!(paths.len(), 2);
293        // The common path: two runs, 30 and 50 measured, 20 and 30 predicted.
294        assert_eq!(
295            (paths[0].lines.clone(), paths[0].runs.clone()),
296            (vec![3, 4], vec![0, 2])
297        );
298        assert_eq!((paths[0].sequential, paths[0].predicted), (40.0, 25.0));
299        // Its slowest run is the third, whose level is set by n0 (line 3, 30).
300        assert_eq!(paths[0].slowest.regions[0].levels, vec![(30, 0)]);
301        // The branch costs what it costs: 80 measured, 70 predicted.
302        assert_eq!((paths[1].sequential, paths[1].predicted), (80.0, 70.0));
303    }
304
305    #[test]
306    fn a_level_costs_its_slowest_chain() {
307        let node = |line| crate::NodeReport {
308            line,
309            awaits: true,
310            ..Default::default()
311        };
312        let r = RegionReport {
313            nodes: vec![node(3), node(4), node(5), node(6)],
314            chains: vec![vec![0, 2], vec![1], vec![3]],
315            levels: vec![vec![0, 1, 2]],
316            ..Default::default()
317        };
318        let report = Report {
319            regions: vec![r],
320            ..Default::default()
321        };
322        let trace =
323            [(3, 10), (4, 10), (5, 10), (6, 10), (9, 5)].map(|(line, cost)| Sample { line, cost });
324        let p = predict(&report, &trace);
325        // 45 sequentially; the region (40) becomes its slowest chain, 3 then 5 (20); line 9 is
326        // outside every region and costs what it cost.
327        assert_eq!((p.sequential, p.predicted), (45, 25));
328        assert_eq!(p.regions[0].levels, vec![(20, 0)]);
329    }
330}