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, decoded_bytes_at_least, decoded_units, 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
63const SELF_CHECK_RECORDS: usize = 4;
65const SELF_CHECK_BYTES: usize = 64 * 1024;
66const SELF_CHECK_SYMBOLS: usize = 4096;
67
68impl Engine {
69 pub fn new() -> Self {
71 let mut registry = Registry::new();
72 kute_bpe::register(&mut registry).expect("built-in algorithm names are unique");
74 kute_algorithms::register(&mut registry).expect("built-in algorithm names are unique");
75 kute_adapters::register(&mut registry).expect("built-in adapter names are unique");
76 Self { registry }
77 }
78
79 pub fn with_registry(registry: Registry) -> Self {
81 Self { registry }
82 }
83
84 pub fn registry(&self) -> &Registry {
85 &self.registry
86 }
87
88 pub fn registry_mut(&mut self) -> &mut Registry {
90 &mut self.registry
91 }
92
93 pub fn train(
98 &self,
99 algorithm: &str,
100 adapter: &str,
101 adapter_config: &AdapterConfig,
102 documents: &[Vec<u8>],
103 config: &TrainingConfig,
104 ) -> Result<Vocabulary> {
105 let mut next = documents.iter();
106 self.train_stream(algorithm, adapter, adapter_config, config, &mut || Ok(next.next().map(std::borrow::Cow::Borrowed)))
107 }
108
109 pub fn train_stream<'a>(
113 &self,
114 algorithm: &str,
115 adapter: &str,
116 adapter_config: &AdapterConfig,
117 config: &TrainingConfig,
118 documents: &mut dyn FnMut() -> Result<Option<std::borrow::Cow<'a, Vec<u8>>>>,
119 ) -> Result<Vocabulary> {
120 let adapter_impl = self.registry.adapter(adapter)?;
121 let mut tokenizer = self.registry.tokenizer(algorithm)?;
122 if config.resume_from.is_some() && algorithm != "bpe" && algorithm != "sequence-bpe" {
123 return Err(KuteError::Unsupported(format!("resuming a training run is implemented for bpe and sequence-bpe, not {algorithm:?}")));
124 }
125 let mut held: Vec<CanonicalInput> = Vec::new();
129 let mut corpus = FnCorpus(|| match documents()? {
130 Some(doc) => {
131 let input = adapter_impl.ingest(&doc, adapter_config)?;
132 if held.len() < SELF_CHECK_RECORDS && !input.payload.is_empty() {
133 held.push(CanonicalInput {
134 modality: input.modality,
135 payload: match &input.payload {
136 Payload::Bytes(b) => Payload::Bytes(b[..b.len().min(SELF_CHECK_BYTES)].to_vec()),
137 Payload::Symbols(v) => Payload::Symbols(v[..v.len().min(SELF_CHECK_SYMBOLS)].to_vec()),
138 },
139 });
140 }
141 Ok(Some(input))
142 }
143 None => Ok(None),
144 });
145 let mut vocabulary = tokenizer.train(&mut corpus, config)?;
146 for (n, input) in held.iter().enumerate() {
147 let back = tokenizer.decode(&tokenizer.encode(input)?)?;
148 if back.payload != input.payload {
149 return Err(KuteError::Backend(format!("trained vocabulary does not reproduce the start of training record {}", n + 1)));
150 }
151 }
152 vocabulary.adapter = Some(adapter_impl.spec(adapter_config));
153 vocabulary.manifest.modality = adapter_impl.modality();
154 vocabulary.seal()?;
155 let report = self.verify(&vocabulary)?;
157 if !report.ok() {
158 return Err(KuteError::Backend(format!("trained vocabulary fails its own test vectors: {}", report.failures.join("; "))));
159 }
160 Ok(vocabulary)
161 }
162
163 pub fn train_paths(
165 &self,
166 algorithm: &str,
167 adapter: &str,
168 adapter_config: &AdapterConfig,
169 paths: &[PathBuf],
170 config: &TrainingConfig,
171 ) -> Result<Vocabulary> {
172 let mut files = Vec::new();
173 for path in paths {
174 files.extend(collect_files(path)?);
175 }
176 if files.is_empty() {
177 return Err(KuteError::InvalidInput("no input files found".into()));
178 }
179 if config.stream_bytes.is_some() && adapter == kute_adapters::JSON {
180 return Err(KuteError::InvalidConfig("the json adapter reads whole documents and cannot be streamed in pieces".into()));
181 }
182 let line_cut = adapter != kute_adapters::BINARY;
185 let mut files = files.into_iter();
186 let mut open: Option<Pieces> = None;
187 self.train_stream(algorithm, adapter, adapter_config, config, &mut || loop {
188 if let Some(pieces) = open.as_mut() {
189 if let Some(piece) = pieces.next_piece()? {
190 return Ok(Some(std::borrow::Cow::Owned(piece)));
191 }
192 open = None;
193 }
194 let Some(file) = files.next() else { return Ok(None) };
195 match config.stream_bytes {
196 Some(size) => open = Some(Pieces::open(&file, size, line_cut)?),
197 None => return Ok(Some(std::borrow::Cow::Owned(std::fs::read(&file)?))),
198 }
199 })
200 }
201
202 pub fn tokenizer(&self, vocabulary: Vocabulary) -> Result<Box<dyn Tokenizer>> {
204 self.registry.tokenizer_for(vocabulary)
205 }
206
207 fn adapter_of(&self, vocabulary: &Vocabulary) -> Result<(Box<dyn ModalityAdapter>, AdapterConfig)> {
208 match &vocabulary.adapter {
209 Some(spec) => Ok((self.registry.adapter(&spec.name)?, AdapterConfig { options: spec.options.clone() })),
210 None => {
211 let name = match vocabulary.manifest.payload_kind {
212 PayloadKind::Bytes => kute_adapters::BINARY,
213 PayloadKind::Symbols => kute_adapters::JSONL_EVENTS,
214 };
215 Ok((self.registry.adapter(name)?, AdapterConfig::default()))
216 }
217 }
218 }
219
220 pub fn encode_raw(&self, tokenizer: &dyn Tokenizer, raw: &[u8]) -> Result<TokenSequence> {
222 let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
223 let (adapter, config) = self.adapter_of(vocabulary)?;
224 tokenizer.encode(&adapter.ingest(raw, &config)?)
225 }
226
227 pub fn encode_raw_open(&self, tokenizer: &dyn Tokenizer, raw: &[u8], policy: UnknownPolicy) -> Result<TokenSequence> {
229 let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
230 let (adapter, config) = self.adapter_of(vocabulary)?;
231 tokenizer.encode_open(&adapter.ingest(raw, &config)?, policy)
232 }
233
234 pub fn decode_raw_bounded(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence, max_units: u64) -> Result<Vec<u8>> {
242 self.decode_raw_within(tokenizer, tokens, max_units, u64::MAX)
243 }
244
245 pub fn decode_raw_within(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence, max_units: u64, max_bytes: u64) -> Result<Vec<u8>> {
256 let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
257 let units = kute_core::decoded_units(vocabulary, tokens)?;
258 if units > max_units {
259 return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units; the budget is {max_units}")));
260 }
261 let bytes = kute_core::decoded_bytes_at_least(vocabulary, tokens)?;
262 if bytes > max_bytes {
263 return Err(KuteError::LimitExceeded(format!("the sequence decodes to at least {bytes} bytes; the budget is {max_bytes}")));
264 }
265 let decoded = self.decode_raw(tokenizer, tokens)?;
266 if decoded.len() as u64 > max_bytes {
267 return Err(KuteError::LimitExceeded(format!("the sequence decodes to {} bytes; the budget is {max_bytes}", decoded.len())));
268 }
269 Ok(decoded)
270 }
271
272 pub fn decode_raw(&self, tokenizer: &dyn Tokenizer, tokens: &TokenSequence) -> Result<Vec<u8>> {
274 let vocabulary = tokenizer.vocabulary().ok_or_else(|| KuteError::NotTrained("tokenizer has no vocabulary".into()))?;
275 let (adapter, config) = self.adapter_of(vocabulary)?;
276 adapter.reconstruct(&tokenizer.decode(tokens)?, &config)
277 }
278
279 pub fn encode_batch(&self, tokenizer: &dyn Tokenizer, documents: &[Vec<u8>]) -> Result<Vec<TokenSequence>> {
281 documents.par_iter().map(|d| self.encode_raw(tokenizer, d)).collect()
282 }
283
284 pub fn verify(&self, vocabulary: &Vocabulary) -> Result<VerifyReport> {
287 vocabulary.validate()?;
288 let tokenizer = self.tokenizer(vocabulary.clone())?;
289 let mut failures = Vec::new();
290 let mut passed = 0;
291 for (i, vector) in vocabulary.test_vectors.iter().enumerate() {
292 let payload = match &vector.input {
293 TokenPayload::Bytes(b) => Payload::Bytes(b.clone()),
294 TokenPayload::Symbols(s) => Payload::Symbols(s.clone()),
295 };
296 let input = CanonicalInput { modality: vocabulary.manifest.modality, payload };
297 match tokenizer.encode(&input) {
298 Err(e) => failures.push(format!("vector {i}: encode failed: {e}")),
299 Ok(sequence) if sequence.ids != vector.ids => failures.push(format!("vector {i}: encoded ids differ from the recorded ids")),
300 Ok(sequence) => match tokenizer.decode(&sequence) {
301 Ok(back) if back.payload == input.payload => passed += 1,
302 Ok(_) => failures.push(format!("vector {i}: decode did not reproduce the input")),
303 Err(e) => failures.push(format!("vector {i}: decode failed: {e}")),
304 },
305 }
306 }
307 Ok(VerifyReport {
308 vocabulary: format!("{} {}", vocabulary.id(), vocabulary.version()),
309 digest: vocabulary.digest()?,
310 vectors: vocabulary.test_vectors.len(),
311 passed,
312 failures,
313 })
314 }
315}
316
317struct Pieces {
321 reader: std::io::BufReader<std::fs::File>,
322 size: usize,
323 line_cut: bool,
324 carry: Vec<u8>,
325 done: bool,
326}
327
328impl Pieces {
329 fn open(path: &Path, size: usize, line_cut: bool) -> Result<Self> {
330 Ok(Self { reader: std::io::BufReader::new(std::fs::File::open(path)?), size, line_cut, carry: Vec::new(), done: false })
331 }
332
333 fn next_piece(&mut self) -> Result<Option<Vec<u8>>> {
334 use std::io::{BufRead, Read};
335 if self.done && self.carry.is_empty() {
336 return Ok(None);
337 }
338 let mut piece = std::mem::take(&mut self.carry);
339 if !self.done && piece.len() < self.size {
340 let want = (self.size - piece.len()) as u64;
341 if (&mut self.reader).take(want).read_to_end(&mut piece)? < want as usize {
342 self.done = true;
343 }
344 }
345 if self.line_cut && !self.done {
346 match piece.iter().rposition(|&b| b == b'\n') {
347 Some(at) => self.carry = piece.split_off(at + 1),
348 None => {
349 if self.reader.read_until(b'\n', &mut piece)? == 0 || piece.last() != Some(&b'\n') {
351 self.done = true;
352 }
353 }
354 }
355 }
356 Ok(if piece.is_empty() { None } else { Some(piece) })
357 }
358}
359
360pub fn collect_files(path: &Path) -> Result<Vec<PathBuf>> {
363 let meta = std::fs::metadata(path).map_err(|e| KuteError::InvalidInput(format!("{}: {e}", path.display())))?;
364 if meta.is_file() {
365 return Ok(vec![path.to_path_buf()]);
366 }
367 let mut out = Vec::new();
368 let mut stack = vec![path.to_path_buf()];
369 while let Some(dir) = stack.pop() {
370 for entry in std::fs::read_dir(&dir)? {
371 let entry = entry?;
372 if entry.file_name().to_string_lossy().starts_with('.') {
373 continue;
374 }
375 let kind = entry.file_type()?;
376 if kind.is_dir() {
377 stack.push(entry.path());
378 } else if kind.is_file() {
379 out.push(entry.path());
380 }
381 }
382 }
383 out.sort();
384 Ok(out)
385}