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, 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        kute_bpe::register(&mut registry);
68        kute_algorithms::register(&mut registry);
69        kute_adapters::register(&mut registry);
70        Self { registry }
71    }
72
73    /// An engine around a caller-built registry.
74    pub fn with_registry(registry: Registry) -> Self {
75        Self { registry }
76    }
77
78    pub fn registry(&self) -> &Registry {
79        &self.registry
80    }
81
82    /// Add algorithms or adapters without touching KUTE's own crates.
83    pub fn registry_mut(&mut self) -> &mut Registry {
84        &mut self.registry
85    }
86
87    /// Train `algorithm` on raw documents read through `adapter`.
88    ///
89    /// The adapter and its options are recorded in the vocabulary, so encoding
90    /// and decoding later go through the same adapter without being told.
91    pub fn train(
92        &self,
93        algorithm: &str,
94        adapter: &str,
95        adapter_config: &AdapterConfig,
96        documents: &[Vec<u8>],
97        config: &TrainingConfig,
98    ) -> Result<Vocabulary> {
99        let adapter_impl = self.registry.adapter(adapter)?;
100        let mut tokenizer = self.registry.tokenizer(algorithm)?;
101        let mut records = Vec::with_capacity(documents.len());
102        for doc in documents {
103            records.push(adapter_impl.ingest(doc, adapter_config)?);
104        }
105        let mut vocabulary = tokenizer.train(&mut VecCorpus::new(records), config)?;
106        vocabulary.adapter = Some(adapter_impl.spec(adapter_config));
107        vocabulary.manifest.modality = adapter_impl.modality();
108        vocabulary.seal()?;
109        // Fail here, not at first use, if the result is not self-consistent.
110        let report = self.verify(&vocabulary)?;
111        if !report.ok() {
112            return Err(KuteError::Backend(format!("trained vocabulary fails its own test vectors: {}", report.failures.join("; "))));
113        }
114        Ok(vocabulary)
115    }
116
117    /// Train on files. A directory is read recursively, in sorted path order.
118    pub fn train_paths(
119        &self,
120        algorithm: &str,
121        adapter: &str,
122        adapter_config: &AdapterConfig,
123        paths: &[PathBuf],
124        config: &TrainingConfig,
125    ) -> Result<Vocabulary> {
126        let mut documents = Vec::new();
127        for path in paths {
128            for file in collect_files(path)? {
129                documents.push(std::fs::read(&file)?);
130            }
131        }
132        if documents.is_empty() {
133            return Err(KuteError::InvalidInput("no input files found".into()));
134        }
135        self.train(algorithm, adapter, adapter_config, &documents, config)
136    }
137
138    /// A tokenizer with `vocabulary` installed.
139    pub fn tokenizer(&self, vocabulary: Vocabulary) -> Result<Box<dyn Tokenizer>> {
140        self.registry.tokenizer_for(vocabulary)
141    }
142
143    fn adapter_of(&self, vocabulary: &Vocabulary) -> Result<(Box<dyn ModalityAdapter>, AdapterConfig)> {
144        match &vocabulary.adapter {
145            Some(spec) => Ok((self.registry.adapter(&spec.name)?, AdapterConfig { options: spec.options.clone() })),
146            None => {
147                let name = match vocabulary.manifest.payload_kind {
148                    PayloadKind::Bytes => kute_adapters::BINARY,
149                    PayloadKind::Symbols => kute_adapters::JSONL_EVENTS,
150                };
151                Ok((self.registry.adapter(name)?, AdapterConfig::default()))
152            }
153        }
154    }
155
156    /// Raw bytes to tokens, through the vocabulary's adapter.
157    pub fn encode_raw(&self, tokenizer: &dyn Tokenizer, raw: &[u8]) -> Result<TokenSequence> {
158        let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
159        let (adapter, config) = self.adapter_of(vocabulary)?;
160        tokenizer.encode(&adapter.ingest(raw, &config)?)
161    }
162
163    /// Tokens back to raw bytes, through the vocabulary's adapter.
164    pub fn decode_raw(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence) -> Result<Vec<u8>> {
165        let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
166        let (adapter, _) = self.adapter_of(vocabulary)?;
167        adapter.reconstruct(&tokenizer.decode(tokens)?)
168    }
169
170    /// Encode many documents in parallel. Output order matches input order.
171    pub fn encode_batch(&self, tokenizer: &dyn Tokenizer, documents: &[Vec<u8>]) -> Result<Vec<TokenSequence>> {
172        documents.par_iter().map(|d| self.encode_raw(tokenizer, d)).collect()
173    }
174
175    /// Run the vocabulary's embedded test vectors: each input must encode to
176    /// the recorded ids and decode back to the input.
177    pub fn verify(&self, vocabulary: &Vocabulary) -> Result<VerifyReport> {
178        vocabulary.validate()?;
179        let tokenizer = self.tokenizer(vocabulary.clone())?;
180        let mut failures = Vec::new();
181        let mut passed = 0;
182        for (i, vector) in vocabulary.test_vectors.iter().enumerate() {
183            let payload = match &vector.input {
184                TokenPayload::Bytes(b) => Payload::Bytes(b.clone()),
185                TokenPayload::Symbols(s) => Payload::Symbols(s.clone()),
186            };
187            let input = CanonicalInput { modality: vocabulary.manifest.modality, payload };
188            match tokenizer.encode(&input) {
189                Err(e) => failures.push(format!("vector {i}: encode failed: {e}")),
190                Ok(sequence) if sequence.ids != vector.ids => failures.push(format!("vector {i}: encoded ids differ from the recorded ids")),
191                Ok(sequence) => match tokenizer.decode(&sequence) {
192                    Ok(back) if back.payload == input.payload => passed += 1,
193                    Ok(_) => failures.push(format!("vector {i}: decode did not reproduce the input")),
194                    Err(e) => failures.push(format!("vector {i}: decode failed: {e}")),
195                },
196            }
197        }
198        Ok(VerifyReport {
199            vocabulary: format!("{} {}", vocabulary.id(), vocabulary.version()),
200            digest: vocabulary.digest()?,
201            vectors: vocabulary.test_vectors.len(),
202            passed,
203            failures,
204        })
205    }
206}
207
208/// Files under `path`, recursively, in sorted order. A file path is returned
209/// as is. Hidden entries (leading dot) inside directories are skipped.
210pub fn collect_files(path: &Path) -> Result<Vec<PathBuf>> {
211    let meta = std::fs::metadata(path).map_err(|e| KuteError::InvalidInput(format!("{}: {e}", path.display())))?;
212    if meta.is_file() {
213        return Ok(vec![path.to_path_buf()]);
214    }
215    let mut out = Vec::new();
216    let mut stack = vec![path.to_path_buf()];
217    while let Some(dir) = stack.pop() {
218        for entry in std::fs::read_dir(&dir)? {
219            let entry = entry?;
220            if entry.file_name().to_string_lossy().starts_with('.') {
221                continue;
222            }
223            let kind = entry.file_type()?;
224            if kind.is_dir() {
225                stack.push(entry.path());
226            } else if kind.is_file() {
227                out.push(entry.path());
228            }
229        }
230    }
231    out.sort();
232    Ok(out)
233}