1use 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
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 decode(&self, tokens: &TokenSequence) -> Result<CanonicalInput>;
65
66 fn vocabulary(&self) -> Option<&Vocabulary>;
67
68 fn capabilities(&self) -> TokenizerCapabilities;
69}
70
71#[derive(Clone, Debug, PartialEq, Eq)]
73pub struct AdapterCapabilities {
74 pub name: String,
75 pub modality: Modality,
76 pub lossless: bool,
78 pub notes: String,
79}
80
81pub 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 fn capabilities(&self) -> AdapterCapabilities;
91
92 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#[derive(Clone, Debug, PartialEq)]
101pub enum Representation {
102 Vector(Vec<f32>),
104 ComplexVector(Vec<(f32, f32)>),
106}
107
108pub 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#[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 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 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 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
183pub 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 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
236pub 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
257pub 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}