interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / infer / tokenizer.rs

265 lines · 9995 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Byte-level BPE tokenizer.
17//!
18//! Vocabulary text is UTF-8 with one record per line. `T id hexbytes` adds a
19//! regular token, `M left_id right_id` adds a merge (records are in increasing
20//! rank order), and `S id hexbytes` adds a special token. Hex is case
21//! insensitive, must contain complete byte pairs, and may be empty. Blank
22//! lines and lines whose first non-space character is `#` are ignored. Token
23//! IDs are unique across `T` and `S`; merge pairs are unique. The merged token
24//! is found by concatenating the two vocabulary byte strings, so it must have
25//! a `T` record. Every byte value used by input must have a one-byte `T`
26//! record, allowing explicit byte fallback without lossy unknown handling.
27
28use alloc::collections::BTreeMap;
29use alloc::vec::Vec;
30use core::cmp::Reverse;
31
32/// Failure while loading vocabulary data or encoding/decoding tokens.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub enum TokenizerError {
35 InvalidRecord,
36 InvalidId,
37 InvalidHex,
38 DuplicateId(u32),
39 DuplicateMerge(u32, u32),
40 MissingToken(u32),
41 MissingByte(u8),
42}
43
44/// A byte-level BPE vocabulary with ranked merges and special tokens.
45#[derive(Clone, Debug)]
46pub struct BpeTokenizer {
47 tokens: BTreeMap<u32, Vec<u8>>,
48 ids_by_bytes: BTreeMap<Vec<u8>, u32>,
49 merges: Vec<(u32, u32)>,
50 specials: Vec<(u32, Vec<u8>)>,
51}
52
53impl BpeTokenizer {
54 /// Load `T`, `M`, and `S` records from the documented text format.
55 pub fn from_text(input: &str) -> Result<Self, TokenizerError> {
56 let mut tokenizer = Self {
57 tokens: BTreeMap::new(),
58 ids_by_bytes: BTreeMap::new(),
59 merges: Vec::new(),
60 specials: Vec::new(),
61 };
62 for line in input.lines() {
63 let line = line.split('#').next().unwrap_or("").trim();
64 if line.is_empty() {
65 continue;
66 }
67 let fields: Vec<&str> = line.split_whitespace().collect();
68 match fields.as_slice() {
69 ["T", id, bytes] | ["S", id, bytes] => {
70 let id = id.parse().map_err(|_| TokenizerError::InvalidId)?;
71 let bytes = decode_hex(bytes)?;
72 if fields[0] == "S" && bytes.is_empty() {
73 return Err(TokenizerError::InvalidRecord);
74 }
75 if tokenizer.tokens.contains_key(&id) {
76 return Err(TokenizerError::DuplicateId(id));
77 }
78 if fields[0] == "T" {
79 if tokenizer.ids_by_bytes.contains_key(&bytes) {
80 return Err(TokenizerError::InvalidRecord);
81 }
82 tokenizer.ids_by_bytes.insert(bytes.clone(), id);
83 } else {
84 tokenizer.specials.push((id, bytes.clone()));
85 }
86 tokenizer.tokens.insert(id, bytes);
87 }
88 ["M", left, right] => {
89 let left = left.parse().map_err(|_| TokenizerError::InvalidId)?;
90 let right = right.parse().map_err(|_| TokenizerError::InvalidId)?;
91 if tokenizer.merges.contains(&(left, right)) {
92 return Err(TokenizerError::DuplicateMerge(left, right));
93 }
94 tokenizer.merges.push((left, right));
95 }
96 _ => return Err(TokenizerError::InvalidRecord),
97 }
98 }
99 for (left, right) in &tokenizer.merges {
100 if !tokenizer.tokens.contains_key(left) {
101 return Err(TokenizerError::MissingToken(*left));
102 }
103 if !tokenizer.tokens.contains_key(right) {
104 return Err(TokenizerError::MissingToken(*right));
105 }
106 let mut bytes = tokenizer.tokens[left].clone();
107 bytes.extend_from_slice(&tokenizer.tokens[right]);
108 if !tokenizer.ids_by_bytes.contains_key(&bytes) {
109 return Err(TokenizerError::InvalidRecord);
110 }
111 }
112 tokenizer
113 .specials
114 .sort_by_key(|special| Reverse(special.1.len()));
115 Ok(tokenizer)
116 }
117
118 /// Encode UTF-8 text, matching special tokens before applying BPE.
119 pub fn encode(&self, text: &str) -> Result<Vec<u32>, TokenizerError> {
120 let input = text.as_bytes();
121 let mut output = Vec::new();
122 let mut ordinary = Vec::new();
123 let mut offset = 0;
124 while offset < input.len() {
125 if let Some((id, bytes)) = self
126 .specials
127 .iter()
128 .find(|(_, bytes)| input[offset..].starts_with(bytes))
129 {
130 self.encode_bytes(&ordinary, &mut output)?;
131 ordinary.clear();
132 output.push(*id);
133 offset += bytes.len();
134 } else {
135 ordinary.push(input[offset]);
136 offset += 1;
137 }
138 }
139 self.encode_bytes(&ordinary, &mut output)?;
140 Ok(output)
141 }
142
143 /// Decode token IDs to their original bytes.
144 pub fn decode(&self, ids: &[u32]) -> Result<Vec<u8>, TokenizerError> {
145 let mut output = Vec::new();
146 for id in ids {
147 let bytes = self
148 .tokens
149 .get(id)
150 .ok_or(TokenizerError::MissingToken(*id))?;
151 output.extend_from_slice(bytes);
152 }
153 Ok(output)
154 }
155
156 fn encode_bytes(&self, bytes: &[u8], output: &mut Vec<u32>) -> Result<(), TokenizerError> {
157 let mut pieces = Vec::with_capacity(bytes.len());
158 for byte in bytes {
159 pieces.push(
160 *self
161 .ids_by_bytes
162 .get(&[*byte][..])
163 .ok_or(TokenizerError::MissingByte(*byte))?,
164 );
165 }
166 loop {
167 let best = self.merges.iter().enumerate().find_map(|(rank, pair)| {
168 pieces
169 .windows(2)
170 .position(|window| window == [pair.0, pair.1])
171 .map(|at| (rank, at))
172 });
173 let Some((_, at)) = best else { break };
174 let left = self.tokens[&pieces[at]].as_slice();
175 let right = self.tokens[&pieces[at + 1]].as_slice();
176 let mut merged = Vec::with_capacity(left.len() + right.len());
177 merged.extend_from_slice(left);
178 merged.extend_from_slice(right);
179 pieces[at] = self.ids_by_bytes[&merged];
180 pieces.remove(at + 1);
181 }
182 output.extend(pieces);
183 Ok(())
184 }
185}
186
187fn decode_hex(hex: &str) -> Result<Vec<u8>, TokenizerError> {
188 if hex.len() & 1 != 0 {
189 return Err(TokenizerError::InvalidHex);
190 }
191 let mut bytes = Vec::with_capacity(hex.len() / 2);
192 let encoded = hex.as_bytes();
193 for index in (0..encoded.len()).step_by(2) {
194 let high = hex_digit(encoded[index]).ok_or(TokenizerError::InvalidHex)?;
195 let low = hex_digit(encoded[index + 1]).ok_or(TokenizerError::InvalidHex)?;
196 bytes.push((high << 4) | low);
197 }
198 Ok(bytes)
199}
200
201fn hex_digit(byte: u8) -> Option<u8> {
202 match byte {
203 b'0'..=b'9' => Some(byte - b'0'),
204 b'a'..=b'f' => Some(byte - b'a' + 10),
205 b'A'..=b'F' => Some(byte - b'A' + 10),
206 _ => None,
207 }
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213 use alloc::format;
214
215 fn tiny() -> BpeTokenizer {
216 let mut vocab = String::new();
217 for byte in 0u8..=255 {
218 vocab.push_str(&format!("T {} {:02x}\n", byte, byte));
219 }
220 vocab.push_str("T 300 6869\nT 301 686920\nT 302 6869207468657265\n");
221 vocab.push_str("T 303 7468\nT 304 746865\nT 305 74686572\nT 306 7468657265\n");
222 vocab.push_str("S 400 3c7c626f737c3e\nS 401 3c7c656f737c3e\n");
223 vocab.push_str("M 104 105\nM 116 104\nM 303 101\nM 304 114\nM 305 101\n");
224 vocab.push_str("M 300 32\nM 301 306\n");
225 BpeTokenizer::from_text(&vocab).unwrap()
226 }
227
228 #[test]
229 fn applies_lowest_ranked_merge_first() {
230 let tokenizer = tiny();
231 assert_eq!(tokenizer.encode("hi").unwrap(), vec![300]);
232 assert_eq!(tokenizer.encode("hi there").unwrap(), vec![302]);
233 }
234
235 #[test]
236 fn round_trips_ascii_utf8_empty_and_fallback() {
237 let tokenizer = tiny();
238 for text in ["hello", "AIENOS", "héllo 世界", "", "🦀"] {
239 let ids = tokenizer.encode(text).unwrap();
240 assert_eq!(tokenizer.decode(&ids).unwrap(), text.as_bytes());
241 }
242 assert_eq!(tokenizer.encode("?").unwrap(), vec![b'?' as u32]);
243 }
244
245 #[test]
246 fn matches_special_tokens_before_bpe() {
247 let tokenizer = tiny();
248 let ids = tokenizer.encode("<|bos|>hi<|eos|>").unwrap();
249 assert_eq!(ids, vec![400, 300, 401]);
250 assert_eq!(tokenizer.decode(&ids).unwrap(), b"<|bos|>hi<|eos|>");
251 }
252
253 #[test]
254 fn reports_missing_byte_and_bad_format() {
255 assert_eq!(
256 BpeTokenizer::from_text("T 1 0").unwrap_err(),
257 TokenizerError::InvalidHex
258 );
259 let tokenizer = BpeTokenizer::from_text("T 1 61").unwrap();
260 assert_eq!(
261 tokenizer.encode("b"),
262 Err(TokenizerError::MissingByte(b'b'))
263 );
264 }
265}