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, TokenSequence,
10    TokenizerCapabilities, TrainingConfig, 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    fn decode(&self, tokens: &TokenSequence) -> Result<CanonicalInput>;
65
66    fn vocabulary(&self) -> Option<&Vocabulary>;
67
68    fn capabilities(&self) -> TokenizerCapabilities;
69}
70
71/// What an adapter declares about itself.
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub struct AdapterCapabilities {
74    pub name: String,
75    pub modality: Modality,
76    /// `reconstruct(ingest(x)) == x` byte for byte, for every accepted `x`.
77    pub lossless: bool,
78    pub notes: String,
79}
80
81/// Converts raw bytes of some format to canonical input and back (PRD 9.3).
82pub trait ModalityAdapter: Send + Sync {
83    fn modality(&self) -> Modality;
84
85    fn ingest(&self, input: &[u8], config: &AdapterConfig) -> Result<CanonicalInput>;
86
87    fn reconstruct(&self, input: &CanonicalInput) -> Result<Vec<u8>>;
88
89    /// Must state whether reconstruction is lossless.
90    fn capabilities(&self) -> AdapterCapabilities;
91
92    /// The specification stored in a vocabulary trained through this adapter.
93    fn spec(&self, config: &AdapterConfig) -> AdapterSpec {
94        let caps = self.capabilities();
95        AdapterSpec { name: caps.name, options: config.options.clone(), lossless: caps.lossless }
96    }
97}
98
99/// A numeric representation of one token (FR-015).
100#[derive(Clone, Debug, PartialEq)]
101pub enum Representation {
102    /// Real-valued vector.
103    Vector(Vec<f32>),
104    /// Complex-valued vector as `(re, im)` pairs.
105    ComplexVector(Vec<(f32, f32)>),
106}
107
108/// Maps token ids to another representation. Mappings are versioned on their
109/// own and never change what a token id means (FR-015, ADR-0011).
110pub trait RepresentationBackend: Send + Sync {
111    fn mapping_id(&self) -> &str;
112    fn mapping_version(&self) -> &str;
113    fn dimension(&self) -> usize;
114    fn map(&self, vocabulary: &Vocabulary, token_id: u32) -> Result<Representation>;
115}
116
117type TokenizerFactory = Arc<dyn Fn() -> Box<dyn Tokenizer> + Send + Sync>;
118type AdapterFactory = Arc<dyn Fn() -> Box<dyn ModalityAdapter> + Send + Sync>;
119
120/// Run-time table of algorithms and adapters.
121#[derive(Clone, Default)]
122pub struct Registry {
123    algorithms: BTreeMap<String, TokenizerFactory>,
124    adapters: BTreeMap<String, AdapterFactory>,
125}
126
127impl Registry {
128    pub fn new() -> Self {
129        Self::default()
130    }
131
132    /// Register a tokenization algorithm under `name`. Replaces an earlier
133    /// registration of the same name.
134    pub fn register_algorithm<F>(&mut self, name: &str, factory: F)
135    where
136        F: Fn() -> Box<dyn Tokenizer> + Send + Sync + 'static,
137    {
138        self.algorithms.insert(name.to_string(), Arc::new(factory));
139    }
140
141    pub fn register_adapter<F>(&mut self, name: &str, factory: F)
142    where
143        F: Fn() -> Box<dyn ModalityAdapter> + Send + Sync + 'static,
144    {
145        self.adapters.insert(name.to_string(), Arc::new(factory));
146    }
147
148    /// A fresh, untrained tokenizer for `name`.
149    pub fn tokenizer(&self, name: &str) -> Result<Box<dyn Tokenizer>> {
150        self.algorithms.get(name).map(|f| f()).ok_or_else(|| {
151            KuteError::Unsupported(format!(
152                "algorithm {name:?} is not registered (available: {})",
153                self.algorithm_names().join(", ")
154            ))
155        })
156    }
157
158    pub fn adapter(&self, name: &str) -> Result<Box<dyn ModalityAdapter>> {
159        self.adapters.get(name).map(|f| f()).ok_or_else(|| {
160            KuteError::Unsupported(format!(
161                "adapter {name:?} is not registered (available: {})",
162                self.adapter_names().join(", ")
163            ))
164        })
165    }
166
167    /// A tokenizer with `vocabulary` installed, chosen by the manifest.
168    pub fn tokenizer_for(&self, vocabulary: Vocabulary) -> Result<Box<dyn Tokenizer>> {
169        let mut t = self.tokenizer(&vocabulary.manifest.algorithm)?;
170        t.load(vocabulary)?;
171        Ok(t)
172    }
173
174    pub fn algorithm_names(&self) -> Vec<String> {
175        self.algorithms.keys().cloned().collect()
176    }
177
178    pub fn adapter_names(&self) -> Vec<String> {
179        self.adapters.keys().cloned().collect()
180    }
181}
182
183/// Order-sensitive fingerprint of a corpus as a tokenizer sees it. Trainers
184/// feed every record through this and store the result as provenance.
185pub struct CorpusFingerprint {
186    hasher: Sha256,
187    records: u64,
188    units: u64,
189}
190
191impl Default for CorpusFingerprint {
192    fn default() -> Self {
193        Self::new()
194    }
195}
196
197impl CorpusFingerprint {
198    pub fn new() -> Self {
199        Self { hasher: Sha256::new(), records: 0, units: 0 }
200    }
201
202    pub fn update(&mut self, input: &CanonicalInput) {
203        match &input.payload {
204            Payload::Bytes(b) => {
205                self.hasher.update(b"B");
206                self.hasher.update((b.len() as u64).to_le_bytes());
207                self.hasher.update(b);
208            }
209            Payload::Symbols(s) => {
210                self.hasher.update(b"S");
211                self.hasher.update((s.len() as u64).to_le_bytes());
212                for sym in s {
213                    self.hasher.update((sym.len() as u64).to_le_bytes());
214                    self.hasher.update(sym.as_bytes());
215                }
216            }
217        }
218        self.records += 1;
219        self.units += input.payload.len() as u64;
220    }
221
222    pub fn records(&self) -> u64 {
223        self.records
224    }
225
226    /// Total bytes or symbols seen.
227    pub fn units(&self) -> u64 {
228        self.units
229    }
230
231    pub fn finish(self) -> String {
232        format!("sha256:{}", kute_types::hex(&self.hasher.finalize()))
233    }
234}
235
236/// Check that a token sequence was produced by exactly this vocabulary.
237pub fn check_sequence(vocabulary: &Vocabulary, tokens: &TokenSequence) -> Result<()> {
238    if &tokens.vocabulary_id != vocabulary.id() || &tokens.vocabulary_version != vocabulary.version() {
239        return Err(KuteError::VocabularyMismatch(format!(
240            "sequence was encoded with {} {} but the loaded vocabulary is {} {}",
241            tokens.vocabulary_id,
242            tokens.vocabulary_version,
243            vocabulary.id(),
244            vocabulary.version()
245        )));
246    }
247    let digest = vocabulary.digest()?;
248    if tokens.vocabulary_digest != digest {
249        return Err(KuteError::VocabularyMismatch(format!(
250            "same id and version but different content: sequence has {}, vocabulary has {digest}",
251            tokens.vocabulary_digest
252        )));
253    }
254    Ok(())
255}
256
257/// Build the sequence header for `vocabulary`.
258pub fn sequence_for(vocabulary: &Vocabulary, modality: Modality, ids: Vec<u32>) -> Result<TokenSequence> {
259    Ok(TokenSequence {
260        vocabulary_id: vocabulary.id().clone(),
261        vocabulary_version: vocabulary.version().clone(),
262        vocabulary_digest: vocabulary.digest()?,
263        modality,
264        adapter: vocabulary.adapter.as_ref().map(|a| a.name.clone()),
265        ids,
266    })
267}