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, value_name = "VOCAB")]
553 resume_from: Option<PathBuf>,
554 #[arg(long, conflicts_with = "no_test_vectors")]
558 embed_test_vectors: bool,
559 #[arg(long, hide = true)]
561 no_test_vectors: bool,
562 #[arg(long)]
563 output: PathBuf,
564 #[arg(long)]
566 force: bool,
567}
568
569fn print(value: &impl serde::Serialize) -> kute::Result<()> {
570 let text = serde_json::to_string_pretty(value)?;
571 let mut out = std::io::stdout().lock();
572 writeln!(out, "{text}")?;
573 Ok(())
574}
575
576fn parse_pretokenizer(spec: Option<&str>, adapter: &str) -> kute::Result<Pretokenizer> {
577 match spec {
578 None => Ok(if adapter == "text" { Pretokenizer::Gpt4 } else { Pretokenizer::None }),
579 Some("none") => Ok(Pretokenizer::None),
580 Some("gpt4") => Ok(Pretokenizer::Gpt4),
581 Some(s) => match s.strip_prefix("regex:") {
582 Some(p) if !p.is_empty() => Ok(Pretokenizer::Regex(p.to_string())),
583 _ => Err(KuteError::InvalidConfig(format!("pretokenizer {s:?}: expected none, gpt4 or regex:<pattern>"))),
584 },
585 }
586}
587
588fn train(engine: &Engine, args: TrainArgs) -> kute::Result<()> {
589 let mut config = TrainingConfig::new(VocabularyId::parse(&args.id)?, args.vocab_size);
590 config.vocabulary_version = Version::parse(&args.vocab_version)
591 .map_err(|e| KuteError::InvalidIdentifier(format!("version {:?}: {e}", args.vocab_version)))?;
592 let symbol_algorithm = args.algorithm == "sequence-bpe";
593 config.pretokenizer = if symbol_algorithm && args.pretokenizer.is_none() {
594 Pretokenizer::None
595 } else {
596 parse_pretokenizer(args.pretokenizer.as_deref(), &args.adapter)?
597 };
598 config.min_frequency = args.min_frequency;
599 config.max_token_length = args.max_token_length;
600 config.reserved_tokens = args.reserved;
601 config.description = args.description;
602 config.license = args.license;
603 config.embed_test_vectors = args.embed_test_vectors;
604 config.stream_bytes = args.stream_bytes;
605 if let Some(path) = &args.resume_from {
606 config.resume_from = Some(Box::new(vocab::load(path)?));
607 }
608 if let Some(path) = &args.dictionary_file {
609 let text = std::fs::read_to_string(path)?;
610 config.dictionary = text.lines().map(|l| l.trim_end_matches('\r')).filter(|l| !l.is_empty()).map(str::to_string).collect();
611 }
612 let mut adapter_config = AdapterConfig::default();
613 for option in &args.adapter_options {
614 let (key, value) = option
615 .split_once('=')
616 .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
617 adapter_config = adapter_config.with(key, value);
618 }
619 let start = std::time::Instant::now();
620 let vocabulary = engine.train_paths(&args.algorithm, &args.adapter, &adapter_config, &args.input, &config)?;
621 let seconds = start.elapsed().as_secs_f64();
622 vocab::save(&vocabulary, &args.output, args.force)?;
623 eprintln!("trained {} {} in {seconds:.2} s -> {}", vocabulary.id(), vocabulary.version(), args.output.display());
624 print(&json!({
625 "output": args.output,
626 "train_seconds": seconds,
627 "peak_memory_bytes": kute_bench::peak_memory_bytes(),
628 "resumed_from": args.resume_from,
629 "summary": vocab::summarize(&vocabulary)?,
630 }))
631}
632
633fn run(engine: Engine, cli: Cli) -> kute::Result<()> {
634 match cli.command {
635 Command::Train(args) => train(&engine, *args),
636 Command::Encode { vocab: vocab_path, input, output, compress, unknown } => {
637 let policy = kute::UnknownPolicy::parse(&unknown)?;
638 let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
639 let raw = std::fs::read(&input)?;
640 let sequence = engine.encode_raw_open(tokenizer.as_ref(), &raw, policy)?;
641 match output {
642 Some(path) => {
643 let bytes = if compress { sequence.to_bytes_compressed()? } else { sequence.to_bytes()? };
644 std::fs::write(&path, &bytes)?;
645 print(&json!({
646 "output": path,
647 "input_bytes": raw.len(),
648 "tokens": sequence.ids.len(),
649 "escaped_symbols": sequence.escapes.len(),
650 "serialized_bytes": bytes.len(),
651 "vocabulary": format!("{} {}", sequence.vocabulary_id, sequence.vocabulary_version),
652 }))
653 }
654 None => print(&sequence),
655 }
656 }
657 Command::Decode { vocab: vocab_path, input, output, max_units } => {
658 let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
659 let sequence = TokenSequence::from_bytes(&std::fs::read(&input)?)?;
660 let bytes = engine.decode_raw_bounded(tokenizer.as_ref(), &sequence, max_units.unwrap_or(u64::MAX))?;
661 match output {
662 Some(path) => {
663 std::fs::write(&path, &bytes)?;
664 print(&json!({ "output": path, "bytes": bytes.len(), "tokens": sequence.ids.len() }))
665 }
666 None => {
667 let mut out = std::io::stdout().lock();
668 out.write_all(&bytes)?;
669 out.flush()?;
670 Ok(())
671 }
672 }
673 }
674 Command::Inspect { vocab: vocab_path, token, longest } => {
675 let vocabulary = vocab::load(&vocab_path)?;
676 if let Some(id) = token {
677 return print(&vocabulary.record(id)?);
678 }
679 let mut report = json!({ "summary": vocab::summarize(&vocabulary)? });
680 if longest > 0 {
681 let mut learned: Vec<&kute::TokenEntry> = vocabulary.tokens.iter().filter(|t| t.kind == kute::TokenKind::Merge).collect();
682 learned.sort_by(|a, b| b.payload.len().cmp(&a.payload.len()).then(a.id.cmp(&b.id)));
683 let rows: Vec<kute::TokenRecord> = learned.into_iter().take(longest).map(|t| vocabulary.record(t.id)).collect::<kute::Result<_>>()?;
684 report["longest_learned_tokens"] = serde_json::to_value(rows)?;
685 }
686 print(&report)
687 }
688 Command::Validate { vocab: vocab_path } => {
689 let vocabulary = vocab::load(&vocab_path)?;
690 let report = engine.verify(&vocabulary)?;
691 print(&report)?;
692 if report.ok() {
693 Ok(())
694 } else {
695 Err(KuteError::InvalidVocabulary(format!("{} of {} test vectors failed", report.failures.len(), report.vectors)))
696 }
697 }
698 Command::Compare { a, b } => print(&vocab::compare(&vocab::load(&a)?, &vocab::load(&b)?)?),
699 Command::Convert { input, output, force } => {
700 let vocabulary = vocab::load(&input)?;
701 vocab::save(&vocabulary, &output, force)?;
702 let written = vocab::load(&output)?;
704 if written != vocabulary {
705 return Err(KuteError::Integrity("the converted file does not read back as the same vocabulary".into()));
706 }
707 let median_ms = |path: &PathBuf| -> kute::Result<f64> {
708 let bytes = std::fs::read(path)?;
709 let mut times = Vec::new();
710 for _ in 0..5 {
711 let start = std::time::Instant::now();
712 vocab::from_slice(&bytes)?;
713 times.push(start.elapsed().as_secs_f64() * 1000.0);
714 }
715 times.sort_by(|a, b| a.total_cmp(b));
716 Ok((times[2] * 1000.0).round() / 1000.0)
717 };
718 print(&json!({
719 "input": { "path": input, "bytes": std::fs::metadata(&input)?.len(), "load_ms_median": median_ms(&input)? },
720 "output": { "path": output, "bytes": std::fs::metadata(&output)?.len(), "load_ms_median": median_ms(&output)? },
721 "digest": written.digest()?,
722 "tokens": written.len(),
723 "identical": true,
724 }))
725 }
726 Command::Export { vocab: vocab_path, format: ExportFormat::Tiktoken, output } => {
727 let vocabulary = vocab::load(&vocab_path)?;
728 let export = vocab::export_tiktoken(&vocabulary)?;
729 std::fs::write(&output, &export.bpe_file)?;
730 let mut sidecar = output.clone().into_os_string();
731 sidecar.push(".json");
732 let sidecar = PathBuf::from(sidecar);
733 let meta = json!({
734 "name": vocabulary.id().as_str().replace(':', "_"),
735 "pat_str": export.pat_str,
736 "special_tokens": export.special_tokens,
737 "explicit_n_vocab": export.n_vocab,
738 "source_vocabulary": format!("{} {}", vocabulary.id(), vocabulary.version()),
739 "source_digest": vocabulary.digest()?,
740 });
741 std::fs::write(&sidecar, serde_json::to_vec_pretty(&meta)?)?;
742 print(&json!({ "bpe_file": output, "metadata": sidecar, "tokens": export.n_vocab }))
743 }
744 Command::Benchmark { vocab: vocab_path, dataset, suite, repo_root, large_text, iterations, output } => {
745 let report = if suite {
746 serde_json::to_value(kute_bench::suite::run(&engine, &kute_bench::suite::Options { repo_root, iterations, large_text })?)?
747 } else {
748 let (Some(vocab_path), Some(dataset)) = (vocab_path, dataset) else {
749 return Err(KuteError::InvalidConfig("benchmark needs --vocab and --dataset, or --suite".into()));
750 };
751 let vocabulary = vocab::load(&vocab_path)?;
752 let documents = kute_bench::read_dataset(&dataset)?;
753 json!({
754 "environment": kute_bench::Environment::detect(),
755 "dataset": dataset,
756 "evaluation": kute_bench::evaluate(&engine, &vocabulary, &documents, iterations)?,
757 })
758 };
759 if let Some(path) = output {
760 let mut text = serde_json::to_string_pretty(&report)?;
761 text.push('\n');
762 std::fs::write(&path, text)?;
763 eprintln!("report written to {}", path.display());
764 }
765 print(&report)
766 }
767 Command::SampleData { output } => {
768 use kute_bench::data;
769 std::fs::create_dir_all(&output)?;
770 let files: Vec<(&str, Vec<u8>, &str)> = vec![
771 ("alarms-train.jsonl", data::alarm_log(51, 4000), "plant alarm log, 4000 episodes"),
772 ("alarms-eval.jsonl", data::alarm_log(52, 1000), "plant alarm log, 1000 episodes, different seed"),
773 ("messages-train.jsonl", data::agent_messages(61, 4000), "agent messages, 4000 records"),
774 ("messages-eval.jsonl", data::agent_messages(62, 1000), "agent messages, 1000 records, different seed"),
775 ("frames-train.bin", data::binary_records(31, 6000), "binary telemetry frames, 6000 records"),
776 ("frames-eval.bin", data::binary_records(32, 2000), "binary telemetry frames, 2000 records, different seed"),
777 ("words-train.txt", data::invented_words(81, 60_000), "invented-word text, 60000 words"),
778 ("words-eval.txt", data::invented_words(82, 15_000), "invented-word text, 15000 words, different seed"),
779 ];
780 let mut written = Vec::new();
781 for (name, bytes, what) in files {
782 std::fs::write(output.join(name), &bytes)?;
783 written.push(json!({ "file": name, "bytes": bytes.len(), "sha256": kute::sha256_tagged(&bytes), "content": what }));
784 }
785 print(&json!({ "output": output, "synthetic": true, "files": written }))
786 }
787 Command::Discover(args) => discover(&engine, *args),
788 Command::Evolve { vocab: vocab_path, additions, new_version, output, force } => {
789 let version = Version::parse(&new_version).map_err(|e| KuteError::InvalidIdentifier(format!("version {new_version:?}: {e}")))?;
790 let parent = vocab::load(&vocab_path)?;
791 let child = kute::bpe::sequence::evolve(&parent, &split_additions(&additions), version)?;
792 let report = engine.verify(&child)?;
793 if !report.ok() {
794 return Err(KuteError::Backend(format!("the evolved vocabulary fails its test vectors: {}", report.failures.join("; "))));
795 }
796 vocab::save(&child, &output, force)?;
797 print(&json!({
798 "output": output,
799 "parent": { "version": parent.version().to_string(), "digest": parent.digest()?, "tokens": parent.len() },
800 "summary": vocab::summarize(&child)?,
801 }))
802 }
803 Command::Peer { action } => peer(engine, action),
804 Command::Capabilities => {
805 let registry = engine.registry();
806 let algorithms: Vec<kute::TokenizerCapabilities> =
807 registry.algorithm_names().iter().map(|n| registry.tokenizer(n).map(|t| t.capabilities())).collect::<kute::Result<_>>()?;
808 let adapters: Vec<serde_json::Value> = registry
809 .adapter_names()
810 .iter()
811 .map(|n| {
812 registry.adapter(n).map(|a| {
813 let c = a.capabilities();
814 json!({ "name": c.name, "modality": c.modality, "lossless": c.lossless, "notes": c.notes })
815 })
816 })
817 .collect::<kute::Result<_>>()?;
818 print(&json!({
819 "kute_version": kute::KUTE_VERSION,
820 "kvf_version": kute::KVF_VERSION,
821 "algorithms": algorithms,
822 "adapters": adapters,
823 }))
824 }
825 }
826}
827
828pub fn main_with(engine: Engine) -> ExitCode {
831 match run(engine, Cli::parse()) {
832 Ok(()) => ExitCode::SUCCESS,
833 Err(e) => {
834 eprintln!("kute: {e}");
835 ExitCode::FAILURE
836 }
837 }
838}