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
63impl Engine {
64    /// An engine with every built-in algorithm and adapter registered.
65    pub fn new() -> Self {
66        let mut registry = Registry::new();
67        // The built-in names are distinct, so these cannot collide.
68        kute_bpe::register(&mut registry).expect("built-in algorithm names are unique");
69        kute_algorithms::register(&mut registry).expect("built-in algorithm names are unique");
70        kute_adapters::register(&mut registry).expect("built-in adapter names are unique");
71        Self { registry }
72    }
73
74    /// An engine around a caller-built registry.
75    pub fn with_registry(registry: Registry) -> Self {
76        Self { registry }
77    }
78
79    pub fn registry(&self) -> &Registry {
80        &self.registry
81    }
82
83    /// Add algorithms or adapters without touching KUTE's own crates.
84    pub fn registry_mut(&mut self) -> &mut Registry {
85        &mut self.registry
86    }
87
88    /// Train `algorithm` on raw documents read through `adapter`.
89    ///
90    /// The adapter and its options are recorded in the vocabulary, so encoding
91    /// and decoding later go through the same adapter without being told.
92    pub fn train(
93        &self,
94        algorithm: &str,
95        adapter: &str,
96        adapter_config: &AdapterConfig,
97        documents: &[Vec<u8>],
98        config: &TrainingConfig,
99    ) -> Result<Vocabulary> {
100        let mut next = documents.iter();
101        self.train_stream(algorithm, adapter, adapter_config, config, &mut || Ok(next.next().map(std::borrow::Cow::Borrowed)))
102    }
103
104    /// Train on documents that are produced one at a time. Only the
105    /// document being read is held, so a corpus larger than memory can be
106    /// trained on as long as each document fits.
107    pub fn train_stream<'a>(
108        &self,
109        algorithm: &str,
110        adapter: &str,
111        adapter_config: &AdapterConfig,
112        config: &TrainingConfig,
113        documents: &mut dyn FnMut() -> Result<Option<std::borrow::Cow<'a, Vec<u8>>>>,
114    ) -> Result<Vocabulary> {
115        let adapter_impl = self.registry.adapter(adapter)?;
116        let mut tokenizer = self.registry.tokenizer(algorithm)?;
117        let mut corpus = FnCorpus(|| match documents()? {
118            Some(doc) => adapter_impl.ingest(&doc, adapter_config).map(Some),
119            None => Ok(None),
120        });
121        let mut vocabulary = tokenizer.train(&mut corpus, config)?;
122        vocabulary.adapter = Some(adapter_impl.spec(adapter_config));
123        vocabulary.manifest.modality = adapter_impl.modality();
124        vocabulary.seal()?;
125        // Fail here, not at first use, if the result is not self-consistent.
126        let report = self.verify(&vocabulary)?;
127        if !report.ok() {
128            return Err(KuteError::Backend(format!("trained vocabulary fails its own test vectors: {}", report.failures.join("; "))));
129        }
130        Ok(vocabulary)
131    }
132
133    /// Train on files. A directory is read recursively, in sorted path order.
134    pub fn train_paths(
135        &self,
136        algorithm: &str,
137        adapter: &str,
138        adapter_config: &AdapterConfig,
139        paths: &[PathBuf],
140        config: &TrainingConfig,
141    ) -> Result<Vocabulary> {
142        let mut files = Vec::new();
143        for path in paths {
144            files.extend(collect_files(path)?);
145        }
146        if files.is_empty() {
147            return Err(KuteError::InvalidInput("no input files found".into()));
148        }
149        if config.stream_bytes.is_some() && adapter == kute_adapters::JSON {
150            return Err(KuteError::InvalidConfig("the json adapter reads whole documents and cannot be streamed in pieces".into()));
151        }
152        // Files are read one at a time, or one piece at a time, so memory
153        // does not grow with the size of the corpus.
154        let line_cut = adapter != kute_adapters::BINARY;
155        let mut files = files.into_iter();
156        let mut open: Option<Pieces> = None;
157        self.train_stream(algorithm, adapter, adapter_config, config, &mut || loop {
158            if let Some(pieces) = open.as_mut() {
159                if let Some(piece) = pieces.next_piece()? {
160                    return Ok(Some(std::borrow::Cow::Owned(piece)));
161                }
162                open = None;
163            }
164            let Some(file) = files.next() else { return Ok(None) };
165            match config.stream_bytes {
166                Some(size) => open = Some(Pieces::open(&file, size, line_cut)?),
167                None => return Ok(Some(std::borrow::Cow::Owned(std::fs::read(&file)?))),
168            }
169        })
170    }
171
172    /// A tokenizer with `vocabulary` installed.
173    pub fn tokenizer(&self, vocabulary: Vocabulary) -> Result<Box<dyn Tokenizer>> {
174        self.registry.tokenizer_for(vocabulary)
175    }
176
177    fn adapter_of(&self, vocabulary: &Vocabulary) -> Result<(Box<dyn ModalityAdapter>, AdapterConfig)> {
178        match &vocabulary.adapter {
179            Some(spec) => Ok((self.registry.adapter(&spec.name)?, AdapterConfig { options: spec.options.clone() })),
180            None => {
181                let name = match vocabulary.manifest.payload_kind {
182                    PayloadKind::Bytes => kute_adapters::BINARY,
183                    PayloadKind::Symbols => kute_adapters::JSONL_EVENTS,
184                };
185                Ok((self.registry.adapter(name)?, AdapterConfig::default()))
186            }
187        }
188    }
189
190    /// Raw bytes to tokens, through the vocabulary's adapter.
191    pub fn encode_raw(&self, tokenizer: &dyn Tokenizer, raw: &[u8]) -> Result<TokenSequence> {
192        let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
193        let (adapter, config) = self.adapter_of(vocabulary)?;
194        tokenizer.encode(&adapter.ingest(raw, &config)?)
195    }
196
197    /// Raw bytes to tokens under an explicit policy for unknown symbols.
198    pub fn encode_raw_open(&self, tokenizer: &dyn Tokenizer, raw: &[u8], policy: UnknownPolicy) -> Result<TokenSequence> {
199        let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
200        let (adapter, config) = self.adapter_of(vocabulary)?;
201        tokenizer.encode_open(&adapter.ingest(raw, &config)?, policy)
202    }
203
204    /// Like [`Engine::decode_raw`], but refuses before decoding when the
205    /// sequence would expand to more than `max_units` bytes or symbols.
206    pub fn decode_raw_bounded(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence, max_units: u64) -> Result<Vec<u8>> {
207        let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
208        let units = kute_core::decoded_units(vocabulary, tokens)?;
209        if units > max_units {
210            return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units; the budget is {max_units}")));
211        }
212        self.decode_raw(tokenizer, tokens)
213    }
214
215    /// Tokens back to raw bytes, through the vocabulary's adapter.
216    pub fn decode_raw(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence) -> Result<Vec<u8>> {
217        let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
218        let (adapter, _) = self.adapter_of(vocabulary)?;
219        adapter.reconstruct(&tokenizer.decode(tokens)?)
220    }
221
222    /// Encode many documents in parallel. Output order matches input order.
223    pub fn encode_batch(&self, tokenizer: &dyn Tokenizer, documents: &[Vec<u8>]) -> Result<Vec<TokenSequence>> {
224        documents.par_iter().map(|d| self.encode_raw(tokenizer, d)).collect()
225    }
226
227    /// Run the vocabulary's embedded test vectors: each input must encode to
228    /// the recorded ids and decode back to the input.
229    pub fn verify(&self, vocabulary: &Vocabulary) -> Result<VerifyReport> {
230        vocabulary.validate()?;
231        let tokenizer = self.tokenizer(vocabulary.clone())?;
232        let mut failures = Vec::new();
233        let mut passed = 0;
234        for (i, vector) in vocabulary.test_vectors.iter().enumerate() {
235            let payload = match &vector.input {
236                TokenPayload::Bytes(b) => Payload::Bytes(b.clone()),
237                TokenPayload::Symbols(s) => Payload::Symbols(s.clone()),
238            };
239            let input = CanonicalInput { modality: vocabulary.manifest.modality, payload };
240            match tokenizer.encode(&input) {
241                Err(e) => failures.push(format!("vector {i}: encode failed: {e}")),
242                Ok(sequence) if sequence.ids != vector.ids => failures.push(format!("vector {i}: encoded ids differ from the recorded ids")),
243                Ok(sequence) => match tokenizer.decode(&sequence) {
244                    Ok(back) if back.payload == input.payload => passed += 1,
245                    Ok(_) => failures.push(format!("vector {i}: decode did not reproduce the input")),
246                    Err(e) => failures.push(format!("vector {i}: decode failed: {e}")),
247                },
248            }
249        }
250        Ok(VerifyReport {
251            vocabulary: format!("{} {}", vocabulary.id(), vocabulary.version()),
252            digest: vocabulary.digest()?,
253            vectors: vocabulary.test_vectors.len(),
254            passed,
255            failures,
256        })
257    }
258}
259
260/// A file read in pieces of about `size` bytes. With `line_cut`, a piece ends
261/// after the last line feed within `size` bytes, or runs on to the next line
262/// feed when a single line is longer than that, so no line is ever split.
263struct Pieces {
264    reader: std::io::BufReader<std::fs::File>,
265    size: usize,
266    line_cut: bool,
267    carry: Vec<u8>,
268    done: bool,
269}
270
271impl Pieces {
272    fn open(path: &Path, size: usize, line_cut: bool) -> Result<Self> {
273        Ok(Self { reader: std::io::BufReader::new(std::fs::File::open(path)?), size, line_cut, carry: Vec::new(), done: false })
274    }
275
276    fn next_piece(&mut self) -> Result<Option<Vec<u8>>> {
277        use std::io::{BufRead, Read};
278        if self.done && self.carry.is_empty() {
279            return Ok(None);
280        }
281        let mut piece = std::mem::take(&mut self.carry);
282        if !self.done && piece.len() < self.size {
283            let want = (self.size - piece.len()) as u64;
284            if (&mut self.reader).take(want).read_to_end(&mut piece)? < want as usize {
285                self.done = true;
286            }
287        }
288        if self.line_cut && !self.done {
289            match piece.iter().rposition(|&b| b == b'\n') {
290                Some(at) => self.carry = piece.split_off(at + 1),
291                None => {
292                    // One line longer than a piece: finish the line.
293                    if self.reader.read_until(b'\n', &mut piece)? == 0 || piece.last() != Some(&b'\n') {
294                        self.done = true;
295                    }
296                }
297            }
298        }
299        Ok(if piece.is_empty() { None } else { Some(piece) })
300    }
301}
302
303/// Files under `path`, recursively, in sorted order. A file path is returned
304/// as is. Hidden entries (leading dot) inside directories are skipped.
305pub fn collect_files(path: &Path) -> Result<Vec<PathBuf>> {
306    let meta = std::fs::metadata(path).map_err(|e| KuteError::InvalidInput(format!("{}: {e}", path.display())))?;
307    if meta.is_file() {
308        return Ok(vec![path.to_path_buf()]);
309    }
310    let mut out = Vec::new();
311    let mut stack = vec![path.to_path_buf()];
312    while let Some(dir) = stack.pop() {
313        for entry in std::fs::read_dir(&dir)? {
314            let entry = entry?;
315            if entry.file_name().to_string_lossy().starts_with('.') {
316                continue;
317            }
318            let kind = entry.file_type()?;
319            if kind.is_dir() {
320                stack.push(entry.path());
321            } else if kind.is_file() {
322                out.push(entry.path());
323            }
324        }
325    }
326    out.sort();
327    Ok(out)
328}