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_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    pub fn decode_raw_bounded(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence, max_units: u64) -> Result<Vec<u8>> {
237        let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
238        let units = kute_core::decoded_units(vocabulary, tokens)?;
239        if units > max_units {
240            return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units; the budget is {max_units}")));
241        }
242        self.decode_raw(tokenizer, tokens)
243    }
244
245    /// Tokens back to raw bytes, through the vocabulary's adapter.
246    pub fn decode_raw(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence) -> Result<Vec<u8>> {
247        let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
248        let (adapter, config) = self.adapter_of(vocabulary)?;
249        adapter.reconstruct(&tokenizer.decode(tokens)?, &config)
250    }
251
252    /// Encode many documents in parallel. Output order matches input order.
253    pub fn encode_batch(&self, tokenizer: &dyn Tokenizer, documents: &[Vec<u8>]) -> Result<Vec<TokenSequence>> {
254        documents.par_iter().map(|d| self.encode_raw(tokenizer, d)).collect()
255    }
256
257    /// Run the vocabulary's embedded test vectors: each input must encode to
258    /// the recorded ids and decode back to the input.
259    pub fn verify(&self, vocabulary: &Vocabulary) -> Result<VerifyReport> {
260        vocabulary.validate()?;
261        let tokenizer = self.tokenizer(vocabulary.clone())?;
262        let mut failures = Vec::new();
263        let mut passed = 0;
264        for (i, vector) in vocabulary.test_vectors.iter().enumerate() {
265            let payload = match &vector.input {
266                TokenPayload::Bytes(b) => Payload::Bytes(b.clone()),
267                TokenPayload::Symbols(s) => Payload::Symbols(s.clone()),
268            };
269            let input = CanonicalInput { modality: vocabulary.manifest.modality, payload };
270            match tokenizer.encode(&input) {
271                Err(e) => failures.push(format!("vector {i}: encode failed: {e}")),
272                Ok(sequence) if sequence.ids != vector.ids => failures.push(format!("vector {i}: encoded ids differ from the recorded ids")),
273                Ok(sequence) => match tokenizer.decode(&sequence) {
274                    Ok(back) if back.payload == input.payload => passed += 1,
275                    Ok(_) => failures.push(format!("vector {i}: decode did not reproduce the input")),
276                    Err(e) => failures.push(format!("vector {i}: decode failed: {e}")),
277                },
278            }
279        }
280        Ok(VerifyReport {
281            vocabulary: format!("{} {}", vocabulary.id(), vocabulary.version()),
282            digest: vocabulary.digest()?,
283            vectors: vocabulary.test_vectors.len(),
284            passed,
285            failures,
286        })
287    }
288}
289
290/// A file read in pieces of about `size` bytes. With `line_cut`, a piece ends
291/// after the last line feed within `size` bytes, or runs on to the next line
292/// feed when a single line is longer than that, so no line is ever split.
293struct Pieces {
294    reader: std::io::BufReader<std::fs::File>,
295    size: usize,
296    line_cut: bool,
297    carry: Vec<u8>,
298    done: bool,
299}
300
301impl Pieces {
302    fn open(path: &Path, size: usize, line_cut: bool) -> Result<Self> {
303        Ok(Self { reader: std::io::BufReader::new(std::fs::File::open(path)?), size, line_cut, carry: Vec::new(), done: false })
304    }
305
306    fn next_piece(&mut self) -> Result<Option<Vec<u8>>> {
307        use std::io::{BufRead, Read};
308        if self.done && self.carry.is_empty() {
309            return Ok(None);
310        }
311        let mut piece = std::mem::take(&mut self.carry);
312        if !self.done && piece.len() < self.size {
313            let want = (self.size - piece.len()) as u64;
314            if (&mut self.reader).take(want).read_to_end(&mut piece)? < want as usize {
315                self.done = true;
316            }
317        }
318        if self.line_cut && !self.done {
319            match piece.iter().rposition(|&b| b == b'\n') {
320                Some(at) => self.carry = piece.split_off(at + 1),
321                None => {
322                    // One line longer than a piece: finish the line.
323                    if self.reader.read_until(b'\n', &mut piece)? == 0 || piece.last() != Some(&b'\n') {
324                        self.done = true;
325                    }
326                }
327            }
328        }
329        Ok(if piece.is_empty() { None } else { Some(piece) })
330    }
331}
332
333/// Files under `path`, recursively, in sorted order. A file path is returned
334/// as is. Hidden entries (leading dot) inside directories are skipped.
335pub fn collect_files(path: &Path) -> Result<Vec<PathBuf>> {
336    let meta = std::fs::metadata(path).map_err(|e| KuteError::InvalidInput(format!("{}: {e}", path.display())))?;
337    if meta.is_file() {
338        return Ok(vec![path.to_path_buf()]);
339    }
340    let mut out = Vec::new();
341    let mut stack = vec![path.to_path_buf()];
342    while let Some(dir) = stack.pop() {
343        for entry in std::fs::read_dir(&dir)? {
344            let entry = entry?;
345            if entry.file_name().to_string_lossy().starts_with('.') {
346                continue;
347            }
348            let kind = entry.file_type()?;
349            if kind.is_dir() {
350                stack.push(entry.path());
351            } else if kind.is_file() {
352                out.push(entry.path());
353            }
354        }
355    }
356    out.sort();
357    Ok(out)
358}