1use clap::{Parser, Subcommand, ValueEnum};
7use kute::{vocab, AdapterConfig, Engine, KuteError, Pretokenizer, TokenSequence, TrainingConfig, Version, VocabularyId};
8use serde_json::json;
9use std::io::Write;
10use std::path::PathBuf;
11use std::process::ExitCode;
12
13#[derive(Parser)]
14#[command(name = "kute", version, about = "Kannaka Universal Tokenization Engine", long_about = None)]
15struct Cli {
16 #[command(subcommand)]
17 command: Command,
18}
19
20#[derive(Subcommand)]
21enum Command {
22 Train(Box<TrainArgs>),
24 Encode {
26 #[arg(long)]
27 vocab: PathBuf,
28 #[arg(long)]
29 input: PathBuf,
30 #[arg(long)]
32 output: Option<PathBuf>,
33 #[arg(long, requires = "output")]
35 compress: bool,
36 #[arg(long, default_value = "strict")]
40 unknown: String,
41 },
42 Decode {
44 #[arg(long)]
45 vocab: PathBuf,
46 #[arg(long)]
47 input: PathBuf,
48 #[arg(long)]
50 output: Option<PathBuf>,
51 #[arg(long)]
54 max_units: Option<u64>,
55 },
56 Inspect {
58 vocab: PathBuf,
59 #[arg(long)]
61 token: Option<u32>,
62 #[arg(long, default_value_t = 0)]
64 longest: usize,
65 },
66 Validate { vocab: PathBuf },
68 Compare { a: PathBuf, b: PathBuf },
70 Convert {
73 #[arg(long)]
74 input: PathBuf,
75 #[arg(long)]
76 output: PathBuf,
77 #[arg(long)]
79 force: bool,
80 },
81 Export {
83 #[arg(long)]
84 vocab: PathBuf,
85 #[arg(long, value_enum, default_value_t = ExportFormat::Tiktoken)]
86 format: ExportFormat,
87 #[arg(long)]
90 output: PathBuf,
91 },
92 Benchmark {
94 #[arg(long, required_unless_present = "suite")]
95 vocab: Option<PathBuf>,
96 #[arg(long, required_unless_present = "suite")]
98 dataset: Option<PathBuf>,
99 #[arg(long, conflicts_with_all = ["vocab", "dataset"])]
101 suite: bool,
102 #[arg(long)]
104 repo_root: Option<PathBuf>,
105 #[arg(long, requires = "suite")]
108 large_text: Option<PathBuf>,
109 #[arg(long, default_value_t = 5)]
110 iterations: usize,
111 #[arg(long)]
113 output: Option<PathBuf>,
114 },
115 Discover(Box<DiscoverArgs>),
117 Evolve {
120 #[arg(long)]
121 vocab: PathBuf,
122 #[arg(long = "add", required = true, value_name = "SYMBOLS")]
124 additions: Vec<String>,
125 #[arg(long)]
127 new_version: String,
128 #[arg(long)]
129 output: PathBuf,
130 #[arg(long)]
131 force: bool,
132 },
133 Peer {
136 #[command(subcommand)]
137 action: PeerAction,
138 },
139 Capabilities,
141 SampleData {
143 #[arg(long)]
145 output: PathBuf,
146 },
147}
148
149#[derive(Clone, Copy, ValueEnum)]
150enum ExportFormat {
151 Tiktoken,
152}
153
154#[derive(Subcommand)]
155enum PeerAction {
156 Serve {
158 #[arg(long)]
160 listen: String,
161 #[arg(long)]
163 vocab: Vec<PathBuf>,
164 #[arg(long)]
166 no_new_vocabularies: bool,
167 #[arg(long)]
169 accept_proposals: bool,
170 #[arg(long, default_value_t = 268_435_456)]
172 max_units: u64,
173 #[arg(long)]
175 output_dir: Option<PathBuf>,
176 },
177 Send {
179 #[arg(long)]
181 connect: String,
182 #[arg(long)]
183 vocab: PathBuf,
184 #[arg(long, num_args = 0..)]
186 input: Vec<PathBuf>,
187 #[arg(long, default_value = "strict")]
189 unknown: String,
190 #[arg(long = "propose", value_name = "SYMBOLS", requires = "new_version")]
192 additions: Vec<String>,
193 #[arg(long)]
194 new_version: Option<String>,
195 },
196}
197
198fn split_additions(additions: &[String]) -> Vec<Vec<String>> {
199 additions.iter().map(|a| a.split_whitespace().map(str::to_string).collect()).collect()
200}
201
202fn peer(engine: Engine, action: PeerAction) -> kute::Result<()> {
203 use kute_protocol::{Framed, Peer, Policy, Session, DEFAULT_MAX_FRAME};
204 match action {
205 PeerAction::Serve { listen, vocab: held, no_new_vocabularies, accept_proposals, max_units, output_dir } => {
206 let policy = Policy { accept_vocabularies: !no_new_vocabularies, accept_proposals, max_decoded_units: max_units, ..Policy::default() };
207 let mut peer = Peer::new("kute", engine, policy);
208 for path in &held {
209 peer.add_vocabulary(vocab::load(path)?)?;
210 }
211 let before = peer.digests();
212 let listener = std::net::TcpListener::bind(&listen)?;
213 eprintln!("listening on {}", listener.local_addr()?);
214 let (stream, from) = listener.accept()?;
215 let mut session = Session::new(peer, Framed::new(stream, DEFAULT_MAX_FRAME));
216 let handled = session.serve()?;
217 let inbox = session.peer.take_inbox();
218 let new: Vec<String> = session.peer.digests().into_iter().filter(|d| !before.contains(d)).collect();
219 if let Some(dir) = &output_dir {
220 std::fs::create_dir_all(dir)?;
221 for message in &inbox {
222 std::fs::write(dir.join(format!("message-{}.bin", message.id)), &message.bytes)?;
223 }
224 for digest in &new {
225 if let Some(v) = session.peer.vocabulary(digest) {
226 let name = format!("{}-{}.kvf", v.id().as_str().replace(':', "_"), v.version());
227 vocab::save(v, dir.join(name), true)?;
228 }
229 }
230 }
231 print(&json!({
232 "from": from.to_string(),
233 "messages_handled": handled,
234 "vocabularies_received": new,
235 "received": inbox.iter().map(|m| json!({
236 "id": m.id,
237 "bytes": m.bytes.len(),
238 "tokens": m.sequence.ids.len(),
239 "escaped_symbols": m.sequence.escapes.len(),
240 "vocabulary": format!("{} {}", m.sequence.vocabulary_id, m.sequence.vocabulary_version),
241 })).collect::<Vec<_>>(),
242 }))
243 }
244 PeerAction::Send { connect, vocab: vocab_path, input, unknown, additions, new_version } => {
245 let policy = kute::UnknownPolicy::parse(&unknown)?;
246 let mut peer = Peer::new("kute", engine, Policy::default());
247 let mut digest = peer.add_vocabulary(vocab::load(&vocab_path)?)?;
248 let mut session = Session::new(peer, Framed::new(std::net::TcpStream::connect(&connect)?, DEFAULT_MAX_FRAME));
249 let remote = session.connect()?;
250 let transferred = session.share(&digest)?;
251 let mut proposed = None;
252 if let Some(version) = &new_version {
253 digest = session.propose(&digest, &split_additions(&additions), version)?;
254 proposed = Some(digest.clone());
255 }
256 let mut sent = Vec::new();
257 for path in &input {
258 let raw = std::fs::read(path)?;
259 let units = session.send(&digest, &raw, policy)?;
260 sent.push(json!({ "input": path, "bytes": raw.len(), "units_decoded_by_peer": units, "receipt_matches": true }));
261 }
262 print(&json!({
263 "peer": remote.peer,
264 "peer_software": remote.software,
265 "vocabulary_transferred": transferred,
266 "vocabulary_after_proposal": proposed,
267 "sent": sent,
268 }))
269 }
270 }
271}
272
273#[derive(clap::Args)]
274struct DiscoverArgs {
275 #[arg(long, required = true, num_args = 1..)]
277 input: Vec<PathBuf>,
278 #[arg(long, default_value = "jsonl-events")]
280 adapter: String,
281 #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
283 adapter_options: Vec<String>,
284 #[arg(long, conflicts_with_all = ["adapter", "adapter_options"])]
287 lines: bool,
288 #[arg(long, value_name = "FIELD", conflicts_with_all = ["adapter", "adapter_options", "lines"])]
292 symbol_field: Option<String>,
293 #[arg(long, value_name = "FIELD", requires = "symbol_field")]
296 time_field: Option<String>,
297 #[arg(long, default_value = "s", requires = "time_field")]
299 time_unit: String,
300 #[arg(long, value_name = "FIELD", requires = "symbol_field")]
303 group_field: Option<String>,
304 #[arg(long, default_value = "kute:events:unnamed", requires = "symbol_field")]
306 schema_id: String,
307 #[arg(long, num_args = 1.., conflicts_with = "holdout_fraction")]
309 holdout: Vec<PathBuf>,
310 #[arg(long)]
313 holdout_fraction: Option<f64>,
314 #[arg(long, default_value_t = 5)]
315 min_support: u64,
316 #[arg(long, default_value_t = 8)]
318 max_length: usize,
319 #[arg(long, default_value_t = 1.0)]
321 min_cohesion: f64,
322 #[arg(long, default_value_t = 8)]
324 window: usize,
325 #[arg(long, default_value_t = 50)]
327 top: usize,
328 #[arg(long)]
331 control: bool,
332 #[arg(long)]
334 output: Option<PathBuf>,
335}
336
337fn read_records(engine: &Engine, args: &DiscoverArgs, paths: &[PathBuf]) -> kute::Result<Vec<Vec<String>>> {
338 let mut adapter_config = AdapterConfig::default();
339 for option in &args.adapter_options {
340 let (key, value) = option
341 .split_once('=')
342 .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
343 adapter_config = adapter_config.with(key, value);
344 }
345 let mut records = Vec::new();
346 for path in paths {
347 for file in kute::collect_files(path)? {
348 let raw = std::fs::read(&file)?;
349 if args.lines {
350 let text = String::from_utf8(raw).map_err(|_| KuteError::InvalidInput(format!("{}: not UTF-8", file.display())))?;
351 records.extend(text.lines().map(|l| l.split_whitespace().map(str::to_string).collect::<Vec<_>>()).filter(|r| !r.is_empty()));
352 } else {
353 let input = engine.registry().adapter(&args.adapter)?.ingest(&raw, &adapter_config)?;
354 records.extend(kute_discover::records_of(&[input])?);
355 }
356 }
357 }
358 if records.is_empty() {
359 return Err(KuteError::InvalidInput("no records found in the input".into()));
360 }
361 Ok(records)
362}
363
364fn read_events(args: &DiscoverArgs, symbol_field: &str, paths: &[PathBuf]) -> kute::Result<kute::EventStream> {
365 let schema = kute::EventSchema {
366 id: args.schema_id.clone(),
367 version: 1,
368 symbol_field: symbol_field.to_string(),
369 time_unit: args.time_field.as_ref().map(|_| kute::TimeUnit::parse(&args.time_unit)).transpose()?,
370 time_field: args.time_field.clone(),
371 group_field: args.group_field.clone(),
372 };
373 let mut stream = kute::EventStream::new(schema)?;
374 for path in paths {
375 for file in kute::collect_files(path)? {
376 let reader = std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(&file)?);
377 stream.read_jsonl(reader, &file.display().to_string())?;
378 }
379 }
380 if stream.records.is_empty() {
381 return Err(KuteError::InvalidInput("no events found in the input".into()));
382 }
383 Ok(stream)
384}
385
386fn take_symbols(stream: &mut kute::EventStream) -> Vec<Vec<String>> {
388 stream.records.iter_mut().map(|r| std::mem::take(&mut r.symbols)).collect()
389}
390
391fn give_symbols(stream: &mut kute::EventStream, records: Vec<Vec<String>>) {
392 for (r, symbols) in stream.records.iter_mut().zip(records) {
393 r.symbols = symbols;
394 }
395}
396
397fn describe(stream: &kute::EventStream) -> kute::Result<serde_json::Value> {
398 Ok(json!({ "records": stream.records.len(), "events": stream.events(), "fingerprint": stream.fingerprint()? }))
399}
400
401fn discover(engine: &Engine, args: DiscoverArgs) -> kute::Result<()> {
402 use kute_discover as kd;
403 let params = kd::Params {
404 min_support: args.min_support,
405 max_length: args.max_length,
406 min_cohesion_bits: args.min_cohesion,
407 window: args.window,
408 max_patterns: args.top,
409 ..kd::Params::default()
410 };
411 let mut streams: Option<(kute::EventStream, Option<kute::EventStream>)> = match &args.symbol_field {
414 None => None,
415 Some(field) => {
416 let stream = read_events(&args, field, &args.input)?;
417 Some(if !args.holdout.is_empty() {
418 (stream, Some(read_events(&args, field, &args.holdout)?))
419 } else if let Some(fraction) = args.holdout_fraction {
420 let (head, tail) = stream.split_last(fraction)?;
421 (head, Some(tail))
422 } else {
423 (stream, None)
424 })
425 }
426 };
427 let typed = streams.is_some();
428 let mut records = match &mut streams {
429 Some((stream, _)) => take_symbols(stream),
430 None => read_records(engine, &args, &args.input)?,
431 };
432 let mut held_out = match &mut streams {
433 Some((_, held)) => held.as_mut().map(take_symbols),
434 None if args.holdout.is_empty() => None,
435 None => Some(read_records(engine, &args, &args.holdout)?),
436 };
437 if let Some(fraction) = args.holdout_fraction.filter(|_| !typed) {
438 if args.lines {
439 if !(fraction > 0.0 && fraction < 1.0) {
440 return Err(KuteError::InvalidConfig("the held-out fraction must be between 0 and 1".into()));
441 }
442 let cut = ((records.len() as f64) * (1.0 - fraction)).round() as usize;
443 held_out = Some(records.split_off(cut.clamp(1, records.len())));
444 } else {
445 let (head, tail) = kd::split_holdout(&records, fraction)?;
446 records = head;
447 held_out = Some(tail);
448 }
449 }
450 let start = std::time::Instant::now();
451 let found = kd::discover(&records, ¶ms)?;
452 let seconds = start.elapsed().as_secs_f64();
453 let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
454 let control = if args.control {
455 let found = kd::discover(&kd::shuffled(&records, 0), ¶ms)?;
456 let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
457 Some(json!({
458 "what": "the same run on a shuffled copy of the input: same symbol counts, no order",
459 "patterns": found.patterns.len(),
460 "strongest_evidence_bits": found.patterns.iter().map(|p| p.evidence_bits).fold(0.0, f64::max),
461 "coverage": found.coverage,
462 "held_out_confirmed": evaluation.as_ref().map(|e| e.confirmed),
463 "held_out_coverage": evaluation.as_ref().map(|e| e.coverage),
464 }))
465 } else {
466 None
467 };
468 let events = match streams {
469 None => None,
470 Some((mut stream, mut held)) => {
471 give_symbols(&mut stream, records);
472 if let (Some(h), Some(symbols)) = (held.as_mut(), held_out) {
473 give_symbols(h, symbols);
474 }
475 let timing = if stream.timed() { Some(kd::timing(&found, &stream)?) } else { None };
476 let held_timing = match &held {
477 Some(h) if h.timed() => Some(kd::timing(&found, h)?),
478 _ => None,
479 };
480 Some(json!({
481 "schema": stream.schema,
482 "searched": describe(&stream)?,
483 "held_out": held.as_ref().map(describe).transpose()?,
484 "timing_what": "per pattern, in the schema's time unit: time from the first event of an occurrence to its last; for a gapped pair, from the first symbol to the nearest second symbol within the window",
485 "timing": timing,
486 "held_out_timing": held_timing,
487 }))
488 }
489 };
490 let report = json!({
491 "kute_version": kute::KUTE_VERSION,
492 "discover_seconds": seconds,
493 "peak_memory_bytes": kute_bench::peak_memory_bytes(),
494 "discovery": found,
495 "held_out": evaluation,
496 "control": control,
497 "events": events,
498 });
499 if let Some(path) = &args.output {
500 std::fs::write(path, serde_json::to_vec_pretty(&report)?)?;
501 }
502 print(&report)
503}
504
505#[derive(clap::Args)]
506struct TrainArgs {
507 #[arg(long, required = true, num_args = 1..)]
509 input: Vec<PathBuf>,
510 #[arg(long)]
512 id: String,
513 #[arg(long, default_value = "0.1.0")]
515 vocab_version: String,
516 #[arg(long, default_value = "bpe")]
517 algorithm: String,
518 #[arg(long, default_value = "text")]
519 adapter: String,
520 #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
522 adapter_options: Vec<String>,
523 #[arg(long, default_value_t = 4096)]
524 vocab_size: u32,
525 #[arg(long)]
527 pretokenizer: Option<String>,
528 #[arg(long, default_value_t = 1)]
529 min_frequency: u64,
530 #[arg(long)]
531 max_token_length: Option<usize>,
532 #[arg(long = "reserved")]
534 reserved: Vec<String>,
535 #[arg(long)]
537 dictionary_file: Option<PathBuf>,
538 #[arg(long)]
539 description: Option<String>,
540 #[arg(long)]
542 license: Option<String>,
543 #[arg(long, value_name = "BYTES")]
547 stream_bytes: Option<usize>,
548 #[arg(long, conflicts_with = "no_test_vectors")]
552 embed_test_vectors: bool,
553 #[arg(long, hide = true)]
555 no_test_vectors: bool,
556 #[arg(long)]
557 output: PathBuf,
558 #[arg(long)]
560 force: bool,
561}
562
563fn print(value: &impl serde::Serialize) -> kute::Result<()> {
564 let text = serde_json::to_string_pretty(value)?;
565 let mut out = std::io::stdout().lock();
566 writeln!(out, "{text}")?;
567 Ok(())
568}
569
570fn parse_pretokenizer(spec: Option<&str>, adapter: &str) -> kute::Result<Pretokenizer> {
571 match spec {
572 None => Ok(if adapter == "text" { Pretokenizer::Gpt4 } else { Pretokenizer::None }),
573 Some("none") => Ok(Pretokenizer::None),
574 Some("gpt4") => Ok(Pretokenizer::Gpt4),
575 Some(s) => match s.strip_prefix("regex:") {
576 Some(p) if !p.is_empty() => Ok(Pretokenizer::Regex(p.to_string())),
577 _ => Err(KuteError::InvalidConfig(format!("pretokenizer {s:?}: expected none, gpt4 or regex:<pattern>"))),
578 },
579 }
580}
581
582fn train(engine: &Engine, args: TrainArgs) -> kute::Result<()> {
583 let mut config = TrainingConfig::new(VocabularyId::parse(&args.id)?, args.vocab_size);
584 config.vocabulary_version = Version::parse(&args.vocab_version)
585 .map_err(|e| KuteError::InvalidIdentifier(format!("version {:?}: {e}", args.vocab_version)))?;
586 let symbol_algorithm = args.algorithm == "sequence-bpe";
587 config.pretokenizer = if symbol_algorithm && args.pretokenizer.is_none() {
588 Pretokenizer::None
589 } else {
590 parse_pretokenizer(args.pretokenizer.as_deref(), &args.adapter)?
591 };
592 config.min_frequency = args.min_frequency;
593 config.max_token_length = args.max_token_length;
594 config.reserved_tokens = args.reserved;
595 config.description = args.description;
596 config.license = args.license;
597 config.embed_test_vectors = args.embed_test_vectors;
598 config.stream_bytes = args.stream_bytes;
599 if let Some(path) = &args.dictionary_file {
600 let text = std::fs::read_to_string(path)?;
601 config.dictionary = text.lines().map(|l| l.trim_end_matches('\r')).filter(|l| !l.is_empty()).map(str::to_string).collect();
602 }
603 let mut adapter_config = AdapterConfig::default();
604 for option in &args.adapter_options {
605 let (key, value) = option
606 .split_once('=')
607 .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
608 adapter_config = adapter_config.with(key, value);
609 }
610 let start = std::time::Instant::now();
611 let vocabulary = engine.train_paths(&args.algorithm, &args.adapter, &adapter_config, &args.input, &config)?;
612 let seconds = start.elapsed().as_secs_f64();
613 vocab::save(&vocabulary, &args.output, args.force)?;
614 eprintln!("trained {} {} in {seconds:.2} s -> {}", vocabulary.id(), vocabulary.version(), args.output.display());
615 print(&json!({
616 "output": args.output,
617 "train_seconds": seconds,
618 "peak_memory_bytes": kute_bench::peak_memory_bytes(),
619 "summary": vocab::summarize(&vocabulary)?,
620 }))
621}
622
623fn run(engine: Engine, cli: Cli) -> kute::Result<()> {
624 match cli.command {
625 Command::Train(args) => train(&engine, *args),
626 Command::Encode { vocab: vocab_path, input, output, compress, unknown } => {
627 let policy = kute::UnknownPolicy::parse(&unknown)?;
628 let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
629 let raw = std::fs::read(&input)?;
630 let sequence = engine.encode_raw_open(tokenizer.as_ref(), &raw, policy)?;
631 match output {
632 Some(path) => {
633 let bytes = if compress { sequence.to_bytes_compressed()? } else { sequence.to_bytes()? };
634 std::fs::write(&path, &bytes)?;
635 print(&json!({
636 "output": path,
637 "input_bytes": raw.len(),
638 "tokens": sequence.ids.len(),
639 "escaped_symbols": sequence.escapes.len(),
640 "serialized_bytes": bytes.len(),
641 "vocabulary": format!("{} {}", sequence.vocabulary_id, sequence.vocabulary_version),
642 }))
643 }
644 None => print(&sequence),
645 }
646 }
647 Command::Decode { vocab: vocab_path, input, output, max_units } => {
648 let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
649 let sequence = TokenSequence::from_bytes(&std::fs::read(&input)?)?;
650 let bytes = engine.decode_raw_bounded(tokenizer.as_ref(), &sequence, max_units.unwrap_or(u64::MAX))?;
651 match output {
652 Some(path) => {
653 std::fs::write(&path, &bytes)?;
654 print(&json!({ "output": path, "bytes": bytes.len(), "tokens": sequence.ids.len() }))
655 }
656 None => {
657 let mut out = std::io::stdout().lock();
658 out.write_all(&bytes)?;
659 out.flush()?;
660 Ok(())
661 }
662 }
663 }
664 Command::Inspect { vocab: vocab_path, token, longest } => {
665 let vocabulary = vocab::load(&vocab_path)?;
666 if let Some(id) = token {
667 return print(&vocabulary.record(id)?);
668 }
669 let mut report = json!({ "summary": vocab::summarize(&vocabulary)? });
670 if longest > 0 {
671 let mut learned: Vec<&kute::TokenEntry> = vocabulary.tokens.iter().filter(|t| t.kind == kute::TokenKind::Merge).collect();
672 learned.sort_by(|a, b| b.payload.len().cmp(&a.payload.len()).then(a.id.cmp(&b.id)));
673 let rows: Vec<kute::TokenRecord> = learned.into_iter().take(longest).map(|t| vocabulary.record(t.id)).collect::<kute::Result<_>>()?;
674 report["longest_learned_tokens"] = serde_json::to_value(rows)?;
675 }
676 print(&report)
677 }
678 Command::Validate { vocab: vocab_path } => {
679 let vocabulary = vocab::load(&vocab_path)?;
680 let report = engine.verify(&vocabulary)?;
681 print(&report)?;
682 if report.ok() {
683 Ok(())
684 } else {
685 Err(KuteError::InvalidVocabulary(format!("{} of {} test vectors failed", report.failures.len(), report.vectors)))
686 }
687 }
688 Command::Compare { a, b } => print(&vocab::compare(&vocab::load(&a)?, &vocab::load(&b)?)?),
689 Command::Convert { input, output, force } => {
690 let vocabulary = vocab::load(&input)?;
691 vocab::save(&vocabulary, &output, force)?;
692 let written = vocab::load(&output)?;
694 if written != vocabulary {
695 return Err(KuteError::Integrity("the converted file does not read back as the same vocabulary".into()));
696 }
697 let median_ms = |path: &PathBuf| -> kute::Result<f64> {
698 let bytes = std::fs::read(path)?;
699 let mut times = Vec::new();
700 for _ in 0..5 {
701 let start = std::time::Instant::now();
702 vocab::from_slice(&bytes)?;
703 times.push(start.elapsed().as_secs_f64() * 1000.0);
704 }
705 times.sort_by(|a, b| a.total_cmp(b));
706 Ok((times[2] * 1000.0).round() / 1000.0)
707 };
708 print(&json!({
709 "input": { "path": input, "bytes": std::fs::metadata(&input)?.len(), "load_ms_median": median_ms(&input)? },
710 "output": { "path": output, "bytes": std::fs::metadata(&output)?.len(), "load_ms_median": median_ms(&output)? },
711 "digest": written.digest()?,
712 "tokens": written.len(),
713 "identical": true,
714 }))
715 }
716 Command::Export { vocab: vocab_path, format: ExportFormat::Tiktoken, output } => {
717 let vocabulary = vocab::load(&vocab_path)?;
718 let export = vocab::export_tiktoken(&vocabulary)?;
719 std::fs::write(&output, &export.bpe_file)?;
720 let mut sidecar = output.clone().into_os_string();
721 sidecar.push(".json");
722 let sidecar = PathBuf::from(sidecar);
723 let meta = json!({
724 "name": vocabulary.id().as_str().replace(':', "_"),
725 "pat_str": export.pat_str,
726 "special_tokens": export.special_tokens,
727 "explicit_n_vocab": export.n_vocab,
728 "source_vocabulary": format!("{} {}", vocabulary.id(), vocabulary.version()),
729 "source_digest": vocabulary.digest()?,
730 });
731 std::fs::write(&sidecar, serde_json::to_vec_pretty(&meta)?)?;
732 print(&json!({ "bpe_file": output, "metadata": sidecar, "tokens": export.n_vocab }))
733 }
734 Command::Benchmark { vocab: vocab_path, dataset, suite, repo_root, large_text, iterations, output } => {
735 let report = if suite {
736 serde_json::to_value(kute_bench::suite::run(&engine, &kute_bench::suite::Options { repo_root, iterations, large_text })?)?
737 } else {
738 let (Some(vocab_path), Some(dataset)) = (vocab_path, dataset) else {
739 return Err(KuteError::InvalidConfig("benchmark needs --vocab and --dataset, or --suite".into()));
740 };
741 let vocabulary = vocab::load(&vocab_path)?;
742 let documents = kute_bench::read_dataset(&dataset)?;
743 json!({
744 "environment": kute_bench::Environment::detect(),
745 "dataset": dataset,
746 "evaluation": kute_bench::evaluate(&engine, &vocabulary, &documents, iterations)?,
747 })
748 };
749 if let Some(path) = output {
750 let mut text = serde_json::to_string_pretty(&report)?;
751 text.push('\n');
752 std::fs::write(&path, text)?;
753 eprintln!("report written to {}", path.display());
754 }
755 print(&report)
756 }
757 Command::SampleData { output } => {
758 use kute_bench::data;
759 std::fs::create_dir_all(&output)?;
760 let files: Vec<(&str, Vec<u8>, &str)> = vec![
761 ("alarms-train.jsonl", data::alarm_log(51, 4000), "plant alarm log, 4000 episodes"),
762 ("alarms-eval.jsonl", data::alarm_log(52, 1000), "plant alarm log, 1000 episodes, different seed"),
763 ("messages-train.jsonl", data::agent_messages(61, 4000), "agent messages, 4000 records"),
764 ("messages-eval.jsonl", data::agent_messages(62, 1000), "agent messages, 1000 records, different seed"),
765 ("frames-train.bin", data::binary_records(31, 6000), "binary telemetry frames, 6000 records"),
766 ("frames-eval.bin", data::binary_records(32, 2000), "binary telemetry frames, 2000 records, different seed"),
767 ("words-train.txt", data::invented_words(81, 60_000), "invented-word text, 60000 words"),
768 ("words-eval.txt", data::invented_words(82, 15_000), "invented-word text, 15000 words, different seed"),
769 ];
770 let mut written = Vec::new();
771 for (name, bytes, what) in files {
772 std::fs::write(output.join(name), &bytes)?;
773 written.push(json!({ "file": name, "bytes": bytes.len(), "sha256": kute::sha256_tagged(&bytes), "content": what }));
774 }
775 print(&json!({ "output": output, "synthetic": true, "files": written }))
776 }
777 Command::Discover(args) => discover(&engine, *args),
778 Command::Evolve { vocab: vocab_path, additions, new_version, output, force } => {
779 let version = Version::parse(&new_version).map_err(|e| KuteError::InvalidIdentifier(format!("version {new_version:?}: {e}")))?;
780 let parent = vocab::load(&vocab_path)?;
781 let child = kute::bpe::sequence::evolve(&parent, &split_additions(&additions), version)?;
782 let report = engine.verify(&child)?;
783 if !report.ok() {
784 return Err(KuteError::Backend(format!("the evolved vocabulary fails its test vectors: {}", report.failures.join("; "))));
785 }
786 vocab::save(&child, &output, force)?;
787 print(&json!({
788 "output": output,
789 "parent": { "version": parent.version().to_string(), "digest": parent.digest()?, "tokens": parent.len() },
790 "summary": vocab::summarize(&child)?,
791 }))
792 }
793 Command::Peer { action } => peer(engine, action),
794 Command::Capabilities => {
795 let registry = engine.registry();
796 let algorithms: Vec<kute::TokenizerCapabilities> =
797 registry.algorithm_names().iter().map(|n| registry.tokenizer(n).map(|t| t.capabilities())).collect::<kute::Result<_>>()?;
798 let adapters: Vec<serde_json::Value> = registry
799 .adapter_names()
800 .iter()
801 .map(|n| {
802 registry.adapter(n).map(|a| {
803 let c = a.capabilities();
804 json!({ "name": c.name, "modality": c.modality, "lossless": c.lossless, "notes": c.notes })
805 })
806 })
807 .collect::<kute::Result<_>>()?;
808 print(&json!({
809 "kute_version": kute::KUTE_VERSION,
810 "kvf_version": kute::KVF_VERSION,
811 "algorithms": algorithms,
812 "adapters": adapters,
813 }))
814 }
815 }
816}
817
818pub fn main_with(engine: Engine) -> ExitCode {
821 match run(engine, Cli::parse()) {
822 Ok(()) => ExitCode::SUCCESS,
823 Err(e) => {
824 eprintln!("kute: {e}");
825 ExitCode::FAILURE
826 }
827 }
828}