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
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
506
507
508
509
510
511
512
513
514
515
// ============================================================================
// Tokenizer-Vocabulary Contract Falsification (FALSIFY-TV-001..006)
//
// Cross-checks three contracts for consistency:
//   1. contracts/tokenizer-vocab-v1.yaml (this contract)
//   2. contracts/special-tokens-registry-v1.yaml (token IDs)
//   3. contracts/model-families/*.yaml (vocab per size variant)
//
// Contract: contracts/tokenizer-vocab-v1.yaml
// ============================================================================

#[cfg(test)]
mod tokenizer_vocab_contract {
    use std::collections::HashMap;
    use std::path::Path;

    use crate::format::model_family::ModelFamilyConfig;
    use crate::format::model_family_loader::load_family_yaml;

    // ========================================================================
    // Parsed types
    // ========================================================================

    #[derive(Debug)]
    struct TvFamily {
        tokenizer_type: String,
        vocab_size: u64,
        bos_id: u32,
        eos_id: u32,
        pad_id: u32,
        im_start_id: u32,
        im_end_id: u32,
    }

    #[derive(Debug)]
    struct StFamily {
        vocab_size: u64,
        bos_id: u32,
        eos_id: u32,
        pad_id: u32,
        im_start_id: u32,
        im_end_id: u32,
    }

    /// Accumulator for token fields during parsing.
    #[derive(Default)]
    struct TokenAcc {
        vocab_size: u64,
        bos_id: u32,
        eos_id: u32,
        pad_id: u32,
        im_start_id: u32,
        im_end_id: u32,
    }

    impl TokenAcc {
        fn reset(&mut self) {
            *self = Self::default();
        }

        /// Try to parse a token field from a trimmed line. Returns true if matched.
        fn try_parse_field(&mut self, trimmed: &str) -> bool {
            let pairs: &[(&str, fn(&mut Self, u32))] = &[
                ("vocab_size:", |s, v| s.vocab_size = u64::from(v)),
                ("bos_id:", |s, v| s.bos_id = v),
                ("eos_id:", |s, v| s.eos_id = v),
                ("pad_id:", |s, v| s.pad_id = v),
                ("im_start_id:", |s, v| s.im_start_id = v),
                ("im_end_id:", |s, v| s.im_end_id = v),
            ];

            for &(prefix, setter) in pairs {
                if let Some(rest) = trimmed.strip_prefix(prefix) {
                    let val: u32 = field_val(rest).parse().unwrap_or(0);
                    setter(self, val);
                    return true;
                }
            }
            false
        }

        /// Try to parse vocab_size as u64 (for large vocabs > u32).
        fn try_parse_vocab(&mut self, trimmed: &str) -> bool {
            if let Some(rest) = trimmed.strip_prefix("vocab_size:") {
                self.vocab_size = field_val(rest).parse().unwrap_or(0);
                return true;
            }
            false
        }
    }

    // ========================================================================
    // YAML parsers
    // ========================================================================

    fn read_file(name: &str) -> String {
        let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..").join(name);
        assert!(path.exists(), "{name} must exist at workspace root");
        std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("Failed to read {name}: {e}"))
    }

    /// Parse field value from a "key: value # comment" string.
    fn field_val(line: &str) -> &str {
        line.split('#').next().unwrap_or("").trim()
    }

    /// Check if a line is a section-ending line (non-empty, non-indented, non-comment).
    fn is_section_end(line: &str) -> bool {
        let trimmed = line.trim();
        !trimmed.is_empty()
            && !line.starts_with(' ')
            && !line.starts_with('\t')
            && !trimmed.starts_with('#')
    }

    /// Check if trimmed line is a family-name key (2-space indent, ends with colon, no spaces).
    fn is_family_name(line: &str, trimmed: &str) -> bool {
        let indent = line.len() - line.trim_start().len();
        indent == 2 && trimmed.ends_with(':') && !trimmed.contains(' ')
    }

    /// Parse the tokenizer_types section — returns set of known type names.
    fn parse_tokenizer_types(content: &str) -> Vec<String> {
        let mut types = Vec::new();
        let mut in_section = false;

        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed == "tokenizer_types:" {
                in_section = true;
                continue;
            }
            if in_section && is_section_end(line) {
                break;
            }
            if !in_section {
                continue;
            }
            if is_family_name(line, trimmed) {
                types.push(trimmed.trim_end_matches(':').to_string());
            }
        }
        types
    }

    /// Parse the families section from tokenizer-vocab-v1.yaml.
    fn parse_tv_families(content: &str) -> HashMap<String, TvFamily> {
        let mut families = HashMap::new();
        let mut in_section = false;
        let mut in_special_tokens = false;
        let mut current_name = String::new();
        let mut current_type = String::new();
        let mut acc = TokenAcc::default();

        for line in content.lines() {
            let trimmed = line.trim();

            if trimmed == "families:" {
                in_section = true;
                continue;
            }
            if in_section && is_section_end(line) {
                break;
            }
            if !in_section {
                continue;
            }

            let indent = line.len() - line.trim_start().len();

            if is_family_name(line, trimmed) {
                save_tv_family(&mut families, &current_name, &current_type, &acc);
                current_name = trimmed.trim_end_matches(':').to_string();
                current_type.clear();
                acc.reset();
                in_special_tokens = false;
                continue;
            }

            if indent == 4 && trimmed == "special_tokens:" {
                in_special_tokens = true;
                continue;
            }

            if indent == 4 && !trimmed.starts_with('#') {
                in_special_tokens = parse_tv_line(trimmed, &mut current_type, &mut acc);
            }

            if indent == 6 && in_special_tokens {
                acc.try_parse_field(trimmed);
            }
        }

        save_tv_family(&mut families, &current_name, &current_type, &acc);
        families
    }

    /// Parse a 4-indent tokenizer-vocab line. Returns true if entering special_tokens.
    fn parse_tv_line(trimmed: &str, current_type: &mut String, acc: &mut TokenAcc) -> bool {
        if let Some(rest) = trimmed.strip_prefix("tokenizer_type:") {
            *current_type = field_val(rest).to_string();
            return false;
        }
        if acc.try_parse_vocab(trimmed) {
            return false;
        }
        false
    }

    fn save_tv_family(
        families: &mut HashMap<String, TvFamily>,
        name: &str,
        tok_type: &str,
        acc: &TokenAcc,
    ) {
        if !name.is_empty() && acc.vocab_size > 0 {
            families.insert(
                name.to_string(),
                TvFamily {
                    tokenizer_type: tok_type.to_string(),
                    vocab_size: acc.vocab_size,
                    bos_id: acc.bos_id,
                    eos_id: acc.eos_id,
                    pad_id: acc.pad_id,
                    im_start_id: acc.im_start_id,
                    im_end_id: acc.im_end_id,
                },
            );
        }
    }

    /// Parse the families section from special-tokens-registry-v1.yaml.
    fn parse_st_families(content: &str) -> HashMap<String, StFamily> {
        let mut families = HashMap::new();
        let mut in_section = false;
        let mut current_name = String::new();
        let mut acc = TokenAcc::default();

        for line in content.lines() {
            let trimmed = line.trim();

            if trimmed == "families:" {
                in_section = true;
                continue;
            }
            if in_section && is_section_end(line) {
                break;
            }
            if !in_section {
                continue;
            }

            let indent = line.len() - line.trim_start().len();

            if is_family_name(line, trimmed) {
                save_st_family(&mut families, &current_name, &acc);
                current_name = trimmed.trim_end_matches(':').to_string();
                acc.reset();
                continue;
            }

            if indent >= 4 {
                acc.try_parse_field(trimmed);
            }
        }

        save_st_family(&mut families, &current_name, &acc);
        families
    }

    fn save_st_family(families: &mut HashMap<String, StFamily>, name: &str, acc: &TokenAcc) {
        if !name.is_empty() && acc.vocab_size > 0 {
            families.insert(
                name.to_string(),
                StFamily {
                    vocab_size: acc.vocab_size,
                    bos_id: acc.bos_id,
                    eos_id: acc.eos_id,
                    pad_id: acc.pad_id,
                    im_start_id: acc.im_start_id,
                    im_end_id: acc.im_end_id,
                },
            );
        }
    }

    /// Load all model-family YAML configs.
    fn load_model_family_configs() -> Vec<(String, ModelFamilyConfig)> {
        let families_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../contracts/model-families");
        let mut families = Vec::new();
        let entries = std::fs::read_dir(&families_dir).expect("read model-families dir");

        for entry in entries {
            let entry = entry.expect("dir entry");
            let path = entry.path();
            let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            let ext_ok = path
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("yaml"));
            if !ext_ok || file_name.starts_with('_') {
                continue;
            }
            if let Ok(config) = load_family_yaml(&path) {
                let name = file_name
                    .trim_end_matches(".yaml")
                    .trim_end_matches(".yml")
                    .to_string();
                families.push((name, config));
            }
        }
        families
    }

    // ========================================================================
    // FALSIFY-TV-001: Special tokens match special-tokens-registry
    // ========================================================================
    #[test]
    fn falsify_tv_001_tokens_match_registry() {
        let tv_content = read_file("contracts/tokenizer-vocab-v1.yaml");
        let st_content = read_file("contracts/special-tokens-registry-v1.yaml");

        let tv_families = parse_tv_families(&tv_content);
        let st_families = parse_st_families(&st_content);

        let mut violations = Vec::new();

        for (name, tv) in &tv_families {
            let Some(st) = st_families.get(name) else {
                violations.push(format!(
                    "{name}: in tokenizer-vocab but not in special-tokens-registry"
                ));
                continue;
            };

            let checks: &[(&str, u32, u32)] = &[
                ("bos_id", tv.bos_id, st.bos_id),
                ("eos_id", tv.eos_id, st.eos_id),
                ("pad_id", tv.pad_id, st.pad_id),
                ("im_start_id", tv.im_start_id, st.im_start_id),
                ("im_end_id", tv.im_end_id, st.im_end_id),
            ];

            for &(field, tv_val, st_val) in checks {
                if tv_val != st_val {
                    violations.push(format!(
                        "{name}.{field}: tokenizer-vocab={tv_val}, special-tokens-registry={st_val}"
                    ));
                }
            }
        }

        assert!(
            violations.is_empty(),
            "FALSIFY-TV-001: Token ID divergence between contracts:\n{}",
            violations.join("\n")
        );
    }

    // ========================================================================
    // FALSIFY-TV-002: Vocab size matches special-tokens-registry
    // ========================================================================
    #[test]
    fn falsify_tv_002_vocab_size_matches_registry() {
        let tv_content = read_file("contracts/tokenizer-vocab-v1.yaml");
        let st_content = read_file("contracts/special-tokens-registry-v1.yaml");

        let tv_families = parse_tv_families(&tv_content);
        let st_families = parse_st_families(&st_content);

        let mut violations = Vec::new();

        for (name, tv) in &tv_families {
            if let Some(st) = st_families.get(name) {
                if tv.vocab_size != st.vocab_size {
                    violations.push(format!(
                        "{name}: tokenizer-vocab vocab_size={}, special-tokens-registry vocab_size={}",
                        tv.vocab_size, st.vocab_size
                    ));
                }
            }
        }

        assert!(
            violations.is_empty(),
            "FALSIFY-TV-002: Vocab size divergence between contracts:\n{}",
            violations.join("\n")
        );
    }

    // ========================================================================
    // FALSIFY-TV-003: Vocab size matches model-family size variants
    // ========================================================================
    #[test]
    fn falsify_tv_003_vocab_matches_model_families() {
        let tv_content = read_file("contracts/tokenizer-vocab-v1.yaml");
        let tv_families = parse_tv_families(&tv_content);
        let mf_configs = load_model_family_configs();

        let mut violations = Vec::new();

        for (tv_name, tv) in &tv_families {
            let matching_mf = mf_configs.iter().find(|(name, _)| name == tv_name);

            if let Some((_, mf_config)) = matching_mf {
                let has_match = mf_config
                    .size_variants
                    .values()
                    .any(|size| size.vocab_size as u64 == tv.vocab_size);

                if !has_match && !mf_config.size_variants.is_empty() {
                    let observed: Vec<String> = mf_config
                        .size_variants
                        .values()
                        .map(|s| format!("{}", s.vocab_size))
                        .collect();
                    violations.push(format!(
                        "{tv_name}: tokenizer-vocab vocab_size={}, model-family has [{}]",
                        tv.vocab_size,
                        observed.join(", ")
                    ));
                }
            }
        }

        assert!(
            violations.is_empty(),
            "FALSIFY-TV-003: Vocab size mismatch with model families:\n{}",
            violations.join("\n")
        );
    }

    // ========================================================================
    // FALSIFY-TV-004: All tokenizer_type references are valid
    // ========================================================================
    #[test]
    fn falsify_tv_004_tokenizer_types_valid() {
        let tv_content = read_file("contracts/tokenizer-vocab-v1.yaml");
        let known_types = parse_tokenizer_types(&tv_content);
        let tv_families = parse_tv_families(&tv_content);

        let mut violations = Vec::new();

        for (name, tv) in &tv_families {
            if !known_types.contains(&tv.tokenizer_type) {
                violations.push(format!(
                    "{name}: tokenizer_type '{}' not in tokenizer_types section (known: {:?})",
                    tv.tokenizer_type, known_types
                ));
            }
        }

        assert!(
            violations.is_empty(),
            "FALSIFY-TV-004: Invalid tokenizer type references:\n{}",
            violations.join("\n")
        );
    }

    // ========================================================================
    // FALSIFY-TV-005: Token IDs within vocab bounds
    // ========================================================================
    #[test]
    fn falsify_tv_005_token_ids_within_bounds() {
        let tv_content = read_file("contracts/tokenizer-vocab-v1.yaml");
        let tv_families = parse_tv_families(&tv_content);

        let mut violations = Vec::new();

        for (name, tv) in &tv_families {
            let checks: &[(&str, u32)] = &[
                ("bos_id", tv.bos_id),
                ("eos_id", tv.eos_id),
                ("pad_id", tv.pad_id),
                ("im_start_id", tv.im_start_id),
                ("im_end_id", tv.im_end_id),
            ];

            for &(field, id) in checks {
                if id > 0 && u64::from(id) >= tv.vocab_size {
                    violations.push(format!(
                        "{name}.{field}: {id} >= vocab_size {}",
                        tv.vocab_size
                    ));
                }
            }
        }

        assert!(
            violations.is_empty(),
            "FALSIFY-TV-005: Token IDs out of vocab bounds:\n{}",
            violations.join("\n")
        );
    }

    // ========================================================================
    // FALSIFY-TV-006: Family count parity with special-tokens-registry
    // ========================================================================
    #[test]
    fn falsify_tv_006_family_count_parity() {
        let tv_content = read_file("contracts/tokenizer-vocab-v1.yaml");
        let st_content = read_file("contracts/special-tokens-registry-v1.yaml");

        let tv_families = parse_tv_families(&tv_content);
        let st_families = parse_st_families(&st_content);

        assert_eq!(
            tv_families.len(),
            st_families.len(),
            "FALSIFY-TV-006: tokenizer-vocab has {} families, special-tokens-registry has {}. \
             Sync contracts/tokenizer-vocab-v1.yaml with contracts/special-tokens-registry-v1.yaml",
            tv_families.len(),
            st_families.len()
        );
    }
}