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    pub fn tokenizer_for(&self, vocabulary: Vocabulary) -> Result<Box<dyn Tokenizer>> {
216        let mut t = self.tokenizer(&vocabulary.manifest.algorithm)?;
217        t.load(vocabulary)?;
218        Ok(t)
219    }
220
221    pub fn algorithm_names(&self) -> Vec<String> {
222        self.algorithms.keys().cloned().collect()
223    }
224
225    pub fn adapter_names(&self) -> Vec<String> {
226        self.adapters.keys().cloned().collect()
227    }
228}
229
230/// Order-sensitive fingerprint of a corpus as a tokenizer sees it. Trainers
231/// feed every record through this and store the result as provenance.
232pub struct CorpusFingerprint {
233    hasher: Sha256,
234    records: u64,
235    units: u64,
236}
237
238impl Default for CorpusFingerprint {
239    fn default() -> Self {
240        Self::new()
241    }
242}
243
244impl CorpusFingerprint {
245    pub fn new() -> Self {
246        Self { hasher: Sha256::new(), records: 0, units: 0 }
247    }
248
249    pub fn update(&mut self, input: &CanonicalInput) {
250        match &input.payload {
251            Payload::Bytes(b) => {
252                self.hasher.update(b"B");
253                self.hasher.update((b.len() as u64).to_le_bytes());
254                self.hasher.update(b);
255            }
256            Payload::Symbols(s) => {
257                self.hasher.update(b"S");
258                self.hasher.update((s.len() as u64).to_le_bytes());
259                for sym in s {
260                    self.hasher.update((sym.len() as u64).to_le_bytes());
261                    self.hasher.update(sym.as_bytes());
262                }
263            }
264        }
265        self.records += 1;
266        self.units += input.payload.len() as u64;
267    }
268
269    pub fn records(&self) -> u64 {
270        self.records
271    }
272
273    /// Total bytes or symbols seen.
274    pub fn units(&self) -> u64 {
275        self.units
276    }
277
278    pub fn finish(self) -> String {
279        format!("sha256:{}", kute_types::hex(&self.hasher.finalize()))
280    }
281}
282
283/// Check that a token sequence was produced by exactly this vocabulary.
284pub fn check_sequence(vocabulary: &Vocabulary, tokens: &TokenSequence) -> Result<()> {
285    if &tokens.vocabulary_id != vocabulary.id() || &tokens.vocabulary_version != vocabulary.version() {
286        return Err(KuteError::VocabularyMismatch(format!(
287            "sequence was encoded with {} {} but the loaded vocabulary is {} {}",
288            tokens.vocabulary_id,
289            tokens.vocabulary_version,
290            vocabulary.id(),
291            vocabulary.version()
292        )));
293    }
294    let digest = vocabulary.digest()?;
295    if tokens.vocabulary_digest != digest {
296        return Err(KuteError::VocabularyMismatch(format!(
297            "same id and version but different content: sequence has {}, vocabulary has {digest}",
298            tokens.vocabulary_digest
299        )));
300    }
301    Ok(())
302}
303
304/// Build the sequence header for `vocabulary`.
305pub fn sequence_for(vocabulary: &Vocabulary, modality: Modality, ids: Vec<u32>) -> Result<TokenSequence> {
306    Ok(TokenSequence {
307        vocabulary_id: vocabulary.id().clone(),
308        vocabulary_version: vocabulary.version().clone(),
309        vocabulary_digest: vocabulary.digest()?,
310        modality,
311        adapter: vocabulary.adapter.as_ref().map(|a| a.name.clone()),
312        ids,
313        escapes: Vec::new(),
314    })
315}
316
317/// How many units (bytes or symbols) `tokens` decodes to, computed from the
318/// token table without decoding. A five-byte id can stand for a 64 KiB
319/// token, so callers that decode untrusted sequences check this against a
320/// budget first.
321pub fn decoded_units(vocabulary: &Vocabulary, tokens: &TokenSequence) -> Result<u64> {
322    let table = vocabulary.tokens.len();
323    let mut total: u64 = 0;
324    for &id in &tokens.ids {
325        let id = id as usize;
326        let units = if id < table {
327            vocabulary.tokens[id].payload.len() as u64
328        } else if id - table < tokens.escapes.len() {
329            match vocabulary.tokens[0].payload {
330                TokenPayload::Bytes(_) => tokens.escapes[id - table].len() as u64,
331                TokenPayload::Symbols(_) => 1,
332            }
333        } else {
334            return Err(KuteError::UnknownToken(id as u32));
335        };
336        total = total.saturating_add(units);
337    }
338    Ok(total)
339}