1use rayon::prelude::*;
22use serde::Serialize;
23use std::path::{Path, PathBuf};
24
25pub use kute_adapters as adapters;
26pub use kute_algorithms as algorithms;
27pub use kute_bpe as bpe;
28pub use kute_core::{
29 check_sequence, AdapterCapabilities, CorpusSource, FnCorpus, ModalityAdapter, Registry, Representation,
30 RepresentationBackend, Tokenizer, VecCorpus,
31};
32pub use kute_types::*;
33pub use kute_vocab as vocab;
34
35#[derive(Clone)]
37pub struct Engine {
38 registry: Registry,
39}
40
41impl Default for Engine {
42 fn default() -> Self {
43 Self::new()
44 }
45}
46
47#[derive(Clone, Debug, Serialize)]
49pub struct VerifyReport {
50 pub vocabulary: String,
51 pub digest: String,
52 pub vectors: usize,
53 pub passed: usize,
54 pub failures: Vec<String>,
55}
56
57impl VerifyReport {
58 pub fn ok(&self) -> bool {
59 self.failures.is_empty()
60 }
61}
62
63impl Engine {
64 pub fn new() -> Self {
66 let mut registry = Registry::new();
67 kute_bpe::register(&mut registry);
68 kute_algorithms::register(&mut registry);
69 kute_adapters::register(&mut registry);
70 Self { registry }
71 }
72
73 pub fn with_registry(registry: Registry) -> Self {
75 Self { registry }
76 }
77
78 pub fn registry(&self) -> &Registry {
79 &self.registry
80 }
81
82 pub fn registry_mut(&mut self) -> &mut Registry {
84 &mut self.registry
85 }
86
87 pub fn train(
92 &self,
93 algorithm: &str,
94 adapter: &str,
95 adapter_config: &AdapterConfig,
96 documents: &[Vec<u8>],
97 config: &TrainingConfig,
98 ) -> Result<Vocabulary> {
99 let adapter_impl = self.registry.adapter(adapter)?;
100 let mut tokenizer = self.registry.tokenizer(algorithm)?;
101 let mut records = Vec::with_capacity(documents.len());
102 for doc in documents {
103 records.push(adapter_impl.ingest(doc, adapter_config)?);
104 }
105 let mut vocabulary = tokenizer.train(&mut VecCorpus::new(records), config)?;
106 vocabulary.adapter = Some(adapter_impl.spec(adapter_config));
107 vocabulary.manifest.modality = adapter_impl.modality();
108 vocabulary.seal()?;
109 let report = self.verify(&vocabulary)?;
111 if !report.ok() {
112 return Err(KuteError::Backend(format!("trained vocabulary fails its own test vectors: {}", report.failures.join("; "))));
113 }
114 Ok(vocabulary)
115 }
116
117 pub fn train_paths(
119 &self,
120 algorithm: &str,
121 adapter: &str,
122 adapter_config: &AdapterConfig,
123 paths: &[PathBuf],
124 config: &TrainingConfig,
125 ) -> Result<Vocabulary> {
126 let mut documents = Vec::new();
127 for path in paths {
128 for file in collect_files(path)? {
129 documents.push(std::fs::read(&file)?);
130 }
131 }
132 if documents.is_empty() {
133 return Err(KuteError::InvalidInput("no input files found".into()));
134 }
135 self.train(algorithm, adapter, adapter_config, &documents, config)
136 }
137
138 pub fn tokenizer(&self, vocabulary: Vocabulary) -> Result<Box<dyn Tokenizer>> {
140 self.registry.tokenizer_for(vocabulary)
141 }
142
143 fn adapter_of(&self, vocabulary: &Vocabulary) -> Result<(Box<dyn ModalityAdapter>, AdapterConfig)> {
144 match &vocabulary.adapter {
145 Some(spec) => Ok((self.registry.adapter(&spec.name)?, AdapterConfig { options: spec.options.clone() })),
146 None => {
147 let name = match vocabulary.manifest.payload_kind {
148 PayloadKind::Bytes => kute_adapters::BINARY,
149 PayloadKind::Symbols => kute_adapters::JSONL_EVENTS,
150 };
151 Ok((self.registry.adapter(name)?, AdapterConfig::default()))
152 }
153 }
154 }
155
156 pub fn encode_raw(&self, tokenizer: &dyn Tokenizer, raw: &[u8]) -> Result<TokenSequence> {
158 let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
159 let (adapter, config) = self.adapter_of(vocabulary)?;
160 tokenizer.encode(&adapter.ingest(raw, &config)?)
161 }
162
163 pub fn decode_raw(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence) -> Result<Vec<u8>> {
165 let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
166 let (adapter, _) = self.adapter_of(vocabulary)?;
167 adapter.reconstruct(&tokenizer.decode(tokens)?)
168 }
169
170 pub fn encode_batch(&self, tokenizer: &dyn Tokenizer, documents: &[Vec<u8>]) -> Result<Vec<TokenSequence>> {
172 documents.par_iter().map(|d| self.encode_raw(tokenizer, d)).collect()
173 }
174
175 pub fn verify(&self, vocabulary: &Vocabulary) -> Result<VerifyReport> {
178 vocabulary.validate()?;
179 let tokenizer = self.tokenizer(vocabulary.clone())?;
180 let mut failures = Vec::new();
181 let mut passed = 0;
182 for (i, vector) in vocabulary.test_vectors.iter().enumerate() {
183 let payload = match &vector.input {
184 TokenPayload::Bytes(b) => Payload::Bytes(b.clone()),
185 TokenPayload::Symbols(s) => Payload::Symbols(s.clone()),
186 };
187 let input = CanonicalInput { modality: vocabulary.manifest.modality, payload };
188 match tokenizer.encode(&input) {
189 Err(e) => failures.push(format!("vector {i}: encode failed: {e}")),
190 Ok(sequence) if sequence.ids != vector.ids => failures.push(format!("vector {i}: encoded ids differ from the recorded ids")),
191 Ok(sequence) => match tokenizer.decode(&sequence) {
192 Ok(back) if back.payload == input.payload => passed += 1,
193 Ok(_) => failures.push(format!("vector {i}: decode did not reproduce the input")),
194 Err(e) => failures.push(format!("vector {i}: decode failed: {e}")),
195 },
196 }
197 }
198 Ok(VerifyReport {
199 vocabulary: format!("{} {}", vocabulary.id(), vocabulary.version()),
200 digest: vocabulary.digest()?,
201 vectors: vocabulary.test_vectors.len(),
202 passed,
203 failures,
204 })
205 }
206}
207
208pub fn collect_files(path: &Path) -> Result<Vec<PathBuf>> {
211 let meta = std::fs::metadata(path).map_err(|e| KuteError::InvalidInput(format!("{}: {e}", path.display())))?;
212 if meta.is_file() {
213 return Ok(vec![path.to_path_buf()]);
214 }
215 let mut out = Vec::new();
216 let mut stack = vec![path.to_path_buf()];
217 while let Some(dir) = stack.pop() {
218 for entry in std::fs::read_dir(&dir)? {
219 let entry = entry?;
220 if entry.file_name().to_string_lossy().starts_with('.') {
221 continue;
222 }
223 let kind = entry.file_type()?;
224 if kind.is_dir() {
225 stack.push(entry.path());
226 } else if kind.is_file() {
227 out.push(entry.path());
228 }
229 }
230 }
231 out.sort();
232 Ok(out)
233}