aprender-serve 0.64.0

Pure Rust ML inference engine built from scratch - model serving for GGUF and safetensors
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

/// IMP-146b: Verify gap analysis calculates ratios correctly
#[test]
fn test_imp_146b_gap_analysis() {
    let realizar = ThroughputBaseline {
        server: "Realizar".to_string(),
        throughput_tps: 80.0, // Per spec: current ~80 tok/s
        p50_latency_ms: 520.0,
        p99_latency_ms: 800.0,
        cv: 0.08,
        samples: 10,
    };

    let llamacpp = ThroughputBaseline {
        server: "llama.cpp".to_string(),
        throughput_tps: 256.0, // Per spec: ~256 tok/s GPU
        p50_latency_ms: 162.0,
        p99_latency_ms: 290.0,
        cv: 0.045,
        samples: 10,
    };

    let gap = GapAnalysis {
        gap_ratio: llamacpp.throughput_tps / realizar.throughput_tps,
        throughput_gap_tps: llamacpp.throughput_tps - realizar.throughput_tps,
        parity_target_tps: llamacpp.throughput_tps * 0.8, // 80% is parity
        realizar,
        reference: llamacpp,
    };

    // IMP-146b: Gap should be ~3.2x per Five Whys analysis
    assert!(
        gap.gap_ratio > 2.5 && gap.gap_ratio < 4.0,
        "IMP-146b: Gap to llama.cpp should be ~3.2x, got {:.1}x",
        gap.gap_ratio
    );

    // IMP-146b: Parity target should be 80% of reference
    assert!(
        (gap.parity_target_tps - 204.8).abs() < 1.0,
        "IMP-146b: Parity target should be ~205 tok/s, got {:.1}",
        gap.parity_target_tps
    );

    println!("\nIMP-146b: Gap Analysis:");
    println!("  Realizar: {:.1} tok/s", gap.realizar.throughput_tps);
    println!("  llama.cpp: {:.1} tok/s", gap.reference.throughput_tps);
    println!("  Gap: {:.1}x", gap.gap_ratio);
    println!("  Target for parity: {:.1} tok/s", gap.parity_target_tps);
}

/// IMP-146c: Real-world baseline measurement against llama.cpp
#[test]
#[ignore = "Requires running llama.cpp server on port 8082"]
fn test_imp_146c_llamacpp_baseline_measurement() {
    // This test requires: llama-server -m model.gguf --host 127.0.0.1 --port 8082 -ngl 99
    let config = HttpBenchmarkConfig {
        cv_criterion: CvStoppingCriterion::new(5, 20, 0.10), // Scientific rigor
        warmup_iterations: 2,
        prompt: "Explain what machine learning is in one paragraph:".to_string(),
        max_tokens: 50,
        temperature: 0.0,
        run_preflight: true,
        filter_outliers: true,
        outlier_k_factor: 3.0,
    };

    let mut runner = HttpBenchmarkRunner::new(config);
    let result = runner
        .benchmark_llamacpp("http://127.0.0.1:8082")
        .expect("IMP-146c: llama.cpp baseline measurement should succeed");

    // IMP-146c: Build baseline from result
    let baseline = ThroughputBaseline {
        server: "llama.cpp".to_string(),
        throughput_tps: result.throughput_tps,
        p50_latency_ms: result.p50_latency_ms,
        p99_latency_ms: result.p99_latency_ms,
        cv: result.cv_at_stop,
        samples: result.sample_count,
    };

    // IMP-146c: Baseline should have reasonable values
    assert!(
        baseline.throughput_tps > 50.0,
        "IMP-146c: llama.cpp should achieve > 50 tok/s, got {:.1}",
        baseline.throughput_tps
    );
    assert!(
        baseline.cv < 0.20,
        "IMP-146c: CV should be < 20% for reliable measurement, got {:.2}",
        baseline.cv
    );

    println!("\nIMP-146c: llama.cpp Baseline Measurement:");
    println!("  Throughput: {:.1} tok/s", baseline.throughput_tps);
    println!("  P50 Latency: {:.1} ms", baseline.p50_latency_ms);
    println!("  P99 Latency: {:.1} ms", baseline.p99_latency_ms);
    println!(
        "  CV: {:.4} ({})",
        baseline.cv,
        if baseline.cv < 0.05 {
            "excellent"
        } else if baseline.cv < 0.10 {
            "good"
        } else {
            "acceptable"
        }
    );
    println!("  Samples: {}", baseline.samples);
}

/// IMP-146d: Real-world baseline measurement against Ollama
#[test]
#[ignore = "Requires running Ollama server on port 11434"]
fn test_imp_146d_ollama_baseline_measurement() {
    // This test requires: ollama serve
    let config = HttpBenchmarkConfig {
        cv_criterion: CvStoppingCriterion::new(5, 20, 0.10),
        warmup_iterations: 2,
        prompt: "Explain what machine learning is in one paragraph:".to_string(),
        max_tokens: 50,
        temperature: 0.0,
        run_preflight: true,
        filter_outliers: true,
        outlier_k_factor: 3.0,
    };

    let mut runner = HttpBenchmarkRunner::new(config);
    let result = runner
        .benchmark_ollama("http://127.0.0.1:11434", "phi2:2.7b")
        .expect("IMP-146d: Ollama baseline measurement should succeed");

    // IMP-146d: Build baseline from result
    let baseline = ThroughputBaseline {
        server: "Ollama".to_string(),
        throughput_tps: result.throughput_tps,
        p50_latency_ms: result.p50_latency_ms,
        p99_latency_ms: result.p99_latency_ms,
        cv: result.cv_at_stop,
        samples: result.sample_count,
    };

    // IMP-146d: Baseline should have reasonable values
    assert!(
        baseline.throughput_tps > 30.0,
        "IMP-146d: Ollama should achieve > 30 tok/s, got {:.1}",
        baseline.throughput_tps
    );
    assert!(
        baseline.cv < 0.20,
        "IMP-146d: CV should be < 20% for reliable measurement, got {:.2}",
        baseline.cv
    );

    println!("\nIMP-146d: Ollama Baseline Measurement:");
    println!("  Throughput: {:.1} tok/s", baseline.throughput_tps);
    println!("  P50 Latency: {:.1} ms", baseline.p50_latency_ms);
    println!("  P99 Latency: {:.1} ms", baseline.p99_latency_ms);
    println!(
        "  CV: {:.4} ({})",
        baseline.cv,
        if baseline.cv < 0.05 {
            "excellent"
        } else if baseline.cv < 0.10 {
            "good"
        } else {
            "acceptable"
        }
    );
    println!("  Samples: {}", baseline.samples);
}

// =========================================================================
// IMP-151: Real-World Throughput Regression Tests (EXTREME TDD)
// =========================================================================
// These tests track performance progress and detect regressions.
// Per Five Whys Analysis, target: 80 tok/s โ†’ 120 tok/s (P1) โ†’ 200 tok/s (P2)

/// IMP-151a: Performance milestone tracking struct
#[derive(Debug, Clone)]
pub struct PerformanceMilestone {
    /// Milestone name (e.g., "P1", "P2", "Parity")
    pub name: String,
    /// Target throughput in tokens/second
    pub target_tps: f64,
    /// Current achieved throughput
    pub achieved_tps: f64,
    /// Gap to target as percentage
    pub gap_percent: f64,
    /// Whether milestone is achieved
    pub achieved: bool,
}

impl PerformanceMilestone {
    pub fn new(name: &str, target_tps: f64, achieved_tps: f64) -> Self {
        let gap_percent = if target_tps > 0.0 {
            ((target_tps - achieved_tps) / target_tps) * 100.0
        } else {
            0.0
        };
        Self {
            name: name.to_string(),
            target_tps,
            achieved_tps,
            gap_percent,
            achieved: achieved_tps >= target_tps,
        }
    }
}

/// IMP-151a: Verify milestone tracking struct works correctly
#[test]
fn test_imp_151a_milestone_tracking() {
    // Current baseline: 80 tok/s
    let current_tps = 80.0;

    // Define milestones per Five Whys roadmap
    let p1_milestone = PerformanceMilestone::new("P1", 120.0, current_tps);
    let p2_milestone = PerformanceMilestone::new("P2", 200.0, current_tps);
    let parity_milestone = PerformanceMilestone::new("Parity", 205.0, current_tps);

    // IMP-151a: Verify milestone calculations
    assert!(
        !p1_milestone.achieved,
        "IMP-151a: P1 not yet achieved at 80 tok/s"
    );
    assert!(
        (p1_milestone.gap_percent - 33.3).abs() < 1.0,
        "IMP-151a: Gap to P1 should be ~33%, got {:.1}%",
        p1_milestone.gap_percent
    );

    assert!(!p2_milestone.achieved, "IMP-151a: P2 not yet achieved");
    assert!(
        (p2_milestone.gap_percent - 60.0).abs() < 1.0,
        "IMP-151a: Gap to P2 should be ~60%, got {:.1}%",
        p2_milestone.gap_percent
    );

    println!("\nIMP-151a: Performance Milestone Tracking:");
    println!("  Current: {:.1} tok/s", current_tps);
    println!(
        "  P1 (120 tok/s): {:.1}% gap, achieved={}",
        p1_milestone.gap_percent, p1_milestone.achieved
    );
    println!(
        "  P2 (200 tok/s): {:.1}% gap, achieved={}",
        p2_milestone.gap_percent, p2_milestone.achieved
    );
    println!(
        "  Parity (205 tok/s): {:.1}% gap, achieved={}",
        parity_milestone.gap_percent, parity_milestone.achieved
    );
}

/// IMP-151b: Regression detection struct
#[derive(Debug, Clone)]
pub struct RegressionCheck {
    /// Test name
    pub test_name: String,
    /// Baseline throughput (previous best)
    pub baseline_tps: f64,
    /// Current throughput
    pub current_tps: f64,
    /// Regression threshold percentage (e.g., 5% = flag if >5% slower)
    pub threshold_percent: f64,
    /// Whether regression detected
    pub regression_detected: bool,
    /// Improvement percentage (negative = regression)
    pub improvement_percent: f64,
}

impl RegressionCheck {
    pub fn new(
        test_name: &str,
        baseline_tps: f64,
        current_tps: f64,
        threshold_percent: f64,
    ) -> Self {
        let improvement_percent = if baseline_tps > 0.0 {
            ((current_tps - baseline_tps) / baseline_tps) * 100.0
        } else {
            0.0
        };
        let regression_detected = improvement_percent < -threshold_percent;
        Self {
            test_name: test_name.to_string(),
            baseline_tps,
            current_tps,
            threshold_percent,
            regression_detected,
            improvement_percent,
        }
    }
}

/// IMP-151b: Verify regression detection works correctly
#[test]
fn test_imp_151b_regression_detection() {
    // Scenario 1: No regression (improvement)
    let check1 = RegressionCheck::new("dequant_q4k", 80.0, 85.0, 5.0);
    assert!(
        !check1.regression_detected,
        "IMP-151b: 85 vs 80 should not be regression"
    );
    assert!(
        (check1.improvement_percent - 6.25).abs() < 0.1,
        "IMP-151b: Should show ~6.25% improvement"
    );

    // Scenario 2: Minor regression within threshold
    let check2 = RegressionCheck::new("fused_matvec", 100.0, 97.0, 5.0);
    assert!(
        !check2.regression_detected,
        "IMP-151b: 3% drop within 5% threshold"
    );

    // Scenario 3: Significant regression exceeds threshold
    let check3 = RegressionCheck::new("simd_extract", 100.0, 90.0, 5.0);
    assert!(
        check3.regression_detected,
        "IMP-151b: 10% drop should trigger regression"
    );

    println!("\nIMP-151b: Regression Detection:");
    println!(
        "  Test 1 (85 vs 80): {:.1}% change, regression={}",
        check1.improvement_percent, check1.regression_detected
    );
    println!(
        "  Test 2 (97 vs 100): {:.1}% change, regression={}",
        check2.improvement_percent, check2.regression_detected
    );
    println!(
        "  Test 3 (90 vs 100): {:.1}% change, regression={}",
        check3.improvement_percent, check3.regression_detected
    );
}

/// IMP-151c: Real-world regression test against llama.cpp baseline
#[test]
#[ignore = "Requires running llama.cpp server on port 8082"]
fn test_imp_151c_llamacpp_regression_check() {
    // This test requires: llama-server -m model.gguf --host 127.0.0.1 --port 8082 -ngl 99
    let config = HttpBenchmarkConfig {
        cv_criterion: CvStoppingCriterion::new(5, 20, 0.10),
        warmup_iterations: 2,
        prompt: "What is 2+2? Answer briefly:".to_string(),
        max_tokens: 20,
        temperature: 0.0,
        run_preflight: true,
        filter_outliers: true,
        outlier_k_factor: 3.0,
    };

    let mut runner = HttpBenchmarkRunner::new(config);
    let result = runner
        .benchmark_llamacpp("http://127.0.0.1:8082")
        .expect("IMP-151c: llama.cpp benchmark should succeed");

    // llama.cpp baseline: ~256 tok/s (per spec)
    let expected_baseline = 256.0;
    let tolerance_percent = 30.0; // Allow 30% variance for different hardware

    let check = RegressionCheck::new(
        "llamacpp_throughput",
        expected_baseline,
        result.throughput_tps,
        tolerance_percent,
    );

    println!("\nIMP-151c: llama.cpp Regression Check:");
    println!("  Expected baseline: {:.1} tok/s", expected_baseline);
    println!("  Measured: {:.1} tok/s", result.throughput_tps);
    println!("  Difference: {:.1}%", check.improvement_percent);
    println!("  Regression: {}", check.regression_detected);

    // Note: Not asserting regression here since hardware varies
    // This is for tracking, not blocking
}

/// IMP-151d: Real-world regression test against Ollama baseline
#[test]
#[ignore = "Requires running Ollama server on port 11434"]
fn test_imp_151d_ollama_regression_check() {
    // This test requires: ollama serve
    let config = HttpBenchmarkConfig {
        cv_criterion: CvStoppingCriterion::new(5, 20, 0.10),
        warmup_iterations: 2,
        prompt: "What is 2+2? Answer briefly:".to_string(),
        max_tokens: 20,
        temperature: 0.0,
        run_preflight: true,
        filter_outliers: true,
        outlier_k_factor: 3.0,
    };

    let mut runner = HttpBenchmarkRunner::new(config);
    let result = runner
        .benchmark_ollama("http://127.0.0.1:11434", "phi2:2.7b")
        .expect("IMP-151d: Ollama benchmark should succeed");

    // Ollama baseline: ~143 tok/s (per spec)
    let expected_baseline = 143.0;
    let tolerance_percent = 30.0;

    let check = RegressionCheck::new(
        "ollama_throughput",
        expected_baseline,
        result.throughput_tps,
        tolerance_percent,
    );

    println!("\nIMP-151d: Ollama Regression Check:");
    println!("  Expected baseline: {:.1} tok/s", expected_baseline);
    println!("  Measured: {:.1} tok/s", result.throughput_tps);
    println!("  Difference: {:.1}%", check.improvement_percent);
    println!("  Regression: {}", check.regression_detected);
}

// =========================================================================
// IMP-152: End-to-End Performance Comparison Benchmark (EXTREME TDD)
// Per spec ยง8.3: Side-by-side comparison of Realizar vs Ollama vs llama.cpp
// =========================================================================

/// IMP-152a: End-to-end comparison result tracking
#[derive(Debug, Clone)]
pub struct E2EComparisonResult {
    /// Realizar throughput (tok/s)
    pub realizar_tps: f64,
    /// Ollama throughput (tok/s)
    pub ollama_tps: f64,
    /// llama.cpp throughput (tok/s)
    pub llamacpp_tps: f64,
    /// Gap vs Ollama (positive = Realizar is faster)
    pub gap_vs_ollama_percent: f64,
    /// Gap vs llama.cpp (positive = Realizar is faster)
    pub gap_vs_llamacpp_percent: f64,
    /// Parity achieved (within 10% of llama.cpp)
    pub parity_achieved: bool,
    /// Timestamp of comparison
    pub timestamp: String,
}