toktier 0.2.7

Rust API preview for TokTier's exact, stateful tokenization runtime
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;

use serde_json::Value;
use toktier_cuda_driver::CudaContext;
use toktier_routing_core::{
    NativeGpuEngine, NativePrebuiltGpu, NativePrebuiltGpuConfig, ReferenceEngine,
};

#[cfg(feature = "jit")]
use crate::jit::JitProduct;
use crate::manifest::{domain_sha256_hex, sha256_hex, LocalArtifact, Registry, PREBUILT_FATBIN};
use crate::{Error, ErrorCode, Policy, Result};

const EMPTY: u64 = u64::MAX;
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x100_0000_01b3;

const CLASS_CL100K: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/kernels/tables/pretok_classes_cl100k.v3.npy"
));
const CLASS_CL100K_M2L: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/kernels/tables/pretok_classes_cl100k_marks_as_letters.v3.npy"
));
const CLASS_DEEPSEEK: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/kernels/tables/pretok_classes_deepseek.v1.npy"
));
const CLASS_O200K: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/kernels/tables/pretok_classes_o200k.v4.npy"
));
const CLASS_KIMI: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/kernels/tables/pretok_classes_kimi.v1.npy"
));
const DEEPSEEK_META: &[u8] = include_bytes!(concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/data/src/toktier/kernels/tables/pretok_classes_deepseek.v1.meta.json"
));

/// How much has been measured about running this kernel on this device.
///
/// Not a policy and not a permission: the policy decides whether an
/// assurance is admitted, and this says which one the route has, so the
/// label a caller reads is a fact rather than a restatement of what was
/// asked for.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Assurance {
    /// A certification campaign ran on this architecture with this
    /// delivery.
    Judged,
    /// The shipped kernel loads and runs here and no campaign has
    /// measured this combination.
    Unjudged,
    /// Reached only through an explicit waiver.
    Experimental,
}

pub(crate) struct BuiltGpu {
    pub(crate) engine: Arc<dyn NativeGpuEngine>,
    pub(crate) architecture: String,
    pub(crate) driver_api_version: i32,
    pub(crate) assurance: Assurance,
    /// `prebuilt` or `jit`: which delivery loaded.
    pub(crate) delivery: &'static str,
    /// The digest of the image that loaded, so a local verification
    /// record can say which kernel it was taken over.
    pub(crate) image_digest: String,
    /// The compiler that produced the image, for a JIT product: the
    /// NVCC release, build and binary digest the compiler stage
    /// recorded. A local verification record is filed under it, so a
    /// product another compiler builds from the same source does not
    /// read a record taken over this one. `None` under the prebuilt
    /// delivery, whose image digest names the shipped bytes outright.
    pub(crate) toolchain: Option<String>,
}

pub(crate) fn build_prebuilt(
    registry: &Registry,
    artifact: &LocalArtifact,
    reference: Arc<ReferenceEngine>,
    device_ordinal: i32,
    policy: Policy,
) -> Result<BuiltGpu> {
    let family = &artifact.identity().family;
    let support = registry.support(family).ok_or_else(|| {
        Error::new(
            ErrorCode::UncertifiedTokenizer,
            format!("family {family} has no shipped certification row"),
        )
    })?;
    if support.artifact_sha256 != artifact.identity().tokenizer_sha256 {
        return Err(Error::new(
            ErrorCode::UncertifiedTokenizer,
            "support registry and verified artifact digest disagree",
        ));
    }
    let prebuilt_support = support
        .backends
        .get("gpu")
        .and_then(|gpu| gpu.get("deliveries"))
        .and_then(|deliveries| deliveries.get("prebuilt"))
        .ok_or_else(|| {
            Error::new(
                ErrorCode::KernelIncompatible,
                format!("family {family} has no prebuilt GPU delivery"),
            )
        })?;
    let expected_host_source = prebuilt_support
        .get("host_source_digest")
        .and_then(Value::as_str)
        .ok_or_else(|| {
            Error::new(
                ErrorCode::RegistryInvalid,
                "prebuilt delivery has no native-host source binding",
            )
        })?;
    if expected_host_source != env!("TOKTIER_RUST_API_NATIVE_HOST_SOURCE_SHA256") {
        return Err(Error::new(
            ErrorCode::UncertifiedRuntime,
            "the Rust CUDA host source does not match the prebuilt delivery certificate",
        ));
    }
    let context = CudaContext::new(device_ordinal).map_err(|error| {
        Error::new(ErrorCode::KernelIncompatible, error.to_string()).with_family(family)
    })?;
    let (major, minor) = context.architecture();
    let architecture = format!("sm_{major}{minor}");
    let driver_api_version = context.driver_version();
    // Which of the three things this device can be. `judged` is a device
    // a campaign ran on; `experimental` is one the registry names as
    // reachable under an explicit waiver; anything else is a device the
    // shipped kernel may still load and run on, which `Policy::Supported`
    // admits and labels rather than refuses.
    let judged = json_string_array(prebuilt_support.get("devices"))
        .iter()
        .any(|device| device == &architecture);
    let experimental = json_string_array(prebuilt_support.get("devices_experimental"))
        .iter()
        .any(|device| device == &architecture);
    let assurance = if judged {
        Assurance::Judged
    } else if policy == Policy::Experimental && experimental {
        Assurance::Experimental
    } else if policy.admits_unjudged_device() {
        Assurance::Unjudged
    } else {
        return Err(Error::new(
            ErrorCode::KernelIncompatible,
            format!(
                "prebuilt GPU architecture {architecture} is not in the judged device list, and \
                 policy {policy:?} admits only judged devices; Policy::Supported loads the \
                 shipped kernel here and labels the route supported instead"
            ),
        ));
    };
    // The build manifest describes the toolchain and the architectures
    // the fatbin was built for. A device outside that list can still be
    // reached, through the PTX the fatbin carries, so the manifest is
    // required to describe the build rather than this device.
    if registry.prebuilt.toolchain.is_empty() {
        return Err(Error::new(
            ErrorCode::RegistryInvalid,
            "prebuilt manifest does not describe the build toolchain",
        ));
    }
    if assurance == Assurance::Judged
        && !registry.prebuilt.architectures.contains_key(&architecture)
    {
        return Err(Error::new(
            ErrorCode::RegistryInvalid,
            "prebuilt manifest does not describe the selected architecture/toolchain",
        ));
    }

    let expected_binary = prebuilt_support
        .get("binary_digest")
        .and_then(Value::as_str)
        .ok_or_else(|| Error::new(ErrorCode::RegistryInvalid, "prebuilt row has no digest"))?;
    if expected_binary.trim_start_matches("sha256:")
        != registry
            .prebuilt
            .fatbin
            .digest
            .trim_start_matches("sha256:")
    {
        return Err(Error::new(
            ErrorCode::RegistryInvalid,
            "support registry and build manifest bind different fatbins",
        ));
    }
    if PREBUILT_FATBIN.len() as u64 != registry.prebuilt.fatbin.size {
        return Err(Error::new(
            ErrorCode::KernelIncompatible,
            "shipped fatbin size differs from its build manifest",
        ));
    }
    let observed_binary = domain_sha256_hex(b"toktier.kernel_fatbin.v1\0", PREBUILT_FATBIN);
    if observed_binary != expected_binary.trim_start_matches("sha256:") {
        return Err(Error::new(
            ErrorCode::KernelIncompatible,
            "shipped fatbin digest differs from its build manifest",
        ));
    }

    build_image(
        registry,
        artifact,
        reference,
        device_ordinal,
        architecture,
        driver_api_version,
        assurance,
        PREBUILT_FATBIN,
        &registry.prebuilt.fatbin.digest,
        "prebuilt",
        None,
    )
}

#[cfg(feature = "jit")]
pub(crate) fn build_jit(
    registry: &Registry,
    artifact: &LocalArtifact,
    reference: Arc<ReferenceEngine>,
    device_ordinal: i32,
    policy: Policy,
    product: &JitProduct,
) -> Result<BuiltGpu> {
    if product.architecture != format!("sm_{}{}", product.compute_major, product.compute_minor) {
        return Err(Error::new(
            ErrorCode::JitCompileFailed,
            "JIT product architecture facts are internally inconsistent",
        ));
    }
    // A product the compiler stage did not admit at all reaches here
    // only under an explicit waiver; one it admitted without a judged
    // (toolchain, device) pair is what `Policy::Supported` labels.
    let assurance = match product.assurance {
        crate::jit::JitAssurance::Certified => Assurance::Judged,
        crate::jit::JitAssurance::Unjudged if policy.admits_unjudged_device() => {
            Assurance::Unjudged
        }
        crate::jit::JitAssurance::Unjudged => {
            return Err(Error::new(
                ErrorCode::UncertifiedJit,
                format!(
                    "this JIT product was compiled for {}, which the registry has not judged \
                     with this compiler; policy {policy:?} admits only judged pairs, and \
                     Policy::Supported runs it labelled supported instead",
                    product.architecture
                ),
            ))
        }
        crate::jit::JitAssurance::Experimental if policy == Policy::Experimental => {
            Assurance::Experimental
        }
        crate::jit::JitAssurance::Experimental => {
            return Err(Error::new(
                ErrorCode::UncertifiedJit,
                "a JIT product built on a waiver is usable only under Policy::Experimental",
            ))
        }
    };
    build_image(
        registry,
        artifact,
        reference,
        device_ordinal,
        product.architecture.clone(),
        product.driver_api_version,
        assurance,
        &product.image,
        &product.domain_digest,
        "jit",
        Some(format!(
            "NVCC {} ({}; sha256 {})",
            product.facts.compiler.release,
            product.facts.compiler.build,
            product.facts.compiler.compiler_sha256
        )),
    )
}

#[allow(clippy::too_many_arguments)]
fn build_image(
    registry: &Registry,
    artifact: &LocalArtifact,
    reference: Arc<ReferenceEngine>,
    device_ordinal: i32,
    architecture: String,
    driver_api_version: i32,
    assurance: Assurance,
    image: &[u8],
    image_digest: &str,
    delivery: &str,
    toolchain: Option<String>,
) -> Result<BuiltGpu> {
    let family = &artifact.identity().family;

    let kernel = registry.kernel_families.get(family).ok_or_else(|| {
        Error::new(
            ErrorCode::KernelIncompatible,
            format!("family {family} has no end-to-end kernel mapping"),
        )
    })?;
    let class_spec = registry
        .class_tables
        .get(&kernel.class_table)
        .ok_or_else(|| {
            Error::new(
                ErrorCode::RegistryInvalid,
                "kernel class-table mapping is incomplete",
            )
        })?;
    if class_spec.dtype != "uint8" || class_spec.shape.as_slice() != [0x11_0000] {
        return Err(Error::new(
            ErrorCode::RegistryInvalid,
            "GPU class table has an unsupported shape or dtype",
        ));
    }
    let class_file = class_file(&class_spec.file)?;
    if sha256_hex(class_file) != class_spec.sha256.trim_start_matches("sha256:") {
        return Err(Error::new(
            ErrorCode::KernelIncompatible,
            "GPU class-table file does not match its registry digest",
        ));
    }
    let class_table = npy_u8_payload(class_file, 0x11_0000)?;
    let digits_max = match kernel.digits_max {
        Some(value) => value,
        None => {
            if class_spec.meta_file.as_deref() != Some("pretok_classes_deepseek.v1.meta.json") {
                return Err(Error::new(
                    ErrorCode::RegistryInvalid,
                    "unbound digits_max metadata",
                ));
            }
            if let Some(expected) = class_spec.meta_sha256.as_deref() {
                if sha256_hex(DEEPSEEK_META) != expected.trim_start_matches("sha256:") {
                    return Err(Error::new(
                        ErrorCode::KernelIncompatible,
                        "class-table metadata digest mismatch",
                    ));
                }
            }
            serde_json::from_slice::<Value>(DEEPSEEK_META)
                .ok()
                .and_then(|value| value.get("digits_max").and_then(Value::as_i64))
                .and_then(|value| i32::try_from(value).ok())
                .ok_or_else(|| {
                    Error::new(ErrorCode::RegistryInvalid, "metadata has no digits_max")
                })?
        }
    };
    let tables = BpeTables::from_tokenizer_json(&artifact.bytes())?;
    // Hash verification already passed; an unparseable document is a
    // kernel-construction failure, not a content-hash mismatch.
    let document: Value = serde_json::from_slice(&artifact.bytes()).map_err(|error| {
        Error::new(
            ErrorCode::KernelIncompatible,
            format!("verified tokenizer JSON cannot be parsed: {error}"),
        )
    })?;
    let needs_nfc = document
        .get("normalizer")
        .and_then(Value::as_object)
        .and_then(|normalizer| normalizer.get("type"))
        .and_then(Value::as_str)
        == Some("NFC");
    let config = NativePrebuiltGpuConfig {
        family: family.clone(),
        artifact_sha256: artifact.identity().tokenizer_sha256.clone(),
        expected_fatbin_sha256: image_digest.to_owned(),
        expected_architecture: architecture.clone(),
        device_ordinal,
        ruleset: kernel.ruleset.clone(),
        digits_max,
        contractions: kernel.contractions,
        needs_nfc,
        ignore_merges: i32::from(tables.ignore_merges),
        pair_count: tables.pair_count,
        vocab_count: tables.vocab_count,
        delivery: delivery.to_owned(),
    };
    let engine = NativePrebuiltGpu::new(
        config,
        (*reference).clone(),
        image,
        registry.prebuilt.kernels.clone(),
        class_table,
        &tables.pair_keys,
        &tables.pair_vals,
        &tables.byte_id,
        &tables.vocab_keys,
        &tables.vocab_vals,
        &tables.vocab_blob,
        &tables.unsafe_bits,
    )
    .map_err(|error| Error::new(ErrorCode::KernelIncompatible, error.to_string()))?;
    Ok(BuiltGpu {
        engine: Arc::new(engine),
        architecture,
        driver_api_version,
        assurance,
        delivery: if delivery == "jit" { "jit" } else { "prebuilt" },
        image_digest: image_digest.to_owned(),
        toolchain,
    })
}

fn class_file(name: &str) -> Result<&'static [u8]> {
    match name {
        "pretok_classes_cl100k.v3.npy" => Ok(CLASS_CL100K),
        "pretok_classes_cl100k_marks_as_letters.v3.npy" => Ok(CLASS_CL100K_M2L),
        "pretok_classes_deepseek.v1.npy" => Ok(CLASS_DEEPSEEK),
        "pretok_classes_o200k.v4.npy" => Ok(CLASS_O200K),
        "pretok_classes_kimi.v1.npy" => Ok(CLASS_KIMI),
        other => Err(Error::new(
            ErrorCode::KernelIncompatible,
            format!("class table {other:?} is not embedded in the Rust crate"),
        )),
    }
}

fn npy_u8_payload(bytes: &[u8], expected: usize) -> Result<&[u8]> {
    if bytes.get(..6) != Some(b"\x93NUMPY") {
        return Err(Error::new(ErrorCode::RegistryInvalid, "invalid NPY magic"));
    }
    let major = *bytes
        .get(6)
        .ok_or_else(|| Error::new(ErrorCode::RegistryInvalid, "truncated NPY header"))?;
    let header_len = match major {
        1 => u16::from_le_bytes(
            bytes
                .get(8..10)
                .and_then(|raw| raw.try_into().ok())
                .ok_or_else(|| Error::new(ErrorCode::RegistryInvalid, "truncated NPY header"))?,
        ) as usize,
        2 | 3 => u32::from_le_bytes(
            bytes
                .get(8..12)
                .and_then(|raw| raw.try_into().ok())
                .ok_or_else(|| Error::new(ErrorCode::RegistryInvalid, "truncated NPY header"))?,
        ) as usize,
        _ => {
            return Err(Error::new(
                ErrorCode::RegistryInvalid,
                "unsupported NPY version",
            ))
        }
    };
    let base = if major == 1 { 10 } else { 12 };
    let offset = base + header_len;
    let payload = bytes
        .get(offset..)
        .ok_or_else(|| Error::new(ErrorCode::RegistryInvalid, "truncated NPY payload"))?;
    if payload.len() != expected {
        return Err(Error::new(
            ErrorCode::RegistryInvalid,
            format!(
                "NPY payload has {} bytes; expected {expected}",
                payload.len()
            ),
        ));
    }
    Ok(payload)
}

fn json_string_array(value: Option<&Value>) -> Vec<String> {
    value
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(Value::as_str)
        .map(str::to_owned)
        .collect()
}

struct BpeTables {
    pair_keys: Vec<u8>,
    pair_vals: Vec<u8>,
    byte_id: Vec<u8>,
    vocab_keys: Vec<u8>,
    vocab_vals: Vec<u8>,
    vocab_blob: Vec<u8>,
    unsafe_bits: Vec<u8>,
    ignore_merges: bool,
    pair_count: usize,
    vocab_count: usize,
}

impl BpeTables {
    fn from_tokenizer_json(bytes: &[u8]) -> Result<Self> {
        // Hash verification already passed; an unparseable document is a
        // kernel-construction failure, not a content-hash mismatch.
        let document: Value = serde_json::from_slice(bytes).map_err(|error| {
            Error::new(
                ErrorCode::KernelIncompatible,
                format!("verified tokenizer JSON cannot be parsed: {error}"),
            )
        })?;
        let model = document
            .get("model")
            .and_then(Value::as_object)
            .ok_or_else(|| Error::new(ErrorCode::KernelIncompatible, "tokenizer has no model"))?;
        let vocab_object = model
            .get("vocab")
            .and_then(Value::as_object)
            .ok_or_else(|| Error::new(ErrorCode::KernelIncompatible, "BPE model has no vocab"))?;
        let mut vocab = HashMap::with_capacity(vocab_object.len());
        for (token, id) in vocab_object {
            let id = id
                .as_u64()
                .and_then(|value| u32::try_from(value).ok())
                .ok_or_else(|| {
                    Error::new(ErrorCode::KernelIncompatible, "vocabulary id is not u32")
                })?;
            vocab.insert(token.clone(), id);
        }
        let merges = model
            .get("merges")
            .and_then(Value::as_array)
            .ok_or_else(|| Error::new(ErrorCode::KernelIncompatible, "BPE model has no merges"))?;
        if merges.len() >= (1 << 27) {
            return Err(Error::new(
                ErrorCode::KernelIncompatible,
                "merge count exceeds kernel packing limits",
            ));
        }
        let mut pair_keys = Vec::with_capacity(merges.len());
        let mut pair_values = Vec::with_capacity(merges.len());
        let mut rules = Vec::with_capacity(merges.len());
        let mut referenced = HashSet::new();
        for (rank, merge) in merges.iter().enumerate() {
            let (left, right) = parse_merge(merge)?;
            let merged = format!("{left}{right}");
            referenced.insert(left.clone());
            referenced.insert(right.clone());
            referenced.insert(merged.clone());
            let left_id = *vocab.get(&left).ok_or_else(|| {
                Error::new(ErrorCode::KernelIncompatible, "merge left token is absent")
            })?;
            let right_id = *vocab.get(&right).ok_or_else(|| {
                Error::new(ErrorCode::KernelIncompatible, "merge right token is absent")
            })?;
            let merged_id = *vocab.get(&merged).ok_or_else(|| {
                Error::new(ErrorCode::KernelIncompatible, "merged token is absent")
            })?;
            pair_keys.push((u64::from(left_id) << 32) | u64::from(right_id));
            pair_values.push(((rank as u64) << 32) | u64::from(merged_id));
            rules.push((left, right, merged));
        }
        let (pair_keys, pair_vals) = build_hash(&pair_keys, &pair_values)?;
        let alphabet = byte_alphabet();
        let reverse = alphabet
            .iter()
            .map(|(byte, character)| (*character, *byte))
            .collect::<HashMap<_, _>>();
        let mut byte_ids = [-1_i32; 256];
        let mut missing = Vec::new();
        for (byte, character) in alphabet {
            match vocab.get(&character.to_string()) {
                Some(id) => {
                    byte_ids[usize::from(byte)] = i32::try_from(*id).map_err(|_| {
                        Error::new(ErrorCode::KernelIncompatible, "token id exceeds i32")
                    })?
                }
                None => missing.push(byte),
            }
        }
        let ignore_merges = model
            .get("ignore_merges")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        if ignore_merges && !missing.is_empty() {
            return Err(Error::new(
                ErrorCode::KernelIncompatible,
                "ignore_merges requires complete byte-alphabet coverage",
            ));
        }
        let mut blob = Vec::new();
        let mut vocab_hashes = Vec::new();
        let mut vocab_values = Vec::new();
        let mut seen = HashMap::<u64, Vec<u8>>::new();
        for (token, &id) in &vocab {
            if id >= (1 << 20) {
                return Err(Error::new(
                    ErrorCode::KernelIncompatible,
                    "vocabulary id exceeds kernel packing limits",
                ));
            }
            let Some(raw) = token_raw(token, &reverse) else {
                if referenced.contains(token) {
                    return Err(Error::new(
                        ErrorCode::KernelIncompatible,
                        "merge references a non-byte-level token",
                    ));
                }
                continue;
            };
            if raw.len() >= 1024 || blob.len() >= (1usize << 34) {
                return Err(Error::new(
                    ErrorCode::KernelIncompatible,
                    "vocabulary entry exceeds kernel packing limits",
                ));
            }
            let key = fnv1a64(&raw);
            if let Some(previous) = seen.get(&key) {
                if previous != &raw {
                    return Err(Error::new(
                        ErrorCode::KernelIncompatible,
                        "whole-vocabulary FNV hash collision",
                    ));
                }
                continue;
            }
            seen.insert(key, raw.clone());
            vocab_hashes.push(key);
            vocab_values
                .push(((blob.len() as u64) << 30) | ((raw.len() as u64) << 20) | u64::from(id));
            blob.extend_from_slice(&raw);
        }
        let (vocab_keys, vocab_vals) = build_hash(&vocab_hashes, &vocab_values)?;
        let mut first_use = HashMap::<String, usize>::new();
        for (rank, (left, right, _)) in rules.iter().enumerate() {
            first_use.entry(left.clone()).or_insert(rank);
            first_use.entry(right.clone()).or_insert(rank);
        }
        let mut unsafe_words = vec![0u32; merges.len().div_ceil(32)];
        for (rank, (_, _, result)) in rules.iter().enumerate() {
            if first_use.get(result).is_some_and(|used_at| *used_at < rank) {
                unsafe_words[rank >> 5] |= 1u32 << (rank & 31);
            }
        }
        if unsafe_words.iter().all(|word| *word == 0) {
            unsafe_words.clear();
        }
        Ok(Self {
            pair_count: pair_keys.len(),
            vocab_count: vocab_keys.len(),
            pair_keys: u64_bytes(&pair_keys),
            pair_vals: u64_bytes(&pair_vals),
            byte_id: i32_bytes(&byte_ids),
            vocab_keys: u64_bytes(&vocab_keys),
            vocab_vals: u64_bytes(&vocab_vals),
            vocab_blob: blob,
            unsafe_bits: u32_bytes(&unsafe_words),
            ignore_merges,
        })
    }
}

fn parse_merge(value: &Value) -> Result<(String, String)> {
    if let Some(parts) = value.as_array() {
        if parts.len() == 2 {
            if let (Some(left), Some(right)) = (parts[0].as_str(), parts[1].as_str()) {
                return Ok((left.to_owned(), right.to_owned()));
            }
        }
    } else if let Some(row) = value.as_str() {
        if let Some((left, right)) = row.split_once(' ') {
            return Ok((left.to_owned(), right.to_owned()));
        }
    }
    Err(Error::new(
        ErrorCode::KernelIncompatible,
        "unsupported BPE merge serialization",
    ))
}

fn build_hash(keys: &[u64], values: &[u64]) -> Result<(Vec<u64>, Vec<u64>)> {
    let mut size = 1usize;
    while size < keys.len().saturating_mul(3) {
        size = size.checked_mul(2).ok_or_else(|| {
            Error::new(
                ErrorCode::KernelIncompatible,
                "GPU hash table size overflow",
            )
        })?;
    }
    let mut out_keys = vec![EMPTY; size];
    let mut out_values = vec![0; size];
    let mask = size - 1;
    for (&key, &value) in keys.iter().zip(values) {
        let mut slot = (splitmix64(key) as usize) & mask;
        while out_keys[slot] != EMPTY {
            if out_keys[slot] == key {
                return Err(Error::new(
                    ErrorCode::KernelIncompatible,
                    "duplicate GPU lookup-table key",
                ));
            }
            slot = (slot + 1) & mask;
        }
        out_keys[slot] = key;
        out_values[slot] = value;
    }
    Ok((out_keys, out_values))
}

fn splitmix64(mut value: u64) -> u64 {
    value = value.wrapping_add(0x9e37_79b9_7f4a_7c15);
    value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
    value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
    value ^ (value >> 31)
}

fn fnv1a64(bytes: &[u8]) -> u64 {
    bytes.iter().fold(FNV_OFFSET, |value, byte| {
        (value ^ u64::from(*byte)).wrapping_mul(FNV_PRIME)
    })
}

fn byte_alphabet() -> BTreeMap<u8, char> {
    let mut visible = (33u16..127)
        .chain(161..173)
        .chain(174..256)
        .collect::<Vec<_>>();
    let mut mapped = visible.clone();
    let mut extra = 0u16;
    for byte in 0u16..=255 {
        if !visible.contains(&byte) {
            visible.push(byte);
            mapped.push(256 + extra);
            extra += 1;
        }
    }
    visible
        .into_iter()
        .zip(mapped)
        .map(|(byte, codepoint)| {
            (
                byte as u8,
                char::from_u32(u32::from(codepoint)).expect("byte alphabet is valid Unicode"),
            )
        })
        .collect()
}

fn token_raw(token: &str, reverse: &HashMap<char, u8>) -> Option<Vec<u8>> {
    token
        .chars()
        .map(|character| reverse.get(&character).copied())
        .collect()
}

fn u64_bytes(values: &[u64]) -> Vec<u8> {
    values
        .iter()
        .flat_map(|value| value.to_le_bytes())
        .collect()
}

fn u32_bytes(values: &[u32]) -> Vec<u8> {
    values
        .iter()
        .flat_map(|value| value.to_le_bytes())
        .collect()
}

fn i32_bytes(values: &[i32]) -> Vec<u8> {
    values
        .iter()
        .flat_map(|value| value.to_le_bytes())
        .collect()
}

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

    /// The class tables are compiled into this crate with their digests,
    /// so the reader that parses them cannot be reached with a file. Its
    /// refusals are still part of the `REGISTRY_INVALID` contract -- a
    /// package whose own table does not decode is a package-integrity
    /// failure -- so they are exercised at the reader.
    #[test]
    fn a_class_table_that_does_not_decode_is_a_package_integrity_failure() {
        fn header(major: u8, header_len: usize) -> Vec<u8> {
            let mut bytes = b"\x93NUMPY".to_vec();
            bytes.push(major);
            bytes.push(0);
            if major == 1 {
                bytes.extend_from_slice(&(header_len as u16).to_le_bytes());
            } else {
                bytes.extend_from_slice(&(header_len as u32).to_le_bytes());
            }
            bytes.extend(std::iter::repeat_n(b' ', header_len));
            bytes
        }

        // A well-formed v1 document of the expected size is accepted.
        let mut good = header(1, 8);
        good.extend_from_slice(&[7u8; 4]);
        assert_eq!(npy_u8_payload(&good, 4).expect("a valid table"), &[7u8; 4]);

        let cases: [(&str, Vec<u8>); 5] = [
            ("invalid NPY magic", b"not an npy file at all".to_vec()),
            ("truncated NPY header", b"\x93NUMPY".to_vec()),
            ("truncated NPY header", b"\x93NUMPY\x01\x00".to_vec()),
            ("unsupported NPY version", header(4, 0)),
            ("NPY payload has 0 bytes; expected 4", header(1, 0)),
        ];
        for (expected_message, bytes) in cases {
            let error = npy_u8_payload(&bytes, 4).expect_err(expected_message);
            assert_eq!(
                error.code(),
                ErrorCode::RegistryInvalid,
                "{expected_message}"
            );
            assert_eq!(error.code().as_str(), "REGISTRY_INVALID");
            assert_eq!(error.message(), expected_message);
        }

        // A header that runs past the end of the document.
        let error = npy_u8_payload(&header(2, 0)[..11], 4).expect_err("truncated");
        assert_eq!(error.code(), ErrorCode::RegistryInvalid);
    }

    #[test]
    fn unparseable_tokenizer_json_is_a_kernel_failure_not_a_hash_mismatch() {
        // Content-hash verification happens before table construction, so
        // a parse failure here must not reuse the hash-mismatch contract
        // code; it reports as a kernel-construction failure.
        let error = match BpeTables::from_tokenizer_json(b"not json") {
            Ok(_) => panic!("non-JSON bytes must not build kernel tables"),
            Err(error) => error,
        };
        assert_eq!(error.code(), ErrorCode::KernelIncompatible);
    }

    #[test]
    fn every_class_table_the_routing_data_names_is_embedded() {
        // The crate carries its own copy of each table, so a family whose
        // table is packaged but not embedded would only fail on hardware,
        // and only for that family.
        let registry = crate::manifest::Registry::load().expect("registry");
        for (family, kernel) in &registry.kernel_families {
            let spec = registry
                .class_tables
                .get(&kernel.class_table)
                .unwrap_or_else(|| panic!("{family}: class table mapping is incomplete"));
            let embedded =
                class_file(&spec.file).unwrap_or_else(|error| panic!("{family}: {error}"));
            assert_eq!(
                sha256_hex(embedded),
                spec.sha256.trim_start_matches("sha256:"),
                "{family}: embedded table disagrees with the routing digest"
            );
        }
    }
}