aprender-train-bench 0.36.0

Distillation benchmarking and hyperparameter sweep tool
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! Distillation strategy comparison.

use crate::stats::StatisticalAnalyzer;
use entrenar_common::Result;

/// A distillation strategy to benchmark.
#[derive(Debug, Clone)]
pub enum DistillStrategy {
    /// Knowledge distillation only (soft targets)
    KDOnly { temperature: f32, alpha: f32 },
    /// Progressive distillation (hidden state matching)
    Progressive {
        temperature: f32,
        alpha: f32,
        layer_weight: f32,
    },
    /// Attention transfer
    Attention {
        temperature: f32,
        alpha: f32,
        attention_weight: f32,
    },
    /// Combined approach
    Combined {
        temperature: f32,
        alpha: f32,
        layer_weight: f32,
        attention_weight: f32,
    },
}

impl DistillStrategy {
    /// Get strategy name.
    pub fn name(&self) -> &'static str {
        match self {
            Self::KDOnly { .. } => "KD-only",
            Self::Progressive { .. } => "Progressive",
            Self::Attention { .. } => "Attention",
            Self::Combined { .. } => "Combined",
        }
    }

    /// Default KD-only strategy.
    pub fn kd_only() -> Self {
        Self::KDOnly {
            temperature: 4.0,
            alpha: 0.7,
        }
    }

    /// Default progressive strategy.
    pub fn progressive() -> Self {
        Self::Progressive {
            temperature: 4.0,
            alpha: 0.7,
            layer_weight: 0.3,
        }
    }

    /// Default attention strategy.
    pub fn attention() -> Self {
        Self::Attention {
            temperature: 4.0,
            alpha: 0.7,
            attention_weight: 0.1,
        }
    }

    /// Default combined strategy.
    pub fn combined() -> Self {
        Self::Combined {
            temperature: 4.0,
            alpha: 0.7,
            layer_weight: 0.3,
            attention_weight: 0.1,
        }
    }

    /// Simulate training with this strategy.
    fn simulate(&self, seed: u64) -> StrategyMetrics {
        let noise = (seed as f64 * 0.1).sin() * 0.02;

        let (base_loss, base_accuracy, time_factor) = match self {
            Self::KDOnly { .. } => (0.82, 0.782, 1.0),
            Self::Progressive { .. } => (0.75, 0.818, 1.15),
            Self::Attention { .. } => (0.78, 0.796, 1.08),
            Self::Combined { .. } => (0.71, 0.831, 1.25),
        };

        StrategyMetrics {
            final_loss: base_loss + noise,
            final_accuracy: base_accuracy + noise * 0.5,
            training_time_hours: 2.0 * time_factor + noise * 0.5,
            peak_memory_gb: 16.0 + noise * 2.0,
        }
    }
}

/// Metrics from running a strategy.
#[derive(Debug, Clone)]
pub struct StrategyMetrics {
    /// Final training loss
    pub final_loss: f64,
    /// Final accuracy/score
    pub final_accuracy: f64,
    /// Training time in hours
    pub training_time_hours: f64,
    /// Peak memory usage in GB
    pub peak_memory_gb: f64,
}

/// Result of comparing strategies.
#[derive(Debug, Clone)]
pub struct StrategyComparison {
    /// Results per strategy
    pub results: Vec<StrategyResult>,
    /// Best strategy by loss
    pub best_by_loss: Option<String>,
    /// Best strategy by accuracy
    pub best_by_accuracy: Option<String>,
    /// Statistical significance of differences
    pub significance: Vec<PairwiseComparison>,
}

/// Result for a single strategy.
#[derive(Debug, Clone)]
pub struct StrategyResult {
    /// Strategy name
    pub name: String,
    /// Mean metrics across runs
    pub mean_loss: f64,
    /// Standard deviation
    pub std_loss: f64,
    /// Mean accuracy
    pub mean_accuracy: f64,
    /// Standard deviation
    pub std_accuracy: f64,
    /// Mean training time
    pub mean_time_hours: f64,
    /// Number of runs
    pub runs: usize,
}

/// Pairwise statistical comparison.
#[derive(Debug, Clone)]
pub struct PairwiseComparison {
    /// First strategy
    pub strategy1: String,
    /// Second strategy
    pub strategy2: String,
    /// P-value for difference
    pub p_value: f64,
    /// Whether difference is significant
    pub significant: bool,
    /// Effect size
    pub effect_size: f64,
}

/// Compare multiple strategies.
pub fn compare(strategies: &[DistillStrategy]) -> Result<StrategyComparison> {
    let runs_per_strategy = 5;
    let mut results = Vec::new();
    let mut all_losses: Vec<(String, Vec<f64>)> = Vec::new();

    for strategy in strategies {
        let mut losses = Vec::new();
        let mut accuracies = Vec::new();
        let mut times = Vec::new();

        for run in 0..runs_per_strategy {
            let metrics = strategy.simulate(run as u64);
            losses.push(metrics.final_loss);
            accuracies.push(metrics.final_accuracy);
            times.push(metrics.training_time_hours);
        }

        let n = losses.len() as f64;
        let mean_loss = losses.iter().sum::<f64>() / n;
        let mean_accuracy = accuracies.iter().sum::<f64>() / n;
        let mean_time = times.iter().sum::<f64>() / n;

        let std_loss =
            (losses.iter().map(|x| (x - mean_loss).powi(2)).sum::<f64>() / (n - 1.0)).sqrt();
        let std_accuracy = (accuracies
            .iter()
            .map(|x| (x - mean_accuracy).powi(2))
            .sum::<f64>()
            / (n - 1.0))
            .sqrt();

        results.push(StrategyResult {
            name: strategy.name().to_string(),
            mean_loss,
            std_loss,
            mean_accuracy,
            std_accuracy,
            mean_time_hours: mean_time,
            runs: runs_per_strategy,
        });

        all_losses.push((strategy.name().to_string(), losses));
    }

    // Find best
    let best_by_loss = results
        .iter()
        .min_by(|a, b| {
            a.mean_loss
                .partial_cmp(&b.mean_loss)
                .unwrap_or(std::cmp::Ordering::Equal)
        })
        .map(|r| r.name.clone());

    let best_by_accuracy = results
        .iter()
        .max_by(|a, b| {
            a.mean_accuracy
                .partial_cmp(&b.mean_accuracy)
                .unwrap_or(std::cmp::Ordering::Equal)
        })
        .map(|r| r.name.clone());

    // Pairwise comparisons
    let mut significance = Vec::new();
    for i in 0..all_losses.len() {
        for j in (i + 1)..all_losses.len() {
            let (name1, losses1) = &all_losses[i];
            let (name2, losses2) = &all_losses[j];

            let test = StatisticalAnalyzer::welch_t_test(losses1, losses2);

            significance.push(PairwiseComparison {
                strategy1: name1.clone(),
                strategy2: name2.clone(),
                p_value: test.p_value,
                significant: test.significant,
                effect_size: test.effect_size,
            });
        }
    }

    Ok(StrategyComparison {
        results,
        best_by_loss,
        best_by_accuracy,
        significance,
    })
}

impl StrategyComparison {
    /// Format as ASCII table.
    pub fn to_table(&self) -> String {
        let mut output = String::from("Strategy Comparison\n");
        output.push_str("┌──────────────┬─────────────────┬─────────────────┬────────────┐\n");
        output.push_str("│ Strategy     │ Loss            │ Accuracy        │ Time (h)   │\n");
        output.push_str("├──────────────┼─────────────────┼─────────────────┼────────────┤\n");

        for result in &self.results {
            let loss_marker = if self.best_by_loss.as_ref() == Some(&result.name) {
                ""
            } else {
                ""
            };
            let acc_marker = if self.best_by_accuracy.as_ref() == Some(&result.name) {
                ""
            } else {
                ""
            };

            output.push_str(&format!(
                "│ {:12} │ {:.3} ± {:.3}{:2}{:.1}% ± {:.1}%{:2} │ {:>10.1} │\n",
                result.name,
                result.mean_loss,
                result.std_loss,
                loss_marker,
                result.mean_accuracy * 100.0,
                result.std_accuracy * 100.0,
                acc_marker,
                result.mean_time_hours
            ));
        }

        output.push_str("└──────────────┴─────────────────┴─────────────────┴────────────┘\n");

        // Significance
        output.push_str("\nStatistical Significance:\n");
        for comp in &self.significance {
            let sig = if comp.significant { "" } else { "" };
            output.push_str(&format!(
                "  {} vs {}: p={:.4} {} (effect={:.2})\n",
                comp.strategy1, comp.strategy2, comp.p_value, sig, comp.effect_size
            ));
        }

        output
    }
}

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

    #[test]
    fn test_strategy_names() {
        assert_eq!(DistillStrategy::kd_only().name(), "KD-only");
        assert_eq!(DistillStrategy::progressive().name(), "Progressive");
        assert_eq!(DistillStrategy::attention().name(), "Attention");
        assert_eq!(DistillStrategy::combined().name(), "Combined");
    }

    #[test]
    fn test_compare_strategies() {
        let strategies = vec![
            DistillStrategy::kd_only(),
            DistillStrategy::progressive(),
            DistillStrategy::combined(),
        ];

        let comparison = compare(&strategies).expect("operation should succeed");

        assert_eq!(comparison.results.len(), 3);
        assert!(comparison.best_by_loss.is_some());
        assert!(comparison.best_by_accuracy.is_some());
    }

    #[test]
    fn test_combined_is_best() {
        let strategies = vec![DistillStrategy::kd_only(), DistillStrategy::combined()];

        let comparison = compare(&strategies).expect("operation should succeed");

        // Combined should generally be best
        assert_eq!(comparison.best_by_accuracy.as_deref(), Some("Combined"));
    }

    #[test]
    fn test_comparison_table() {
        let strategies = vec![DistillStrategy::kd_only(), DistillStrategy::progressive()];

        let comparison = compare(&strategies).expect("operation should succeed");
        let table = comparison.to_table();

        assert!(table.contains("KD-only"));
        assert!(table.contains("Progressive"));
        assert!(table.contains("Significance"));
    }

    #[test]
    fn test_strategy_constructors() {
        let kd = DistillStrategy::kd_only();
        if let DistillStrategy::KDOnly { temperature, alpha } = kd {
            assert_eq!(temperature, 4.0);
            assert_eq!(alpha, 0.7);
        } else {
            panic!("Expected KDOnly");
        }

        let prog = DistillStrategy::progressive();
        if let DistillStrategy::Progressive {
            temperature,
            alpha,
            layer_weight,
        } = prog
        {
            assert_eq!(temperature, 4.0);
            assert_eq!(alpha, 0.7);
            assert_eq!(layer_weight, 0.3);
        } else {
            panic!("Expected Progressive");
        }

        let attn = DistillStrategy::attention();
        if let DistillStrategy::Attention {
            temperature,
            alpha,
            attention_weight,
        } = attn
        {
            assert_eq!(temperature, 4.0);
            assert_eq!(alpha, 0.7);
            assert_eq!(attention_weight, 0.1);
        } else {
            panic!("Expected Attention");
        }

        let combined = DistillStrategy::combined();
        if let DistillStrategy::Combined {
            temperature,
            alpha,
            layer_weight,
            attention_weight,
        } = combined
        {
            assert_eq!(temperature, 4.0);
            assert_eq!(alpha, 0.7);
            assert_eq!(layer_weight, 0.3);
            assert_eq!(attention_weight, 0.1);
        } else {
            panic!("Expected Combined");
        }
    }

    #[test]
    fn test_strategy_simulate_deterministic() {
        let strategy = DistillStrategy::kd_only();
        let metrics1 = strategy.simulate(42);
        let metrics2 = strategy.simulate(42);

        // Same seed should produce same results
        assert_eq!(metrics1.final_loss, metrics2.final_loss);
        assert_eq!(metrics1.final_accuracy, metrics2.final_accuracy);
    }

    #[test]
    fn test_strategy_simulate_different_seeds() {
        let strategy = DistillStrategy::kd_only();
        let metrics1 = strategy.simulate(1);
        let metrics2 = strategy.simulate(2);

        // Different seeds should produce different results (due to noise)
        assert_ne!(metrics1.final_loss, metrics2.final_loss);
    }

    #[test]
    fn test_strategy_metrics_fields() {
        let metrics = StrategyMetrics {
            final_loss: 0.75,
            final_accuracy: 0.82,
            training_time_hours: 2.5,
            peak_memory_gb: 16.0,
        };

        assert_eq!(metrics.final_loss, 0.75);
        assert_eq!(metrics.final_accuracy, 0.82);
        assert_eq!(metrics.training_time_hours, 2.5);
        assert_eq!(metrics.peak_memory_gb, 16.0);
    }

    #[test]
    fn test_strategy_result_fields() {
        let result = StrategyResult {
            name: "test".to_string(),
            mean_loss: 0.7,
            std_loss: 0.02,
            mean_accuracy: 0.85,
            std_accuracy: 0.01,
            mean_time_hours: 3.0,
            runs: 5,
        };

        assert_eq!(result.name, "test");
        assert_eq!(result.runs, 5);
    }

    #[test]
    fn test_pairwise_comparison_fields() {
        let comp = PairwiseComparison {
            strategy1: "A".to_string(),
            strategy2: "B".to_string(),
            p_value: 0.03,
            significant: true,
            effect_size: 0.8,
        };

        assert!(comp.significant);
        assert_eq!(comp.effect_size, 0.8);
    }

    #[test]
    fn test_comparison_significance_markers() {
        let strategies = vec![DistillStrategy::kd_only(), DistillStrategy::combined()];

        let comparison = compare(&strategies).expect("operation should succeed");

        // Should have one pairwise comparison
        assert_eq!(comparison.significance.len(), 1);
    }

    #[test]
    fn test_compare_all_strategies() {
        let strategies = vec![
            DistillStrategy::kd_only(),
            DistillStrategy::progressive(),
            DistillStrategy::attention(),
            DistillStrategy::combined(),
        ];

        let comparison = compare(&strategies).expect("operation should succeed");

        // 4 choose 2 = 6 pairwise comparisons
        assert_eq!(comparison.significance.len(), 6);
        assert_eq!(comparison.results.len(), 4);
    }

    #[test]
    fn test_comparison_table_star_markers() {
        let strategies = vec![DistillStrategy::kd_only(), DistillStrategy::combined()];

        let comparison = compare(&strategies).expect("operation should succeed");
        let table = comparison.to_table();

        // Should have star marker for best
        assert!(table.contains(''));
    }
}