Skip to main content

trustformers_models/
benchmarking.rs

1//! # Simplified Model Benchmarking Suite
2//!
3//! This module provides basic benchmarking capabilities for comparing model performance.
4
5use anyhow::Result;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::time::{Duration, Instant};
9use trustformers_core::tensor::Tensor;
10
11/// Basic benchmark configuration
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct BenchmarkConfig {
14    /// Number of warmup iterations
15    pub warmup_iterations: usize,
16    /// Number of benchmark iterations
17    pub benchmark_iterations: usize,
18    /// Test batch sizes
19    pub batch_sizes: Vec<usize>,
20    /// Test sequence lengths
21    pub sequence_lengths: Vec<usize>,
22}
23
24impl Default for BenchmarkConfig {
25    fn default() -> Self {
26        Self {
27            warmup_iterations: 5,
28            benchmark_iterations: 20,
29            batch_sizes: vec![1, 4, 8, 16],
30            sequence_lengths: vec![128, 256, 512],
31        }
32    }
33}
34
35/// Benchmark results for a single test
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct BenchmarkResult {
38    /// Test name
39    pub test_name: String,
40    /// Average latency in milliseconds
41    pub avg_latency_ms: f64,
42    /// Standard deviation of latency
43    pub std_latency_ms: f64,
44    /// Throughput in samples per second
45    pub throughput: f64,
46    /// Memory usage in MB (if measured)
47    pub memory_mb: Option<f64>,
48}
49
50/// Model benchmark function type
51pub type ModelBenchmarkFn = Box<dyn Fn(&Tensor) -> Result<Tensor>>;
52
53/// Simplified benchmarking suite
54pub struct BenchmarkSuite {
55    config: BenchmarkConfig,
56    models: HashMap<String, ModelBenchmarkFn>,
57}
58
59impl BenchmarkSuite {
60    /// Create a new benchmark suite
61    pub fn new(config: BenchmarkConfig) -> Self {
62        Self {
63            config,
64            models: HashMap::new(),
65        }
66    }
67
68    /// Add a model function to benchmark
69    pub fn add_model<F>(&mut self, name: &str, model_fn: F)
70    where
71        F: Fn(&Tensor) -> Result<Tensor> + 'static,
72    {
73        self.models.insert(name.to_string(), Box::new(model_fn));
74    }
75
76    /// Run all benchmarks
77    pub fn run_benchmarks(&self) -> Result<Vec<BenchmarkResult>> {
78        let mut results = Vec::new();
79
80        for (model_name, model_fn) in &self.models {
81            for &batch_size in &self.config.batch_sizes {
82                for &seq_len in &self.config.sequence_lengths {
83                    let test_name =
84                        format!("{}_{}_{}x{}", model_name, "forward", batch_size, seq_len);
85                    let input = Tensor::randn(&[batch_size, seq_len])?;
86
87                    let result = self.benchmark_model_with_input(&test_name, model_fn, &input)?;
88                    results.push(result);
89                }
90            }
91        }
92
93        Ok(results)
94    }
95
96    /// Benchmark a single model with specific input
97    fn benchmark_model_with_input(
98        &self,
99        test_name: &str,
100        model_fn: &ModelBenchmarkFn,
101        input: &Tensor,
102    ) -> Result<BenchmarkResult> {
103        // Warmup
104        for _ in 0..self.config.warmup_iterations {
105            model_fn(input)?;
106        }
107
108        if self.config.benchmark_iterations == 0 {
109            return Err(anyhow::anyhow!(
110                "benchmark_iterations is 0, so no timing sample can be taken for {test_name}"
111            ));
112        }
113
114        // Benchmark.
115        //
116        // `Duration::as_millis()` truncates to whole milliseconds, so every
117        // sub-millisecond forward pass used to be recorded as exactly `0.0 ms`,
118        // which made `avg_latency_ms` zero and `1000.0 / 0.0` report an
119        // *infinite* throughput. Timings are kept as `Duration` and converted
120        // with `as_secs_f64()` so the full nanosecond resolution survives.
121        let mut durations: Vec<Duration> = Vec::with_capacity(self.config.benchmark_iterations);
122        for _ in 0..self.config.benchmark_iterations {
123            let start = Instant::now();
124            model_fn(input)?;
125            durations.push(start.elapsed());
126        }
127
128        let samples_ms: Vec<f64> = durations.iter().map(|d| d.as_secs_f64() * 1_000.0).collect();
129        let total_secs: f64 = durations.iter().map(Duration::as_secs_f64).sum();
130
131        // Calculate statistics
132        let avg_latency_ms = samples_ms.iter().sum::<f64>() / samples_ms.len() as f64;
133        let variance = samples_ms.iter().map(|&x| (x - avg_latency_ms).powi(2)).sum::<f64>()
134            / samples_ms.len() as f64;
135        let std_latency_ms = variance.sqrt();
136
137        // Throughput is derived from the *total* measured wall time rather than
138        // from a reciprocal of a possibly-zero average. A zero total means the
139        // platform clock did not advance across the whole loop, which is a
140        // measurement failure, not an infinitely fast model.
141        if total_secs <= 0.0 || !total_secs.is_finite() {
142            return Err(anyhow::anyhow!(
143                "monotonic clock did not advance across {} iteration(s) of {test_name}; \
144                 throughput cannot be measured on this platform",
145                self.config.benchmark_iterations
146            ));
147        }
148        let throughput = self.config.benchmark_iterations as f64 / total_secs;
149
150        Ok(BenchmarkResult {
151            test_name: test_name.to_string(),
152            avg_latency_ms,
153            std_latency_ms,
154            throughput,
155            memory_mb: None, // Memory measurement would require platform-specific code
156        })
157    }
158
159    /// Generate a simple benchmark report
160    pub fn generate_report(&self, results: &[BenchmarkResult]) -> String {
161        let mut report = String::new();
162        report.push_str("# Benchmark Report\n\n");
163
164        report
165            .push_str("| Test Name | Avg Latency (ms) | Std Dev (ms) | Throughput (samples/s) |\n");
166        report.push_str("|-----------|------------------|--------------|----------------------|\n");
167
168        for result in results {
169            report.push_str(&format!(
170                "| {} | {:.2} | {:.2} | {:.2} |\n",
171                result.test_name, result.avg_latency_ms, result.std_latency_ms, result.throughput
172            ));
173        }
174
175        report
176    }
177}
178
179/// Model performance comparison utilities
180pub struct ModelComparator;
181
182impl ModelComparator {
183    /// Compare two sets of benchmark results
184    pub fn compare_results(baseline: &[BenchmarkResult], comparison: &[BenchmarkResult]) -> String {
185        let mut report = String::new();
186        report.push_str("# Performance Comparison\n\n");
187
188        // Match results by test name
189        let baseline_map: HashMap<_, _> =
190            baseline.iter().map(|r| (r.test_name.clone(), r)).collect();
191
192        report
193            .push_str("| Test | Baseline (ms) | Comparison (ms) | Speedup | Throughput Change |\n");
194        report
195            .push_str("|------|---------------|-----------------|---------|------------------|\n");
196
197        for comp_result in comparison {
198            if let Some(base_result) = baseline_map.get(&comp_result.test_name) {
199                let speedup = base_result.avg_latency_ms / comp_result.avg_latency_ms;
200                let throughput_change = (comp_result.throughput - base_result.throughput)
201                    / base_result.throughput
202                    * 100.0;
203
204                report.push_str(&format!(
205                    "| {} | {:.2} | {:.2} | {:.2}x | {:.1}% |\n",
206                    comp_result.test_name,
207                    base_result.avg_latency_ms,
208                    comp_result.avg_latency_ms,
209                    speedup,
210                    throughput_change
211                ));
212            }
213        }
214
215        report
216    }
217}
218
219/// Simple benchmarking utilities
220pub struct BenchmarkUtils;
221
222impl BenchmarkUtils {
223    /// Create test inputs for benchmarking
224    pub fn create_test_inputs(batch_sizes: &[usize], seq_lengths: &[usize]) -> Result<Vec<Tensor>> {
225        let mut inputs = Vec::new();
226        for &batch_size in batch_sizes {
227            for &seq_len in seq_lengths {
228                inputs.push(Tensor::randn(&[batch_size, seq_len])?);
229            }
230        }
231        Ok(inputs)
232    }
233
234    /// Measure single function execution time
235    pub fn measure_execution_time<F, T>(mut f: F) -> (T, Duration)
236    where
237        F: FnMut() -> T,
238    {
239        let start = Instant::now();
240        let result = f();
241        let duration = start.elapsed();
242        (result, duration)
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    #[test]
251    fn test_benchmark_suite_creation() {
252        let config = BenchmarkConfig::default();
253        let suite = BenchmarkSuite::new(config);
254        // Suite should be created successfully
255        assert_eq!(suite.models.len(), 0);
256    }
257
258    #[test]
259    fn test_benchmark_config() {
260        let config = BenchmarkConfig::default();
261        assert_eq!(config.warmup_iterations, 5);
262        assert_eq!(config.benchmark_iterations, 20);
263        assert!(!config.batch_sizes.is_empty());
264        assert!(!config.sequence_lengths.is_empty());
265    }
266
267    #[test]
268    fn test_benchmark_utils() -> Result<()> {
269        let inputs = BenchmarkUtils::create_test_inputs(&[2, 4], &[10, 20])?;
270        assert_eq!(inputs.len(), 4);
271        Ok(())
272    }
273
274    /// Regression: sub-millisecond work must not report `0.00 ms` and infinite
275    /// throughput.
276    ///
277    /// The previous implementation stored `start.elapsed().as_millis() as f64`,
278    /// so a forward pass faster than one millisecond was recorded as exactly
279    /// zero; `avg_latency_ms` then became `0.0` and `1000.0 / 0.0` produced
280    /// `inf` samples/s. Both assertions below fail against that code.
281    #[test]
282    fn sub_millisecond_benchmarks_report_real_latency_and_finite_throughput() {
283        let config = BenchmarkConfig {
284            warmup_iterations: 1,
285            benchmark_iterations: 8,
286            batch_sizes: vec![1],
287            sequence_lengths: vec![4],
288        };
289        let mut suite = BenchmarkSuite::new(config);
290        // A clone is far faster than a millisecond on any supported platform.
291        suite.add_model("identity", |t: &Tensor| Ok(t.clone()));
292
293        let results = suite.run_benchmarks().expect("benchmark run must succeed");
294        assert_eq!(results.len(), 1);
295        let result = &results[0];
296
297        assert!(
298            result.avg_latency_ms > 0.0,
299            "sub-millisecond latency must not be truncated to zero, got {}",
300            result.avg_latency_ms
301        );
302        assert!(
303            result.throughput.is_finite() && result.throughput > 0.0,
304            "throughput must be a finite positive rate, got {}",
305            result.throughput
306        );
307        assert!(
308            result.std_latency_ms.is_finite(),
309            "standard deviation must be finite, got {}",
310            result.std_latency_ms
311        );
312    }
313
314    #[test]
315    fn zero_iteration_benchmarks_are_rejected_rather_than_reporting_nan() {
316        let config = BenchmarkConfig {
317            warmup_iterations: 0,
318            benchmark_iterations: 0,
319            batch_sizes: vec![1],
320            sequence_lengths: vec![2],
321        };
322        let mut suite = BenchmarkSuite::new(config);
323        suite.add_model("identity", |t: &Tensor| Ok(t.clone()));
324        let err = suite
325            .run_benchmarks()
326            .expect_err("a benchmark with no iterations must not report a measurement");
327        assert!(
328            err.to_string().contains("benchmark_iterations is 0"),
329            "unexpected error: {err}"
330        );
331    }
332
333    #[test]
334    fn test_execution_time_measurement() {
335        let (result, duration) = BenchmarkUtils::measure_execution_time(|| {
336            std::thread::sleep(std::time::Duration::from_millis(10));
337            42
338        });
339
340        assert_eq!(result, 42);
341        assert!(duration.as_millis() >= 10);
342    }
343}