Skip to main content

alpha2_gpu/
rate.rs

1//! Device throughput in milliseconds per unit of effect cost per pixel, and per measured pass.
2
3use std::collections::HashMap;
4use std::sync::Mutex;
5
6/// The rate assumed before calibration, in milliseconds per unit pixel: twice the slowest
7/// measured rate (integrated GPUs), so early frames are split too finely rather than too
8/// coarsely.
9pub const UNCALIBRATED_MS_PER_UNIT_PIXEL: f64 = 2.0e-8;
10
11/// What a measurement is multiplied by to become a rate.
12pub const MARGIN: f64 = 2.0;
13
14const SLOWEST_FALL_PER_FRAME: f64 = 0.9;
15const DISAGREEING_FACTOR_UNDER_FLOOR: f64 = 4.0;
16const RAISING_SHARE_OF_BUDGET: f64 = 0.25;
17const DISAGREEING_SHARE_OF_BUDGET: f64 = 0.5;
18const CONFIRMING_FACTOR: f64 = 2.0;
19const PASS_RATES_KEPT: usize = 1024;
20
21/// How a frame's measured span relates to the GPU time it measures.
22#[derive(Copy, Clone, Debug, Eq, PartialEq)]
23pub enum SpanTrust {
24    /// The queue was idle at the first submit, but the completion may have been seen late.
25    UpperBound,
26    /// The queue was idle at the first submit and the completion was seen as it happened.
27    Exact,
28}
29
30/// One measured frame, as [`GpuRate::observe`] folds it in.
31#[derive(Copy, Clone, Debug, PartialEq)]
32pub struct FrameMeasurement {
33    /// Milliseconds from the first submit to the completion.
34    pub measured_ms: f64,
35    /// Milliseconds the plan predicted.
36    pub predicted_ms: f64,
37    /// The part of `predicted_ms` planned at the device rate; the rest was planned at passes'
38    /// own measured rates.
39    pub device_rated_ms: f64,
40    /// The device rate the frame was planned at.
41    pub planned_ms_per_unit_pixel: f64,
42    /// The submission budget the frame was planned under, in milliseconds.
43    pub budget_ms: f64,
44    /// How far `measured_ms` can be trusted.
45    pub trust: SpanTrust,
46}
47
48/// A kind of pass at a size class, whose own rate a device keeps.
49#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
50pub struct PassKey {
51    pass: u64,
52    size_class: u32,
53}
54
55impl PassKey {
56    /// The pass identified by `pass` over `pixels` pixels. Pixel counts fall in classes a factor
57    /// of the square root of two wide.
58    #[must_use]
59    pub fn new(pass: u64, pixels: u64) -> Self {
60        #[expect(
61            clippy::cast_precision_loss,
62            clippy::cast_possible_truncation,
63            clippy::cast_sign_loss,
64            reason = "a pixel count's doubled logarithm is far below 2^32"
65        )]
66        let size_class = (2.0 * (pixels.max(1) as f64).log2()).ceil() as u32;
67        Self { pass, size_class }
68    }
69}
70
71#[derive(Debug)]
72struct RateState {
73    ms_per_unit_pixel: Option<f64>,
74    calibrated: Option<f64>,
75    calibrating: bool,
76    recalibration_requested: bool,
77    disagreements: u32,
78    disagreements_before_calibration: u32,
79    passes: HashMap<PassKey, f64>,
80}
81
82impl Default for RateState {
83    fn default() -> Self {
84        Self {
85            ms_per_unit_pixel: None,
86            calibrated: None,
87            calibrating: false,
88            recalibration_requested: false,
89            disagreements: 0,
90            disagreements_before_calibration: 1,
91            passes: HashMap::new(),
92        }
93    }
94}
95
96/// One device's rate, shared by every context clone and renderer on it.
97#[derive(Debug, Default)]
98pub struct GpuRate {
99    state: Mutex<RateState>,
100}
101
102impl GpuRate {
103    fn state(&self) -> std::sync::MutexGuard<'_, RateState> {
104        self.state
105            .lock()
106            .unwrap_or_else(std::sync::PoisonError::into_inner)
107    }
108
109    /// The rate in milliseconds per unit pixel, once seeded.
110    #[must_use]
111    pub fn ms_per_unit_pixel(&self) -> Option<f64> {
112        self.state().ms_per_unit_pixel
113    }
114
115    /// The rate over the floor, or [`MARGIN`] before calibration.
116    #[must_use]
117    pub fn margin(&self) -> f64 {
118        let state = self.state();
119        match (state.ms_per_unit_pixel, state.calibrated) {
120            (Some(rate), Some(floor)) => (rate / floor).max(1.0),
121            _ => MARGIN,
122        }
123    }
124
125    /// Returns true once per calibration due, telling that caller to run the calibration draw:
126    /// before the first seed, and after frames disagreed with the floor.
127    pub fn begin_calibration(&self) -> bool {
128        let mut state = self.state();
129        let due = state.ms_per_unit_pixel.is_none() || state.recalibration_requested;
130        if !due || state.calibrating {
131            return false;
132        }
133        state.calibrating = true;
134        true
135    }
136
137    /// Seeds the rate at [`MARGIN`] times `measured_ms_per_unit_pixel`, which becomes the floor. A
138    /// calibration drawn again that confirms the previous one keeps the rate learned since, within
139    /// the new floor and seed; one that does not forgets every pass rate.
140    pub fn seed(&self, measured_ms_per_unit_pixel: f64) {
141        let mut state = self.state();
142        state.calibrating = false;
143        if !(measured_ms_per_unit_pixel.is_finite() && measured_ms_per_unit_pixel > 0.0) {
144            return;
145        }
146        let seeded = MARGIN * measured_ms_per_unit_pixel;
147        let mut rate = seeded;
148        if state.recalibration_requested {
149            state.recalibration_requested = false;
150            let confirmed = state.calibrated.is_some_and(|previous| {
151                let ratio = measured_ms_per_unit_pixel / previous;
152                (1.0 / CONFIRMING_FACTOR..=CONFIRMING_FACTOR).contains(&ratio)
153            });
154            state.disagreements_before_calibration = if confirmed {
155                state.disagreements_before_calibration.saturating_mul(2)
156            } else {
157                1
158            };
159            match (confirmed, state.ms_per_unit_pixel) {
160                (true, Some(learned)) => rate = learned.clamp(measured_ms_per_unit_pixel, seeded),
161                _ => state.passes.clear(),
162            }
163        }
164        state.disagreements = 0;
165        state.calibrated = Some(measured_ms_per_unit_pixel);
166        state.ms_per_unit_pixel = Some(rate);
167    }
168
169    /// Allows a later caller to calibrate again after a failed draw.
170    pub fn abandon_calibration(&self) {
171        self.state().calibrating = false;
172    }
173
174    /// Folds in a measured frame, its work planned at passes' own rates counted at their
175    /// prediction, so only the rest moves the device rate. Any trust lowers the rate by at most a
176    /// tenth per frame, never below the floor; an exact span over the prediction raises it to
177    /// [`MARGIN`] times the measurement.
178    pub fn observe(&self, frame: FrameMeasurement) {
179        let device_predicted_ms = frame.device_rated_ms.clamp(0.0, frame.predicted_ms);
180        let pass_rated_ms = frame.predicted_ms - device_predicted_ms;
181        let device_measured_ms = (frame.measured_ms - pass_rated_ms).max(0.0);
182        let measured = device_measured_ms / (device_predicted_ms / frame.planned_ms_per_unit_pixel);
183        if !(measured.is_finite() && measured >= 0.0 && device_predicted_ms > 0.0) {
184            return;
185        }
186        let mut state = self.state();
187        let (Some(rate), Some(floor)) = (state.ms_per_unit_pixel, state.calibrated) else {
188            return;
189        };
190        if measured < rate {
191            state.ms_per_unit_pixel =
192                Some((rate * SLOWEST_FALL_PER_FRAME).max(measured).max(floor));
193        } else if frame.trust == SpanTrust::Exact
194            && device_measured_ms > device_predicted_ms
195            && frame.measured_ms >= frame.budget_ms * RAISING_SHARE_OF_BUDGET
196        {
197            state.ms_per_unit_pixel = Some(MARGIN * measured);
198        }
199        if measured * DISAGREEING_FACTOR_UNDER_FLOOR < floor
200            && frame.predicted_ms >= frame.budget_ms * DISAGREEING_SHARE_OF_BUDGET
201        {
202            state.disagreements = state.disagreements.saturating_add(1);
203            if state.disagreements >= state.disagreements_before_calibration {
204                state.disagreements = 0;
205                state.recalibration_requested = true;
206            }
207        }
208    }
209
210    /// What draws of `pass` measured, in milliseconds per unit pixel.
211    #[must_use]
212    pub fn pass_rate(&self, pass: PassKey) -> Option<f64> {
213        self.state().passes.get(&pass).copied()
214    }
215
216    /// Keeps what a draw of `pass` measured, replacing an earlier measurement.
217    pub fn record_pass_rate(&self, pass: PassKey, measured_ms_per_unit_pixel: f64) {
218        if !(measured_ms_per_unit_pixel.is_finite() && measured_ms_per_unit_pixel >= 0.0) {
219            return;
220        }
221        let mut state = self.state();
222        if state.passes.len() >= PASS_RATES_KEPT && !state.passes.contains_key(&pass) {
223            state.passes.clear();
224        }
225        state.passes.insert(pass, measured_ms_per_unit_pixel);
226    }
227
228    /// The rate to predict `pass` at: the device rate, or the pass's own measurement scaled by
229    /// [`Self::margin`], and at least [`MARGIN`], when that is slower.
230    #[must_use]
231    pub fn planning_rate(&self, device_rate: f64, pass: Option<PassKey>) -> f64 {
232        let Some(measured) = pass.and_then(|pass| self.pass_rate(pass)) else {
233            return device_rate;
234        };
235        device_rate.max(measured * self.margin().max(MARGIN))
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use super::{FrameMeasurement, GpuRate, PassKey, SpanTrust};
242
243    fn frame(measured_ms: f64, predicted_ms: f64, trust: SpanTrust) -> FrameMeasurement {
244        FrameMeasurement {
245            measured_ms,
246            predicted_ms,
247            device_rated_ms: predicted_ms,
248            planned_ms_per_unit_pixel: predicted_ms,
249            budget_ms: 1_000.0,
250            trust,
251        }
252    }
253
254    #[test]
255    fn the_rate_falls_slowly_to_the_calibration_on_any_trusted_frame() {
256        let rate = GpuRate::default();
257        assert_eq!(rate.ms_per_unit_pixel(), None);
258        rate.observe(frame(10.0, 1.0, SpanTrust::Exact));
259        assert_eq!(
260            rate.ms_per_unit_pixel(),
261            None,
262            "nothing to fold before a seed"
263        );
264        assert!(rate.begin_calibration());
265        assert!(!rate.begin_calibration(), "one calibration at a time");
266        rate.seed(1.0);
267        assert_eq!(rate.ms_per_unit_pixel(), Some(2.0));
268        assert!((rate.margin() - 2.0).abs() < 1e-12);
269        rate.observe(frame(1.0, 2.0, SpanTrust::UpperBound));
270        assert_eq!(rate.ms_per_unit_pixel(), Some(1.8));
271        for _ in 0..100 {
272            rate.observe(frame(0.0, 2.0, SpanTrust::UpperBound));
273        }
274        assert_eq!(rate.ms_per_unit_pixel(), Some(1.0));
275        assert!(!rate.begin_calibration());
276    }
277
278    #[test]
279    fn only_an_exact_material_frame_over_its_prediction_raises_the_rate() {
280        let rate = GpuRate::default();
281        rate.seed(1.0);
282        rate.observe(frame(500.0, 2.0, SpanTrust::UpperBound));
283        assert_eq!(rate.ms_per_unit_pixel(), Some(2.0), "a late completion");
284        rate.observe(frame(100.0, 2.0, SpanTrust::Exact));
285        assert_eq!(
286            rate.ms_per_unit_pixel(),
287            Some(2.0),
288            "under a quarter of the budget"
289        );
290        rate.observe(frame(400.0, 2.0, SpanTrust::Exact));
291        assert_eq!(rate.ms_per_unit_pixel(), Some(800.0));
292    }
293
294    #[test]
295    fn only_the_work_planned_at_the_device_rate_moves_it() {
296        let rate = GpuRate::default();
297        rate.seed(1.0);
298        let piloted = |measured_ms| FrameMeasurement {
299            device_rated_ms: 100.0,
300            ..frame(measured_ms, 400.0, SpanTrust::Exact)
301        };
302        rate.observe(piloted(700.0));
303        assert_eq!(
304            rate.ms_per_unit_pixel(),
305            Some(3200.0),
306            "the device-rated 100 ms ran 400 ms"
307        );
308        let all_piloted = FrameMeasurement {
309            device_rated_ms: 0.0,
310            ..frame(4_000.0, 400.0, SpanTrust::Exact)
311        };
312        rate.observe(all_piloted);
313        assert_eq!(
314            rate.ms_per_unit_pixel(),
315            Some(3200.0),
316            "a frame of piloted work leaves the device rate"
317        );
318    }
319
320    #[test]
321    fn frames_far_under_a_splitting_floor_ask_for_calibration_less_often_each_confirmation() {
322        let rate = GpuRate::default();
323        rate.seed(1_000.0);
324        rate.observe(frame(1.0, 100.0, SpanTrust::UpperBound));
325        assert!(!rate.begin_calibration(), "predicted under half the budget");
326        rate.observe(frame(1.0, 2_000.0, SpanTrust::UpperBound));
327        assert!(rate.begin_calibration());
328        rate.seed(10.0);
329        assert_eq!(
330            rate.ms_per_unit_pixel(),
331            Some(20.0),
332            "a lower calibration replaces"
333        );
334        for needed in [1, 2, 4] {
335            for _ in 1..needed {
336                rate.observe(frame(0.1, 2_000.0, SpanTrust::UpperBound));
337                assert!(!rate.begin_calibration());
338            }
339            rate.observe(frame(0.1, 2_000.0, SpanTrust::UpperBound));
340            assert!(rate.begin_calibration());
341            rate.seed(12.0);
342            assert!(
343                rate.ms_per_unit_pixel() < Some(24.0),
344                "a confirming calibration keeps the rate learned: {:?}",
345                rate.ms_per_unit_pixel()
346            );
347        }
348    }
349
350    #[test]
351    fn a_pass_slower_than_the_device_is_planned_at_its_own_rate() {
352        let rate = GpuRate::default();
353        rate.seed(1.0);
354        let scattered = PassKey::new(7, 1920 * 1080);
355        let coherent = PassKey::new(8, 1920 * 1080);
356        assert_eq!(rate.planning_rate(2.0, Some(scattered)), 2.0);
357        rate.record_pass_rate(scattered, 10.0);
358        rate.record_pass_rate(coherent, 0.1);
359        assert_eq!(rate.planning_rate(2.0, Some(scattered)), 20.0);
360        assert_eq!(rate.planning_rate(2.0, Some(coherent)), 2.0);
361        assert_eq!(rate.pass_rate(PassKey::new(7, 3840 * 2160)), None);
362        assert_eq!(rate.pass_rate(PassKey::new(7, 1920 * 1088)), Some(10.0));
363    }
364
365    #[test]
366    fn a_calibration_that_moves_forgets_what_passes_measured() {
367        let rate = GpuRate::default();
368        rate.seed(1_000.0);
369        let pass = PassKey::new(1, 100);
370        rate.record_pass_rate(pass, 5_000.0);
371        rate.observe(frame(1.0, 2_000.0, SpanTrust::UpperBound));
372        assert!(rate.begin_calibration());
373        rate.seed(10.0);
374        assert_eq!(rate.pass_rate(pass), None);
375    }
376
377    #[test]
378    fn a_pass_keeps_the_margin_when_the_device_rate_reaches_its_floor() {
379        let rate = GpuRate::default();
380        rate.seed(1.0);
381        for _ in 0..100 {
382            rate.observe(frame(0.0, 2.0, SpanTrust::UpperBound));
383        }
384        assert_eq!(rate.ms_per_unit_pixel(), Some(1.0));
385        let pass = PassKey::new(1, 100);
386        rate.record_pass_rate(pass, 3.0);
387        assert_eq!(rate.planning_rate(1.0, Some(pass)), 6.0);
388    }
389}