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) -> Result<Vec<u8>>;
105
106 fn capabilities(&self) -> AdapterCapabilities;
108
109 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#[derive(Clone, Debug, PartialEq)]
118pub enum Representation {
119 Vector(Vec<f32>),
121 ComplexVector(Vec<(f32, f32)>),
123}
124
125pub 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#[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 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 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 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 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 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 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
228pub 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 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
281pub 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
302pub 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
315pub 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}