Files

58 lines
2.0 KiB
Rust

//! Encode/decode throughput of the tokenizer on a long synthetic prompt (host cost of TTFT and of token publication).
//!
//! `cargo run --release -p leleka-tokenizer --example bench_encode -- TOKENIZER_DIR PROMPTS.txt [REPEAT]`
use std::{
env, fs,
path::Path,
process::ExitCode,
time::{Duration, Instant},
};
use leleka_tokenizer::Tokenizer;
fn main() -> ExitCode {
let args: Vec<String> = env::args().collect();
if args.len() < 3 {
eprintln!("usage: bench_encode TOKENIZER_DIR PROMPTS.txt [REPEAT]");
return ExitCode::from(2);
}
let tokenizer = Tokenizer::from_assets(Path::new(&args[1])).expect("tokenizer assets");
let corpus = fs::read_to_string(&args[2]).expect("prompts");
let repeat: usize = args.get(3).and_then(|v| v.parse().ok()).unwrap_or(200);
let text: String = (0..repeat).map(|_| corpus.as_str()).collect::<Vec<_>>().join("\n");
for _ in 0..2 {
let started = Instant::now();
let ids = tokenizer.encode(&text, true).expect("encode");
let encode = started.elapsed();
let started = Instant::now();
let bytes = decoded_bytes(&tokenizer, &ids);
report(&text, &ids, (encode, started.elapsed()), bytes);
}
ExitCode::SUCCESS
}
/// Decode one id at a time and total the bytes.
fn decoded_bytes(tokenizer: &Tokenizer, ids: &[u32]) -> usize {
let mut bytes = 0usize;
for &id in ids {
bytes += tokenizer.decode_bytes(&[id]).expect("decode").len();
}
bytes
}
fn report(text: &str, ids: &[u32], (encode, decode): (Duration, Duration), bytes: usize) {
eprintln!(
concat!(
"text {} bytes -> {} tokens: encode {:.1} ms ({:.2} Mtok/s); ",
"decode_bytes one id at a time {:.2} us/token ({} bytes)"
),
text.len(),
ids.len(),
encode.as_secs_f64() * 1e3,
ids.len() as f64 / encode.as_secs_f64() / 1e6,
decode.as_secs_f64() * 1e6 / ids.len() as f64,
bytes
);
}