1use anyhow::Result;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::path::Path;
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct BenchmarkGeneratorConfig {
13 pub model_name: String,
15 pub benchmark_types: Vec<BenchmarkType>,
17 pub test_configs: HashMap<String, TestConfig>,
19 pub hardware_targets: Vec<HardwareTarget>,
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
25pub enum BenchmarkType {
26 Latency,
27 Throughput,
28 Memory,
29 Accuracy,
30 Scalability,
31 Comparative,
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize)]
36pub struct TestConfig {
37 pub batch_sizes: Vec<usize>,
38 pub sequence_lengths: Vec<usize>,
39 pub iterations: usize,
40 pub warmup_iterations: usize,
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
45pub enum HardwareTarget {
46 CPU,
47 GPU,
48 Metal,
49 WASM,
50}
51
52pub struct BenchmarkGenerator {
54 config: BenchmarkGeneratorConfig,
55}
56
57impl BenchmarkGenerator {
58 pub fn new(config: BenchmarkGeneratorConfig) -> Self {
60 Self { config }
61 }
62
63 pub fn generate_benchmarks(&self, output_path: &Path) -> Result<()> {
65 let mut benchmark_content = self.generate_header();
66
67 for benchmark_type in &self.config.benchmark_types {
68 match benchmark_type {
69 BenchmarkType::Latency => {
70 benchmark_content.push_str(&self.generate_latency_benchmark())
71 },
72 BenchmarkType::Throughput => {
73 benchmark_content.push_str(&self.generate_throughput_benchmark())
74 },
75 BenchmarkType::Memory => {
76 benchmark_content.push_str(&self.generate_memory_benchmark())
77 },
78 BenchmarkType::Accuracy => {
79 benchmark_content.push_str(&self.generate_accuracy_benchmark())
80 },
81 BenchmarkType::Scalability => {
82 benchmark_content.push_str(&self.generate_scalability_benchmark())
83 },
84 BenchmarkType::Comparative => {
85 benchmark_content.push_str(&self.generate_comparative_benchmark())
86 },
87 }
88 }
89
90 std::fs::write(output_path, benchmark_content)?;
91 Ok(())
92 }
93
94 fn test_config(&self) -> TestConfig {
99 let mut names: Vec<&String> = self.config.test_configs.keys().collect();
100 names.sort();
101 names
102 .first()
103 .and_then(|name| self.config.test_configs.get(*name))
104 .cloned()
105 .unwrap_or(TestConfig {
106 batch_sizes: vec![1],
107 sequence_lengths: vec![128],
108 iterations: 100,
109 warmup_iterations: 10,
110 })
111 }
112
113 fn size_list(values: &[usize]) -> String {
115 let rendered: Vec<String> = values.iter().map(usize::to_string).collect();
116 format!("vec![{}]", rendered.join(", "))
117 }
118
119 fn generate_header(&self) -> String {
121 format!(
122 "//! Performance Benchmarks for {name}\n\
123 //!\n\
124 //! This file is auto-generated. Do not edit manually.\n\
125 //!\n\
126 //! Every benchmark below runs a real forward pass of the model; a failed\n\
127 //! model construction or forward pass aborts the benchmark instead of\n\
128 //! silently measuring nothing.\n\n\
129 use criterion::{{criterion_group, criterion_main, Criterion}};\n\
130 use std::hint::black_box;\n\
131 use std::time::Duration;\n\
132 use super::{{{name}Config, {name}Model}};\n\
133 use trustformers_core::tensor::Tensor;\n\n\
134 /// Build the model under test, panicking with a clear message on failure.\n\
135 fn build_model() -> {name}Model {{\n\
136 \x20 match {name}Model::new({name}Config::default()) {{\n\
137 \x20 Ok(model) => model,\n\
138 \x20 Err(error) => panic!(\"failed to build {name}Model: {{error}}\"),\n\
139 \x20 }}\n\
140 }}\n\n\
141 /// Build an input tensor, panicking with a clear message on failure.\n\
142 fn build_input(shape: &[usize]) -> Tensor {{\n\
143 \x20 match Tensor::randn(shape) {{\n\
144 \x20 Ok(tensor) => tensor,\n\
145 \x20 Err(error) => panic!(\"failed to build a {{shape:?}} input: {{error}}\"),\n\
146 \x20 }}\n\
147 }}\n\n\
148 /// Run one forward pass, panicking if the model reports an error so a\n\
149 /// broken model can never be recorded as fast.\n\
150 fn forward(model: &{name}Model, input: &Tensor) -> Tensor {{\n\
151 \x20 match model.forward(input) {{\n\
152 \x20 Ok(output) => output,\n\
153 \x20 Err(error) => panic!(\"forward pass failed: {{error}}\"),\n\
154 \x20 }}\n\
155 }}\n\n",
156 name = self.config.model_name
157 )
158 }
159
160 fn generate_latency_benchmark(&self) -> String {
162 let test_config = self.test_config();
163 format!(
164 "// ========== Latency Benchmarks ==========\n\n\
165 fn bench_{lower}_latency(c: &mut Criterion) {{\n\
166 \x20 let model = build_model();\n\
167 \x20 let mut group = c.benchmark_group(\"{lower}_latency\");\n\
168 \x20 group.warm_up_time(Duration::from_millis(500));\n\
169 \x20 group.measurement_time(Duration::from_secs(3));\n\
170 \x20 // Sample count from the generator's TestConfig (criterion's floor is 10).\n\
171 \x20 group.sample_size({samples});\n\n\
172 \x20 let batch_sizes = {batches};\n\
173 \x20 let sequence_length = {seq_len};\n\n\
174 \x20 for batch_size in batch_sizes {{\n\
175 \x20 let input = build_input(&[batch_size, sequence_length]);\n\
176 \x20 group.throughput(criterion::Throughput::Elements(\n\
177 \x20 (batch_size * sequence_length) as u64,\n\
178 \x20 ));\n\
179 \x20 group.bench_with_input(\n\
180 \x20 format!(\"batch_{{}}\", batch_size),\n\
181 \x20 &batch_size,\n\
182 \x20 |b, _| {{\n\
183 \x20 b.iter(|| black_box(forward(&model, black_box(&input))));\n\
184 \x20 }},\n\
185 \x20 );\n\
186 \x20 }}\n\n\
187 \x20 group.finish();\n\
188 }}\n\n",
189 lower = self.config.model_name.to_lowercase(),
190 batches = Self::size_list(&test_config.batch_sizes),
191 seq_len = test_config.sequence_lengths.first().copied().unwrap_or(128),
192 samples = test_config.iterations.max(10),
193 )
194 }
195
196 fn generate_throughput_benchmark(&self) -> String {
198 let test_config = self.test_config();
199 let batch_size = test_config.batch_sizes.last().copied().unwrap_or(1);
200 let sequence_length = test_config.sequence_lengths.last().copied().unwrap_or(128);
201 format!(
202 "// ========== Throughput Benchmarks ==========\n\n\
203 fn bench_{lower}_throughput(c: &mut Criterion) {{\n\
204 \x20 let model = build_model();\n\
205 \x20 let mut group = c.benchmark_group(\"{lower}_throughput\");\n\
206 \x20 group.warm_up_time(Duration::from_millis({warmup}));\n\
207 \x20 group.measurement_time(Duration::from_secs(5));\n\
208 \x20 group.sample_size({samples});\n\n\
209 \x20 let batch_size = {batch_size};\n\
210 \x20 let sequence_length = {sequence_length};\n\
211 \x20 let input = build_input(&[batch_size, sequence_length]);\n\
212 \x20 // Criterion divides the measured time by this element count, so the\n\
213 \x20 // reported throughput is tokens per second of real work.\n\
214 \x20 group.throughput(criterion::Throughput::Elements(\n\
215 \x20 (batch_size * sequence_length) as u64,\n\
216 \x20 ));\n\n\
217 \x20 group.bench_function(\"tokens_per_second\", |b| {{\n\
218 \x20 b.iter(|| black_box(forward(&model, black_box(&input))));\n\
219 \x20 }});\n\n\
220 \x20 group.finish();\n\
221 }}\n\n",
222 lower = self.config.model_name.to_lowercase(),
223 batch_size = batch_size,
224 sequence_length = sequence_length,
225 samples = test_config.iterations.max(10),
226 warmup = (test_config.warmup_iterations.max(1) * 100).min(5_000),
227 )
228 }
229
230 fn generate_memory_benchmark(&self) -> String {
232 let test_config = self.test_config();
233 format!(
234 "// ========== Sequence-Length Scaling ==========\n\n\
235 fn bench_{lower}_memory(c: &mut Criterion) {{\n\
236 \x20 let model = build_model();\n\
237 \x20 let mut group = c.benchmark_group(\"{lower}_memory\");\n\
238 \x20 group.warm_up_time(Duration::from_millis(100));\n\
239 \x20 group.measurement_time(Duration::from_secs(2));\n\n\
240 \x20 let sequence_lengths = {seq_lens};\n\
241 \x20 let batch_size = {batch_size};\n\n\
242 \x20 for seq_len in sequence_lengths {{\n\
243 \x20 let input = build_input(&[batch_size, seq_len]);\n\
244 \x20 group.bench_with_input(\n\
245 \x20 format!(\"seq_len_{{}}\", seq_len),\n\
246 \x20 &seq_len,\n\
247 \x20 |b, _| {{\n\
248 \x20 b.iter(|| black_box(forward(&model, black_box(&input))));\n\
249 \x20 }},\n\
250 \x20 );\n\
251 \x20 }}\n\n\
252 \x20 group.finish();\n\
253 }}\n\n",
254 lower = self.config.model_name.to_lowercase(),
255 seq_lens = Self::size_list(&test_config.sequence_lengths),
256 batch_size = test_config.batch_sizes.first().copied().unwrap_or(1),
257 )
258 }
259
260 fn generate_accuracy_benchmark(&self) -> String {
262 let test_config = self.test_config();
263 format!(
264 "// ========== Numerical Consistency ==========\n\n\
265 fn bench_{lower}_accuracy(c: &mut Criterion) {{\n\
266 \x20 let model = build_model();\n\
267 \x20 let mut group = c.benchmark_group(\"{lower}_accuracy\");\n\
268 \x20 group.warm_up_time(Duration::from_millis(200));\n\
269 \x20 group.measurement_time(Duration::from_secs(2));\n\n\
270 \x20 let input = build_input(&[{batch_size}, {seq_len}]);\n\
271 \x20 // Reference output: every iteration must reproduce it exactly.\n\
272 \x20 let reference = match forward(&model, &input).data() {{\n\
273 \x20 Ok(values) => values,\n\
274 \x20 Err(error) => panic!(\"failed to read the reference output: {{error}}\"),\n\
275 \x20 }};\n\n\
276 \x20 group.bench_function(\"deterministic_forward\", |b| {{\n\
277 \x20 b.iter(|| {{\n\
278 \x20 let output = forward(&model, black_box(&input));\n\
279 \x20 let values = match output.data() {{\n\
280 \x20 Ok(values) => values,\n\
281 \x20 Err(error) => panic!(\"failed to read the output: {{error}}\"),\n\
282 \x20 }};\n\
283 \x20 assert_eq!(values.len(), reference.len());\n\
284 \x20 for (actual, expected) in values.iter().zip(reference.iter()) {{\n\
285 \x20 assert!((actual - expected).abs() < 1e-5);\n\
286 \x20 }}\n\
287 \x20 black_box(values);\n\
288 \x20 }});\n\
289 \x20 }});\n\n\
290 \x20 group.finish();\n\
291 }}\n\n",
292 lower = self.config.model_name.to_lowercase(),
293 batch_size = test_config.batch_sizes.first().copied().unwrap_or(1),
294 seq_len = test_config.sequence_lengths.first().copied().unwrap_or(128),
295 )
296 }
297
298 fn generate_scalability_benchmark(&self) -> String {
300 let test_config = self.test_config();
301 let mut cases = Vec::new();
302 for batch in &test_config.batch_sizes {
303 for seq_len in &test_config.sequence_lengths {
304 cases.push(format!("({batch}, {seq_len})"));
305 }
306 }
307 format!(
308 "// ========== Scalability Benchmarks ==========\n\n\
309 fn bench_{lower}_scalability(c: &mut Criterion) {{\n\
310 \x20 let model = build_model();\n\
311 \x20 let mut group = c.benchmark_group(\"{lower}_scalability\");\n\
312 \x20 group.warm_up_time(Duration::from_millis(500));\n\
313 \x20 group.measurement_time(Duration::from_secs(3));\n\n\
314 \x20 let test_cases = vec![{cases}];\n\n\
315 \x20 for (batch_size, seq_len) in test_cases {{\n\
316 \x20 let input = build_input(&[batch_size, seq_len]);\n\
317 \x20 group.throughput(criterion::Throughput::Elements(\n\
318 \x20 (batch_size * seq_len) as u64,\n\
319 \x20 ));\n\
320 \x20 group.bench_with_input(\n\
321 \x20 format!(\"batch_{{}}x{{}}\", batch_size, seq_len),\n\
322 \x20 &(batch_size, seq_len),\n\
323 \x20 |b, _| {{\n\
324 \x20 b.iter(|| black_box(forward(&model, black_box(&input))));\n\
325 \x20 }},\n\
326 \x20 );\n\
327 \x20 }}\n\n\
328 \x20 group.finish();\n\
329 }}\n\n",
330 lower = self.config.model_name.to_lowercase(),
331 cases = cases.join(", "),
332 )
333 }
334
335 fn generate_comparative_benchmark(&self) -> String {
337 let test_config = self.test_config();
338 format!(
339 "// ========== Comparative Benchmarks ==========\n\n\
340 fn bench_{lower}_comparative(c: &mut Criterion) {{\n\
341 \x20 let model = build_model();\n\
342 \x20 let mut group = c.benchmark_group(\"{lower}_comparative\");\n\
343 \x20 group.warm_up_time(Duration::from_millis(300));\n\
344 \x20 group.measurement_time(Duration::from_secs(2));\n\n\
345 \x20 let input = build_input(&[{batch_size}, {seq_len}]);\n\n\
346 \x20 group.bench_function(\"baseline\", |b| {{\n\
347 \x20 b.iter(|| black_box(forward(&model, black_box(&input))));\n\
348 \x20 }});\n\n\
349 \x20 // Add further configurations here to compare against this baseline.\n\n\
350 \x20 group.finish();\n\
351 }}\n\n",
352 lower = self.config.model_name.to_lowercase(),
353 batch_size = test_config.batch_sizes.last().copied().unwrap_or(1),
354 seq_len = test_config.sequence_lengths.last().copied().unwrap_or(128),
355 )
356 }
357}
358
359impl BenchmarkGenerator {
360 pub fn generate_main(&self) -> String {
362 let function_names: Vec<String> = self
363 .config
364 .benchmark_types
365 .iter()
366 .map(|bt| {
367 format!(
368 "bench_{}_{}",
369 self.config.model_name.to_lowercase(),
370 match bt {
371 BenchmarkType::Latency => "latency",
372 BenchmarkType::Throughput => "throughput",
373 BenchmarkType::Memory => "memory",
374 BenchmarkType::Accuracy => "accuracy",
375 BenchmarkType::Scalability => "scalability",
376 BenchmarkType::Comparative => "comparative",
377 }
378 )
379 })
380 .collect();
381
382 format!(
383 "criterion_group!(benches, {});\ncriterion_main!(benches);\n",
384 function_names.join(", ")
385 )
386 }
387}
388
389pub struct BenchmarkTemplates;
391
392impl BenchmarkTemplates {
393 pub fn comprehensive(model_name: String) -> BenchmarkGeneratorConfig {
395 let mut test_configs = HashMap::new();
396 test_configs.insert(
397 "default".to_string(),
398 TestConfig {
399 batch_sizes: vec![1, 4, 8, 16],
400 sequence_lengths: vec![128, 256, 512, 1024],
401 iterations: 100,
402 warmup_iterations: 10,
403 },
404 );
405
406 BenchmarkGeneratorConfig {
407 model_name,
408 benchmark_types: vec![
409 BenchmarkType::Latency,
410 BenchmarkType::Throughput,
411 BenchmarkType::Memory,
412 BenchmarkType::Accuracy,
413 BenchmarkType::Scalability,
414 BenchmarkType::Comparative,
415 ],
416 test_configs,
417 hardware_targets: vec![HardwareTarget::CPU],
418 }
419 }
420
421 pub fn performance(model_name: String) -> BenchmarkGeneratorConfig {
423 let mut test_configs = HashMap::new();
424 test_configs.insert(
425 "performance".to_string(),
426 TestConfig {
427 batch_sizes: vec![1, 8, 16, 32],
428 sequence_lengths: vec![256, 512, 1024],
429 iterations: 200,
430 warmup_iterations: 20,
431 },
432 );
433
434 BenchmarkGeneratorConfig {
435 model_name,
436 benchmark_types: vec![
437 BenchmarkType::Latency,
438 BenchmarkType::Throughput,
439 BenchmarkType::Scalability,
440 ],
441 test_configs,
442 hardware_targets: vec![HardwareTarget::CPU, HardwareTarget::GPU],
443 }
444 }
445
446 pub fn accuracy(model_name: String) -> BenchmarkGeneratorConfig {
448 let mut test_configs = HashMap::new();
449 test_configs.insert(
450 "accuracy".to_string(),
451 TestConfig {
452 batch_sizes: vec![4, 8],
453 sequence_lengths: vec![512],
454 iterations: 50,
455 warmup_iterations: 5,
456 },
457 );
458
459 BenchmarkGeneratorConfig {
460 model_name,
461 benchmark_types: vec![BenchmarkType::Accuracy, BenchmarkType::Comparative],
462 test_configs,
463 hardware_targets: vec![HardwareTarget::CPU],
464 }
465 }
466}
467
468#[cfg(test)]
469mod tests {
470 use super::*;
471
472 fn generator() -> BenchmarkGenerator {
473 let mut test_configs = HashMap::new();
474 test_configs.insert(
475 "default".to_string(),
476 TestConfig {
477 batch_sizes: vec![2, 7],
478 sequence_lengths: vec![33, 64],
479 iterations: 5,
480 warmup_iterations: 1,
481 },
482 );
483
484 BenchmarkGenerator::new(BenchmarkGeneratorConfig {
485 model_name: "Demo".to_string(),
486 benchmark_types: vec![
487 BenchmarkType::Latency,
488 BenchmarkType::Throughput,
489 BenchmarkType::Memory,
490 BenchmarkType::Accuracy,
491 BenchmarkType::Scalability,
492 BenchmarkType::Comparative,
493 ],
494 test_configs,
495 hardware_targets: vec![HardwareTarget::CPU],
496 })
497 }
498
499 #[test]
500 fn test_generated_benchmarks_use_the_configured_shapes() {
501 let generator = generator();
502 let code = generator.generate_latency_benchmark();
503
504 assert!(
505 code.contains("vec![2, 7]"),
506 "the configured batch sizes must be used:\n{code}"
507 );
508 assert!(
509 code.contains("let sequence_length = 33"),
510 "the configured sequence length must be used:\n{code}"
511 );
512 assert!(
513 !code.contains("vec![1, 4, 8, 16]"),
514 "the generator must not fall back to hardcoded shapes:\n{code}"
515 );
516 assert!(
517 code.contains("group.sample_size(10)"),
518 "the configured iteration count must reach criterion:\n{code}"
519 );
520
521 let scalability = generator.generate_scalability_benchmark();
522 for case in ["(2, 33)", "(2, 64)", "(7, 33)", "(7, 64)"] {
523 assert!(
524 scalability.contains(case),
525 "missing case {case}:\n{scalability}"
526 );
527 }
528 }
529
530 #[test]
531 fn test_generated_benchmarks_run_real_forward_passes() {
532 let generator = generator();
533 let mut code = generator.generate_header();
534 code.push_str(&generator.generate_latency_benchmark());
535 code.push_str(&generator.generate_throughput_benchmark());
536 code.push_str(&generator.generate_accuracy_benchmark());
537
538 assert!(code.contains("model.forward(input)"));
540 assert!(code.contains("b.iter(|| black_box(forward(&model, black_box(&input))))"));
541 assert!(code.contains("criterion::Throughput::Elements"));
543 }
544
545 #[test]
546 fn test_generated_code_handles_fallible_constructors() {
547 let code = generator().generate_header();
548
549 assert!(code.contains("fn build_input(shape: &[usize]) -> Tensor"));
552 assert!(code.contains("match Tensor::randn(shape)"));
553 assert!(code.contains("match DemoModel::new(DemoConfig::default())"));
554 assert!(
555 !code.contains("let input = Tensor::randn(&[batch_size, sequence_length]);"),
556 "a raw Result must never be passed off as a Tensor"
557 );
558 }
559
560 #[test]
561 fn test_failed_forward_passes_are_not_silently_ignored() {
562 let code = generator().generate_latency_benchmark();
563 assert!(
564 !code.contains("if let Ok(output) = model.forward"),
565 "a failing forward pass must abort the benchmark, not measure an empty loop:\n{code}"
566 );
567 }
568
569 #[test]
570 fn test_generate_benchmarks_writes_a_file() {
571 let generator = generator();
572 let path = std::env::temp_dir().join("trustformers_generated_benchmark.rs");
573 let _ = std::fs::remove_file(&path);
574
575 generator.generate_benchmarks(&path).expect("benchmark generation");
576 let written = std::fs::read_to_string(&path).expect("generated file");
577
578 assert!(written.contains("fn bench_demo_latency"));
579 assert!(written.contains("fn bench_demo_comparative"));
580 let _ = std::fs::remove_file(&path);
581 }
582
583 #[test]
584 fn test_main_registration_lists_every_benchmark() {
585 let main = generator().generate_main();
586 for name in [
587 "bench_demo_latency",
588 "bench_demo_throughput",
589 "bench_demo_memory",
590 "bench_demo_accuracy",
591 "bench_demo_scalability",
592 "bench_demo_comparative",
593 ] {
594 assert!(main.contains(name), "{main}");
595 }
596 }
597}