Skip to main content

oa/ml/
tokenizer.rs

1//! Deterministic byte-pair tokenization for language-model inputs.
2
3use std::{collections::BTreeMap, fs, path::Path};
4
5use crate::{Error, Result};
6
7const BPE_MAGIC: &str = "oa_bpe_v1";
8const BASE_VOCAB_SIZE: usize = 256;
9const MAX_PERSISTED_MERGES: usize = 1_000_000;
10
11/// One learned byte-pair merge. Merge rank `i` creates token `256 + i`.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub struct BpeMerge {
14	/// Left byte or previously learned token.
15	pub left: u32,
16	/// Right byte or previously learned token.
17	pub right: u32,
18}
19
20/// Deterministic byte-pair encoder compatible with OA's `oa_bpe_v1` files.
21pub struct BpeTokenizer {
22	target_vocab: usize,
23	merges: Vec<BpeMerge>,
24}
25
26impl BpeTokenizer {
27	/// Construct an untrained tokenizer, clamping the target to the 256 base bytes.
28	pub fn new(target_vocab: usize) -> Self {
29		Self {
30			target_vocab: target_vocab.clamp(BASE_VOCAB_SIZE, u32::MAX as usize),
31			merges: Vec::new(),
32		}
33	}
34
35	/// Learn at most `num_merges` deterministic pair ranks from raw bytes.
36	pub fn train(&mut self, bytes: &[u8], num_merges: usize) {
37		self.merges.clear();
38		let mut ids = bytes
39			.iter()
40			.map(|byte| u32::from(*byte))
41			.collect::<Vec<_>>();
42		let limit = num_merges.min(self.target_vocab - BASE_VOCAB_SIZE);
43		for _ in 0..limit {
44			if ids.len() < 2 {
45				break;
46			}
47			let mut counts = BTreeMap::<(u32, u32), usize>::new();
48			for pair in ids.windows(2) {
49				*counts.entry((pair[0], pair[1])).or_default() += 1;
50			}
51			let best = counts.into_iter().filter(|(_, count)| *count >= 2).max_by(
52				|(left_pair, left_count), (right_pair, right_count)| {
53					left_count
54						.cmp(right_count)
55						.then_with(|| right_pair.cmp(left_pair))
56				},
57			);
58			let Some(((left, right), _)) = best else {
59				break;
60			};
61			let merge = BpeMerge { left, right };
62			let new_token = u32::try_from(BASE_VOCAB_SIZE + self.merges.len())
63				.expect("BPE target vocabulary cannot exceed usize before u32");
64			self.merges.push(merge);
65			ids = apply_merge(&ids, merge, new_token);
66		}
67	}
68
69	/// Learn merges from UTF-8 text without changing its byte representation.
70	pub fn train_text(&mut self, text: &str, num_merges: usize) {
71		self.train(text.as_bytes(), num_merges);
72	}
73
74	/// Apply learned ranks to raw bytes.
75	pub fn encode(&self, bytes: &[u8]) -> Vec<u32> {
76		let mut tokens = bytes
77			.iter()
78			.map(|byte| u32::from(*byte))
79			.collect::<Vec<_>>();
80		for (rank, merge) in self.merges.iter().copied().enumerate() {
81			let new_token =
82				u32::try_from(BASE_VOCAB_SIZE + rank).expect("validated BPE rank must fit u32");
83			tokens = apply_merge(&tokens, merge, new_token);
84		}
85		tokens
86	}
87
88	/// Apply learned ranks to UTF-8 text.
89	pub fn encode_text(&self, text: &str) -> Vec<u32> {
90		self.encode(text.as_bytes())
91	}
92
93	/// Expand valid tokens recursively to their exact original bytes.
94	///
95	/// Negative C++ token IDs cannot occur in this Rust spelling. Unknown token
96	/// IDs are ignored, matching the donor decoder's failure behavior.
97	///
98	/// # Errors
99	///
100	/// Returns [`crate::ErrorKind::ResourceExhausted`] when expansion storage
101	/// cannot be reserved. Expansion is iterative, so nested persisted ranks do
102	/// not consume the native call stack.
103	pub fn decode(&self, tokens: &[u32]) -> Result<Vec<u8>> {
104		let mut output = Vec::new();
105		let mut pending = Vec::new();
106		pending
107			.try_reserve(tokens.len())
108			.map_err(|_| Error::resource_exhausted("BPE decode stack allocation failed"))?;
109		pending.extend(tokens.iter().rev().copied());
110		while let Some(token) = pending.pop() {
111			if token < BASE_VOCAB_SIZE as u32 {
112				output
113					.try_reserve(1)
114					.map_err(|_| Error::resource_exhausted("BPE decoded output allocation failed"))?;
115				output.push(token as u8);
116				continue;
117			}
118			let Ok(rank) = usize::try_from(token - BASE_VOCAB_SIZE as u32) else {
119				continue;
120			};
121			let Some(merge) = self.merges.get(rank) else {
122				continue;
123			};
124			pending
125				.try_reserve(2)
126				.map_err(|_| Error::resource_exhausted("BPE decode stack allocation failed"))?;
127			pending.push(merge.right);
128			pending.push(merge.left);
129		}
130		Ok(output)
131	}
132
133	/// Decode tokens as UTF-8 text.
134	///
135	/// # Errors
136	///
137	/// Returns [`crate::ErrorKind::DataLoss`] when the exact decoded bytes are not
138	/// valid UTF-8.
139	pub fn decode_text(&self, tokens: &[u32]) -> Result<String> {
140		String::from_utf8(self.decode(tokens)?)
141			.map_err(|_| Error::data_loss("BPE tokens do not decode to valid UTF-8"))
142	}
143
144	/// Right-align an encoded prompt in a zero-padded fixed context.
145	pub fn encode_prompt(&self, prompt: &[u8], context_length: usize) -> Vec<u32> {
146		let tokens = self.encode(prompt);
147		let copied = tokens.len().min(context_length);
148		let mut output = vec![0_u32; context_length];
149		output[context_length - copied..].copy_from_slice(&tokens[tokens.len() - copied..]);
150		output
151	}
152
153	/// Persist exact merge ranks in OA's architecture-independent text format.
154	///
155	/// # Errors
156	///
157	/// Returns an I/O error when the file cannot be written.
158	pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
159		let mut text = format!("{BPE_MAGIC}\n{}\n", self.merges.len());
160		for merge in &self.merges {
161			text.push_str(&format!("{} {}\n", merge.left, merge.right));
162		}
163		fs::write(path, text).map_err(|source| Error::io("BPE vocabulary write", source))
164	}
165
166	/// Load exact merge ranks transactionally from an OA `oa_bpe_v1` file.
167	///
168	/// # Errors
169	///
170	/// Returns an I/O error when reading fails or [`crate::ErrorKind::DataLoss`]
171	/// when the header, count, integer syntax, or merge dependency order is invalid.
172	pub fn load(&mut self, path: impl AsRef<Path>) -> Result<()> {
173		let bytes = fs::read(path).map_err(|source| Error::io("BPE vocabulary read", source))?;
174		let text = std::str::from_utf8(&bytes)
175			.map_err(|_| Error::data_loss("BPE vocabulary is not UTF-8 text"))?;
176		let mut fields = text.split_ascii_whitespace();
177		if fields.next() != Some(BPE_MAGIC) {
178			return Err(Error::data_loss("BPE vocabulary has an invalid header"));
179		}
180		let count = parse_usize(fields.next(), "merge count")?;
181		if count > MAX_PERSISTED_MERGES {
182			return Err(Error::data_loss("BPE merge count exceeds the format limit"));
183		}
184		let mut merges = Vec::with_capacity(count);
185		for rank in 0..count {
186			let left = parse_u32(fields.next(), "left merge token")?;
187			let right = parse_u32(fields.next(), "right merge token")?;
188			let next_token = u32::try_from(BASE_VOCAB_SIZE + rank)
189				.map_err(|_| Error::data_loss("BPE token rank exceeds u32"))?;
190			if left >= next_token || right >= next_token {
191				return Err(Error::data_loss(
192					"BPE merge references its own or a later token",
193				));
194			}
195			merges.push(BpeMerge { left, right });
196		}
197		if fields.next().is_some() {
198			return Err(Error::data_loss("BPE vocabulary has trailing fields"));
199		}
200		self.target_vocab = BASE_VOCAB_SIZE + merges.len();
201		self.merges = merges;
202		Ok(())
203	}
204
205	/// Current vocabulary size, including the 256 base bytes.
206	pub const fn vocab_size(&self) -> usize {
207		BASE_VOCAB_SIZE + self.merges.len()
208	}
209
210	/// Number of learned merge ranks.
211	pub const fn num_merges(&self) -> usize {
212		self.merges.len()
213	}
214
215	/// Borrow the deterministic learned merge sequence.
216	pub fn merges(&self) -> &[BpeMerge] {
217		&self.merges
218	}
219
220	/// Return the exact decoded byte width of one valid token.
221	///
222	/// Unknown tokens have width zero, matching decode's skip behavior.
223	///
224	/// # Errors
225	///
226	/// Returns [`crate::ErrorKind::ResourceExhausted`] when the expansion width
227	/// or temporary traversal storage cannot be represented.
228	pub fn token_byte_len(&self, token: u32) -> Result<usize> {
229		let mut length = 0_usize;
230		let mut pending = vec![token];
231		while let Some(token) = pending.pop() {
232			if token < BASE_VOCAB_SIZE as u32 {
233				length = length
234					.checked_add(1)
235					.ok_or_else(|| Error::resource_exhausted("BPE token byte length overflows usize"))?;
236				continue;
237			}
238			let Ok(rank) = usize::try_from(token - BASE_VOCAB_SIZE as u32) else {
239				continue;
240			};
241			let Some(merge) = self.merges.get(rank) else {
242				continue;
243			};
244			pending
245				.try_reserve(2)
246				.map_err(|_| Error::resource_exhausted("BPE token traversal allocation failed"))?;
247			pending.push(merge.right);
248			pending.push(merge.left);
249		}
250		Ok(length)
251	}
252}
253
254impl Default for BpeTokenizer {
255	fn default() -> Self {
256		Self::new(512)
257	}
258}
259
260fn apply_merge(ids: &[u32], merge: BpeMerge, new_token: u32) -> Vec<u32> {
261	let mut output = Vec::with_capacity(ids.len());
262	let mut index = 0;
263	while index < ids.len() {
264		if index + 1 < ids.len() && ids[index] == merge.left && ids[index + 1] == merge.right {
265			output.push(new_token);
266			index += 2;
267		} else {
268			output.push(ids[index]);
269			index += 1;
270		}
271	}
272	output
273}
274
275fn parse_usize(field: Option<&str>, label: &str) -> Result<usize> {
276	field
277		.and_then(|field| field.parse().ok())
278		.ok_or_else(|| Error::data_loss(format!("BPE vocabulary has an invalid {label}")))
279}
280
281fn parse_u32(field: Option<&str>, label: &str) -> Result<u32> {
282	field
283		.and_then(|field| field.parse().ok())
284		.ok_or_else(|| Error::data_loss(format!("BPE vocabulary has an invalid {label}")))
285}