Files
leleka/crates/tokenizer/src/cache.rs
T

143 lines
4.4 KiB
Rust

//! A bounded cache of the token ids of text segments.
//!
//! A chat prompt is split at the special tokens (`<|im_start|>`, `<think>`, `<tool_call>`, ...) before byte-level BPE, so
//! the ids of the text *between* two special tokens depend on that text alone. A coding agent sends its whole history
//! again on every turn; all of the history except the last few segments is text this process tokenized on an earlier turn.
//! Keyed by the exact segment text, the cache returns those ids without the pre-tokenizer or the merges, and a hit is
//! verified byte for byte against the stored text, so a hash collision can only cost a miss, never a wrong id.
//!
//! The bound is a two-generation scheme: inserts go to the young generation; when it has taken half the budget it becomes
//! the old generation and the previous old one is dropped. A hit in the old generation is promoted. That evicts what has
//! not been used for a whole generation, in O(1), without an LRU list.
use std::{
collections::HashMap,
hash::Hasher,
sync::{Arc, Mutex},
};
/// Segments shorter than this are tokenized every time: hashing and locking would cost about what the merges do.
pub const MIN_SEGMENT_BYTES: usize = 96;
/// Default budget (text + ids of both generations), bytes.
pub const DEFAULT_BUDGET: usize = 64 << 20;
struct Entry {
text: Box<str>,
ids: Arc<[u32]>,
}
impl Entry {
fn cost(&self) -> usize {
self.text.len() + self.ids.len() * 4 + 64
}
}
#[derive(Default)]
struct Generations {
young: HashMap<u64, Entry>,
old: HashMap<u64, Entry>,
young_bytes: usize,
budget: usize,
}
pub struct SegmentCache {
inner: Mutex<Generations>,
}
fn digest(text: &str) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
hasher.write(text.as_bytes());
hasher.finish()
}
impl SegmentCache {
pub fn new(budget: usize) -> Self {
Self {
inner: Mutex::new(Generations {
budget,
..Default::default()
}),
}
}
pub fn set_budget(&self, budget: usize) {
if let Ok(mut cache) = self.inner.lock() {
cache.budget = budget;
if budget == 0 {
cache.young.clear();
cache.old.clear();
cache.young_bytes = 0;
}
}
}
/// `(hash, ids)` for a segment seen before; the hash is returned either way so the caller can insert without hashing again.
pub fn lookup(&self, text: &str) -> (u64, Option<Arc<[u32]>>) {
let key = digest(text);
let Ok(mut cache) = self.inner.lock() else {
return (key, None);
};
if let Some(entry) = cache.young.get(&key)
&& &*entry.text == text
{
return (key, Some(Arc::clone(&entry.ids)));
}
if let Some(entry) = cache.old.get(&key)
&& &*entry.text == text
{
let ids = Arc::clone(&entry.ids);
if let Some(entry) = cache.old.remove(&key) {
cache.young_bytes += entry.cost();
cache.young.insert(key, entry);
cache.rotate_if_full();
}
return (key, Some(ids));
}
(key, None)
}
pub fn insert(&self, key: u64, text: &str, ids: &[u32]) {
let Ok(mut cache) = self.inner.lock() else {
return;
};
if cache.budget == 0 {
return;
}
let entry = Entry {
text: text.into(),
ids: ids.into(),
};
if entry.cost() > cache.budget / 2 {
return;
}
cache.young_bytes += entry.cost();
cache.young.insert(key, entry);
cache.rotate_if_full();
}
/// (entries, approximate bytes) held now.
pub fn stats(&self) -> (usize, usize) {
self.inner
.lock()
.map(|cache| {
let bytes =
|map: &HashMap<u64, Entry>| map.values().map(Entry::cost).sum::<usize>();
(
cache.young.len() + cache.old.len(),
bytes(&cache.young) + bytes(&cache.old),
)
})
.unwrap_or((0, 0))
}
}
impl Generations {
fn rotate_if_full(&mut self) {
if self.young_bytes > self.budget / 2 {
self.old = std::mem::take(&mut self.young);
self.young_bytes = 0;
}
}
}