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    fn reconstruct(&self, input: &CanonicalInput) -> Result<Vec<u8>>;
105
106    /// Must state whether reconstruction is lossless.
107    fn capabilities(&self) -> AdapterCapabilities;
108
109    /// The specification stored in a vocabulary trained through this adapter.
110    fn spec(&self, config: &AdapterConfig) -> AdapterSpec {
111        let caps = self.capabilities();
112        AdapterSpec { name: caps.name, options: config.options.clone(), lossless: caps.lossless }
113    }
114}
115
116/// A numeric representation of one token (FR-015).
117#[derive(Clone, Debug, PartialEq)]
118pub enum Representation {
119    /// Real-valued vector.
120    Vector(Vec<f32>),
121    /// Complex-valued vector as `(re, im)` pairs.
122    ComplexVector(Vec<(f32, f32)>),
123}
124
125/// Maps token ids to another representation. Mappings are versioned on their
126/// own and never change what a token id means (FR-015, ADR-0011).
127pub trait RepresentationBackend: Send + Sync {
128    fn mapping_id(&self) -> &str;
129    fn mapping_version(&self) -> &str;
130    fn dimension(&self) -> usize;
131    fn map(&self, vocabulary: &Vocabulary, token_id: u32) -> Result<Representation>;
132}
133
134type TokenizerFactory = Arc<dyn Fn() -> Box<dyn Tokenizer> + Send + Sync>;
135type AdapterFactory = Arc<dyn Fn() -> Box<dyn ModalityAdapter> + Send + Sync>;
136
137/// Run-time table of algorithms and adapters.
138#[derive(Clone, Default)]
139pub struct Registry {
140    algorithms: BTreeMap<String, TokenizerFactory>,
141    adapters: BTreeMap<String, AdapterFactory>,
142}
143
144impl Registry {
145    pub fn new() -> Self {
146        Self::default()
147    }
148
149    /// Register a tokenization algorithm under `name`. A name can be taken
150    /// once: a second registration is an error, so one plugin cannot quietly
151    /// change what another's vocabularies mean. Use
152    /// [`Registry::replace_algorithm`] to override on purpose.
153    pub fn register_algorithm<F>(&mut self, name: &str, factory: F) -> Result<()>
154    where
155        F: Fn() -> Box<dyn Tokenizer> + Send + Sync + 'static,
156    {
157        if self.algorithms.contains_key(name) {
158            return Err(KuteError::InvalidConfig(format!("algorithm {name:?} is already registered")));
159        }
160        self.algorithms.insert(name.to_string(), Arc::new(factory));
161        Ok(())
162    }
163
164    /// Register or replace the algorithm under `name`.
165    pub fn replace_algorithm<F>(&mut self, name: &str, factory: F)
166    where
167        F: Fn() -> Box<dyn Tokenizer> + Send + Sync + 'static,
168    {
169        self.algorithms.insert(name.to_string(), Arc::new(factory));
170    }
171
172    /// Register an adapter under `name`. Like algorithms, a name can be
173    /// taken once.
174    pub fn register_adapter<F>(&mut self, name: &str, factory: F) -> Result<()>
175    where
176        F: Fn() -> Box<dyn ModalityAdapter> + Send + Sync + 'static,
177    {
178        if self.adapters.contains_key(name) {
179            return Err(KuteError::InvalidConfig(format!("adapter {name:?} is already registered")));
180        }
181        self.adapters.insert(name.to_string(), Arc::new(factory));
182        Ok(())
183    }
184
185    /// Register or replace the adapter under `name`.
186    pub fn replace_adapter<F>(&mut self, name: &str, factory: F)
187    where
188        F: Fn() -> Box<dyn ModalityAdapter> + Send + Sync + 'static,
189    {
190        self.adapters.insert(name.to_string(), Arc::new(factory));
191    }
192
193    /// A fresh, untrained tokenizer for `name`.
194    pub fn tokenizer(&self, name: &str) -> Result<Box<dyn Tokenizer>> {
195        self.algorithms.get(name).map(|f| f()).ok_or_else(|| {
196            KuteError::Unsupported(format!(
197                "algorithm {name:?} is not registered (available: {})",
198                self.algorithm_names().join(", ")
199            ))
200        })
201    }
202
203    pub fn adapter(&self, name: &str) -> Result<Box<dyn ModalityAdapter>> {
204        self.adapters.get(name).map(|f| f()).ok_or_else(|| {
205            KuteError::Unsupported(format!(
206                "adapter {name:?} is not registered (available: {})",
207                self.adapter_names().join(", ")
208            ))
209        })
210    }
211
212    /// A tokenizer with `vocabulary` installed, chosen by the manifest.
213    pub fn tokenizer_for(&self, vocabulary: Vocabulary) -> Result<Box<dyn Tokenizer>> {
214        let mut t = self.tokenizer(&vocabulary.manifest.algorithm)?;
215        t.load(vocabulary)?;
216        Ok(t)
217    }
218
219    pub fn algorithm_names(&self) -> Vec<String> {
220        self.algorithms.keys().cloned().collect()
221    }
222
223    pub fn adapter_names(&self) -> Vec<String> {
224        self.adapters.keys().cloned().collect()
225    }
226}
227
228/// Order-sensitive fingerprint of a corpus as a tokenizer sees it. Trainers
229/// feed every record through this and store the result as provenance.
230pub struct CorpusFingerprint {
231    hasher: Sha256,
232    records: u64,
233    units: u64,
234}
235
236impl Default for CorpusFingerprint {
237    fn default() -> Self {
238        Self::new()
239    }
240}
241
242impl CorpusFingerprint {
243    pub fn new() -> Self {
244        Self { hasher: Sha256::new(), records: 0, units: 0 }
245    }
246
247    pub fn update(&mut self, input: &CanonicalInput) {
248        match &input.payload {
249            Payload::Bytes(b) => {
250                self.hasher.update(b"B");
251                self.hasher.update((b.len() as u64).to_le_bytes());
252                self.hasher.update(b);
253            }
254            Payload::Symbols(s) => {
255                self.hasher.update(b"S");
256                self.hasher.update((s.len() as u64).to_le_bytes());
257                for sym in s {
258                    self.hasher.update((sym.len() as u64).to_le_bytes());
259                    self.hasher.update(sym.as_bytes());
260                }
261            }
262        }
263        self.records += 1;
264        self.units += input.payload.len() as u64;
265    }
266
267    pub fn records(&self) -> u64 {
268        self.records
269    }
270
271    /// Total bytes or symbols seen.
272    pub fn units(&self) -> u64 {
273        self.units
274    }
275
276    pub fn finish(self) -> String {
277        format!("sha256:{}", kute_types::hex(&self.hasher.finalize()))
278    }
279}
280
281/// Check that a token sequence was produced by exactly this vocabulary.
282pub fn check_sequence(vocabulary: &Vocabulary, tokens: &TokenSequence) -> Result<()> {
283    if &tokens.vocabulary_id != vocabulary.id() || &tokens.vocabulary_version != vocabulary.version() {
284        return Err(KuteError::VocabularyMismatch(format!(
285            "sequence was encoded with {} {} but the loaded vocabulary is {} {}",
286            tokens.vocabulary_id,
287            tokens.vocabulary_version,
288            vocabulary.id(),
289            vocabulary.version()
290        )));
291    }
292    let digest = vocabulary.digest()?;
293    if tokens.vocabulary_digest != digest {
294        return Err(KuteError::VocabularyMismatch(format!(
295            "same id and version but different content: sequence has {}, vocabulary has {digest}",
296            tokens.vocabulary_digest
297        )));
298    }
299    Ok(())
300}
301
302/// Build the sequence header for `vocabulary`.
303pub fn sequence_for(vocabulary: &Vocabulary, modality: Modality, ids: Vec<u32>) -> Result<TokenSequence> {
304    Ok(TokenSequence {
305        vocabulary_id: vocabulary.id().clone(),
306        vocabulary_version: vocabulary.version().clone(),
307        vocabulary_digest: vocabulary.digest()?,
308        modality,
309        adapter: vocabulary.adapter.as_ref().map(|a| a.name.clone()),
310        ids,
311        escapes: Vec::new(),
312    })
313}
314
315/// How many units (bytes or symbols) `tokens` decodes to, computed from the
316/// token table without decoding. A five-byte id can stand for a 64 KiB
317/// token, so callers that decode untrusted sequences check this against a
318/// budget first.
319pub fn decoded_units(vocabulary: &Vocabulary, tokens: &TokenSequence) -> Result<u64> {
320    let table = vocabulary.tokens.len();
321    let mut total: u64 = 0;
322    for &id in &tokens.ids {
323        let id = id as usize;
324        let units = if id < table {
325            vocabulary.tokens[id].payload.len() as u64
326        } else if id - table < tokens.escapes.len() {
327            match vocabulary.tokens[0].payload {
328                TokenPayload::Bytes(_) => tokens.escapes[id - table].len() as u64,
329                TokenPayload::Symbols(_) => 1,
330            }
331        } else {
332            return Err(KuteError::UnknownToken(id as u32));
333        };
334        total = total.saturating_add(units);
335    }
336    Ok(total)
337}