1use 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
18pub trait CorpusSource {
20 fn next_record(&mut self) -> Result<Option<CanonicalInput>>;
22}
23
24pub 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
41pub 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
50pub trait Tokenizer: Send + Sync {
56 fn train(&mut self, corpus: &mut dyn CorpusSource, config: &TrainingConfig) -> Result<Vocabulary>;
58
59 fn load(&mut self, vocabulary: Vocabulary) -> Result<()>;
61
62 fn encode(&self, input: &CanonicalInput) -> Result<TokenSequence>;
63
64 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#[derive(Clone, Debug, PartialEq, Eq)]
90pub struct AdapterCapabilities {
91 pub name: String,
92 pub modality: Modality,
93 pub lossless: bool,
95 pub notes: String,
96}
97
98pub 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, config: &AdapterConfig) -> Result<Vec<u8>>;
107
108 fn capabilities(&self) -> AdapterCapabilities;
110
111 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#[derive(Clone, Debug, PartialEq)]
120pub enum Representation {
121 Vector(Vec<f32>),
123 ComplexVector(Vec<(f32, f32)>),
125}
126
127pub 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#[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 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 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 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 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 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 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
248pub 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 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
301pub 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
322pub 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
335pub 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
359pub 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}