realizar 0.3.2

Pure Rust ML inference engine built from scratch - model serving for GGUF and safetensors
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
439
440
441
442
443
444
445
446
447
448
449
//! Benchmark visualization using trueno-viz.
//!
//! Provides terminal-based visualizations for benchmark results including
//! histograms, sparklines, and performance comparisons.

// Statistical calculations require numeric casts that may lose precision
// on 64-bit systems, but this is acceptable for visualization purposes
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_sign_loss)]

#[cfg(feature = "visualization")]
use trueno_viz::{
    output::{TerminalEncoder, TerminalMode},
    plots::{BinStrategy, Histogram},
    prelude::Rgba,
};

#[cfg(feature = "visualization")]
use crate::error::{RealizarError, Result};

/// Benchmark result data for visualization.
#[derive(Debug, Clone)]
pub struct BenchmarkData {
    /// Name of the benchmark
    pub name: String,
    /// Latency samples in microseconds
    pub latencies_us: Vec<f64>,
    /// Throughput samples (ops/sec)
    pub throughput: Option<Vec<f64>>,
}

impl BenchmarkData {
    /// Create new benchmark data.
    #[must_use]
    pub fn new(name: impl Into<String>, latencies_us: Vec<f64>) -> Self {
        Self {
            name: name.into(),
            latencies_us,
            throughput: None,
        }
    }

    /// Add throughput data.
    #[must_use]
    pub fn with_throughput(mut self, throughput: Vec<f64>) -> Self {
        self.throughput = Some(throughput);
        self
    }

    /// Calculate statistics.
    #[must_use]
    pub fn stats(&self) -> BenchmarkStats {
        let n = self.latencies_us.len();
        if n == 0 {
            return BenchmarkStats::default();
        }

        let mut sorted = self.latencies_us.clone();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let sum: f64 = sorted.iter().sum();
        let mean = sum / n as f64;

        let variance = sorted.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / n as f64;
        let std_dev = variance.sqrt();

        let p50 = percentile(&sorted, 50.0);
        let p95 = percentile(&sorted, 95.0);
        let p99 = percentile(&sorted, 99.0);

        BenchmarkStats {
            count: n,
            mean,
            std_dev,
            min: sorted.first().copied().unwrap_or(0.0),
            max: sorted.last().copied().unwrap_or(0.0),
            p50,
            p95,
            p99,
        }
    }
}

/// Calculate percentile from sorted data.
fn percentile(sorted: &[f64], p: f64) -> f64 {
    if sorted.is_empty() {
        return 0.0;
    }
    let idx = (p / 100.0 * (sorted.len() - 1) as f64).round() as usize;
    sorted[idx.min(sorted.len() - 1)]
}

/// Statistics for benchmark results.
#[derive(Debug, Clone, Default)]
pub struct BenchmarkStats {
    /// Number of samples
    pub count: usize,
    /// Mean latency (us)
    pub mean: f64,
    /// Standard deviation (us)
    pub std_dev: f64,
    /// Minimum latency (us)
    pub min: f64,
    /// Maximum latency (us)
    pub max: f64,
    /// 50th percentile (median)
    pub p50: f64,
    /// 95th percentile
    pub p95: f64,
    /// 99th percentile
    pub p99: f64,
}

impl std::fmt::Display for BenchmarkStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "  samples: {}", self.count)?;
        writeln!(f, "  mean:    {:.2} us", self.mean)?;
        writeln!(f, "  std_dev: {:.2} us", self.std_dev)?;
        writeln!(f, "  min:     {:.2} us", self.min)?;
        writeln!(f, "  p50:     {:.2} us", self.p50)?;
        writeln!(f, "  p95:     {:.2} us", self.p95)?;
        writeln!(f, "  p99:     {:.2} us", self.p99)?;
        write!(f, "  max:     {:.2} us", self.max)
    }
}

/// Render a latency histogram to terminal.
///
/// # Errors
///
/// Returns error if visualization fails or data is empty.
#[cfg(feature = "visualization")]
pub fn render_histogram_terminal(data: &BenchmarkData, width: u32) -> Result<String> {
    if data.latencies_us.is_empty() {
        return Err(RealizarError::InvalidShape {
            reason: "No latency data to visualize".to_string(),
        });
    }

    // Convert to f32 for trueno-viz
    let latencies: Vec<f32> = data.latencies_us.iter().map(|&x| x as f32).collect();

    let hist = Histogram::new()
        .data(&latencies)
        .bins(BinStrategy::Sturges)
        .color(Rgba::rgb(70, 130, 180)) // Steel blue
        .dimensions(width * 8, 200) // Scale up for better resolution
        .build()
        .map_err(|e| RealizarError::InvalidShape {
            reason: format!("Failed to build histogram: {e}"),
        })?;

    let fb = hist
        .to_framebuffer()
        .map_err(|e| RealizarError::InvalidShape {
            reason: format!("Failed to render histogram: {e}"),
        })?;

    let encoder = TerminalEncoder::new()
        .mode(TerminalMode::Ascii)
        .width(width);

    Ok(encoder.render(&fb))
}

/// Render a latency histogram with ANSI colors.
///
/// # Errors
///
/// Returns error if visualization fails or data is empty.
#[cfg(feature = "visualization")]
pub fn render_histogram_ansi(data: &BenchmarkData, width: u32) -> Result<String> {
    if data.latencies_us.is_empty() {
        return Err(RealizarError::InvalidShape {
            reason: "No latency data to visualize".to_string(),
        });
    }

    let latencies: Vec<f32> = data.latencies_us.iter().map(|&x| x as f32).collect();

    let hist = Histogram::new()
        .data(&latencies)
        .bins(BinStrategy::Sturges)
        .color(Rgba::rgb(70, 130, 180))
        .dimensions(width * 8, 200)
        .build()
        .map_err(|e| RealizarError::InvalidShape {
            reason: format!("Failed to build histogram: {e}"),
        })?;

    let fb = hist
        .to_framebuffer()
        .map_err(|e| RealizarError::InvalidShape {
            reason: format!("Failed to render histogram: {e}"),
        })?;

    let encoder = TerminalEncoder::new()
        .mode(TerminalMode::UnicodeHalfBlock)
        .width(width);

    Ok(encoder.render(&fb))
}

/// Sparkline bar characters (8 levels).
const SPARKLINE_BARS: &[char] = &['', '', '', '', '', '', '', ''];

/// Render an ASCII sparkline for quick visualization.
///
/// This is a lightweight alternative that doesn't require trueno-viz.
#[must_use]
pub fn render_sparkline(values: &[f64], width: usize) -> String {
    if values.is_empty() {
        return String::new();
    }

    let min = values.iter().copied().fold(f64::INFINITY, f64::min);
    let max = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    let range = max - min;

    // Sample values to fit width
    let step = values.len().max(1) / width.max(1);
    let step = step.max(1);

    let mut result = String::with_capacity(width);

    for i in 0..width {
        let idx = (i * step).min(values.len() - 1);
        let value = values[idx];

        let normalized = if range > 0.0 {
            (value - min) / range
        } else {
            0.5
        };

        let bar_idx = (normalized * (SPARKLINE_BARS.len() - 1) as f64).round() as usize;
        result.push(SPARKLINE_BARS[bar_idx.min(SPARKLINE_BARS.len() - 1)]);
    }

    result
}

/// Render a simple ASCII histogram (no dependencies).
///
/// This provides basic visualization without trueno-viz.
#[must_use]
pub fn render_ascii_histogram(values: &[f64], bins: usize, width: usize) -> String {
    use std::fmt::Write;

    if values.is_empty() {
        return String::new();
    }

    let min = values.iter().copied().fold(f64::INFINITY, f64::min);
    let max = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    let range = max - min;
    let bin_width = range / bins as f64;

    // Count values in each bin
    let mut counts = vec![0usize; bins];
    for &v in values {
        let bin = if bin_width > 0.0 {
            ((v - min) / bin_width).floor() as usize
        } else {
            0
        };
        let bin = bin.min(bins - 1);
        counts[bin] += 1;
    }

    let max_count = *counts.iter().max().unwrap_or(&1);
    let scale = width as f64 / max_count as f64;

    let mut result = String::new();

    for (i, &count) in counts.iter().enumerate() {
        let bar_len = (count as f64 * scale).round() as usize;
        let bin_start = min + i as f64 * bin_width;
        let bin_end = bin_start + bin_width;

        let _ = writeln!(
            result,
            "{:>8.1}-{:<8.1} |{}",
            bin_start,
            bin_end,
            "".repeat(bar_len)
        );
    }

    result
}

/// Print benchmark results with optional visualization.
pub fn print_benchmark_results(data: &BenchmarkData, use_ansi: bool) {
    let stats = data.stats();

    println!("Benchmark: {}", data.name);
    println!("{stats}");
    println!();

    // Sparkline (always available)
    println!("  trend: {}", render_sparkline(&data.latencies_us, 40));
    println!();

    // ASCII histogram (always available)
    println!("  distribution:");
    let hist = render_ascii_histogram(&data.latencies_us, 10, 40);
    for line in hist.lines() {
        println!("    {line}");
    }

    // Full visualization if available
    #[cfg(feature = "visualization")]
    {
        println!();
        println!("  visual:");
        let rendered = if use_ansi {
            render_histogram_ansi(data, 60)
        } else {
            render_histogram_terminal(data, 60)
        };

        if let Ok(viz) = rendered {
            for line in viz.lines() {
                println!("    {line}");
            }
        }
    }

    let _ = use_ansi; // Suppress unused warning when feature disabled
}

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

    #[test]
    fn test_benchmark_data_creation() {
        let data = BenchmarkData::new("test", vec![1.0, 2.0, 3.0, 4.0, 5.0]);
        assert_eq!(data.name, "test");
        assert_eq!(data.latencies_us.len(), 5);
    }

    #[test]
    fn test_benchmark_stats() {
        let data = BenchmarkData::new("test", vec![1.0, 2.0, 3.0, 4.0, 5.0]);
        let stats = data.stats();

        assert_eq!(stats.count, 5);
        assert!((stats.mean - 3.0).abs() < 0.01);
        assert!((stats.min - 1.0).abs() < 0.01);
        assert!((stats.max - 5.0).abs() < 0.01);
    }

    #[test]
    fn test_empty_stats() {
        let data = BenchmarkData::new("empty", vec![]);
        let stats = data.stats();
        assert_eq!(stats.count, 0);
    }

    #[test]
    fn test_sparkline() {
        let values = vec![1.0, 2.0, 3.0, 4.0, 5.0, 4.0, 3.0, 2.0, 1.0];
        let sparkline = render_sparkline(&values, 9);
        assert_eq!(sparkline.chars().count(), 9);
        assert!(sparkline.contains('')); // Min
        assert!(sparkline.contains('')); // Max
    }

    #[test]
    fn test_sparkline_empty() {
        let sparkline = render_sparkline(&[], 10);
        assert!(sparkline.is_empty());
    }

    #[test]
    fn test_sparkline_constant() {
        let values = vec![5.0; 10];
        let sparkline = render_sparkline(&values, 10);
        // All same value should produce uniform bars
        let unique: std::collections::HashSet<char> = sparkline.chars().collect();
        assert_eq!(unique.len(), 1);
    }

    #[test]
    fn test_ascii_histogram() {
        let values: Vec<f64> = (0..100).map(|i| i as f64).collect();
        let hist = render_ascii_histogram(&values, 10, 40);

        assert!(!hist.is_empty());
        assert!(hist.contains(''));
        assert_eq!(hist.lines().count(), 10);
    }

    #[test]
    fn test_ascii_histogram_empty() {
        let hist = render_ascii_histogram(&[], 10, 40);
        assert!(hist.is_empty());
    }

    #[test]
    fn test_percentile() {
        let sorted = vec![1.0, 2.0, 3.0, 4.0, 5.0];
        assert!((percentile(&sorted, 0.0) - 1.0).abs() < 0.01);
        assert!((percentile(&sorted, 50.0) - 3.0).abs() < 0.01);
        assert!((percentile(&sorted, 100.0) - 5.0).abs() < 0.01);
    }

    #[test]
    fn test_percentile_empty() {
        assert!((percentile(&[], 50.0) - 0.0).abs() < 0.01);
    }

    #[test]
    fn test_stats_display() {
        let data = BenchmarkData::new("test", vec![1.0, 2.0, 3.0]);
        let stats = data.stats();
        let display = format!("{stats}");
        assert!(display.contains("mean"));
        assert!(display.contains("p50"));
        assert!(display.contains("p99"));
    }

    #[test]
    fn test_with_throughput() {
        let data = BenchmarkData::new("test", vec![1.0, 2.0]).with_throughput(vec![1000.0, 2000.0]);
        assert!(data.throughput.is_some());
        assert_eq!(data.throughput.unwrap().len(), 2);
    }

    #[cfg(feature = "visualization")]
    #[test]
    fn test_histogram_terminal() {
        let data = BenchmarkData::new("test", vec![1.0, 2.0, 3.0, 4.0, 5.0]);
        let result = render_histogram_terminal(&data, 40);
        assert!(result.is_ok());
        assert!(!result.unwrap().is_empty());
    }

    #[cfg(feature = "visualization")]
    #[test]
    fn test_histogram_empty_error() {
        let data = BenchmarkData::new("empty", vec![]);
        let result = render_histogram_terminal(&data, 40);
        assert!(result.is_err());
    }
}