exatok 0.1.1

Exact GPU-resident BPE tokenizer whose token ids match tiktoken byte for byte
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
//! Host reference BPE. OWNER: CpuRef.
//!
//! Exact leftmost-greedy-lowest-rank merging over pretokens. This is the
//! oracle every GPU path is gated against, so it optimizes for auditability
//! over speed.
//!
//! Acceptance: byte-exact token ids versus the reference tokenizer across the
//! parity corpus for both `gpt2` and `cl100k_base`.
//!
//! # Semantics
//!
//! One pretoken is encoded by repeating a single rule until it no longer
//! applies: find the adjacent pair with the lowest rank in the merge table,
//! break ties toward the leftmost occurrence, and replace that pair with its
//! merged id. Two properties of the rule matter and are easy to get wrong:
//!
//! 1. Selection is by rank, not by position. A pair further right wins if its
//!    rank is lower, so a left-to-right first-match scan is not equivalent.
//! 2. A merged id can pair with its neighbour, and that new pair may carry a
//!    lower rank than anything the sequence started with. Ranks therefore
//!    cannot be pre-sorted once and replayed; selection must be recomputed
//!    after every merge.
//!
//! Termination is structural: every merge removes exactly one element, so at
//! most `len - 1` merges run on a pretoken of length `len`.

use std::collections::BTreeMap;

use crate::{PairKey, Rank, TokenId, ExatokError};

/// What a merge table holds for a mergeable pair.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MergeEntry {
    /// Id of the token the pair merges into.
    pub id: TokenId,
    /// Merge rank. Lower ranks merge first.
    pub rank: Rank,
}

/// Read-only merge table: `PairKey -> (TokenId, Rank)`.
///
/// The encoder takes a table by reference so a loaded vocabulary, a synthetic
/// test table, and a device-table readback all drive the identical oracle.
pub trait MergeTable {
    /// Entry for `pair`, or `None` when the pair is not mergeable.
    fn lookup(&self, pair: PairKey) -> Option<MergeEntry>;

    /// Rank for `pair`, or [`Rank::ABSENT`] on a miss.
    ///
    /// Mirrors the device probe, which writes the miss sentinel into the rank
    /// array instead of signalling absence out of band.
    fn rank(&self, pair: PairKey) -> Rank {
        match self.lookup(pair) {
            Some(entry) => entry.rank,
            None => Rank::ABSENT,
        }
    }
}

impl<T: MergeTable + ?Sized> MergeTable for &T {
    fn lookup(&self, pair: PairKey) -> Option<MergeEntry> {
        (**self).lookup(pair)
    }
}

/// Host merge table backed by an ordered map.
///
/// Ordered rather than hashed so [`HostMergeTable::iter`] is reproducible: a
/// device upload built from it must not vary between runs.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HostMergeTable {
    entries: BTreeMap<PairKey, MergeEntry>,
}

impl HostMergeTable {
    /// An empty table.
    #[must_use]
    pub fn new() -> Self {
        Self {
            entries: BTreeMap::new(),
        }
    }

    /// Build from `(pair, merged id, rank)` triples.
    ///
    /// `artifact` names the source for error reporting, for example
    /// `cl100k_base.tiktoken`.
    pub fn from_entries(
        artifact: &str,
        entries: impl IntoIterator<Item = (PairKey, TokenId, Rank)>,
    ) -> Result<Self, ExatokError> {
        let mut table = Self::new();
        for (pair, id, rank) in entries {
            table.insert(artifact, pair, id, rank)?;
        }
        Ok(table)
    }

    /// Record one merge.
    ///
    /// Rejects [`Rank::ABSENT`] as a real rank, which would make a pair both
    /// present and invisible to the minimum reduction, and rejects a duplicate
    /// pair, which would silently pick one of two conflicting merges. The table
    /// is left unchanged when either check fails.
    pub fn insert(
        &mut self,
        artifact: &str,
        pair: PairKey,
        id: TokenId,
        rank: Rank,
    ) -> Result<(), ExatokError> {
        if !rank.is_present() {
            return Err(ExatokError::Artifact {
                artifact: artifact.to_owned(),
                location: pair_location(pair),
                detail: "merge rank equals the ABSENT sentinel u32::MAX".to_owned(),
                fix: "renumber merges so every real rank stays below u32::MAX, \
                      keeping the sentinel unused so a min reduction skips \
                      unmergeable pairs"
                    .to_owned(),
            });
        }
        if let Some(existing) = self.entries.get(&pair) {
            return Err(ExatokError::Artifact {
                artifact: artifact.to_owned(),
                location: pair_location(pair),
                detail: format!(
                    "duplicate merge: rank {} already recorded, rank {} seen again",
                    existing.rank.0, rank.0
                ),
                fix: "remove the repeated pair from the merge list so exactly \
                      one rank governs it"
                    .to_owned(),
            });
        }
        self.entries.insert(pair, MergeEntry { id, rank });
        Ok(())
    }

    /// Number of recorded merges.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// True when no merge is recorded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Merges in ascending packed-key order.
    pub fn iter(&self) -> impl Iterator<Item = (PairKey, MergeEntry)> + '_ {
        self.entries.iter().map(|(&pair, &entry)| (pair, entry))
    }
}

impl MergeTable for HostMergeTable {
    fn lookup(&self, pair: PairKey) -> Option<MergeEntry> {
        self.entries.get(&pair).copied()
    }
}

fn pair_location(pair: PairKey) -> String {
    format!("pair ({}, {})", pair.left().0, pair.right().0)
}

/// Leftmost occurrence of the lowest-rank adjacent pair, if any.
///
/// The comparison is strict, so an equal rank further right never displaces the
/// leftmost occurrence. That is the tie-break the reference tokenizers use.
fn best_merge(tokens: &[TokenId], table: &impl MergeTable) -> Option<(usize, MergeEntry)> {
    let mut best: Option<(usize, MergeEntry)> = None;
    for (index, window) in tokens.windows(2).enumerate() {
        let (Some(&left), Some(&right)) = (window.first(), window.get(1)) else {
            continue;
        };
        let Some(entry) = table.lookup(PairKey::new(left, right)) else {
            continue;
        };
        let wins = match best {
            None => true,
            Some((_, current)) => entry.rank < current.rank,
        };
        if wins {
            best = Some((index, entry));
        }
    }
    best
}

/// Replace the pair starting at `index` with `merged`.
///
/// Every index [`best_merge`] reports has a right neighbour; the length guard
/// keeps this helper total rather than relying on that from the outside.
fn apply_merge(state: &mut Vec<TokenId>, index: usize, merged: TokenId) {
    if index + 1 >= state.len() {
        return;
    }
    state[index] = merged;
    state.remove(index + 1);
}

/// Merge `state` until no adjacent pair is in `table`.
///
/// The single definition of the fixpoint loop. Both public encoders call it, so
/// the two entry points cannot drift: a defect here fails every caller instead
/// of hiding behind whichever one a given test happens to exercise.
fn merge_to_fixpoint(state: &mut Vec<TokenId>, table: &impl MergeTable) {
    while let Some((index, entry)) = best_merge(state, table) {
        apply_merge(state, index, entry.id);
    }
}

/// Encode one pretoken to its exact BPE ids.
#[must_use]
pub fn encode_pretoken(tokens: &[TokenId], table: &impl MergeTable) -> Vec<TokenId> {
    let mut state = tokens.to_vec();
    merge_to_fixpoint(&mut state, table);
    state
}

/// Encode a pretoken sequence into one flat id stream.
///
/// Pretokens are independent: merges never cross a pretoken boundary, which is
/// exactly the property the GPU path exploits for parallelism. One scratch
/// buffer is reused across pretokens, so this allocates once rather than once
/// per pretoken while running the identical loop as [`encode_pretoken`].
#[must_use]
pub fn encode<S: AsRef<[TokenId]>>(pretokens: &[S], table: &impl MergeTable) -> Vec<TokenId> {
    let mut ids = Vec::new();
    let mut state: Vec<TokenId> = Vec::new();
    for pretoken in pretokens {
        state.clear();
        state.extend_from_slice(pretoken.as_ref());
        merge_to_fixpoint(&mut state, table);
        ids.extend_from_slice(&state);
    }
    ids
}

/// One applied merge, with the sequence state it produced.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeStep {
    /// Index in the pre-merge sequence where the merged pair started.
    pub index: usize,
    /// The pair that merged.
    pub pair: PairKey,
    /// Id the pair merged into.
    pub merged: TokenId,
    /// Rank that won this pass.
    pub rank: Rank,
    /// Sequence state after this merge.
    pub state: Vec<TokenId>,
}

/// Merge history for one pretoken.
///
/// The GPU differential and the confluence experiment compare intermediate
/// states, not only final ids: a device pass that reaches the right answer by
/// the wrong merge order is a latent divergence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeTrace {
    initial: Vec<TokenId>,
    steps: Vec<MergeStep>,
}

impl MergeTrace {
    /// Sequence before any merge.
    #[must_use]
    pub fn initial(&self) -> &[TokenId] {
        &self.initial
    }

    /// Applied merges, in the order the encoder chose them.
    #[must_use]
    pub fn steps(&self) -> &[MergeStep] {
        &self.steps
    }

    /// Number of merges applied.
    #[must_use]
    pub fn merge_count(&self) -> usize {
        self.steps.len()
    }

    /// Final sequence, equal to [`encode_pretoken`] on the same input.
    #[must_use]
    pub fn final_state(&self) -> &[TokenId] {
        match self.steps.last() {
            Some(step) => &step.state,
            None => &self.initial,
        }
    }
}

/// Encode one pretoken, recording the state after every individual merge.
#[must_use]
pub fn trace_pretoken(tokens: &[TokenId], table: &impl MergeTable) -> MergeTrace {
    let mut state = tokens.to_vec();
    let mut steps = Vec::new();
    while let Some((index, entry)) = best_merge(&state, table) {
        let pair = match (state.get(index), state.get(index + 1)) {
            (Some(&left), Some(&right)) => PairKey::new(left, right),
            _ => break,
        };
        apply_merge(&mut state, index, entry.id);
        steps.push(MergeStep {
            index,
            pair,
            merged: entry.id,
            rank: entry.rank,
            state: state.clone(),
        });
    }
    MergeTrace {
        initial: tokens.to_vec(),
        steps,
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

    use super::{
        encode_pretoken, trace_pretoken, HostMergeTable, MergeEntry, MergeStep, MergeTable,
    };
    use crate::{PairKey, Rank, TokenId, ExatokError};

    fn pair(left: u32, right: u32) -> PairKey {
        PairKey::new(TokenId(left), TokenId(right))
    }

    /// Locks in that a present pair returns its exact merged id and rank.
    ///
    /// If `lookup` dropped or transposed the id and rank fields, the encoder
    /// would emit the rank as a token id and every downstream embedding lookup
    /// would read the wrong row.
    #[test]
    fn lookup_returns_exact_id_and_rank() {
        let table = HostMergeTable::from_entries(
            "synthetic",
            [(pair(1, 2), TokenId(300), Rank(7))],
        )
        .unwrap();

        assert_eq!(
            table.lookup(pair(1, 2)),
            Some(MergeEntry {
                id: TokenId(300),
                rank: Rank(7),
            })
        );
        assert_eq!(table.rank(pair(1, 2)), Rank(7));
        assert_eq!(table.len(), 1);
    }

    /// Locks in that a miss reports [`Rank::ABSENT`], not rank zero.
    ///
    /// `Rank::ABSENT` is `u32::MAX` so an unsigned min reduction skips absent
    /// pairs. If a miss returned `Rank(0)` instead, every unmergeable pair
    /// would look like the highest-priority merge in the sequence.
    #[test]
    fn missing_pair_reports_absent_sentinel() {
        let table = HostMergeTable::new();

        assert_eq!(table.lookup(pair(1, 2)), None);
        assert_eq!(table.rank(pair(1, 2)), Rank::ABSENT);
        assert_eq!(table.rank(pair(1, 2)).0, u32::MAX);
        assert!(!table.rank(pair(1, 2)).is_present());
        assert_eq!(table.len(), 0);
    }

    /// Locks out storing `Rank::ABSENT` as a real rank.
    ///
    /// Such an entry is present in the table yet invisible to the min
    /// reduction, so the host oracle would merge it while the device skipped
    /// it: a divergence that only shows up on the one vocabulary that has
    /// exactly `u32::MAX` merges.
    ///
    /// The `fix` clause is asserted verbatim because it carries the reason the
    /// sentinel must stay unused: an unsigned min reduction skips unmergeable
    /// pairs only while no real rank equals `u32::MAX`. A regression that
    /// reworded it into a generic remedy would strip the one explanation a
    /// maintainer acts on, and nothing else in the crate asserts that text.
    #[test]
    fn absent_sentinel_rejected_as_real_rank() {
        let error = HostMergeTable::from_entries(
            "synthetic.tiktoken",
            [(pair(1, 2), TokenId(9), Rank::ABSENT)],
        )
        .expect_err("ABSENT must not be accepted as a merge rank");

        match error {
            ExatokError::Artifact {
                artifact,
                location,
                detail,
                fix,
            } => {
                assert_eq!(artifact, "synthetic.tiktoken");
                assert_eq!(location, "pair (1, 2)");
                assert_eq!(detail, "merge rank equals the ABSENT sentinel u32::MAX");
                assert_eq!(
                    fix,
                    "renumber merges so every real rank stays below u32::MAX, keeping \
                     the sentinel unused so a min reduction skips unmergeable pairs"
                );
            }
            other => panic!("expected Artifact error, got {other:?}"),
        }
    }

    /// Locks out silently accepting two ranks for one pair.
    ///
    /// A duplicated pair in a merges file would leave the winning rank up to
    /// map insertion order, so the host and device could disagree on which of
    /// the two merges applies.
    ///
    /// The `fix` clause is asserted verbatim here too, and it differs from the
    /// sentinel path's clause, so a regression that copied one remedy onto every
    /// artifact error fails this test rather than shipping a remedy that names
    /// the wrong defect.
    #[test]
    fn duplicate_pair_rejected_and_table_unchanged() {
        let mut table =
            HostMergeTable::from_entries("synthetic", [(pair(1, 2), TokenId(9), Rank(4))]).unwrap();

        let error = table
            .insert("synthetic", pair(1, 2), TokenId(11), Rank(6))
            .expect_err("a duplicate pair must be rejected");

        match error {
            ExatokError::Artifact { detail, fix, .. } => {
                assert_eq!(
                    detail,
                    "duplicate merge: rank 4 already recorded, rank 6 seen again"
                );
                assert_eq!(
                    fix,
                    "remove the repeated pair from the merge list so exactly one rank \
                     governs it"
                );
            }
            other => panic!("expected Artifact error, got {other:?}"),
        }

        assert_eq!(table.len(), 1);
        assert_eq!(
            table.lookup(pair(1, 2)),
            Some(MergeEntry {
                id: TokenId(9),
                rank: Rank(4),
            })
        );
    }

    /// Locks in ascending packed-key iteration order.
    ///
    /// `iter` feeds the device table upload. A nondeterministic order would
    /// make two runs build different probe layouts from one vocabulary, so a
    /// collision-dependent bug would reproduce only intermittently.
    #[test]
    fn iter_is_ordered_by_packed_key() {
        let table = HostMergeTable::from_entries(
            "synthetic",
            [
                (pair(2, 0), TokenId(31), Rank(1)),
                (pair(1, 9), TokenId(30), Rank(2)),
                (pair(1, 3), TokenId(32), Rank(0)),
            ],
        )
        .unwrap();

        let keys: Vec<(u32, u32)> = table
            .iter()
            .map(|(key, _)| (key.left().0, key.right().0))
            .collect();

        assert_eq!(keys, vec![(1, 3), (1, 9), (2, 0)]);
    }

    /// Three chained merges: `(1,2) -> 10`, then `(10,3) -> 11`, then `(11,4) -> 12`.
    ///
    /// The merges chain rather than stand independent so a loop that stops one
    /// iteration early leaves a visibly longer sequence instead of the right
    /// answer reached by luck.
    fn chain_table() -> HostMergeTable {
        HostMergeTable::from_entries(
            "synthetic.chain",
            [
                (pair(1, 2), TokenId(10), Rank(0)),
                (pair(10, 3), TokenId(11), Rank(1)),
                (pair(11, 4), TokenId(12), Rank(2)),
            ],
        )
        .unwrap()
    }

    /// Locks [`trace_pretoken`] to the same final sequence as the real loop.
    ///
    /// `trace_pretoken` is the only genuine second copy of the fixpoint loop in
    /// this file. `encode` and `encode_pretoken` both call `merge_to_fixpoint`,
    /// so those two cannot drift, but the trace walks `best_merge` and
    /// `apply_merge` itself in order to record each step. It therefore cannot
    /// drift on merge selection, only on loop structure and termination, and it
    /// carries a `_ => break` arm that the real loop does not have. If that arm
    /// ever fires, or the trace loop exits early, the trace reports a final
    /// state the encoder never produces, and every divergence hunt driven by a
    /// trace chases a sequence the tokenizer does not emit.
    ///
    /// [`MergeTrace::final_state`] documents this equality as its contract, and
    /// before this test nothing anywhere asserted it.
    #[test]
    fn trace_final_state_matches_encode_pretoken() {
        let table = chain_table();

        let inputs: Vec<Vec<TokenId>> = vec![
            vec![],
            vec![TokenId(1)],
            vec![TokenId(7), TokenId(8)],
            vec![TokenId(1), TokenId(2)],
            vec![TokenId(1), TokenId(2), TokenId(3)],
            vec![TokenId(1), TokenId(2), TokenId(3), TokenId(4)],
            vec![
                TokenId(1),
                TokenId(2),
                TokenId(3),
                TokenId(4),
                TokenId(1),
                TokenId(2),
            ],
        ];

        for tokens in inputs {
            let encoded = encode_pretoken(&tokens, &table);
            let trace = trace_pretoken(&tokens, &table);

            assert_eq!(
                trace.final_state(),
                encoded.as_slice(),
                "trace and encoder disagree on {tokens:?}"
            );
            assert_eq!(trace.initial(), tokens.as_slice());
        }
    }

    /// Pins the exact per-step trace for the three-merge chain.
    ///
    /// Agreement on the final state alone still passes if the trace records the
    /// right ending with wrong intermediate states, indices, or ranks, which is
    /// exactly what a trace exists to show. These are the values a maintainer
    /// reads when localizing a device divergence, so they are asserted as whole
    /// sequences rather than counts.
    #[test]
    fn trace_records_every_step_with_exact_indices_and_ranks() {
        let table = chain_table();
        let tokens = vec![TokenId(1), TokenId(2), TokenId(3), TokenId(4)];

        let trace = trace_pretoken(&tokens, &table);

        assert_eq!(encode_pretoken(&tokens, &table), vec![TokenId(12)]);
        assert_eq!(trace.merge_count(), 3);
        assert_eq!(trace.final_state(), &[TokenId(12)]);

        let expected = [
            MergeStep {
                index: 0,
                pair: pair(1, 2),
                merged: TokenId(10),
                rank: Rank(0),
                state: vec![TokenId(10), TokenId(3), TokenId(4)],
            },
            MergeStep {
                index: 0,
                pair: pair(10, 3),
                merged: TokenId(11),
                rank: Rank(1),
                state: vec![TokenId(11), TokenId(4)],
            },
            MergeStep {
                index: 0,
                pair: pair(11, 4),
                merged: TokenId(12),
                rank: Rank(2),
                state: vec![TokenId(12)],
            },
        ];

        assert_eq!(trace.steps(), expected.as_slice());
    }

    /// Locks in that an input with no applicable merge traces zero steps and
    /// still reports its input as the final state.
    ///
    /// This is the branch where `final_state()` falls through to `initial`
    /// rather than to the last step. If that fallback returned an empty slice,
    /// an unmergeable pretoken would appear to encode to nothing, dropping
    /// tokens silently rather than failing.
    #[test]
    fn unmergeable_input_traces_no_steps_and_keeps_its_bytes() {
        let table = chain_table();
        let tokens = vec![TokenId(7), TokenId(8), TokenId(9)];

        let trace = trace_pretoken(&tokens, &table);

        assert_eq!(trace.merge_count(), 0);
        assert!(trace.steps().is_empty());
        assert_eq!(trace.final_state(), &[TokenId(7), TokenId(8), TokenId(9)]);
        assert_eq!(
            encode_pretoken(&tokens, &table),
            vec![TokenId(7), TokenId(8), TokenId(9)]
        );
    }
}