tenflowers-core 0.1.1

Core tensor operations and execution engine for TenfloweRS
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! Performance benchmarking for optimized operations
//!
//! This module provides benchmarking utilities to measure and compare
//! the performance of optimized vs original tensor operations.

use crate::{Result, Tensor};
use std::time::{Duration, Instant};

/// Benchmark configuration
#[derive(Debug, Clone)]
pub struct BenchmarkConfig {
    pub warmup_iterations: usize,
    pub measurement_iterations: usize,
    pub sizes: Vec<usize>,
    pub verify_correctness: bool,
}

impl Default for BenchmarkConfig {
    fn default() -> Self {
        Self {
            warmup_iterations: 5,
            measurement_iterations: 10,
            sizes: vec![1000, 10000, 100000, 1000000],
            verify_correctness: true,
        }
    }
}

/// Benchmark result
#[derive(Debug, Clone)]
pub struct BenchmarkResult {
    pub operation: String,
    pub size: usize,
    pub original_time: Duration,
    pub optimized_time: Duration,
    pub speedup: f64,
    pub throughput_original: f64,  // elements per second
    pub throughput_optimized: f64, // elements per second
    pub correctness_verified: bool,
}

impl BenchmarkResult {
    pub fn new(
        operation: String,
        size: usize,
        original_time: Duration,
        optimized_time: Duration,
        correctness_verified: bool,
    ) -> Self {
        let speedup = original_time.as_nanos() as f64 / optimized_time.as_nanos() as f64;
        let throughput_original = size as f64 / original_time.as_secs_f64();
        let throughput_optimized = size as f64 / optimized_time.as_secs_f64();

        Self {
            operation,
            size,
            original_time,
            optimized_time,
            speedup,
            throughput_original,
            throughput_optimized,
            correctness_verified,
        }
    }
}

/// Binary operation benchmark suite
pub fn benchmark_binary_operations(config: BenchmarkConfig) -> Result<Vec<BenchmarkResult>> {
    let mut results = Vec::new();

    for &size in &config.sizes {
        println!("Benchmarking size: {size}");

        // Test addition
        if let Ok(result) = benchmark_add_f32(size, &config) {
            results.push(result);
        }

        // Test multiplication
        if let Ok(_result) = benchmark_mul_f32(size, &config) {}

        // Test subtraction
        if let Ok(result) = benchmark_sub_f32(size, &config) {
            results.push(result);
        }

        // Test division
        if let Ok(result) = benchmark_div_f32(size, &config) {
            results.push(result);
        }
    }

    Ok(results)
}

/// Benchmark addition operation
fn benchmark_add_f32(size: usize, config: &BenchmarkConfig) -> Result<BenchmarkResult> {
    // Create test data
    let a_data: Vec<f32> = (0..size).map(|i| i as f32).collect();
    let b_data: Vec<f32> = (0..size).map(|i| (i as f32) + 1.0).collect();

    let a = Tensor::from_vec(a_data, &[size])?;
    let b = Tensor::from_vec(b_data, &[size])?;

    // Warmup for original implementation
    for _ in 0..config.warmup_iterations {
        let _ = super::binary::add(&a, &b)?;
    }

    // Benchmark original implementation
    let start = Instant::now();
    for _ in 0..config.measurement_iterations {
        let _ = super::binary::add(&a, &b)?;
    }
    let original_time = start.elapsed() / config.measurement_iterations as u32;

    // Warmup for optimized implementation
    for _ in 0..config.warmup_iterations {
        let _ = super::optimized_binary::optimized_add(&a, &b)?;
    }

    // Benchmark optimized implementation
    let start = Instant::now();
    for _ in 0..config.measurement_iterations {
        let _ = super::optimized_binary::optimized_add(&a, &b)?;
    }
    let optimized_time = start.elapsed() / config.measurement_iterations as u32;

    // Verify correctness
    let correctness_verified = if config.verify_correctness {
        let original_result = super::binary::add(&a, &b)?;
        let optimized_result = super::optimized_binary::optimized_add(&a, &b)?;

        // Compare results element-wise with small tolerance for floating point
        let orig_data = original_result.to_vec()?;
        let opt_data = optimized_result.to_vec()?;

        orig_data
            .iter()
            .zip(opt_data.iter())
            .all(|(o, p)| (o - p).abs() < 1e-6)
    } else {
        true
    };

    Ok(BenchmarkResult::new(
        "Add".to_string(),
        size,
        original_time,
        optimized_time,
        correctness_verified,
    ))
}

/// Benchmark multiplication operation
fn benchmark_mul_f32(size: usize, config: &BenchmarkConfig) -> Result<BenchmarkResult> {
    // Create test data
    let a_data: Vec<f32> = (0..size).map(|i| (i as f32) + 1.0).collect();
    let b_data: Vec<f32> = (0..size).map(|i| (i as f32) + 2.0).collect();

    let a = Tensor::from_vec(a_data, &[size])?;
    let b = Tensor::from_vec(b_data, &[size])?;

    // Warmup and benchmark original
    for _ in 0..config.warmup_iterations {
        let _ = super::binary::mul(&a, &b)?;
    }

    let start = Instant::now();
    for _ in 0..config.measurement_iterations {
        let _ = super::binary::mul(&a, &b)?;
    }
    let original_time = start.elapsed() / config.measurement_iterations as u32;

    // Warmup and benchmark optimized
    for _ in 0..config.warmup_iterations {
        let _ = super::optimized_binary::optimized_mul(&a, &b)?;
    }

    let start = Instant::now();
    for _ in 0..config.measurement_iterations {
        let _ = super::optimized_binary::optimized_mul(&a, &b)?;
    }
    let optimized_time = start.elapsed() / config.measurement_iterations as u32;

    let correctness_verified = if config.verify_correctness {
        let original_result = super::binary::mul(&a, &b)?;
        let optimized_result = super::optimized_binary::optimized_mul(&a, &b)?;

        let orig_data = original_result.to_vec()?;
        let opt_data = optimized_result.to_vec()?;

        orig_data
            .iter()
            .zip(opt_data.iter())
            .all(|(o, p)| (o - p).abs() < 1e-6)
    } else {
        true
    };

    Ok(BenchmarkResult::new(
        "Mul".to_string(),
        size,
        original_time,
        optimized_time,
        correctness_verified,
    ))
}

/// Benchmark subtraction operation
fn benchmark_sub_f32(size: usize, config: &BenchmarkConfig) -> Result<BenchmarkResult> {
    let a_data: Vec<f32> = (0..size).map(|i| (i as f32) + 5.0).collect();
    let b_data: Vec<f32> = (0..size).map(|i| (i as f32) + 1.0).collect();

    let a = Tensor::from_vec(a_data, &[size])?;
    let b = Tensor::from_vec(b_data, &[size])?;

    // Warmup and benchmark original
    for _ in 0..config.warmup_iterations {
        let _ = super::binary::sub(&a, &b)?;
    }

    let start = Instant::now();
    for _ in 0..config.measurement_iterations {
        let _ = super::binary::sub(&a, &b)?;
    }
    let original_time = start.elapsed() / config.measurement_iterations as u32;

    // Warmup and benchmark optimized
    for _ in 0..config.warmup_iterations {
        let _ = super::optimized_binary::optimized_sub(&a, &b)?;
    }

    let start = Instant::now();
    for _ in 0..config.measurement_iterations {
        let _ = super::optimized_binary::optimized_sub(&a, &b)?;
    }
    let optimized_time = start.elapsed() / config.measurement_iterations as u32;

    let correctness_verified = if config.verify_correctness {
        let original_result = super::binary::sub(&a, &b)?;
        let optimized_result = super::optimized_binary::optimized_sub(&a, &b)?;

        let orig_data = original_result.to_vec()?;
        let opt_data = optimized_result.to_vec()?;

        orig_data
            .iter()
            .zip(opt_data.iter())
            .all(|(o, p)| (o - p).abs() < 1e-6)
    } else {
        true
    };

    Ok(BenchmarkResult::new(
        "Sub".to_string(),
        size,
        original_time,
        optimized_time,
        correctness_verified,
    ))
}

/// Benchmark division operation
fn benchmark_div_f32(size: usize, config: &BenchmarkConfig) -> Result<BenchmarkResult> {
    let a_data: Vec<f32> = (0..size).map(|i| (i as f32) + 10.0).collect();
    let b_data: Vec<f32> = (0..size).map(|i| (i as f32) + 2.0).collect();

    let a = Tensor::from_vec(a_data, &[size])?;
    let b = Tensor::from_vec(b_data, &[size])?;

    // Warmup and benchmark original
    for _ in 0..config.warmup_iterations {
        let _ = super::binary::div(&a, &b)?;
    }

    let start = Instant::now();
    for _ in 0..config.measurement_iterations {
        let _ = super::binary::div(&a, &b)?;
    }
    let original_time = start.elapsed() / config.measurement_iterations as u32;

    // Warmup and benchmark optimized
    for _ in 0..config.warmup_iterations {
        let _ = super::optimized_binary::optimized_div(&a, &b)?;
    }

    let start = Instant::now();
    for _ in 0..config.measurement_iterations {
        let _ = super::optimized_binary::optimized_div(&a, &b)?;
    }
    let optimized_time = start.elapsed() / config.measurement_iterations as u32;

    let correctness_verified = if config.verify_correctness {
        let original_result = super::binary::div(&a, &b)?;
        let optimized_result = super::optimized_binary::optimized_div(&a, &b)?;

        let orig_data = original_result.to_vec()?;
        let opt_data = optimized_result.to_vec()?;

        orig_data
            .iter()
            .zip(opt_data.iter())
            .all(|(o, p)| (o - p).abs() < 1e-6)
    } else {
        true
    };

    Ok(BenchmarkResult::new(
        "Div".to_string(),
        size,
        original_time,
        optimized_time,
        correctness_verified,
    ))
}

/// Print benchmark results in a formatted table
pub fn print_benchmark_results(results: &[BenchmarkResult]) {
    println!("\n{:-<100}", "");
    println!(
        "| {:^12} | {:^12} | {:^12} | {:^12} | {:^10} | {:^15} | {:^15} |",
        "Operation",
        "Size",
        "Original (μs)",
        "Optimized (μs)",
        "Speedup",
        "Orig Throughput",
        "Opt Throughput"
    );
    println!("{:-<100}", "");

    for result in results {
        let orig_us = result.original_time.as_micros();
        let opt_us = result.optimized_time.as_micros();
        let orig_throughput = format!("{:.1e}", result.throughput_original);
        let opt_throughput = format!("{:.1e}", result.throughput_optimized);

        println!(
            "| {:^12} | {:^12} | {:^12} | {:^12} | {:^10.2} | {:^15} | {:^15} |",
            result.operation,
            result.size,
            orig_us,
            opt_us,
            result.speedup,
            orig_throughput,
            opt_throughput
        );

        if !result.correctness_verified {
            println!(
                "  ⚠️  WARNING: Correctness verification failed for {} size {}",
                result.operation, result.size
            );
        }
    }
    println!("{:-<100}", "");

    // Summary statistics
    let avg_speedup: f64 = results.iter().map(|r| r.speedup).sum::<f64>() / results.len() as f64;
    let max_speedup = results.iter().map(|r| r.speedup).fold(0.0, f64::max);
    let min_speedup = results
        .iter()
        .map(|r| r.speedup)
        .fold(f64::INFINITY, f64::min);

    println!("Summary:");
    println!("  Average speedup: {avg_speedup:.2}x");
    println!("  Maximum speedup: {max_speedup:.2}x");
    println!("  Minimum speedup: {min_speedup:.2}x");

    let correctness_issues = results.iter().filter(|r| !r.correctness_verified).count();
    if correctness_issues > 0 {
        println!("  ⚠️  {correctness_issues} correctness verification failures");
    } else {
        println!("  ✅ All correctness verifications passed");
    }
}

/// Run a complete benchmark suite and return results
pub fn run_performance_benchmark() -> Result<Vec<BenchmarkResult>> {
    println!("Running TenfloweRS CPU Performance Benchmark");
    println!("Testing optimized vs original binary operations...\n");

    let config = BenchmarkConfig::default();
    let results = benchmark_binary_operations(config)?;

    print_benchmark_results(&results);

    Ok(results)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_benchmark_correctness() {
        let config = BenchmarkConfig {
            warmup_iterations: 1,
            measurement_iterations: 1,
            sizes: vec![1000],
            verify_correctness: true,
        };

        let results = benchmark_binary_operations(config)
            .expect("test: benchmark_binary_operations should succeed");

        // All results should have correctness verified
        for result in &results {
            assert!(
                result.correctness_verified,
                "Correctness verification failed for {}",
                result.operation
            );
        }

        // Should have results for all operations
        assert!(!results.is_empty());
    }

    #[test]
    fn test_small_benchmark() {
        let config = BenchmarkConfig {
            warmup_iterations: 1,
            measurement_iterations: 2,
            sizes: vec![100],
            verify_correctness: true,
        };

        let results = benchmark_binary_operations(config)
            .expect("test: benchmark_binary_operations should succeed");
        assert!(!results.is_empty());

        // Print results for manual inspection
        print_benchmark_results(&results);
    }
}