Skip to main content

kute/
lib.rs

1//! Kannaka Universal Tokenization Engine.
2//!
3//! [`Engine`] wires the built-in algorithms and adapters into one registry and
4//! offers the operations the CLI, the Python bindings and the benchmarks share:
5//! train through an adapter, encode and decode raw bytes, verify a vocabulary
6//! against its own test vectors.
7//!
8//! ```
9//! use kute::{Engine, TrainingConfig, VocabularyId, Pretokenizer, AdapterConfig};
10//!
11//! let engine = Engine::new();
12//! let mut config = TrainingConfig::new(VocabularyId::parse("example:greetings").unwrap(), 300);
13//! config.pretokenizer = Pretokenizer::Gpt4;
14//! let corpus = vec![b"hello hello hello world".to_vec()];
15//! let vocab = engine.train("bpe", "text", &AdapterConfig::default(), &corpus, &config).unwrap();
16//! let tokenizer = engine.tokenizer(vocab).unwrap();
17//! let tokens = engine.encode_raw(tokenizer.as_ref(), b"hello world").unwrap();
18//! assert_eq!(engine.decode_raw(tokenizer.as_ref(), &tokens).unwrap(), b"hello world");
19//! ```
20
21use rayon::prelude::*;
22use serde::Serialize;
23use std::path::{Path, PathBuf};
24
25pub use kute_adapters as adapters;
26pub use kute_algorithms as algorithms;
27pub use kute_bpe as bpe;
28pub use kute_core::{
29    check_sequence, decoded_bytes_at_least, decoded_units, AdapterCapabilities, CorpusSource, FnCorpus, ModalityAdapter, Registry, Representation,
30    RepresentationBackend, Tokenizer, VecCorpus,
31};
32pub use kute_types::*;
33pub use kute_vocab as vocab;
34
35/// The engine: a registry plus the common workflows.
36#[derive(Clone)]
37pub struct Engine {
38    registry: Registry,
39}
40
41impl Default for Engine {
42    fn default() -> Self {
43        Self::new()
44    }
45}
46
47/// Result of running a vocabulary's embedded test vectors.
48#[derive(Clone, Debug, Serialize)]
49pub struct VerifyReport {
50    pub vocabulary: String,
51    pub digest: String,
52    pub vectors: usize,
53    pub passed: usize,
54    pub failures: Vec<String>,
55}
56
57impl VerifyReport {
58    pub fn ok(&self) -> bool {
59        self.failures.is_empty()
60    }
61}
62
63/// How much of the corpus a training run re-encodes to check its result.
64const SELF_CHECK_RECORDS: usize = 4;
65const SELF_CHECK_BYTES: usize = 64 * 1024;
66const SELF_CHECK_SYMBOLS: usize = 4096;
67
68impl Engine {
69    /// An engine with every built-in algorithm and adapter registered.
70    pub fn new() -> Self {
71        let mut registry = Registry::new();
72        // The built-in names are distinct, so these cannot collide.
73        kute_bpe::register(&mut registry).expect("built-in algorithm names are unique");
74        kute_algorithms::register(&mut registry).expect("built-in algorithm names are unique");
75        kute_adapters::register(&mut registry).expect("built-in adapter names are unique");
76        Self { registry }
77    }
78
79    /// An engine around a caller-built registry.
80    pub fn with_registry(registry: Registry) -> Self {
81        Self { registry }
82    }
83
84    pub fn registry(&self) -> &Registry {
85        &self.registry
86    }
87
88    /// Add algorithms or adapters without touching KUTE's own crates.
89    pub fn registry_mut(&mut self) -> &mut Registry {
90        &mut self.registry
91    }
92
93    /// Train `algorithm` on raw documents read through `adapter`.
94    ///
95    /// The adapter and its options are recorded in the vocabulary, so encoding
96    /// and decoding later go through the same adapter without being told.
97    pub fn train(
98        &self,
99        algorithm: &str,
100        adapter: &str,
101        adapter_config: &AdapterConfig,
102        documents: &[Vec<u8>],
103        config: &TrainingConfig,
104    ) -> Result<Vocabulary> {
105        let mut next = documents.iter();
106        self.train_stream(algorithm, adapter, adapter_config, config, &mut || Ok(next.next().map(std::borrow::Cow::Borrowed)))
107    }
108
109    /// Train on documents that are produced one at a time. Only the
110    /// document being read is held, so a corpus larger than memory can be
111    /// trained on as long as each document fits.
112    pub fn train_stream<'a>(
113        &self,
114        algorithm: &str,
115        adapter: &str,
116        adapter_config: &AdapterConfig,
117        config: &TrainingConfig,
118        documents: &mut dyn FnMut() -> Result<Option<std::borrow::Cow<'a, Vec<u8>>>>,
119    ) -> Result<Vocabulary> {
120        let adapter_impl = self.registry.adapter(adapter)?;
121        let mut tokenizer = self.registry.tokenizer(algorithm)?;
122        if config.resume_from.is_some() && algorithm != "bpe" && algorithm != "sequence-bpe" {
123            return Err(KuteError::Unsupported(format!("resuming a training run is implemented for bpe and sequence-bpe, not {algorithm:?}")));
124        }
125        // The start of the first few records is kept and, after training,
126        // encoded and decoded again. This happens whether or not test
127        // vectors are stored in the vocabulary, and nothing of it is kept.
128        let mut held: Vec<CanonicalInput> = Vec::new();
129        let mut corpus = FnCorpus(|| match documents()? {
130            Some(doc) => {
131                let input = adapter_impl.ingest(&doc, adapter_config)?;
132                if held.len() < SELF_CHECK_RECORDS && !input.payload.is_empty() {
133                    held.push(CanonicalInput {
134                        modality: input.modality,
135                        payload: match &input.payload {
136                            Payload::Bytes(b) => Payload::Bytes(b[..b.len().min(SELF_CHECK_BYTES)].to_vec()),
137                            Payload::Symbols(v) => Payload::Symbols(v[..v.len().min(SELF_CHECK_SYMBOLS)].to_vec()),
138                        },
139                    });
140                }
141                Ok(Some(input))
142            }
143            None => Ok(None),
144        });
145        let mut vocabulary = tokenizer.train(&mut corpus, config)?;
146        for (n, input) in held.iter().enumerate() {
147            let back = tokenizer.decode(&tokenizer.encode(input)?)?;
148            if back.payload != input.payload {
149                return Err(KuteError::Backend(format!("trained vocabulary does not reproduce the start of training record {}", n + 1)));
150            }
151        }
152        vocabulary.adapter = Some(adapter_impl.spec(adapter_config));
153        vocabulary.manifest.modality = adapter_impl.modality();
154        vocabulary.seal()?;
155        // Fail here, not at first use, if the result is not self-consistent.
156        let report = self.verify(&vocabulary)?;
157        if !report.ok() {
158            return Err(KuteError::Backend(format!("trained vocabulary fails its own test vectors: {}", report.failures.join("; "))));
159        }
160        Ok(vocabulary)
161    }
162
163    /// Train on files. A directory is read recursively, in sorted path order.
164    pub fn train_paths(
165        &self,
166        algorithm: &str,
167        adapter: &str,
168        adapter_config: &AdapterConfig,
169        paths: &[PathBuf],
170        config: &TrainingConfig,
171    ) -> Result<Vocabulary> {
172        let mut files = Vec::new();
173        for path in paths {
174            files.extend(collect_files(path)?);
175        }
176        if files.is_empty() {
177            return Err(KuteError::InvalidInput("no input files found".into()));
178        }
179        if config.stream_bytes.is_some() && adapter == kute_adapters::JSON {
180            return Err(KuteError::InvalidConfig("the json adapter reads whole documents and cannot be streamed in pieces".into()));
181        }
182        // Files are read one at a time, or one piece at a time, so memory
183        // does not grow with the size of the corpus.
184        let line_cut = adapter != kute_adapters::BINARY;
185        let mut files = files.into_iter();
186        let mut open: Option<Pieces> = None;
187        self.train_stream(algorithm, adapter, adapter_config, config, &mut || loop {
188            if let Some(pieces) = open.as_mut() {
189                if let Some(piece) = pieces.next_piece()? {
190                    return Ok(Some(std::borrow::Cow::Owned(piece)));
191                }
192                open = None;
193            }
194            let Some(file) = files.next() else { return Ok(None) };
195            match config.stream_bytes {
196                Some(size) => open = Some(Pieces::open(&file, size, line_cut)?),
197                None => return Ok(Some(std::borrow::Cow::Owned(std::fs::read(&file)?))),
198            }
199        })
200    }
201
202    /// A tokenizer with `vocabulary` installed.
203    pub fn tokenizer(&self, vocabulary: Vocabulary) -> Result<Box<dyn Tokenizer>> {
204        self.registry.tokenizer_for(vocabulary)
205    }
206
207    fn adapter_of(&self, vocabulary: &Vocabulary) -> Result<(Box<dyn ModalityAdapter>, AdapterConfig)> {
208        match &vocabulary.adapter {
209            Some(spec) => Ok((self.registry.adapter(&spec.name)?, AdapterConfig { options: spec.options.clone() })),
210            None => {
211                let name = match vocabulary.manifest.payload_kind {
212                    PayloadKind::Bytes => kute_adapters::BINARY,
213                    PayloadKind::Symbols => kute_adapters::JSONL_EVENTS,
214                };
215                Ok((self.registry.adapter(name)?, AdapterConfig::default()))
216            }
217        }
218    }
219
220    /// Raw bytes to tokens, through the vocabulary's adapter.
221    pub fn encode_raw(&self, tokenizer: &dyn Tokenizer, raw: &[u8]) -> Result<TokenSequence> {
222        let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
223        let (adapter, config) = self.adapter_of(vocabulary)?;
224        tokenizer.encode(&adapter.ingest(raw, &config)?)
225    }
226
227    /// Raw bytes to tokens under an explicit policy for unknown symbols.
228    pub fn encode_raw_open(&self, tokenizer: &dyn Tokenizer, raw: &[u8], policy: UnknownPolicy) -> Result<TokenSequence> {
229        let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
230        let (adapter, config) = self.adapter_of(vocabulary)?;
231        tokenizer.encode_open(&adapter.ingest(raw, &config)?, policy)
232    }
233
234    /// Like [`Engine::decode_raw`], but refuses before decoding when the
235    /// sequence would expand to more than `max_units` bytes or symbols.
236    ///
237    /// For a symbol vocabulary this bounds the number of symbols and not
238    /// their size: a symbol can be a kilobyte long, and an escaped one is
239    /// chosen by whoever made the sequence. For a sequence from a party you
240    /// do not trust, use [`Engine::decode_raw_within`].
241    pub fn decode_raw_bounded(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence, max_units: u64) -> Result<Vec<u8>> {
242        self.decode_raw_within(tokenizer, tokens, max_units, u64::MAX)
243    }
244
245    /// Like [`Engine::decode_raw_bounded`], and also refuses before
246    /// decoding when the decoded content comes to more than `max_bytes`:
247    /// the bytes of a byte vocabulary, or the names of the symbols of a
248    /// symbol vocabulary. What an adapter writes around each name (a few
249    /// bytes of JSON, and escapes inside it) cannot be known before it is
250    /// written, so the result is checked again afterwards: nothing longer
251    /// than `max_bytes` is returned. While decoding, memory is bounded by
252    /// the two limits together (at most six bytes written per byte of a
253    /// name, plus the framing of `max_units` symbols), not by `max_bytes`
254    /// alone.
255    pub fn decode_raw_within(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence, max_units: u64, max_bytes: u64) -> Result<Vec<u8>> {
256        let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
257        let units = kute_core::decoded_units(vocabulary, tokens)?;
258        if units > max_units {
259            return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units; the budget is {max_units}")));
260        }
261        let bytes = kute_core::decoded_bytes_at_least(vocabulary, tokens)?;
262        if bytes > max_bytes {
263            return Err(KuteError::LimitExceeded(format!("the sequence decodes to at least {bytes} bytes; the budget is {max_bytes}")));
264        }
265        let decoded = self.decode_raw(tokenizer, tokens)?;
266        if decoded.len() as u64 > max_bytes {
267            return Err(KuteError::LimitExceeded(format!("the sequence decodes to {} bytes; the budget is {max_bytes}", decoded.len())));
268        }
269        Ok(decoded)
270    }
271
272    /// Tokens back to raw bytes, through the vocabulary's adapter.
273    pub fn decode_raw(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence) -> Result<Vec<u8>> {
274        let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
275        let (adapter, config) = self.adapter_of(vocabulary)?;
276        adapter.reconstruct(&tokenizer.decode(tokens)?, &config)
277    }
278
279    /// Encode many documents in parallel. Output order matches input order.
280    pub fn encode_batch(&self, tokenizer: &dyn Tokenizer, documents: &[Vec<u8>]) -> Result<Vec<TokenSequence>> {
281        documents.par_iter().map(|d| self.encode_raw(tokenizer, d)).collect()
282    }
283
284    /// Run the vocabulary's embedded test vectors: each input must encode to
285    /// the recorded ids and decode back to the input.
286    pub fn verify(&self, vocabulary: &Vocabulary) -> Result<VerifyReport> {
287        vocabulary.validate()?;
288        let tokenizer = self.tokenizer(vocabulary.clone())?;
289        let mut failures = Vec::new();
290        let mut passed = 0;
291        for (i, vector) in vocabulary.test_vectors.iter().enumerate() {
292            let payload = match &vector.input {
293                TokenPayload::Bytes(b) => Payload::Bytes(b.clone()),
294                TokenPayload::Symbols(s) => Payload::Symbols(s.clone()),
295            };
296            let input = CanonicalInput { modality: vocabulary.manifest.modality, payload };
297            match tokenizer.encode(&input) {
298                Err(e) => failures.push(format!("vector {i}: encode failed: {e}")),
299                Ok(sequence) if sequence.ids != vector.ids => failures.push(format!("vector {i}: encoded ids differ from the recorded ids")),
300                Ok(sequence) => match tokenizer.decode(&sequence) {
301                    Ok(back) if back.payload == input.payload => passed += 1,
302                    Ok(_) => failures.push(format!("vector {i}: decode did not reproduce the input")),
303                    Err(e) => failures.push(format!("vector {i}: decode failed: {e}")),
304                },
305            }
306        }
307        Ok(VerifyReport {
308            vocabulary: format!("{} {}", vocabulary.id(), vocabulary.version()),
309            digest: vocabulary.digest()?,
310            vectors: vocabulary.test_vectors.len(),
311            passed,
312            failures,
313        })
314    }
315}
316
317/// A file read in pieces of about `size` bytes. With `line_cut`, a piece ends
318/// after the last line feed within `size` bytes, or runs on to the next line
319/// feed when a single line is longer than that, so no line is ever split.
320struct Pieces {
321    reader: std::io::BufReader<std::fs::File>,
322    size: usize,
323    line_cut: bool,
324    carry: Vec<u8>,
325    done: bool,
326}
327
328impl Pieces {
329    fn open(path: &Path, size: usize, line_cut: bool) -> Result<Self> {
330        Ok(Self { reader: std::io::BufReader::new(std::fs::File::open(path)?), size, line_cut, carry: Vec::new(), done: false })
331    }
332
333    fn next_piece(&mut self) -> Result<Option<Vec<u8>>> {
334        use std::io::{BufRead, Read};
335        if self.done && self.carry.is_empty() {
336            return Ok(None);
337        }
338        let mut piece = std::mem::take(&mut self.carry);
339        if !self.done && piece.len() < self.size {
340            let want = (self.size - piece.len()) as u64;
341            if (&mut self.reader).take(want).read_to_end(&mut piece)? < want as usize {
342                self.done = true;
343            }
344        }
345        if self.line_cut && !self.done {
346            match piece.iter().rposition(|&b| b == b'\n') {
347                Some(at) => self.carry = piece.split_off(at + 1),
348                None => {
349                    // One line longer than a piece: finish the line.
350                    if self.reader.read_until(b'\n', &mut piece)? == 0 || piece.last() != Some(&b'\n') {
351                        self.done = true;
352                    }
353                }
354            }
355        }
356        Ok(if piece.is_empty() { None } else { Some(piece) })
357    }
358}
359
360/// Files under `path`, recursively, in sorted order. A file path is returned
361/// as is. Hidden entries (leading dot) inside directories are skipped.
362pub fn collect_files(path: &Path) -> Result<Vec<PathBuf>> {
363    let meta = std::fs::metadata(path).map_err(|e| KuteError::InvalidInput(format!("{}: {e}", path.display())))?;
364    if meta.is_file() {
365        return Ok(vec![path.to_path_buf()]);
366    }
367    let mut out = Vec::new();
368    let mut stack = vec![path.to_path_buf()];
369    while let Some(dir) = stack.pop() {
370        for entry in std::fs::read_dir(&dir)? {
371            let entry = entry?;
372            if entry.file_name().to_string_lossy().starts_with('.') {
373                continue;
374            }
375            let kind = entry.file_type()?;
376            if kind.is_dir() {
377                stack.push(entry.path());
378            } else if kind.is_file() {
379                out.push(entry.path());
380            }
381        }
382    }
383    out.sort();
384    Ok(out)
385}