use std::sync::Arc;
use anyhow::Result;
const LOWER_LETTERS_PER_TOKEN: usize = 6;
const UPPER_LETTERS_PER_TOKEN: usize = 2;
const NON_ASCII_TOKENS_PER_CHAR: usize = 2;
pub const NAMED_TOKENIZERS: [&str; 2] = ["cl100k_base", "o200k_base"];
#[derive(Clone, Default)]
pub struct TokenCounter {
kind: CounterKind,
}
#[derive(Clone, Default)]
enum CounterKind {
#[default]
Estimate,
Custom(Arc<dyn Fn(&str) -> usize + Send + Sync>),
#[cfg(feature = "tokenizers")]
HuggingFace(Arc<tokenizers::Tokenizer>),
#[cfg(feature = "openai-tokenizers")]
OpenAi(&'static tiktoken_rs::CoreBPE),
}
impl std::fmt::Debug for TokenCounter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let name = match &self.kind {
CounterKind::Estimate => "estimate",
CounterKind::Custom(_) => "custom",
#[cfg(feature = "tokenizers")]
CounterKind::HuggingFace(_) => "tokenizer.json",
#[cfg(feature = "openai-tokenizers")]
CounterKind::OpenAi(_) => "byte-pair encoding",
};
write!(f, "TokenCounter({name})")
}
}
impl TokenCounter {
pub fn estimate() -> Self {
Self::default()
}
pub fn custom(count: impl Fn(&str) -> usize + Send + Sync + 'static) -> Self {
Self {
kind: CounterKind::Custom(Arc::new(count)),
}
}
pub fn load(spec: &str) -> Result<Self> {
if NAMED_TOKENIZERS.contains(&spec) {
return Self::named(spec);
}
Self::from_file(spec)
}
pub fn count(&self, text: &str) -> usize {
match &self.kind {
CounterKind::Estimate => estimate(text),
CounterKind::Custom(count) => count(text),
#[cfg(feature = "tokenizers")]
CounterKind::HuggingFace(tokenizer) => tokenizer
.encode_fast(text, false)
.map_or_else(|_| estimate(text), |enc| enc.len()),
#[cfg(feature = "openai-tokenizers")]
CounterKind::OpenAi(bpe) => bpe.encode_ordinary(text).len(),
}
}
#[cfg(feature = "openai-tokenizers")]
fn named(name: &str) -> Result<Self> {
let bpe = if name == "cl100k_base" {
tiktoken_rs::cl100k_base_singleton()
} else {
tiktoken_rs::o200k_base_singleton()
};
Ok(Self {
kind: CounterKind::OpenAi(bpe),
})
}
#[cfg(not(feature = "openai-tokenizers"))]
fn named(name: &str) -> Result<Self> {
anyhow::bail!("this kakemono was built without the openai-tokenizers feature: {name} is not available")
}
#[cfg(feature = "tokenizers")]
fn from_file(path: &str) -> Result<Self> {
let mut tokenizer = tokenizers::Tokenizer::from_file(path)
.map_err(|err| anyhow::anyhow!("cannot read the tokenizer {path}: {err}"))?;
tokenizer
.with_truncation(None)
.map_err(|err| anyhow::anyhow!("cannot turn off truncation of {path}: {err}"))?;
tokenizer.with_padding(None);
Ok(Self {
kind: CounterKind::HuggingFace(Arc::new(tokenizer)),
})
}
#[cfg(not(feature = "tokenizers"))]
fn from_file(path: &str) -> Result<Self> {
anyhow::bail!("this kakemono was built without the tokenizers feature: cannot read {path}")
}
}
pub fn estimate(text: &str) -> usize {
let chars: Vec<char> = text.chars().collect();
let mut tokens = 0;
let mut i = 0;
while i < chars.len() {
let ch = chars[i];
if ch.is_ascii_alphabetic() {
let (len, upper) = letter_piece(&chars[i..]);
let per_token = if upper && len > 1 {
UPPER_LETTERS_PER_TOKEN
} else {
LOWER_LETTERS_PER_TOKEN
};
tokens += 1 + (len - 1) / per_token;
i += len;
continue;
}
if ch.is_whitespace() {
if chars.get(i + 1).is_some_and(char::is_ascii_digit) {
tokens += 1;
}
} else {
tokens += if ch.is_ascii() && !ch.is_ascii_control() {
1
} else {
NON_ASCII_TOKENS_PER_CHAR
};
}
i += 1;
}
tokens
}
fn letter_piece(chars: &[char]) -> (usize, bool) {
let upper = chars.iter().take_while(|ch| ch.is_ascii_uppercase()).count();
let lower_after = |from: usize| chars[from..].iter().take_while(|ch| ch.is_ascii_lowercase()).count();
match upper {
0 => (lower_after(0), false),
1 => (1 + lower_after(1), lower_after(1) == 0),
_ if lower_after(upper) > 0 => (upper - 1, true), _ => (upper, true),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_words_are_one_token_each() {
assert_eq!(estimate("the cat sat on a mat"), 6);
}
#[test]
fn long_words_and_acronyms_count_more() {
assert_eq!(estimate("transformers"), 2);
assert_eq!(estimate("BERT"), 2);
}
#[test]
fn camel_case_splits_at_case_changes() {
assert_eq!(estimate("MedDRA"), 3);
assert_eq!(estimate("HTMLParser"), 3);
}
#[test]
fn digits_and_symbols_count_one_each() {
assert_eq!(estimate("3.14"), 4);
assert_eq!(estimate("α"), NON_ASCII_TOKENS_PER_CHAR);
}
#[test]
fn white_space_counts_nothing_but_before_numbers() {
assert_eq!(estimate("a b"), estimate("a") + estimate("b"));
assert_eq!(estimate(" \n\t"), 0);
assert_eq!(estimate("x 12"), 4);
}
#[cfg(feature = "tokenizers")]
const WORD_TOKENIZER: &str = r#"{"version":"1.0","truncation":{"direction":"Right","max_length":2,"strategy":"LongestFirst","stride":0},
"padding":null,"added_tokens":[],"normalizer":null,"pre_tokenizer":{"type":"Whitespace"},"post_processor":null,"decoder":null,
"model":{"type":"WordLevel","vocab":{"[UNK]":0,"a":1},"unk_token":"[UNK]"}}"#;
#[cfg(feature = "tokenizers")]
#[test]
fn a_tokenizer_json_counts_without_truncation() {
let path = std::env::temp_dir().join(format!("kakemono-tokenizer-{}.json", std::process::id()));
std::fs::write(&path, WORD_TOKENIZER).unwrap();
let counter = TokenCounter::load(path.to_str().unwrap()).unwrap();
std::fs::remove_file(&path).unwrap();
assert_eq!(counter.count("a b c d e"), 5);
}
#[test]
fn a_missing_tokenizer_is_an_error() {
assert!(TokenCounter::load("/no/such/tokenizer.json").is_err());
}
#[cfg(feature = "openai-tokenizers")]
#[test]
fn openai_tokenizers_are_known_by_name() {
let counter = TokenCounter::load("cl100k_base").unwrap();
assert_eq!(counter.count("hello world"), 2);
}
#[test]
fn a_custom_counter_is_used() {
let counter = TokenCounter::custom(|text| text.len());
assert_eq!(counter.count("abcd"), 4);
}
}