1use 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
24static 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
34pub fn timing_method(default: TimingMethod) -> TimingMethod {
38 TIMING_OVERRIDE.unwrap_or(default)
39}
40
41pub fn supports_f16_arithmetic(client: &Client) -> bool {
44 half::f16::supported_uses(client).contains(TypeUsage::Arithmetic)
45}
46
47pub 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
64pub fn client() -> Client {
68 let device = cubecl::test_device();
69 device.client()
70}
71
72static PEAKS: LazyLock<Mutex<HashMap<ThroughputKey, f64>>> =
77 LazyLock::new(|| Mutex::new(HashMap::new()));
78
79static CURVES: LazyLock<Mutex<HashMap<MemoryAccess, MemoryCurve>>> =
84 LazyLock::new(|| Mutex::new(HashMap::new()));
85
86fn 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
100fn 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
141pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
174enum Ceiling {
175 Probe(ThroughputKey),
176 Curve(MemoryAccess),
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub enum ResourceKind {
182 Compute,
183 Read,
184 Write,
185 Launch,
187}
188
189#[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 pub tflops: Option<f64>,
208 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 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 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 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#[derive(Debug, Clone, Copy)]
264pub struct CategoryWork {
265 pub compute: Option<ComputeWork>,
269 pub bytes_read: usize,
271 pub bytes_written: usize,
273}
274
275#[derive(Debug, Clone, Copy)]
280pub struct ComputeWork {
281 pub ops: usize,
284 pub key: ThroughputKey,
287}
288
289impl ComputeWork {
290 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 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 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
355fn 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
370fn 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
401pub trait Category: Sync {
407 type Problem;
408 type Strategy;
409
410 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 fn work(&self, _problem: &Self::Problem) -> Option<CategoryWork> {
425 None
426 }
427
428 fn timing_method(&self) -> TimingMethod {
433 crate::timing_method(TimingMethod::System)
434 }
435
436 fn correctness(
440 &self,
441 ) -> Option<&dyn Correctness<Problem = Self::Problem, Strategy = Self::Strategy>> {
442 None
443 }
444}
445
446pub trait Correctness: Sync {
455 type Problem;
456 type Strategy;
457
458 fn kernel_result(
463 &self,
464 strategy: &Self::Strategy,
465 problem: &Self::Problem,
466 seeds: &[u64],
467 ) -> Result<HostData, String>;
468
469 fn reference_result(
474 &self,
475 problem: &Self::Problem,
476 seeds: &[u64],
477 progress: Option<&Progress>,
478 ) -> Result<HostData, String>;
479}
480
481pub trait BenchmarkCategory: Sync {
485 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 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 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 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 const NO_LAUNCH: TimingMethod = TimingMethod::Device;
655
656 #[test]
660 fn zero_work_declares_no_resources() {
661 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 #[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 #[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 #[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 #[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 assert_ne!(small[0].2, small[1].2);
725
726 assert_eq!(small[0].1, 16384);
728 assert_eq!(large[0].1, 1 << 30);
729 }
730
731 #[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 #[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 #[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 #[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 }; let read = ResourceBound {
781 amount: 900_000,
782 peak_per_s: 1_000_000.0,
783 }; let write = ResourceBound {
785 amount: 100_000,
786 peak_per_s: 200_000.0,
787 }; 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 #[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 #[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 }; let launch = ResourceBound {
832 amount: 1,
833 peak_per_s: 125_000.0,
834 }; 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 #[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 }; let launch = ResourceBound {
852 amount: 1,
853 peak_per_s: 125_000.0,
854 }; 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}