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>> {
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
230pub 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 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
283pub 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
304pub 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
317pub 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}