use crate::ContextError;
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
#[cfg(feature = "bpe")]
mod ordinary;
#[cfg(all(test, feature = "bpe"))]
mod ordinary_patterns;
#[cfg(feature = "bpe")]
mod segmenter;
#[cfg(feature = "bpe")]
mod vocabulary;
#[cfg(feature = "bpe")]
mod vocabulary_hash;
pub trait TokenCounter {
fn identity(&self) -> &str;
fn count(&self, text: &str) -> Result<usize, ContextError>;
}
#[derive(Clone, Copy, Debug)]
pub struct TokenCacheLimits {
pub max_entries: usize,
pub max_text_bytes: usize,
}
impl Default for TokenCacheLimits {
fn default() -> Self {
Self {
max_entries: 2048,
max_text_bytes: 8 * 1024 * 1024,
}
}
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct TokenCacheStats {
pub hits: u64,
pub misses: u64,
pub entries: usize,
pub text_bytes: usize,
}
#[derive(Default)]
struct Cache {
values: HashMap<Arc<str>, usize>,
order: VecDeque<Arc<str>>,
stats: TokenCacheStats,
generation: u64,
}
pub struct CachedTokenCounter<T> {
inner: T,
limits: TokenCacheLimits,
cache: Mutex<Cache>,
}
impl<T: TokenCounter> CachedTokenCounter<T> {
pub fn new(inner: T, limits: TokenCacheLimits) -> Self {
Self {
inner,
limits,
cache: Mutex::new(Cache::default()),
}
}
pub fn cache_stats(&self) -> Result<TokenCacheStats, ContextError> {
self.cache
.lock()
.map(|cache| cache.stats)
.map_err(|_| ContextError::Tokenizer)
}
pub fn clear_cache(&self) -> Result<(), ContextError> {
let mut cache = self.cache.lock().map_err(|_| ContextError::Tokenizer)?;
let generation = cache
.generation
.checked_add(1)
.ok_or(ContextError::LimitExceeded)?;
*cache = Cache {
generation,
..Cache::default()
};
Ok(())
}
}
impl<T: TokenCounter> TokenCounter for CachedTokenCounter<T> {
fn identity(&self) -> &str {
self.inner.identity()
}
fn count(&self, text: &str) -> Result<usize, ContextError> {
let generation = {
let mut cache = self.cache.lock().map_err(|_| ContextError::Tokenizer)?;
if let Some(value) = cache.values.get(text).copied() {
cache.stats.hits = cache.stats.hits.saturating_add(1);
return Ok(value);
}
cache.stats.misses = cache.stats.misses.saturating_add(1);
cache.generation
};
let count = self.inner.count(text)?;
if self.limits.max_entries == 0
|| text.len() > self.limits.max_text_bytes
|| self.limits.max_text_bytes == 0
{
return Ok(count);
}
let mut cache = self.cache.lock().map_err(|_| ContextError::Tokenizer)?;
if cache.generation != generation || cache.values.contains_key(text) {
return Ok(count);
}
while cache.values.len() >= self.limits.max_entries
|| cache.stats.text_bytes > self.limits.max_text_bytes - text.len()
{
if let Some(old) = cache.order.pop_front() {
cache.values.remove(old.as_ref());
cache.stats.text_bytes -= old.len();
} else {
break;
}
}
let key: Arc<str> = Arc::from(text);
cache.values.insert(Arc::clone(&key), count);
cache.order.push_back(key);
cache.stats.text_bytes += text.len();
cache.stats.entries = cache.values.len();
Ok(count)
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Utf8ByteCounter;
impl TokenCounter for Utf8ByteCounter {
fn identity(&self) -> &str {
"cigar.utf8-bytes.v1"
}
fn count(&self, text: &str) -> Result<usize, ContextError> {
Ok(text.len())
}
}
#[cfg(feature = "bpe")]
pub struct O200kTokenizer(CachedTokenCounter<RawO200kTokenizer>);
#[cfg(feature = "bpe")]
struct RawO200kTokenizer(ordinary::OrdinaryCounter);
#[cfg(feature = "bpe")]
impl O200kTokenizer {
pub fn new() -> Result<Self, ContextError> {
Self::with_cache_limits(TokenCacheLimits::default())
}
pub fn with_cache_limits(limits: TokenCacheLimits) -> Result<Self, ContextError> {
ordinary::OrdinaryCounter::new()
.map(|bpe| Self(CachedTokenCounter::new(RawO200kTokenizer(bpe), limits)))
.map_err(|_| ContextError::Tokenizer)
}
pub fn cache_stats(&self) -> Result<TokenCacheStats, ContextError> {
self.0.cache_stats()
}
pub fn clear_cache(&self) -> Result<(), ContextError> {
self.0.clear_cache()
}
}
#[cfg(feature = "bpe")]
impl TokenCounter for O200kTokenizer {
fn identity(&self) -> &str {
self.0.identity()
}
fn count(&self, text: &str) -> Result<usize, ContextError> {
self.0.count(text)
}
}
#[cfg(feature = "bpe")]
impl TokenCounter for RawO200kTokenizer {
fn identity(&self) -> &str {
"o200k_base.tiktoken-rs-0.12.0.ordinary"
}
fn count(&self, text: &str) -> Result<usize, ContextError> {
self.0.count(text)
}
}