Skip to main content

cubek_test_utils/
registry.rs

1//! Benchmark / correctness registry traits shared across kernel crates.
2//!
3//! Each kernel crate exposes a `pub mod benchmarks` (gated behind its
4//! `benchmarks` cargo feature) that defines a [`Category`] over the kernel's
5//! own problem and strategy types. The top-level `benchmarks` crate then
6//! collects those into a single `all()` slice for harnesses (Cargo benches)
7//! and for the tuner-runner.
8
9use std::collections::{HashMap, HashSet};
10use std::sync::{LazyLock, Mutex};
11use std::time::Duration;
12
13use cubecl::benchmark::{ProfileDuration, TimingMethod};
14use cubecl::client::Client;
15use cubecl::features::TypeUsage;
16use cubecl::prelude::*;
17use cubecl::std::throughput::{measure_memory_curve, measure_peak_throughput};
18use cubecl::throughput::{
19    self, MemoryAccess, MemoryCurve, ResourceBound, ThroughputKey, ThroughputMode, score_resources,
20};
21
22use crate::{HostData, Progress};
23
24/// `CUBEK_BENCH_TIMING`'s override, read once: it can't change over a
25/// process's life, and every category consults it once per row.
26static TIMING_OVERRIDE: LazyLock<Option<TimingMethod>> =
27    LazyLock::new(|| match std::env::var("CUBEK_BENCH_TIMING").as_deref() {
28        Ok("device") => Some(TimingMethod::Device),
29        Ok("system") => Some(TimingMethod::System),
30        Ok(other) => panic!("CUBEK_BENCH_TIMING takes 'device' or 'system', not {other:?}"),
31        Err(_) => None,
32    });
33
34/// The timing method a category measures with, overridden for a whole run by
35/// `CUBEK_BENCH_TIMING`. Device timestamps leave the launch out, so a row that
36/// beats its ceiling is checked by measuring it again on the wall clock.
37pub fn timing_method(default: TimingMethod) -> TimingMethod {
38    TIMING_OVERRIDE.unwrap_or(default)
39}
40
41/// Whether `client`'s device does real f16 arithmetic, not just storage, so a
42/// category can skip f16 rows the device would only fail on.
43pub fn supports_f16_arithmetic(client: &Client) -> bool {
44    half::f16::supported_uses(client).contains(TypeUsage::Arithmetic)
45}
46
47/// Times one launch on the device, failing the row when the launch itself failed.
48///
49/// Categories override [`Benchmark::profile`](cubecl::benchmark::Benchmark::profile) only to
50/// name their profiling scope. Writing that override by hand invites keeping the duration and
51/// dropping the launch result, which reports the time a failure took as a measurement.
52pub fn profile_launch<O: Send + 'static>(
53    client: &Client,
54    scope: &str,
55    launch: impl FnOnce() -> Result<O, String> + Send,
56) -> Result<ProfileDuration, String> {
57    let (launched, duration) = client
58        .profile(launch, scope)
59        .map_err(|err| format!("{err:?}"))?;
60
61    launched.map(|_| duration)
62}
63
64/// The client every category scores against: `measure_peak_throughput` is
65/// always run on `cubecl::test_device()`, so the
66/// process-wide peak memo below can key on [`ThroughputKey`] alone.
67pub fn client() -> Client {
68    let device = cubecl::test_device();
69    device.client()
70}
71
72/// Process-wide memo of measured peaks.
73///
74/// `measure_peak_throughput` primes a probe buffer before consulting its own
75/// cache, so calling it between two timed rows moves real memory regardless.
76static PEAKS: LazyLock<Mutex<HashMap<ThroughputKey, f64>>> =
77    LazyLock::new(|| Mutex::new(HashMap::new()));
78
79/// Process-wide memo of measured memory curves, one per access.
80///
81/// A curve answers every working set from one sweep, so a run asks the device
82/// once per access rather than once per distinct size a problem declares.
83static CURVES: LazyLock<Mutex<HashMap<MemoryAccess, MemoryCurve>>> =
84    LazyLock::new(|| Mutex::new(HashMap::new()));
85
86/// The rate a kernel moving `bytes` in the direction `access` names can reach,
87/// read off [`CURVES`] and measuring the curve on a miss.
88///
89/// Zero when the sweep measured nothing, which leaves the resource unscored
90/// rather than dividing by a ceiling that does not exist.
91fn curve_ceiling(access: MemoryAccess, bytes: usize) -> f64 {
92    let mut curves = CURVES.lock().expect("curves mutex is not poisoned");
93    let curve = curves
94        .entry(access)
95        .or_insert_with(|| measure_memory_curve(&client(), access));
96
97    curve.ceiling_at(bytes as u64).unwrap_or(0.0)
98}
99
100/// Looks up `key`'s peak rate in [`PEAKS`], measuring and caching it on a
101/// miss. Never re-enters itself, so holding the lock across the measurement
102/// cannot deadlock.
103///
104/// The unit comes from the key's own mode rather than from the caller, so a
105/// memo keyed on the key alone cannot serve one resource's rate to another.
106///
107/// NaN when the device has no peak for the key, which leaves the resource
108/// unscored rather than dividing by a ceiling that does not exist.
109fn peak_per_s(key: ThroughputKey) -> f64 {
110    let mut peaks = PEAKS.lock().expect("peaks mutex is not poisoned");
111    *peaks.entry(key).or_insert_with(|| {
112        let Ok(value) = measure_peak_throughput(&client(), key) else {
113            return f64::NAN;
114        };
115
116        match key.mode {
117            ThroughputMode::ComputeDirect { .. } | ThroughputMode::ComputeCmma { .. } => {
118                value.ops_per_s()
119            }
120            ThroughputMode::Memory(_) => value.bytes_per_s(&key),
121            ThroughputMode::Launch => 1.0 / value.duration_per_op().as_secs_f64(),
122        }
123    })
124}
125
126#[derive(Debug, Clone)]
127pub struct ItemDescriptor {
128    pub id: String,
129    pub label: String,
130}
131
132impl ItemDescriptor {
133    pub fn new(id: impl Into<String>, label: impl Into<String>) -> Self {
134        Self {
135            id: id.into(),
136            label: label.into(),
137        }
138    }
139}
140
141/// A catalogued problem or strategy: stable id, human label, and the typed
142/// payload the category needs to actually run with. Categories build vectors
143/// of these and the registry erases them to [`ItemDescriptor`] for callers
144/// that only care about the id/label pair.
145pub struct CatalogEntry<T> {
146    pub id: String,
147    pub label: String,
148    pub value: T,
149}
150
151impl<T> CatalogEntry<T> {
152    pub fn new(id: impl Into<String>, label: impl Into<String>, value: T) -> Self {
153        Self {
154            id: id.into(),
155            label: label.into(),
156            value,
157        }
158    }
159
160    pub fn descriptor(&self) -> ItemDescriptor {
161        ItemDescriptor {
162            id: self.id.clone(),
163            label: self.label.clone(),
164        }
165    }
166}
167
168/// Where a declared resource's ceiling comes from.
169///
170/// Memory names only its direction: the working set is applied when the curve
171/// is read, so two rows of different sizes share one sweep instead of each
172/// asking the device for a probe of its own.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
174enum Ceiling {
175    Probe(ThroughputKey),
176    Curve(MemoryAccess),
177}
178
179/// Which resource a bench row's binding measurement is judged against.
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub enum ResourceKind {
182    Compute,
183    Read,
184    Write,
185    /// Getting the kernel onto the device at all, whatever it then does.
186    Launch,
187}
188
189/// The resource that bound a run's duration, the slowest of the declared
190/// resources even running flat out at its own peak, alongside how fast the
191/// run actually achieved it. Mirrors the selection rule in
192/// [`throughput::binding_achieved`].
193#[derive(Debug, Clone, Copy)]
194pub struct Binding {
195    pub resource: ResourceKind,
196    pub achieved_per_s: f64,
197    pub peak_per_s: f64,
198    pub fraction_of_peak: f64,
199}
200
201#[derive(Debug, Clone)]
202pub struct RunSamples {
203    pub durations: Vec<Duration>,
204    /// TFLOPS achieved against the measured compute peak. `None` when the
205    /// category's [`CategoryWork`] declares no compute (memcpy, contiguous,
206    /// random, ...).
207    pub tflops: Option<f64>,
208    /// The resource that bound this run's duration. `None` when the category
209    /// declares no [`CategoryWork`] for this problem, or none of the declared
210    /// resources had a usable peak measurement.
211    pub binding: Option<Binding>,
212}
213
214impl RunSamples {
215    pub fn new(durations: Vec<Duration>) -> Self {
216        Self {
217            durations,
218            tflops: None,
219            binding: None,
220        }
221    }
222
223    /// Score the run as a single compute resource, from a raw operation count
224    /// and the measured compute peak.
225    ///
226    /// For callers that know their own FLOP count and have no full
227    /// [`CategoryWork`] to declare. `peak_ops_per_s` is `None` when the probe
228    /// found no usable ceiling, in which case the run still reports the TFLOPS
229    /// it achieved but nothing binds it.
230    pub fn with_flops(mut self, flops: f64, peak_ops_per_s: Option<f64>) -> Self {
231        let Some(median_secs) = self.median_secs() else {
232            return self;
233        };
234
235        let bound = ResourceBound {
236            amount: flops as usize,
237            // A non-finite fraction of peak is what drops the resource out of
238            // the binding selection, which is the wanted behaviour with no peak.
239            peak_per_s: peak_ops_per_s.unwrap_or(f64::NAN),
240        };
241        let (tflops, binding) = score_bounds(median_secs, &[(ResourceKind::Compute, bound)]);
242        self.tflops = tflops;
243        self.binding = binding;
244
245        self
246    }
247
248    /// Median sample duration in seconds, or `None` when there are no samples
249    /// or the median is zero (which would divide a throughput into NaN/inf).
250    fn median_secs(&self) -> Option<f64> {
251        if self.durations.is_empty() {
252            return None;
253        }
254        let mut ns: Vec<u128> = self.durations.iter().map(|d| d.as_nanos()).collect();
255        ns.sort_unstable();
256        let median_secs = ns[ns.len() / 2] as f64 / 1e9;
257        (median_secs > 0.0).then_some(median_secs)
258    }
259}
260
261/// What a `(strategy, problem)` run honestly moves and computes, built from
262/// `problem` alone and never from a measurement of its own run.
263#[derive(Debug, Clone, Copy)]
264pub struct CategoryWork {
265    /// The compute the run performs, with the probe its ceiling comes from.
266    /// `None` when the category has no honest count (an elementwise
267    /// transcendental, an FFT); the adapter then declares no compute bound.
268    pub compute: Option<ComputeWork>,
269    /// Bytes read from global memory.
270    pub bytes_read: usize,
271    /// Bytes written to global memory.
272    pub bytes_written: usize,
273}
274
275/// Operations a run performs, and the probe whose peak they are judged against.
276///
277/// The probe is declared because the two compute ceilings are different
278/// hardware: an MMA kernel does not run where the scalar peak is measured.
279#[derive(Debug, Clone, Copy)]
280pub struct ComputeWork {
281    /// Counted the way `key`'s probe counts them, so a multiply-add is 2 for
282    /// [`ThroughputMode::ComputeDirect`].
283    pub ops: usize,
284    /// [`ThroughputMode::ComputeDirect`] for scalar arithmetic,
285    /// [`ThroughputMode::ComputeCmma`] for a kernel on the tensor cores.
286    pub key: ThroughputKey,
287}
288
289impl ComputeWork {
290    /// Scalar arithmetic, the ceiling for a kernel that issues no MMA.
291    pub fn direct(ops: usize, dtype: ElemType) -> Self {
292        Self {
293            ops,
294            key: ThroughputKey {
295                mode: ThroughputMode::ComputeDirect { dtype },
296            },
297        }
298    }
299}
300
301impl CategoryWork {
302    /// Launch joins the declared resources only under [`TimingMethod::System`];
303    /// a device-timed row's timestamps begin once the dispatch is already paid
304    /// for. It counts one, so a strategy launching several leaves it a floor.
305    ///
306    /// A memory probe is asked for the octave at or below the traffic, not the
307    /// traffic itself: that is the grid [`MemoryCurve`] is measured on, so rows
308    /// of neighbouring sizes share one probe instead of each paying for their
309    /// own. The amount stays exact, since that is what the kernel moves.
310    fn declared_resources(&self, timing: TimingMethod) -> Vec<(ResourceKind, usize, Ceiling)> {
311        let mut out = Vec::with_capacity(4);
312
313        if let Some(compute) = self.compute.filter(|c| c.ops > 0) {
314            out.push((
315                ResourceKind::Compute,
316                compute.ops,
317                Ceiling::Probe(compute.key),
318            ));
319        }
320        if self.bytes_read > 0 {
321            let read = Ceiling::Curve(MemoryAccess::Read);
322            out.push((ResourceKind::Read, self.bytes_read, read));
323        }
324        if self.bytes_written > 0 {
325            let write = Ceiling::Curve(MemoryAccess::Write);
326            out.push((ResourceKind::Write, self.bytes_written, write));
327        }
328        if !out.is_empty() && timing == TimingMethod::System {
329            let launch = Ceiling::Probe(ThroughputKey {
330                mode: ThroughputMode::Launch,
331            });
332            out.push((ResourceKind::Launch, 1, launch));
333        }
334
335        out
336    }
337
338    /// The declared resources as `(kind, bound)` pairs, peaks pulled from the
339    /// process-wide memo (see [`peak_per_s`]).
340    fn resources(&self, timing: TimingMethod) -> Vec<(ResourceKind, ResourceBound)> {
341        self.declared_resources(timing)
342            .into_iter()
343            .map(|(kind, amount, ceiling)| {
344                let peak_per_s = match ceiling {
345                    Ceiling::Probe(key) => peak_per_s(key),
346                    Ceiling::Curve(access) => curve_ceiling(access, amount),
347                };
348
349                (kind, ResourceBound { amount, peak_per_s })
350            })
351            .collect()
352    }
353}
354
355/// Scores `work` against measured device peaks, from the median sample
356/// duration. Left unfilled when there are no samples or the median is zero.
357fn score(mut samples: RunSamples, work: &CategoryWork, timing: TimingMethod) -> RunSamples {
358    let Some(median_secs) = samples.median_secs() else {
359        return samples;
360    };
361
362    let resources = work.resources(timing);
363    let (tflops, binding) = score_bounds(median_secs, &resources);
364    samples.tflops = tflops;
365    samples.binding = binding;
366
367    samples
368}
369
370/// The pure half of [`score`], so the selection is testable against fabricated
371/// bounds rather than a device's measured peaks.
372fn score_bounds(
373    median_secs: f64,
374    resources: &[(ResourceKind, ResourceBound)],
375) -> (Option<f64>, Option<Binding>) {
376    let bounds: Vec<ResourceBound> = resources.iter().map(|(_, bound)| *bound).collect();
377    let scores = score_resources(Duration::from_secs_f64(median_secs), &bounds);
378
379    let tflops = resources
380        .iter()
381        .position(|(kind, _)| *kind == ResourceKind::Compute)
382        .map(|idx| scores[idx].achieved_per_s / 1e12);
383
384    let binding = throughput::binding_achieved(&scores).map(|best| {
385        let idx = scores
386            .iter()
387            .position(|candidate| candidate == best)
388            .expect("binding_achieved returns an element of scores");
389        let (resource, bound) = resources[idx];
390        Binding {
391            resource,
392            achieved_per_s: best.achieved_per_s,
393            peak_per_s: bound.peak_per_s,
394            fraction_of_peak: best.fraction_of_peak,
395        }
396    });
397
398    (tflops, binding)
399}
400
401/// Typed per-category definition. Implementors expose their problem and
402/// strategy catalogues with the actual payloads attached, plus a typed
403/// `bench` closure. The blanket impl below adapts to the string-keyed
404/// [`BenchmarkCategory`] consumed by the public registry, so categories no
405/// longer have to write the lookup boilerplate.
406pub trait Category: Sync {
407    type Problem;
408    type Strategy;
409
410    /// Stable identifier — persisted in tuner-results history. Don't rename.
411    fn id(&self) -> &'static str;
412    fn label(&self) -> &'static str;
413    fn problems(&self) -> Vec<CatalogEntry<Self::Problem>>;
414    fn strategies(&self) -> Vec<CatalogEntry<Self::Strategy>>;
415    fn bench(
416        &self,
417        strategy: &Self::Strategy,
418        problem: &Self::Problem,
419        num_samples: usize,
420    ) -> Result<RunSamples, String>;
421
422    /// The work `problem` represents, the same for every strategy that runs it.
423    /// `None` leaves the run unscored, reporting plain durations.
424    fn work(&self, _problem: &Self::Problem) -> Option<CategoryWork> {
425        None
426    }
427
428    /// Which timing method [`Self::bench`] uses internally — used by the bench
429    /// runner to label its printed stats. Defaults to `System`; categories
430    /// running on the device timing method (unary/contiguous/memcpy_async)
431    /// override this.
432    fn timing_method(&self) -> TimingMethod {
433        crate::timing_method(TimingMethod::System)
434    }
435
436    /// Override to expose seeded `kernel_result` / `reference_result`. Decoupled
437    /// from `Category` itself so unary/contiguous/memcpy_async don't need
438    /// `cfg`-gated stub methods.
439    fn correctness(
440        &self,
441    ) -> Option<&dyn Correctness<Problem = Self::Problem, Strategy = Self::Strategy>> {
442        None
443    }
444}
445
446/// Optional correctness surface for a category. Both methods take a `seeds`
447/// slice instead of fixed `seed_lhs`/`seed_rhs` so unary ops use just
448/// `seeds[0]` and future ops with more inputs can take more seeds without
449/// churning the trait.
450///
451/// Convention: `seeds[0]` is the lhs seed, `seeds[1]` (when present) the rhs
452/// seed. The registry's `BenchmarkCategory` adapter always passes a 2-element
453/// slice today.
454pub trait Correctness: Sync {
455    type Problem;
456    type Strategy;
457
458    /// Run `strategy` on `problem` with the given seeded inputs and return its
459    /// output as [`HostData`]. Output must be deterministic under
460    /// `(strategy, problem, seeds)` so the same call on two commits produces
461    /// directly-comparable bits.
462    fn kernel_result(
463        &self,
464        strategy: &Self::Strategy,
465        problem: &Self::Problem,
466        seeds: &[u64],
467    ) -> Result<HostData, String>;
468
469    /// CPU-side ground-truth counterpart of [`Self::kernel_result`] for the
470    /// same `(problem, seeds)`. `progress`, when provided, is `set_total`'d
471    /// to the output-write count and bumped once per write so callers can
472    /// stream a progression bar.
473    fn reference_result(
474        &self,
475        problem: &Self::Problem,
476        seeds: &[u64],
477        progress: Option<&Progress>,
478    ) -> Result<HostData, String>;
479}
480
481/// Public, string-keyed registry surface. Implemented automatically for any
482/// type that implements [`Category`]; categories should implement `Category`
483/// rather than this trait directly.
484pub trait BenchmarkCategory: Sync {
485    /// Stable identifier — persisted in tuner-results history. Don't rename.
486    fn id(&self) -> &'static str;
487    fn label(&self) -> &'static str;
488    fn strategies(&self) -> Vec<ItemDescriptor>;
489    fn problems(&self) -> Vec<ItemDescriptor>;
490    fn timing_method(&self) -> TimingMethod {
491        TimingMethod::System
492    }
493
494    /// Measures and memoizes every distinct peak the named problems declare, so
495    /// the first timed row never pays for a probe. Returns how many distinct
496    /// keys it warmed.
497    fn warm_peaks(&self, problem_ids: &[String]) -> usize;
498
499    fn run(
500        &self,
501        strategy_id: &str,
502        problem_id: &str,
503        num_samples: usize,
504    ) -> Result<RunSamples, String>;
505
506    /// `None` means the category doesn't expose a kernel result (e.g.
507    /// memcpy_async: no semantic-level output).
508    fn kernel_result(
509        &self,
510        _strategy_id: &str,
511        _problem_id: &str,
512        _seed_lhs: u64,
513        _seed_rhs: u64,
514    ) -> Option<Result<HostData, String>> {
515        None
516    }
517
518    /// `None` when the category has no CPU-equivalent reference (e.g. unary,
519    /// contiguous).
520    fn reference_result(
521        &self,
522        _problem_id: &str,
523        _seed_lhs: u64,
524        _seed_rhs: u64,
525        _progress: Option<&Progress>,
526    ) -> Option<Result<HostData, String>> {
527        None
528    }
529}
530
531impl<C: Category> BenchmarkCategory for C {
532    fn id(&self) -> &'static str {
533        Category::id(self)
534    }
535
536    fn label(&self) -> &'static str {
537        Category::label(self)
538    }
539
540    fn strategies(&self) -> Vec<ItemDescriptor> {
541        Category::strategies(self)
542            .iter()
543            .map(CatalogEntry::descriptor)
544            .collect()
545    }
546
547    fn problems(&self) -> Vec<ItemDescriptor> {
548        Category::problems(self)
549            .iter()
550            .map(CatalogEntry::descriptor)
551            .collect()
552    }
553
554    fn timing_method(&self) -> TimingMethod {
555        Category::timing_method(self)
556    }
557
558    fn warm_peaks(&self, problem_ids: &[String]) -> usize {
559        let mut seen = HashSet::new();
560        for problem in Category::problems(self) {
561            if !problem_ids.contains(&problem.id) {
562                continue;
563            }
564            let Some(work) = Category::work(self, &problem.value) else {
565                continue;
566            };
567            for (_, amount, ceiling) in work.declared_resources(Category::timing_method(self)) {
568                if seen.insert(ceiling) {
569                    match ceiling {
570                        Ceiling::Probe(key) => peak_per_s(key),
571                        Ceiling::Curve(access) => curve_ceiling(access, amount),
572                    };
573                }
574            }
575        }
576        seen.len()
577    }
578
579    fn run(
580        &self,
581        strategy_id: &str,
582        problem_id: &str,
583        num_samples: usize,
584    ) -> Result<RunSamples, String> {
585        let problems = Category::problems(self);
586        let problem = problems
587            .iter()
588            .find(|e| e.id == problem_id)
589            .ok_or_else(|| format!("unknown problem: {problem_id}"))?;
590        let strategies = Category::strategies(self);
591        let strategy = strategies
592            .iter()
593            .find(|e| e.id == strategy_id)
594            .ok_or_else(|| format!("unknown strategy: {strategy_id}"))?;
595        let samples = Category::bench(self, &strategy.value, &problem.value, num_samples)?;
596        Ok(match Category::work(self, &problem.value) {
597            Some(work) => score(samples, &work, Category::timing_method(self)),
598            None => samples,
599        })
600    }
601
602    fn kernel_result(
603        &self,
604        strategy_id: &str,
605        problem_id: &str,
606        seed_lhs: u64,
607        seed_rhs: u64,
608    ) -> Option<Result<HostData, String>> {
609        let correctness = Category::correctness(self)?;
610        let problems = Category::problems(self);
611        let problem = match problems.iter().find(|e| e.id == problem_id) {
612            Some(p) => p,
613            None => return Some(Err(format!("unknown problem: {problem_id}"))),
614        };
615        let strategies = Category::strategies(self);
616        let strategy = match strategies.iter().find(|e| e.id == strategy_id) {
617            Some(s) => s,
618            None => return Some(Err(format!("unknown strategy: {strategy_id}"))),
619        };
620        Some(correctness.kernel_result(&strategy.value, &problem.value, &[seed_lhs, seed_rhs]))
621    }
622
623    fn reference_result(
624        &self,
625        problem_id: &str,
626        seed_lhs: u64,
627        seed_rhs: u64,
628        progress: Option<&Progress>,
629    ) -> Option<Result<HostData, String>> {
630        let correctness = Category::correctness(self)?;
631        let problems = Category::problems(self);
632        let problem = match problems.iter().find(|e| e.id == problem_id) {
633            Some(p) => p,
634            None => return Some(Err(format!("unknown problem: {problem_id}"))),
635        };
636        Some(correctness.reference_result(&problem.value, &[seed_lhs, seed_rhs], progress))
637    }
638}
639
640#[cfg(test)]
641mod tests {
642    use super::*;
643
644    fn work(compute_ops: usize, bytes_read: usize, bytes_written: usize) -> CategoryWork {
645        CategoryWork {
646            compute: (compute_ops > 0)
647                .then(|| ComputeWork::direct(compute_ops, f32::elem_type_native())),
648            bytes_read,
649            bytes_written,
650        }
651    }
652
653    /// The timing method that charges nothing for the dispatch.
654    const NO_LAUNCH: TimingMethod = TimingMethod::Device;
655
656    /// Zero-ops, zero-bytes work declares no resource, the launch it would
657    /// still pay for included: the dispatch bound rides along with declared
658    /// work rather than standing in for it.
659    #[test]
660    fn zero_work_declares_no_resources() {
661        // Declares nothing, so this measures nothing.
662        let resources = work(0, 0, 0).resources(TimingMethod::System);
663        assert!(resources.is_empty());
664
665        let (tflops, binding) = score_bounds(1.0, &resources);
666        assert_eq!(tflops, None);
667        assert!(binding.is_none());
668    }
669
670    /// A read-only declaration produces exactly one `Read` bound, carrying the
671    /// declared byte count as its `amount`; no `Write` or `Compute` entry.
672    #[test]
673    fn read_only_work_declares_a_single_read_resource() {
674        let resources = work(0, 4096, 0).declared_resources(NO_LAUNCH);
675        assert_eq!(resources.len(), 1);
676        assert_eq!(resources[0].0, ResourceKind::Read);
677        assert_eq!(resources[0].1, 4096);
678    }
679
680    /// A write-only declaration produces exactly one `Write` bound, mirroring
681    /// the read-only case.
682    #[test]
683    fn write_only_work_declares_a_single_write_resource() {
684        let resources = work(0, 0, 2048).declared_resources(NO_LAUNCH);
685        assert_eq!(resources.len(), 1);
686        assert_eq!(resources[0].0, ResourceKind::Write);
687        assert_eq!(resources[0].1, 2048);
688    }
689
690    /// A mixed declaration produces all three bounds, each carrying its own
691    /// field's amount, compute first.
692    #[test]
693    fn mixed_work_declares_compute_read_and_write_resources() {
694        let resources = work(1_000_000, 4096, 1024).declared_resources(NO_LAUNCH);
695        assert_eq!(resources.len(), 3);
696        assert_eq!(
697            resources.iter().map(|(kind, ..)| *kind).collect::<Vec<_>>(),
698            vec![
699                ResourceKind::Compute,
700                ResourceKind::Read,
701                ResourceKind::Write
702            ]
703        );
704        assert_eq!(resources[0].1, 1_000_000);
705        assert_eq!(resources[1].1, 4096);
706        assert_eq!(resources[2].1, 1024);
707    }
708
709    /// Every working set of one direction reads the same curve, so a sweep of
710    /// problem shapes asks the device once per access rather than once per
711    /// distinct size. The size is carried as the amount and applied when the
712    /// curve is read.
713    #[test]
714    fn memory_resources_share_one_curve_per_access() {
715        let small = work(0, 16384, 4096).declared_resources(NO_LAUNCH);
716        let large = work(0, 1 << 30, 1 << 30).declared_resources(NO_LAUNCH);
717
718        assert_eq!(small[0].2, Ceiling::Curve(MemoryAccess::Read));
719        assert_eq!(small[1].2, Ceiling::Curve(MemoryAccess::Write));
720        assert_eq!(small[0].2, large[0].2);
721        assert_eq!(small[1].2, large[1].2);
722
723        // Read and write are still distinct ceilings.
724        assert_ne!(small[0].2, small[1].2);
725
726        // The amount is exactly what the kernel moves.
727        assert_eq!(small[0].1, 16384);
728        assert_eq!(large[0].1, 1 << 30);
729    }
730
731    /// No resources to score: `score_bounds` leaves both `tflops` and `binding`
732    /// unset rather than dividing by an empty bound set.
733    #[test]
734    fn score_bounds_with_no_resources_is_unscored() {
735        let (tflops, binding) = score_bounds(1.0, &[]);
736        assert_eq!(tflops, None);
737        assert!(binding.is_none());
738    }
739
740    /// A single `Read` resource at a known peak scores its own achieved rate
741    /// and becomes the binding one, with no `tflops` (no `Compute` entry).
742    #[test]
743    fn score_bounds_read_only_binds_on_read() {
744        let bound = ResourceBound {
745            amount: 1000,
746            peak_per_s: 500.0,
747        };
748        let (tflops, binding) = score_bounds(2.0, &[(ResourceKind::Read, bound)]);
749
750        assert_eq!(tflops, None);
751        let binding = binding.expect("a usable peak binds");
752        assert_eq!(binding.resource, ResourceKind::Read);
753        assert_eq!(binding.achieved_per_s, 500.0);
754        assert_eq!(binding.peak_per_s, 500.0);
755        assert_eq!(binding.fraction_of_peak, 1.0);
756    }
757
758    /// Same shape as the read-only case, on `Write`.
759    #[test]
760    fn score_bounds_write_only_binds_on_write() {
761        let bound = ResourceBound {
762            amount: 300,
763            peak_per_s: 100.0,
764        };
765        let (_, binding) = score_bounds(1.0, &[(ResourceKind::Write, bound)]);
766
767        let binding = binding.expect("a usable peak binds");
768        assert_eq!(binding.resource, ResourceKind::Write);
769        assert_eq!(binding.fraction_of_peak, 3.0);
770    }
771
772    /// `tflops` reads the compute entry whichever resource bound the run.
773    #[test]
774    fn score_bounds_mixed_picks_the_slower_at_peak_resource() {
775        let duration = 1.0;
776        let compute = ResourceBound {
777            amount: 200,
778            peak_per_s: 1000.0,
779        }; // 0.2s at peak
780        let read = ResourceBound {
781            amount: 900_000,
782            peak_per_s: 1_000_000.0,
783        }; // 0.9s at peak, the binding one
784        let write = ResourceBound {
785            amount: 100_000,
786            peak_per_s: 200_000.0,
787        }; // 0.5s at peak
788
789        let resources = vec![
790            (ResourceKind::Compute, compute),
791            (ResourceKind::Read, read),
792            (ResourceKind::Write, write),
793        ];
794        let (tflops, binding) = score_bounds(duration, &resources);
795
796        assert_eq!(tflops, Some(200.0 / 1e12));
797        let binding = binding.expect("a usable peak binds");
798        assert_eq!(binding.resource, ResourceKind::Read);
799        assert_eq!(binding.fraction_of_peak, 0.9);
800    }
801
802    /// A device-timed row's timestamps start once the dispatch is already
803    /// paid for, so charging it for one would score it against time it never
804    /// spent.
805    #[test]
806    fn launch_is_declared_only_when_the_timing_measures_it() {
807        let timed = work(0, 0, 2048).declared_resources(TimingMethod::System);
808        assert_eq!(timed.len(), 2);
809        assert_eq!(timed[1].0, ResourceKind::Launch);
810        assert_eq!(timed[1].1, 1);
811        assert_eq!(
812            timed[1].2,
813            Ceiling::Probe(ThroughputKey {
814                mode: ThroughputMode::Launch
815            })
816        );
817
818        let untimed = work(0, 0, 2048).declared_resources(TimingMethod::Device);
819        assert_eq!(untimed.len(), 1);
820        assert_eq!(untimed[0].0, ResourceKind::Write);
821    }
822
823    /// A launch bound's fraction of peak is the share of the run the dispatch
824    /// cost, not a rate: 8us of overhead in a 10us run reads 80%.
825    #[test]
826    fn score_bounds_binds_on_launch_for_a_run_that_barely_outlasts_it() {
827        let write = ResourceBound {
828            amount: 16_384,
829            peak_per_s: 20e9,
830        }; // 0.8us at peak, 8% of the run
831        let launch = ResourceBound {
832            amount: 1,
833            peak_per_s: 125_000.0,
834        }; // one launch every 8us
835
836        let resources = vec![(ResourceKind::Write, write), (ResourceKind::Launch, launch)];
837        let (_, binding) = score_bounds(10e-6, &resources);
838
839        let binding = binding.expect("a usable peak binds");
840        assert_eq!(binding.resource, ResourceKind::Launch);
841        assert!((binding.fraction_of_peak - 0.8).abs() < 1e-9);
842    }
843
844    /// The same two resources on a run long enough to bury the dispatch.
845    #[test]
846    fn score_bounds_ignores_launch_once_the_run_outgrows_it() {
847        let write = ResourceBound {
848            amount: 2_000_000_000,
849            peak_per_s: 20e9,
850        }; // 0.1s at peak, the whole run
851        let launch = ResourceBound {
852            amount: 1,
853            peak_per_s: 125_000.0,
854        }; // 8us of a 0.1s run
855
856        let resources = vec![(ResourceKind::Write, write), (ResourceKind::Launch, launch)];
857        let (_, binding) = score_bounds(0.1, &resources);
858
859        let binding = binding.expect("a usable peak binds");
860        assert_eq!(binding.resource, ResourceKind::Write);
861        assert_eq!(binding.fraction_of_peak, 1.0);
862    }
863}