Skip to main content

kute_core/
lib.rs

1//! Core interfaces of the Kannaka Universal Tokenization Engine.
2//!
3//! Nothing here knows about a particular algorithm or data format. Algorithms
4//! implement [`Tokenizer`], formats implement [`ModalityAdapter`], and both are
5//! added to a [`Registry`] at run time, so third parties extend KUTE without
6//! changing this crate (FR-002, ADR-0003).
7
8use kute_types::{
9    AdapterConfig, AdapterSpec, CanonicalInput, KuteError, Modality, Payload, Result, TokenPayload, TokenSequence,
10    TokenizerCapabilities, TrainingConfig, UnknownPolicy, Vocabulary,
11};
12use sha2::{Digest, Sha256};
13use std::collections::BTreeMap;
14use std::sync::Arc;
15
16pub use kute_types as types;
17
18/// A stream of canonical records to train on.
19pub trait CorpusSource {
20    /// The next record, or `None` when the corpus is exhausted.
21    fn next_record(&mut self) -> Result<Option<CanonicalInput>>;
22}
23
24/// An in-memory corpus.
25pub struct VecCorpus {
26    records: std::vec::IntoIter<CanonicalInput>,
27}
28
29impl VecCorpus {
30    pub fn new(records: Vec<CanonicalInput>) -> Self {
31        Self { records: records.into_iter() }
32    }
33}
34
35impl CorpusSource for VecCorpus {
36    fn next_record(&mut self) -> Result<Option<CanonicalInput>> {
37        Ok(self.records.next())
38    }
39}
40
41/// A corpus backed by a closure, for streaming sources.
42pub struct FnCorpus<F: FnMut() -> Result<Option<CanonicalInput>>>(pub F);
43
44impl<F: FnMut() -> Result<Option<CanonicalInput>>> CorpusSource for FnCorpus<F> {
45    fn next_record(&mut self) -> Result<Option<CanonicalInput>> {
46        (self.0)()
47    }
48}
49
50/// The generic tokenizer interface (PRD 9.3).
51///
52/// Two deliberate differences from the PRD sketch: `vocabulary` returns an
53/// `Option` because a tokenizer exists before it is trained, and `load` installs
54/// an existing vocabulary. Both are recorded in ADR-0003.
55pub trait Tokenizer: Send + Sync {
56    /// Learn a vocabulary from `corpus`, install it, and return a copy.
57    fn train(&mut self, corpus: &mut dyn CorpusSource, config: &TrainingConfig) -> Result<Vocabulary>;
58
59    /// Install a vocabulary produced earlier. Implementations validate it.
60    fn load(&mut self, vocabulary: Vocabulary) -> Result<()>;
61
62    fn encode(&self, input: &CanonicalInput) -> Result<TokenSequence>;
63
64    /// Encode under an explicit policy for symbols the vocabulary lacks.
65    ///
66    /// `Strict` is plain [`Tokenizer::encode`]. `Escape` must return a
67    /// sequence that decodes to the input exactly, without changing the
68    /// vocabulary. Algorithms that can meet no unknown symbol (byte-level
69    /// ones) need not override this; algorithms that can, and have no
70    /// escape support, report that instead of guessing.
71    fn encode_open(&self, input: &CanonicalInput, policy: UnknownPolicy) -> Result<TokenSequence> {
72        match (policy, self.encode(input)) {
73            (UnknownPolicy::Escape, Err(KuteError::UnknownSymbol(symbol))) => Err(KuteError::Unsupported(format!(
74                "symbol {symbol:?} is not in the vocabulary and the {} algorithm has no escape encoding",
75                self.capabilities().algorithm
76            ))),
77            (_, result) => result,
78        }
79    }
80
81    fn decode(&self, tokens: &TokenSequence) -> Result<CanonicalInput>;
82
83    fn vocabulary(&self) -> Option<&Vocabulary>;
84
85    fn capabilities(&self) -> TokenizerCapabilities;
86}
87
88/// What an adapter declares about itself.
89#[derive(Clone, Debug, PartialEq, Eq)]
90pub struct AdapterCapabilities {
91    pub name: String,
92    pub modality: Modality,
93    /// `reconstruct(ingest(x)) == x` byte for byte, for every accepted `x`.
94    pub lossless: bool,
95    pub notes: String,
96}
97
98/// Converts raw bytes of some format to canonical input and back (PRD 9.3).
99pub trait ModalityAdapter: Send + Sync {
100    fn modality(&self) -> Modality;
101
102    fn ingest(&self, input: &[u8], config: &AdapterConfig) -> Result<CanonicalInput>;
103
104    /// `config` is the configuration the input was ingested with; a
105    /// vocabulary stores it, so decoding uses the same field names and options.
106    fn reconstruct(&self, input: &CanonicalInput, config: &AdapterConfig) -> Result<Vec<u8>>;
107
108    /// Must state whether reconstruction is lossless.
109    fn capabilities(&self) -> AdapterCapabilities;
110
111    /// The specification stored in a vocabulary trained through this adapter.
112    fn spec(&self, config: &AdapterConfig) -> AdapterSpec {
113        let caps = self.capabilities();
114        AdapterSpec { name: caps.name, options: config.options.clone(), lossless: caps.lossless }
115    }
116}
117
118/// A numeric representation of one token (FR-015).
119#[derive(Clone, Debug, PartialEq)]
120pub enum Representation {
121    /// Real-valued vector.
122    Vector(Vec<f32>),
123    /// Complex-valued vector as `(re, im)` pairs.
124    ComplexVector(Vec<(f32, f32)>),
125}
126
127/// Maps token ids to another representation. Mappings are versioned on their
128/// own and never change what a token id means (FR-015, ADR-0011).
129pub trait RepresentationBackend: Send + Sync {
130    fn mapping_id(&self) -> &str;
131    fn mapping_version(&self) -> &str;
132    fn dimension(&self) -> usize;
133    fn map(&self, vocabulary: &Vocabulary, token_id: u32) -> Result<Representation>;
134}
135
136type TokenizerFactory = Arc<dyn Fn() -> Box<dyn Tokenizer> + Send + Sync>;
137type AdapterFactory = Arc<dyn Fn() -> Box<dyn ModalityAdapter> + Send + Sync>;
138
139/// Run-time table of algorithms and adapters.
140#[derive(Clone, Default)]
141pub struct Registry {
142    algorithms: BTreeMap<String, TokenizerFactory>,
143    adapters: BTreeMap<String, AdapterFactory>,
144}
145
146impl Registry {
147    pub fn new() -> Self {
148        Self::default()
149    }
150
151    /// Register a tokenization algorithm under `name`. A name can be taken
152    /// once: a second registration is an error, so one plugin cannot quietly
153    /// change what another's vocabularies mean. Use
154    /// [`Registry::replace_algorithm`] to override on purpose.
155    pub fn register_algorithm<F>(&mut self, name: &str, factory: F) -> Result<()>
156    where
157        F: Fn() -> Box<dyn Tokenizer> + Send + Sync + 'static,
158    {
159        if self.algorithms.contains_key(name) {
160            return Err(KuteError::InvalidConfig(format!("algorithm {name:?} is already registered")));
161        }
162        self.algorithms.insert(name.to_string(), Arc::new(factory));
163        Ok(())
164    }
165
166    /// Register or replace the algorithm under `name`.
167    pub fn replace_algorithm<F>(&mut self, name: &str, factory: F)
168    where
169        F: Fn() -> Box<dyn Tokenizer> + Send + Sync + 'static,
170    {
171        self.algorithms.insert(name.to_string(), Arc::new(factory));
172    }
173
174    /// Register an adapter under `name`. Like algorithms, a name can be
175    /// taken once.
176    pub fn register_adapter<F>(&mut self, name: &str, factory: F) -> Result<()>
177    where
178        F: Fn() -> Box<dyn ModalityAdapter> + Send + Sync + 'static,
179    {
180        if self.adapters.contains_key(name) {
181            return Err(KuteError::InvalidConfig(format!("adapter {name:?} is already registered")));
182        }
183        self.adapters.insert(name.to_string(), Arc::new(factory));
184        Ok(())
185    }
186
187    /// Register or replace the adapter under `name`.
188    pub fn replace_adapter<F>(&mut self, name: &str, factory: F)
189    where
190        F: Fn() -> Box<dyn ModalityAdapter> + Send + Sync + 'static,
191    {
192        self.adapters.insert(name.to_string(), Arc::new(factory));
193    }
194
195    /// A fresh, untrained tokenizer for `name`.
196    pub fn tokenizer(&self, name: &str) -> Result<Box<dyn Tokenizer>> {
197        self.algorithms.get(name).map(|f| f()).ok_or_else(|| {
198            KuteError::Unsupported(format!(
199                "algorithm {name:?} is not registered (available: {})",
200                self.algorithm_names().join(", ")
201            ))
202        })
203    }
204
205    pub fn adapter(&self, name: &str) -> Result<Box<dyn ModalityAdapter>> {
206        self.adapters.get(name).map(|f| f()).ok_or_else(|| {
207            KuteError::Unsupported(format!(
208                "adapter {name:?} is not registered (available: {})",
209                self.adapter_names().join(", ")
210            ))
211        })
212    }
213
214    /// A tokenizer with `vocabulary` installed, chosen by the manifest.
215    /// A tokenizer with `vocabulary` installed.
216    ///
217    /// This is the sealed boundary of the runtime. A `Vocabulary` value is
218    /// plain data with public fields, and its `digest()` reports what was
219    /// recorded; code may have changed the content since. What a tokenizer
220    /// returned from here holds cannot be changed (it hands out only shared
221    /// references), and it is checked here, whatever the algorithm's own
222    /// `load` did: it carries a digest, and that digest is the hash of its
223    /// content. So `tokenizer.vocabulary().digest()` always names the
224    /// vocabulary that is doing the encoding.
225    pub fn tokenizer_for(&self, vocabulary: Vocabulary) -> Result<Box<dyn Tokenizer>> {
226        let mut t = self.tokenizer(&vocabulary.manifest.algorithm)?;
227        t.load(vocabulary)?;
228        let held = t.vocabulary().ok_or_else(|| KuteError::InvalidVocabulary("the tokenizer holds no vocabulary after loading one".into()))?;
229        let Some(integrity) = &held.integrity else {
230            return Err(KuteError::Integrity("the tokenizer loaded a vocabulary without recording its digest".into()));
231        };
232        let actual = held.compute_digest()?;
233        if actual != integrity.digest {
234            return Err(KuteError::Integrity(format!("recorded digest {} does not match content digest {actual}", integrity.digest)));
235        }
236        Ok(t)
237    }
238
239    pub fn algorithm_names(&self) -> Vec<String> {
240        self.algorithms.keys().cloned().collect()
241    }
242
243    pub fn adapter_names(&self) -> Vec<String> {
244        self.adapters.keys().cloned().collect()
245    }
246}
247
248/// Order-sensitive fingerprint of a corpus as a tokenizer sees it. Trainers
249/// feed every record through this and store the result as provenance.
250pub struct CorpusFingerprint {
251    hasher: Sha256,
252    records: u64,
253    units: u64,
254}
255
256impl Default for CorpusFingerprint {
257    fn default() -> Self {
258        Self::new()
259    }
260}
261
262impl CorpusFingerprint {
263    pub fn new() -> Self {
264        Self { hasher: Sha256::new(), records: 0, units: 0 }
265    }
266
267    pub fn update(&mut self, input: &CanonicalInput) {
268        match &input.payload {
269            Payload::Bytes(b) => {
270                self.hasher.update(b"B");
271                self.hasher.update((b.len() as u64).to_le_bytes());
272                self.hasher.update(b);
273            }
274            Payload::Symbols(s) => {
275                self.hasher.update(b"S");
276                self.hasher.update((s.len() as u64).to_le_bytes());
277                for sym in s {
278                    self.hasher.update((sym.len() as u64).to_le_bytes());
279                    self.hasher.update(sym.as_bytes());
280                }
281            }
282        }
283        self.records += 1;
284        self.units += input.payload.len() as u64;
285    }
286
287    pub fn records(&self) -> u64 {
288        self.records
289    }
290
291    /// Total bytes or symbols seen.
292    pub fn units(&self) -> u64 {
293        self.units
294    }
295
296    pub fn finish(self) -> String {
297        format!("sha256:{}", kute_types::hex(&self.hasher.finalize()))
298    }
299}
300
301/// Check that a token sequence was produced by exactly this vocabulary.
302pub fn check_sequence(vocabulary: &Vocabulary, tokens: &TokenSequence) -> Result<()> {
303    if &tokens.vocabulary_id != vocabulary.id() || &tokens.vocabulary_version != vocabulary.version() {
304        return Err(KuteError::VocabularyMismatch(format!(
305            "sequence was encoded with {} {} but the loaded vocabulary is {} {}",
306            tokens.vocabulary_id,
307            tokens.vocabulary_version,
308            vocabulary.id(),
309            vocabulary.version()
310        )));
311    }
312    let digest = vocabulary.digest()?;
313    if tokens.vocabulary_digest != digest {
314        return Err(KuteError::VocabularyMismatch(format!(
315            "same id and version but different content: sequence has {}, vocabulary has {digest}",
316            tokens.vocabulary_digest
317        )));
318    }
319    Ok(())
320}
321
322/// Build the sequence header for `vocabulary`.
323pub fn sequence_for(vocabulary: &Vocabulary, modality: Modality, ids: Vec<u32>) -> Result<TokenSequence> {
324    Ok(TokenSequence {
325        vocabulary_id: vocabulary.id().clone(),
326        vocabulary_version: vocabulary.version().clone(),
327        vocabulary_digest: vocabulary.digest()?,
328        modality,
329        adapter: vocabulary.adapter.as_ref().map(|a| a.name.clone()),
330        ids,
331        escapes: Vec::new(),
332    })
333}
334
335/// How many units (bytes or symbols) `tokens` decodes to, computed from the
336/// token table without decoding. A five-byte id can stand for a 64 KiB
337/// token, so callers that decode untrusted sequences check this against a
338/// budget first.
339pub fn decoded_units(vocabulary: &Vocabulary, tokens: &TokenSequence) -> Result<u64> {
340    let table = vocabulary.tokens.len();
341    let mut total: u64 = 0;
342    for &id in &tokens.ids {
343        let id = id as usize;
344        let units = if id < table {
345            vocabulary.tokens[id].payload.len() as u64
346        } else if id - table < tokens.escapes.len() {
347            match vocabulary.tokens[0].payload {
348                TokenPayload::Bytes(_) => tokens.escapes[id - table].len() as u64,
349                TokenPayload::Symbols(_) => 1,
350            }
351        } else {
352            return Err(KuteError::UnknownToken(id as u32));
353        };
354        total = total.saturating_add(units);
355    }
356    Ok(total)
357}
358
359/// A lower bound on the bytes `tokens` decodes to. For a byte vocabulary it
360/// is the decoded length. For a symbol vocabulary it is the total length of
361/// the symbol names, before the adapter writes them out, which only adds to
362/// it. A symbol may be up to 1024 bytes long, so the number of symbols
363/// ([`decoded_units`]) says little about the bytes; this does.
364pub fn decoded_bytes_at_least(vocabulary: &Vocabulary, tokens: &TokenSequence) -> Result<u64> {
365    let size = |payload: &TokenPayload| match payload {
366        TokenPayload::Bytes(b) => b.len() as u64,
367        TokenPayload::Symbols(s) => s.iter().map(|symbol| symbol.len() as u64).sum(),
368    };
369    let sizes: Vec<u64> = vocabulary.tokens.iter().map(|t| size(&t.payload)).collect();
370    let mut total: u64 = 0;
371    for &id in &tokens.ids {
372        let id = id as usize;
373        let bytes = if id < sizes.len() {
374            sizes[id]
375        } else if id - sizes.len() < tokens.escapes.len() {
376            tokens.escapes[id - sizes.len()].len() as u64
377        } else {
378            return Err(KuteError::UnknownToken(id as u32));
379        };
380        total = total.saturating_add(bytes);
381    }
382    Ok(total)
383}