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