aprender-core 0.31.2

Next-generation machine learning library in pure Rust
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
use super::*;

// ============================================================================
// Scoring tests
// ============================================================================

#[test]
fn test_score_multiple_choice_basic() {
    let scores = vec![-1.0, -2.0, -3.0, -4.0];
    let (idx, score) = score_multiple_choice(&scores, false);
    assert_eq!(idx, 0);
    assert!((score - (-1.0)).abs() < 1e-10);
}

#[test]
fn test_score_multiple_choice_second_best() {
    let scores = vec![-5.0, -1.0, -3.0, -4.0];
    let (idx, _) = score_multiple_choice(&scores, false);
    assert_eq!(idx, 1);
}

#[test]
fn test_score_multiple_choice_empty() {
    let (idx, score) = score_multiple_choice(&[], false);
    assert_eq!(idx, 0);
    assert!(score == f64::NEG_INFINITY);
}

#[test]
fn test_score_multiple_choice_single() {
    let scores = vec![-2.5];
    let (idx, score) = score_multiple_choice(&scores, false);
    assert_eq!(idx, 0);
    assert!((score - (-2.5)).abs() < 1e-10);
}

#[test]
fn test_score_multiple_choice_equal() {
    let scores = vec![-2.0, -2.0, -2.0];
    let (idx, _) = score_multiple_choice(&scores, false);
    // Any index is valid when all equal; just check it's in range
    assert!(idx < 3);
}

// ============================================================================
// Perplexity tests
// ============================================================================

#[test]
fn test_compute_perplexity_basic() {
    // PPL = exp(-LL/N)
    let ppl = compute_perplexity(-10.0, 10);
    assert!((ppl - 1.0_f64.exp()).abs() < 1e-10);
}

#[test]
fn test_compute_perplexity_zero_tokens() {
    let ppl = compute_perplexity(-5.0, 0);
    assert!(ppl == f64::INFINITY);
}

#[test]
fn test_compute_perplexity_zero_ll() {
    // exp(0) = 1.0
    let ppl = compute_perplexity(0.0, 10);
    assert!((ppl - 1.0).abs() < 1e-10);
}

#[test]
fn test_compute_perplexity_large_negative() {
    let ppl = compute_perplexity(-100.0, 10);
    // exp(10) ≈ 22026
    assert!(ppl > 20000.0);
    assert!(ppl.is_finite());
}

// ============================================================================
// Accuracy tests
// ============================================================================

#[test]
fn test_compute_accuracy_perfect() {
    let preds = vec![0, 1, 2, 3];
    let gold = vec![0, 1, 2, 3];
    assert!((compute_accuracy(&preds, &gold) - 1.0).abs() < 1e-10);
}

#[test]
fn test_compute_accuracy_zero() {
    let preds = vec![1, 2, 3, 0];
    let gold = vec![0, 1, 2, 3];
    assert!((compute_accuracy(&preds, &gold) - 0.0).abs() < 1e-10);
}

#[test]
fn test_compute_accuracy_half() {
    let preds = vec![0, 1, 0, 0];
    let gold = vec![0, 1, 2, 3];
    assert!((compute_accuracy(&preds, &gold) - 0.5).abs() < 1e-10);
}

#[test]
fn test_compute_accuracy_empty() {
    assert!((compute_accuracy(&[], &[]) - 0.0).abs() < 1e-10);
}

#[test]
fn test_compute_accuracy_mismatched_len() {
    let preds = vec![0, 1];
    let gold = vec![0, 1, 2];
    assert!((compute_accuracy(&preds, &gold) - 0.0).abs() < 1e-10);
}

// ============================================================================
// EvalTask tests
// ============================================================================

#[test]
fn test_eval_task_new() {
    let task = EvalTask::new("test_task", TaskType::MultipleChoice);
    assert_eq!(task.name, "test_task");
    assert_eq!(task.task_type, TaskType::MultipleChoice);
    assert!(task.is_empty());
    assert_eq!(task.len(), 0);
    assert_eq!(task.num_fewshot, 0);
}

#[test]
fn test_eval_task_add_example() {
    let mut task = EvalTask::new("t", TaskType::Classification);
    task.add_example(EvalExample {
        context: "ctx".to_string(),
        choices: vec!["a".to_string(), "b".to_string()],
        gold_idx: Some(0),
        reference: None,
    });
    assert_eq!(task.len(), 1);
    assert!(!task.is_empty());
}

#[test]
fn test_eval_task_with_fewshot() {
    let task = EvalTask::new("t", TaskType::MultipleChoice).with_fewshot(5);
    assert_eq!(task.num_fewshot, 5);
}

// ============================================================================
// Mock data tests
// ============================================================================

#[test]
fn test_mock_hellaswag() {
    let task = mock_hellaswag();
    assert_eq!(task.name, "hellaswag");
    assert_eq!(task.task_type, TaskType::MultipleChoice);
    assert_eq!(task.len(), 2);
    assert_eq!(task.examples[0].choices.len(), 4);
    assert_eq!(task.examples[0].gold_idx, Some(0));
    assert_eq!(task.examples[1].gold_idx, Some(1));
}

// ============================================================================
// EvalReport tests
// ============================================================================

#[test]
fn test_eval_report_from_tasks() {
    let metrics = vec![
        TaskMetrics {
            task_name: "task_a".to_string(),
            task_type: TaskType::MultipleChoice,
            num_examples: 10,
            accuracy: Some(0.8),
            perplexity: None,
            avg_log_likelihood: None,
            predictions: vec![],
        },
        TaskMetrics {
            task_name: "task_b".to_string(),
            task_type: TaskType::MultipleChoice,
            num_examples: 20,
            accuracy: Some(0.6),
            perplexity: None,
            avg_log_likelihood: None,
            predictions: vec![],
        },
    ];
    let report = EvalReport::from_tasks(metrics);
    assert_eq!(report.num_tasks, 2);
    assert_eq!(report.total_examples, 30);
    assert!((report.macro_accuracy - 0.7).abs() < 1e-10);
}

#[test]
fn test_eval_report_empty() {
    let report = EvalReport::from_tasks(vec![]);
    assert_eq!(report.num_tasks, 0);
    assert_eq!(report.total_examples, 0);
    assert!((report.macro_accuracy - 0.0).abs() < 1e-10);
}

#[test]
fn test_eval_report_perplexity_only() {
    let metrics = vec![TaskMetrics {
        task_name: "ppl_task".to_string(),
        task_type: TaskType::Perplexity,
        num_examples: 5,
        accuracy: None,
        perplexity: Some(15.3),
        avg_log_likelihood: Some(-2.5),
        predictions: vec![],
    }];
    let report = EvalReport::from_tasks(metrics);
    assert_eq!(report.num_tasks, 1);
    // No accuracy tasks → macro_accuracy = 0.0
    assert!((report.macro_accuracy - 0.0).abs() < 1e-10);
}

// ============================================================================
// Harness config tests
// ============================================================================

#[test]
fn test_harness_config_default() {
    let cfg = HarnessConfig::default();
    assert!(cfg.tasks.is_empty());
    assert!(!cfg.length_normalize);
    assert_eq!(cfg.max_examples, 0);
}

// ============================================================================
// run_harness tests
// ============================================================================

#[test]
fn test_run_harness_empty_tasks() {
    let config = HarnessConfig::default();
    let result = run_harness(&config, |_: &str, _: &str| 0.0);
    assert!(result.is_err());
}

#[test]
fn test_run_harness_multiple_choice() {
    let task = mock_hellaswag();
    let config = HarnessConfig {
        tasks: vec![task],
        length_normalize: false,
        max_examples: 0,
    };

    // Score function: longer completions get higher scores (sensible choices are longer)
    let report = run_harness(&config, |_ctx: &str, completion: &str| {
        -(completion.len() as f64)
    })
    .unwrap();

    assert_eq!(report.num_tasks, 1);
    assert_eq!(report.total_examples, 2);
    assert!(report.tasks[0].accuracy.is_some());
}

#[test]
fn test_run_harness_perfect_scorer() {
    let task = mock_hellaswag();
    let config = HarnessConfig {
        tasks: vec![task],
        length_normalize: false,
        max_examples: 0,
    };

    // Perfect scorer: gives highest score to the correct answer
    let report = run_harness(&config, |ctx: &str, completion: &str| {
        if (ctx.contains("sandwich") && completion.contains("butter"))
            || (ctx.contains("cat") && completion.contains("purred"))
        {
            0.0 // Highest (least negative)
        } else {
            -10.0
        }
    })
    .unwrap();

    assert!((report.tasks[0].accuracy.unwrap() - 1.0).abs() < 1e-10);
}

#[test]
fn test_run_harness_max_examples() {
    let mut task = mock_hellaswag();
    // Add more examples
    for i in 0..10 {
        task.add_example(EvalExample {
            context: format!("Context {}", i),
            choices: vec!["a".to_string(), "b".to_string()],
            gold_idx: Some(0),
            reference: None,
        });
    }

    let config = HarnessConfig {
        tasks: vec![task],
        length_normalize: false,
        max_examples: 3,
    };

    let report = run_harness(&config, |_: &str, _: &str| -1.0).unwrap();
    assert_eq!(report.tasks[0].num_examples, 3);
}

#[test]
fn test_run_harness_perplexity() {
    let mut task = EvalTask::new("ppl_test", TaskType::Perplexity);
    task.add_example(EvalExample {
        context: "The quick brown fox".to_string(),
        choices: vec![],
        gold_idx: None,
        reference: Some("The quick brown fox jumps over the lazy dog".to_string()),
    });
    task.add_example(EvalExample {
        context: "Hello world".to_string(),
        choices: vec![],
        gold_idx: None,
        reference: None, // Falls back to context
    });

    let config = HarnessConfig {
        tasks: vec![task],
        length_normalize: false,
        max_examples: 0,
    };

    let report = run_harness(&config, |_: &str, text: &str| {
        // Fake log-likelihood: -0.5 per whitespace-delimited token
        -(text.split_whitespace().count() as f64) * 0.5
    })
    .unwrap();

    assert!(report.tasks[0].perplexity.is_some());
    let ppl = report.tasks[0].perplexity.unwrap();
    assert!(ppl > 0.0);
    assert!(ppl.is_finite());
    assert!(report.tasks[0].avg_log_likelihood.is_some());
}

#[test]
fn test_run_harness_generation() {
    let mut task = EvalTask::new("gen_test", TaskType::Generation);
    task.add_example(EvalExample {
        context: "Translate: hello".to_string(),
        choices: vec![],
        gold_idx: None,
        reference: Some("hola".to_string()),
    });

    let config = HarnessConfig {
        tasks: vec![task],
        length_normalize: false,
        max_examples: 0,
    };

    let report = run_harness(&config, |_: &str, _: &str| 0.0).unwrap();
    // Generation returns placeholder metrics
    assert!(report.tasks[0].accuracy.is_none());
    assert!(report.tasks[0].perplexity.is_none());
}

#[test]
fn test_run_harness_multi_task() {
    let mc_task = mock_hellaswag();
    let mut ppl_task = EvalTask::new("ppl", TaskType::Perplexity);
    ppl_task.add_example(EvalExample {
        context: "test text".to_string(),
        choices: vec![],
        gold_idx: None,
        reference: None,
    });

    let config = HarnessConfig {
        tasks: vec![mc_task, ppl_task],
        length_normalize: false,
        max_examples: 0,
    };

    let report = run_harness(&config, |_: &str, _: &str| -1.0).unwrap();
    assert_eq!(report.num_tasks, 2);
}

// ============================================================================
// Falsification tests
// ============================================================================

/// FALSIFY-EVAL-001: Perplexity is always positive.
#[test]
fn falsify_eval_001_perplexity_positive() {
    for ll in [-100.0, -10.0, -1.0, 0.0, 1.0] {
        for tokens in [1, 5, 10, 100, 1000] {
            let ppl = compute_perplexity(ll, tokens);
            assert!(
                ppl > 0.0,
                "PPL must be > 0, got {} for ll={}, tokens={}",
                ppl,
                ll,
                tokens
            );
        }
    }
}

/// FALSIFY-EVAL-002: Accuracy is bounded in [0.0, 1.0].
#[test]
fn falsify_eval_002_accuracy_bounded() {
    let test_cases: Vec<(Vec<usize>, Vec<usize>)> = vec![
        (vec![0, 0, 0, 0], vec![0, 0, 0, 0]),
        (vec![0, 1, 2, 3], vec![3, 2, 1, 0]),
        (vec![0, 1, 0, 1], vec![0, 0, 1, 1]),
        (vec![0], vec![0]),
    ];

    for (preds, gold) in &test_cases {
        let acc = compute_accuracy(preds, gold);
        assert!(
            (0.0..=1.0).contains(&acc),
            "Accuracy must be in [0,1], got {} for {:?} vs {:?}",
            acc,
            preds,
            gold
        );
    }
}

/// FALSIFY-EVAL-003: Harness report aggregation is consistent.
#[test]
fn falsify_eval_003_report_consistency() {
    let metrics = vec![
        TaskMetrics {
            task_name: "a".to_string(),
            task_type: TaskType::MultipleChoice,
            num_examples: 100,
            accuracy: Some(0.9),
            perplexity: None,
            avg_log_likelihood: None,
            predictions: vec![],
        },
        TaskMetrics {
            task_name: "b".to_string(),
            task_type: TaskType::Classification,
            num_examples: 50,
            accuracy: Some(0.7),
            perplexity: None,
            avg_log_likelihood: None,
            predictions: vec![],
        },
        TaskMetrics {
            task_name: "c".to_string(),
            task_type: TaskType::Perplexity,
            num_examples: 25,
            accuracy: None,
            perplexity: Some(10.0),
            avg_log_likelihood: Some(-2.3),
            predictions: vec![],
        },
    ];

    let report = EvalReport::from_tasks(metrics);

    // Total examples = sum of all tasks
    assert_eq!(report.total_examples, 175);
    // num_tasks = number of tasks
    assert_eq!(report.num_tasks, 3);
    // macro_accuracy = mean of non-None accuracies only
    let expected_macro = (0.9 + 0.7) / 2.0;
    assert!(
        (report.macro_accuracy - expected_macro).abs() < 1e-10,
        "Macro accuracy should be mean of accuracy tasks only, got {}",
        report.macro_accuracy
    );
}