aprender-cbtop 0.35.0

Compute Block Top - Real-time load testing and hardware monitoring TUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Headless benchmark mode for CI/CD and AI agent integration
//!
//! Enables cbtop to run without a TTY, outputting machine-readable results.
//!
//! # Example
//!
//! ```bash
//! # Run headless benchmark
//! cbtop --headless --format json --duration 5
//!
//! # Use bench subcommand
//! cbtop bench --backend simd --workload gemm --duration 5
//! ```

mod types;
pub use types::*;

use crate::brick::Scorable;
use crate::bricks::generators::SimdLoadBrick;
use crate::config::{ComputeBackend, WorkloadType};
use crate::error::CbtopError;
use std::time::{Duration, Instant};

/// Headless benchmark runner
pub struct HeadlessBenchmark {
    backend: ComputeBackend,
    workload: WorkloadType,
    size: usize,
    duration: Duration,
}

impl HeadlessBenchmark {
    /// Create a new headless benchmark
    pub fn new(
        backend: ComputeBackend,
        workload: WorkloadType,
        size: usize,
        duration: Duration,
    ) -> Self {
        Self {
            backend,
            workload,
            size,
            duration,
        }
    }

    /// Run the benchmark and return results
    pub fn run(&self) -> Result<BenchmarkResult, CbtopError> {
        let system = SystemInfo::detect();
        let start_time = Instant::now();

        // Create and configure the load brick
        let mut brick = SimdLoadBrick::new(self.size);
        brick.set_workload(self.workload);
        brick.set_intensity(1.0); // Full intensity for benchmarking
        brick.start();

        // OPT-013: Warmup phase with scaled duration
        // Longer warmup for small sizes to ensure stable cache/branch predictor state
        // Small sizes complete quickly, need more warmup time to reach steady state
        let base_warmup_ms = (self.duration.as_millis() / 10).max(100) as u64;
        let warmup_duration = if self.size < 100_000 {
            Duration::from_millis(base_warmup_ms * 2) // 2x warmup for small sizes
        } else {
            Duration::from_millis(base_warmup_ms)
        };
        let warmup_start = Instant::now();
        while warmup_start.elapsed() < warmup_duration {
            brick.run_iteration();
        }

        // Reset metrics after warmup
        let mut brick = SimdLoadBrick::new(self.size);
        brick.set_workload(self.workload);
        brick.set_intensity(1.0);
        brick.start();

        // OPT-014: Sample CPU frequency at start of measurement
        let start_freq_mhz = Self::sample_cpu_freq();

        // OPT-008: Calculate minimum iterations for statistical stability
        // Small workloads complete too quickly, causing high variance (CV > 600%)
        // Require more iterations for smaller sizes to get stable measurements
        let min_iterations: u64 = if self.size < 10_000 {
            5000 // Very small: need many iterations
        } else if self.size < 100_000 {
            1000 // Small: need moderate iterations
        } else if self.size < 1_000_000 {
            100 // Medium: fewer iterations needed
        } else {
            10 // Large: minimal iterations (each takes significant time)
        };

        // Measurement phase
        let mut iterations = 0u64;
        let measure_start = Instant::now();

        // OPT-008: Run until both duration AND minimum iterations are satisfied
        while measure_start.elapsed() < self.duration || iterations < min_iterations {
            brick.run_iteration();
            iterations += 1;

            // Safety: cap at 100K iterations to prevent runaway benchmarks
            if iterations >= 100_000 {
                break;
            }
        }

        let total_duration = start_time.elapsed();
        brick.stop();

        // OPT-014: Sample CPU frequency at end and detect throttling
        let end_freq_mhz = Self::sample_cpu_freq();

        // Calculate statistics using brick's internal latency history (PERF-002)
        // This ensures CV calculation matches what score() uses
        let latencies = brick.latency_history_slice();
        let latency_stats = Self::calculate_latency_stats(&latencies);
        let gflops = brick.gflops();
        let throughput = if latency_stats.mean > 0.0 {
            1000.0 / latency_stats.mean
        } else {
            0.0
        };

        // Get score
        let score = brick.score();

        // PERF-003: Check for benchmark environment warnings
        let mut warnings = system.check_benchmark_readiness();

        // OPT-014: Detect frequency throttling during benchmark
        if let (Some(start), Some(end)) = (start_freq_mhz, end_freq_mhz) {
            if start > 0 {
                let drop_percent = ((start as f64 - end as f64) / start as f64) * 100.0;
                if drop_percent > 5.0 {
                    warnings.push(format!(
                        "CPU frequency dropped {}MHz -> {}MHz ({:.1}% drop) during benchmark. \
                         Possible thermal throttling.",
                        start, end, drop_percent
                    ));
                }
            }
        }

        Ok(BenchmarkResult {
            version: env!("CARGO_PKG_VERSION").to_string(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            duration_secs: total_duration.as_secs_f64(),
            system,
            benchmark: BenchmarkConfig {
                backend: format!("{:?}", self.backend),
                workload: format!("{:?}", self.workload),
                size: self.size,
                iterations,
            },
            results: BenchmarkResults {
                gflops,
                throughput_ops_sec: throughput,
                latency_ms: latency_stats,
            },
            score: score.into(),
            warnings,
        })
    }

    /// OPT-014: Sample current CPU frequency for throttling detection
    fn sample_cpu_freq() -> Option<u32> {
        #[cfg(target_os = "linux")]
        {
            let path = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq";
            if let Ok(content) = std::fs::read_to_string(path) {
                return content.trim().parse::<u32>().ok().map(|khz| khz / 1000);
            }
        }
        None
    }

    fn calculate_latency_stats(latencies: &[f64]) -> LatencyStats {
        if latencies.is_empty() {
            return LatencyStats {
                mean: 0.0,
                min: 0.0,
                max: 0.0,
                p50: 0.0,
                p95: 0.0,
                p99: 0.0,
                cv_percent: 0.0,
            };
        }

        // OPT-015: Filter outliers using IQR method before calculating CV
        // This reduces measurement noise from system interrupts, GC pauses, etc.
        let filtered = Self::filter_outliers_iqr(latencies);
        let data = if filtered.len() >= 10 {
            &filtered
        } else {
            latencies
        };

        let n = data.len() as f64;
        let mean = data.iter().sum::<f64>() / n;
        let min = data.iter().cloned().fold(f64::INFINITY, f64::min);
        let max = data.iter().cloned().fold(f64::NEG_INFINITY, f64::max);

        // Calculate standard deviation on filtered data
        let variance = data.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / n;
        let std_dev = variance.sqrt();
        let cv_percent = if mean > 0.0 {
            (std_dev / mean) * 100.0
        } else {
            0.0
        };

        // Calculate percentiles on original data (for accurate p95/p99)
        let mut sorted = latencies.to_vec();
        sorted.sort_by(|a, b| {
            a.partial_cmp(b)
                .expect("latency values MUST be comparable (no NaN)")
        });

        let percentile = |p: f64| -> f64 {
            let idx = (p * (sorted.len() - 1) as f64).round() as usize;
            sorted[idx.min(sorted.len() - 1)]
        };

        LatencyStats {
            mean,
            min,
            max,
            p50: percentile(0.50),
            p95: percentile(0.95),
            p99: percentile(0.99),
            cv_percent,
        }
    }

    /// OPT-015: Filter outliers using IQR (Interquartile Range) method
    /// Removes values outside Q1 - 1.5*IQR and Q3 + 1.5*IQR
    fn filter_outliers_iqr(data: &[f64]) -> Vec<f64> {
        if data.len() < 4 {
            return data.to_vec();
        }

        let mut sorted = data.to_vec();
        sorted.sort_by(|a, b| {
            a.partial_cmp(b)
                .expect("data values MUST be comparable (no NaN)")
        });

        let n = sorted.len();
        let q1_idx = n / 4;
        let q3_idx = (3 * n) / 4;

        let q1 = sorted[q1_idx];
        let q3 = sorted[q3_idx];
        let iqr = q3 - q1;

        // Use 1.5*IQR rule (standard for outlier detection)
        let lower_bound = q1 - 1.5 * iqr;
        let upper_bound = q3 + 1.5 * iqr;

        data.iter()
            .cloned()
            .filter(|&x| x >= lower_bound && x <= upper_bound)
            .collect()
    }
}

// ============================================================================
// Library API for Programmatic Access (HL-007)
// ============================================================================

/// Builder for creating benchmarks programmatically
///
/// This provides an ergonomic API for running cbtop benchmarks from Rust code.
///
/// # Example
///
/// ```rust,no_run
/// use cbtop::{Benchmark, BenchmarkResult};
/// use std::time::Duration;
///
/// let result: BenchmarkResult = Benchmark::builder()
///     .workload("gemm")
///     .size(1_000_000)
///     .duration(Duration::from_secs(5))
///     .build()
///     .unwrap()
///     .run()
///     .unwrap();
///
/// println!("GFLOP/s: {}", result.results.gflops);
/// ```
#[derive(Default)]
pub struct BenchmarkBuilder {
    backend: Option<ComputeBackend>,
    workload: Option<WorkloadType>,
    size: Option<usize>,
    duration: Option<Duration>,
}

impl BenchmarkBuilder {
    /// Create a new benchmark builder with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the compute backend (default: Auto/Simd)
    pub fn backend(mut self, backend: ComputeBackend) -> Self {
        self.backend = Some(backend);
        self
    }

    /// Set the compute backend from string (e.g., "simd", "cuda", "auto")
    pub fn backend_str(mut self, backend: &str) -> Self {
        self.backend = Some(match backend.to_lowercase().as_str() {
            "cuda" => ComputeBackend::Cuda,
            "wgpu" => ComputeBackend::Wgpu,
            "simd" => ComputeBackend::Simd,
            _ => ComputeBackend::Simd, // Default to SIMD
        });
        self
    }

    /// Set the workload type (default: Gemm)
    pub fn workload_type(mut self, workload: WorkloadType) -> Self {
        self.workload = Some(workload);
        self
    }

    /// Set the workload type from string (e.g., "gemm", "dot", "elementwise")
    pub fn workload(mut self, workload: &str) -> Self {
        self.workload = Some(match workload.to_lowercase().as_str() {
            "dot" | "dotproduct" | "dot_product" => WorkloadType::Gemm,
            "elementwise" | "element_wise" => WorkloadType::Elementwise,
            "reduction" | "reduce" => WorkloadType::Reduction,
            "bandwidth" | "memcpy" => WorkloadType::Bandwidth,
            "conv2d" | "conv" | "convolution" => WorkloadType::Conv2d,
            "attention" | "attn" => WorkloadType::Attention,
            "all" => WorkloadType::All,
            _ => WorkloadType::Gemm, // Default to GEMM
        });
        self
    }

    /// Set the problem size (default: 1_000_000)
    pub fn size(mut self, size: usize) -> Self {
        self.size = Some(size);
        self
    }

    /// Set the benchmark duration (default: 5 seconds)
    pub fn duration(mut self, duration: Duration) -> Self {
        self.duration = Some(duration);
        self
    }

    /// Set the benchmark duration in seconds
    pub fn duration_secs(mut self, secs: u64) -> Self {
        self.duration = Some(Duration::from_secs(secs));
        self
    }

    /// Build the benchmark with the configured parameters
    pub fn build(self) -> Result<Benchmark, CbtopError> {
        Ok(Benchmark {
            inner: HeadlessBenchmark::new(
                self.backend.unwrap_or(ComputeBackend::Simd),
                self.workload.unwrap_or(WorkloadType::Gemm),
                self.size.unwrap_or(1_000_000),
                self.duration.unwrap_or(Duration::from_secs(5)),
            ),
        })
    }
}

/// Benchmark runner for programmatic access
///
/// Created via [`Benchmark::builder()`].
pub struct Benchmark {
    inner: HeadlessBenchmark,
}

impl Benchmark {
    /// Create a new benchmark builder
    pub fn builder() -> BenchmarkBuilder {
        BenchmarkBuilder::new()
    }

    /// Run the benchmark and return results
    pub fn run(&self) -> Result<BenchmarkResult, CbtopError> {
        self.inner.run()
    }

    /// Run the benchmark and compare against a baseline
    pub fn run_with_baseline(
        &self,
        baseline: &BenchmarkResult,
        threshold: f64,
    ) -> Result<(BenchmarkResult, RegressionResult), CbtopError> {
        let result = self.inner.run()?;
        let regression = result.check_regression(baseline, threshold);
        Ok((result, regression))
    }
}

#[cfg(test)]
mod tests;