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
// Contract: Tokenizer Trait
//
// This file defines the interface that all tokenizer implementations must follow.
// It is a specification document, not compilable code.
/// Tokenizer trait for encoding/decoding text to/from token IDs
///
/// All tokenizer implementations must be thread-safe (Send + Sync) to enable
/// future parallelization and use in multi-threaded contexts.
// Implementation Notes:
//
// 1. Thread Safety:
// - All implementations must be Send + Sync
// - Tokenizers may cache internal state (e.g., BPE encoder)
// - Must not use mutable state without synchronization
//
// 2. Performance:
// - encode() should minimize allocations (use &str, not String)
// - count_tokens() may be optimized to avoid allocating Vec<u32>
// - Implementations should lazy-load tokenizer data (not in constructor)
//
// 3. Error Handling:
// - encode() fails on invalid UTF-8 (should be caught earlier)
// - decode() fails on invalid token IDs (e.g., out of vocab range)
// - Implementations should not panic (return Result)
//
// 4. Special Tokens:
// - OpenAI models: encode_with_special_tokens() handles <|endoftext|>, etc.
// - Other models: TBD based on provider specifications
//
// 5. Zero-Copy:
// - Use &str (not String) to avoid cloning large inputs
// - Return Vec<u32> (caller owns, can reuse)
// - Decode returns String (must allocate, UTF-8 construction)
// Future Extensions (Post-MVP):
//
// 1. Streaming Interface:
// fn encode_streaming(&self, text: &str, callback: impl FnMut(u32)) -> Result<(), TokenError>;
// - Useful for very large inputs (avoid allocating full Vec)
//
// 2. Batch Encoding:
// fn encode_batch(&self, texts: &[&str]) -> Result<Vec<Vec<u32>>, TokenError>;
// - Parallelize encoding across multiple inputs
//
// 3. Metadata:
// fn vocab_size(&self) -> usize;
// fn special_tokens(&self) -> &[String];
// - Expose tokenizer internals for advanced use cases