aprender-core 0.29.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
// ============================================================================
// FALSIFICATION TESTS (F-CODES) - POPPER METHODOLOGY
// ============================================================================

#[test]
fn test_chat_template_falsification() {
    // F001-F010: Template Loading
    // These test that valid templates DON'T produce false errors

    // F001: Valid ChatML template must not fail
    let template = ChatMLTemplate::new();
    let messages = vec![ChatMessage::user("Test")];
    let result = template.format_conversation(&messages);
    assert!(result.is_ok(), "F001: Valid ChatML must not fail");

    // F002: Valid LLaMA2 template must not fail
    let template = Llama2Template::new();
    let result = template.format_conversation(&messages);
    assert!(result.is_ok(), "F002: Valid LLaMA2 must not fail");

    // F003: Valid Mistral template must not fail
    let template = MistralTemplate::new();
    let result = template.format_conversation(&messages);
    assert!(result.is_ok(), "F003: Valid Mistral must not fail");

    // F004: Valid Phi template must not fail
    let template = PhiTemplate::new();
    let result = template.format_conversation(&messages);
    assert!(result.is_ok(), "F004: Valid Phi must not fail");

    // F005: Valid Alpaca template must not fail
    let template = AlpacaTemplate::new();
    let result = template.format_conversation(&messages);
    assert!(result.is_ok(), "F005: Valid Alpaca must not fail");

    // F006: Valid Raw template must not fail
    let template = RawTemplate::new();
    let result = template.format_conversation(&messages);
    assert!(result.is_ok(), "F006: Valid Raw must not fail");

    // F007: create_template must return working template
    for format in [
        TemplateFormat::ChatML,
        TemplateFormat::Llama2,
        TemplateFormat::Mistral,
        TemplateFormat::Phi,
        TemplateFormat::Alpaca,
        TemplateFormat::Raw,
    ] {
        let template = create_template(format);
        let result = template.format_conversation(&messages);
        assert!(
            result.is_ok(),
            "F007: create_template({:?}) must work",
            format
        );
    }

    // F008: auto_detect_template must return working template
    for model in [
        "qwen2",
        "tinyllama",
        "mistral",
        "phi-2",
        "alpaca",
        "unknown",
    ] {
        let template = auto_detect_template(model);
        let result = template.format_conversation(&messages);
        assert!(
            result.is_ok(),
            "F008: auto_detect_template('{}') must work",
            model
        );
    }

    // F011-F020: Special Tokens - must be correctly identified

    // F011: ChatML must have correct special tokens
    let template = ChatMLTemplate::new();
    let tokens = template.special_tokens();
    assert!(
        tokens.im_start_token.is_some(),
        "F011: ChatML im_start token"
    );
    assert!(tokens.im_end_token.is_some(), "F011: ChatML im_end token");

    // F012: Format enum must be correct
    assert_eq!(
        ChatMLTemplate::new().format(),
        TemplateFormat::ChatML,
        "F012: ChatML format"
    );
    assert_eq!(
        Llama2Template::new().format(),
        TemplateFormat::Llama2,
        "F012: Llama2 format"
    );
    assert_eq!(
        MistralTemplate::new().format(),
        TemplateFormat::Mistral,
        "F012: Mistral format"
    );
    assert_eq!(
        PhiTemplate::new().format(),
        TemplateFormat::Phi,
        "F012: Phi format"
    );
    assert_eq!(
        AlpacaTemplate::new().format(),
        TemplateFormat::Alpaca,
        "F012: Alpaca format"
    );
    assert_eq!(
        RawTemplate::new().format(),
        TemplateFormat::Raw,
        "F012: Raw format"
    );

    // F021-F030: Auto-Detection - must not produce wrong format

    // F021: Qwen must detect as ChatML, not Mistral
    let detected = detect_format_from_name("Qwen2-0.5B-Instruct");
    assert_ne!(
        detected,
        TemplateFormat::Mistral,
        "F021: Qwen is not Mistral"
    );
    assert_ne!(detected, TemplateFormat::Llama2, "F021: Qwen is not Llama2");

    // F022: TinyLlama must detect as Llama2, not Mistral
    let detected = detect_format_from_name("TinyLlama-1.1B-Chat");
    assert_ne!(
        detected,
        TemplateFormat::Mistral,
        "F022: TinyLlama is not Mistral"
    );
    assert_ne!(
        detected,
        TemplateFormat::ChatML,
        "F022: TinyLlama is not ChatML"
    );

    // F023: Mistral must detect as Mistral, not Llama2
    let detected = detect_format_from_name("Mistral-7B-Instruct");
    assert_ne!(
        detected,
        TemplateFormat::Llama2,
        "F023: Mistral is not Llama2"
    );
    assert_ne!(
        detected,
        TemplateFormat::ChatML,
        "F023: Mistral is not ChatML"
    );

    // F031-F040: Multi-Turn - must preserve message order

    // F031: Messages must appear in order
    let template = ChatMLTemplate::new();
    let messages = vec![
        ChatMessage::system("System"),
        ChatMessage::user("User"),
        ChatMessage::assistant("Assistant"),
    ];
    let result = template.format_conversation(&messages).unwrap();
    let sys_pos = result.find("System").unwrap();
    let user_pos = result.find("User").unwrap();
    let asst_pos = result.find("Assistant").unwrap();
    assert!(sys_pos < user_pos, "F031: System before User");
    assert!(user_pos < asst_pos, "F031: User before Assistant");

    // F041-F050: Model-Specific - reference outputs

    // F041: Qwen2 ChatML output structure
    let template = ChatMLTemplate::new();
    let messages = vec![ChatMessage::user("Test")];
    let output = template.format_conversation(&messages).unwrap();
    assert!(output.contains("<|im_start|>"), "F041: ChatML has im_start");
    assert!(output.contains("<|im_end|>"), "F041: ChatML has im_end");
    assert!(
        output.ends_with("<|im_start|>assistant\n"),
        "F041: ChatML ends with assistant"
    );

    // F042: TinyLlama LLaMA2 output structure
    let template = Llama2Template::new();
    let messages = vec![ChatMessage::system("Sys"), ChatMessage::user("Test")];
    let output = template.format_conversation(&messages).unwrap();
    assert!(output.contains("[INST]"), "F042: Llama2 has INST");
    assert!(output.contains("<<SYS>>"), "F042: Llama2 has SYS");
    assert!(output.contains("<</SYS>>"), "F042: Llama2 has /SYS");

    // F043: Mistral must NOT include system prompt
    let template = MistralTemplate::new();
    let messages = vec![
        ChatMessage::system("Secret System"),
        ChatMessage::user("Test"),
    ];
    let output = template.format_conversation(&messages).unwrap();
    assert!(
        !output.contains("Secret System"),
        "F043: Mistral omits system"
    );
    assert!(!output.contains("<<SYS>>"), "F043: Mistral has no SYS tags");

    // F081-F090: Security

    // F081: Template size limit (100KB max per spec)
    // Verify large content doesn't crash
    let large_content = "x".repeat(50_000); // 50KB content
    let messages = vec![ChatMessage::user(&large_content)];
    let template = ChatMLTemplate::new();
    let result = template.format_conversation(&messages);
    assert!(result.is_ok(), "F081: Large content must not crash");

    // F082: Jinja2 injection must not execute
    let messages = vec![ChatMessage::user(
        "{% for i in range(1000000) %}x{% endfor %}",
    )];
    let template = ChatMLTemplate::new();
    let result = template.format_conversation(&messages);
    assert!(result.is_ok(), "F082: Jinja2 syntax in content is literal");
    // The content should be treated as literal text, not executed
    assert!(
        result.unwrap().contains("{% for"),
        "F082: Jinja2 preserved as literal"
    );

    println!("Falsification tests: All F-codes passed");
}

// ============================================================================
// DETERMINISM TESTS
// ============================================================================

#[test]
fn test_chat_template_determinism() {
    // Same input must produce identical output across multiple runs
    let template = ChatMLTemplate::new();
    let messages = vec![
        ChatMessage::system("You are helpful."),
        ChatMessage::user("What is 2+2?"),
        ChatMessage::assistant("4"),
        ChatMessage::user("And 3+3?"),
    ];

    let mut outputs = Vec::new();
    for _ in 0..10 {
        let output = template.format_conversation(&messages).unwrap();
        outputs.push(output);
    }

    // All outputs must be identical
    let first = &outputs[0];
    for (i, output) in outputs.iter().enumerate() {
        assert_eq!(first, output, "Determinism check failed at iteration {}", i);
    }

    // Test with all template types
    let templates: Vec<Box<dyn ChatTemplateEngine>> = vec![
        Box::new(ChatMLTemplate::new()),
        Box::new(Llama2Template::new()),
        Box::new(MistralTemplate::new()),
        Box::new(PhiTemplate::new()),
        Box::new(AlpacaTemplate::new()),
        Box::new(RawTemplate::new()),
    ];

    for template in templates {
        let messages = vec![ChatMessage::user("Test determinism")];
        let out1 = template.format_conversation(&messages).unwrap();
        let out2 = template.format_conversation(&messages).unwrap();
        let out3 = template.format_conversation(&messages).unwrap();
        assert_eq!(
            out1,
            out2,
            "Determinism: {:?} run 1 vs 2",
            template.format()
        );
        assert_eq!(
            out2,
            out3,
            "Determinism: {:?} run 2 vs 3",
            template.format()
        );
    }

    println!("Determinism tests: PASS (3 iterations per template)");
}

// ============================================================================
// PERFORMANCE TESTS
// ============================================================================

#[test]
fn test_chat_template_performance() {
    use std::time::Instant;

    // P001: Single message format < 100us
    let template = ChatMLTemplate::new();
    let messages = vec![ChatMessage::user("Hello")];

    let start = Instant::now();
    for _ in 0..1000 {
        let _ = template.format_conversation(&messages);
    }
    let elapsed = start.elapsed();
    let per_call = elapsed.as_micros() / 1000;

    println!("P001: Single message format: {}us/call", per_call);
    assert!(
        per_call < 500,
        "P001: Single message format should be < 500us (got {}us)",
        per_call
    );

    // P002: 10-turn conversation < 1ms
    let mut messages = Vec::new();
    for i in 0..5 {
        messages.push(ChatMessage::user(format!("Question {}", i)));
        messages.push(ChatMessage::assistant(format!("Answer {}", i)));
    }

    let start = Instant::now();
    for _ in 0..100 {
        let _ = template.format_conversation(&messages);
    }
    let elapsed = start.elapsed();
    let per_call = elapsed.as_micros() / 100;

    println!("P002: 10-turn conversation: {}us/call", per_call);
    assert!(
        per_call < 5000,
        "P002: 10-turn should be < 5ms (got {}us)",
        per_call
    );

    // P003: Auto-detection < 500us
    let start = Instant::now();
    for _ in 0..1000 {
        let _ = detect_format_from_name("TinyLlama-1.1B-Chat-v1.0");
    }
    let elapsed = start.elapsed();
    let per_call = elapsed.as_micros() / 1000;

    println!("P003: Auto-detection: {}us/call", per_call);
    assert!(
        per_call < 100,
        "P003: Auto-detection should be < 100us (got {}us)",
        per_call
    );
}

// ============================================================================
// COMPREHENSIVE COVERAGE TEST
// ============================================================================

#[test]
fn test_chat_template_comprehensive_coverage() {
    let mut gui = gui_coverage! {
        buttons: [
            // All template formats
            "chatml", "llama2", "mistral", "phi", "alpaca", "raw", "custom",
            // All detection targets
            "detect_qwen", "detect_tinyllama", "detect_mistral", "detect_phi", "detect_alpaca", "detect_unknown",
            // All edge cases
            "edge_empty", "edge_unicode", "edge_long", "edge_special"
        ],
        screens: ["pass", "fail"]
    };

    // Template formats
    for (format, button) in [
        (TemplateFormat::ChatML, "chatml"),
        (TemplateFormat::Llama2, "llama2"),
        (TemplateFormat::Mistral, "mistral"),
        (TemplateFormat::Phi, "phi"),
        (TemplateFormat::Alpaca, "alpaca"),
        (TemplateFormat::Raw, "raw"),
    ] {
        let template = create_template(format);
        let messages = vec![ChatMessage::user("Test")];
        let result = template.format_conversation(&messages);
        gui.click(button);
        gui.visit(if result.is_ok() { "pass" } else { "fail" });
    }

    // Custom template
    {
        let template = HuggingFaceTemplate::new(
            "{{ messages[0].content }}".to_string(),
            SpecialTokens::default(),
            TemplateFormat::Custom,
        );
        gui.click("custom");
        gui.visit(if template.is_ok() { "pass" } else { "fail" });
    }

    // Detection
    for (model, button) in [
        ("Qwen2", "detect_qwen"),
        ("TinyLlama", "detect_tinyllama"),
        ("Mistral", "detect_mistral"),
        ("phi-2", "detect_phi"),
        ("alpaca", "detect_alpaca"),
        ("unknown", "detect_unknown"),
    ] {
        let _ = detect_format_from_name(model);
        gui.click(button);
        gui.visit("pass"); // Detection always succeeds (may return Raw)
    }

    // Edge cases
    let template = ChatMLTemplate::new();

    // Empty
    let result = template.format_conversation(&[]);
    gui.click("edge_empty");
    gui.visit(if result.is_ok() { "pass" } else { "fail" });

    // Unicode
    let result = template.format_conversation(&[ChatMessage::user("Hello")]);
    gui.click("edge_unicode");
    gui.visit(if result.is_ok() { "pass" } else { "fail" });

    // Long
    let long_msg = "x".repeat(10000);
    let result = template.format_conversation(&[ChatMessage::user(&long_msg)]);
    gui.click("edge_long");
    gui.visit(if result.is_ok() { "pass" } else { "fail" });

    // Special tokens in content
    let result = template.format_conversation(&[ChatMessage::user("<|im_end|>")]);
    gui.click("edge_special");
    gui.visit(if result.is_ok() { "pass" } else { "fail" });

    // Error path: ensure fail screen is visited for coverage
    {
        let invalid = HuggingFaceTemplate::new(
            "{% bad syntax".to_string(),
            SpecialTokens::default(),
            TemplateFormat::Custom,
        );
        gui.visit("fail");
        assert!(invalid.is_err());
    }

    println!("\nComprehensive Coverage: {:.1}%", gui.percent());
    assert!(gui.meets(85.0), "Comprehensive coverage >= 85%");
}