dynamo_tokenizers/cache/mod.rs
1// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3//
4// SPDX-FileCopyrightText: Copyright (c) 2024 Simo Lin, Chang Su, Keyang Ru (llm-tokenizer authors)
5//
6// Portions adapted from sgl-project/llm-tokenizer v1.3.2 (Apache-2.0).
7// Upstream: https://github.com/lightseekorg/smg
8// Modifications: removed L0 layer, removed `add_special_tokens` plumbing (Dynamo's
9// `Encoder::encode` has no such flag), dropped fingerprinting, retargeted onto
10// `crate::traits::Tokenizer`.
11
12//! Tokenizer caching layer (L1: prefix matching at special-token boundaries).
13//!
14//! Wraps any [`Tokenizer`] in a cache that records prefix tokenizations at every
15//! special-token boundary. On a hit, the cached prefix tokens are merged with a
16//! fresh encode of the trailing suffix only — turning O(N) tokenization work
17//! into O(suffix_len) when prompts share a system prefix.
18//!
19//! # Correctness
20//!
21//! Boundaries are taken **only** at positions immediately following a registered
22//! special token (e.g. `<|im_start|>`, `<|im_end|>`, `<s>`, `</s>`). Special tokens
23//! are atomic in BPE (`special: true, normalized: false`), so splitting there
24//! preserves the invariant `tokenize(prefix) + tokenize(suffix) == tokenize(prefix + suffix)`.
25//! No fallback to whitespace or punctuation — better to miss than to corrupt.
26//!
27//! # Storage normalization
28//!
29//! When L1 is enabled, **every** `encode` returns [`Encoding::Sp`] (token-ids only) —
30//! hits merge cached prefix ids with a fresh suffix encode, and misses assemble the ids
31//! from the per-boundary segment encodes (see [`L1Cache::populate_and_encode`]) — even
32//! when the inner tokenizer would have produced [`Encoding::Hf`] (rich offsets/attention/
33//! etc). All current downstream consumers in Dynamo only call [`Encoding::token_ids`], so
34//! this lossy normalization is safe; revisit if a caller starts reading offsets or
35//! attention masks from encodings produced through the cache.
36//!
37//! # Configuration
38//!
39//! - `special_tokens: Vec<String>` — must be supplied at construction (the
40//! [`Tokenizer`] trait is intentionally minimal and does not expose them).
41//! An empty list disables L1: `encode`/`encode_batch` short-circuit straight
42//! to the inner tokenizer with no lookup, no miss-counter bump, and no
43//! insert attempt.
44//! - `max_memory_bytes` — L1 byte budget; entries evicted via approximate LRU.
45//!
46//! # Provenance
47//!
48//! Adapted from `llm-tokenizer` v1.3.2 (`cache/l1.rs`, `cache/mod.rs`). L0 and
49//! fingerprinting were dropped; L1 alone covers the headline multi-turn-chat
50//! workload, and the in-memory cache lifetime is bound to a single tokenizer
51//! instance so fingerprint-based invalidation is unnecessary.
52
53mod l1;
54
55use std::sync::Arc;
56
57pub use l1::{CacheEventFn, L1Cache, L1CacheStats};
58
59use crate::{
60 Encoding, Result, TokenIdType,
61 traits::{DecodeResult, Decoder, Encoder, Tokenizer},
62};
63
64/// Token-level cache usage for one successful encode.
65///
66/// A partial cache hit reports both cached prefix tokens and uncached suffix tokens.
67/// Their sum always equals the number of tokens returned by the encode operation.
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub struct CacheTokenUsage {
70 /// Tokens returned from the cached prefix.
71 pub cached_tokens: usize,
72 /// Tokens freshly encoded from the uncached suffix.
73 pub uncached_tokens: usize,
74}
75
76/// Optional observer for token-level cache usage.
77pub type CacheTokenUsageFn = Arc<dyn Fn(CacheTokenUsage) + Send + Sync>;
78
79/// Caching wrapper around an inner tokenizer.
80///
81/// Implements [`Encoder`], [`Decoder`], and [`Tokenizer`]; decode calls pass
82/// through to the inner tokenizer (decoding is fast and rarely repeated).
83pub struct CachedTokenizer {
84 inner: Arc<dyn Tokenizer>,
85 l1: L1Cache,
86 /// Whether L1 is active. False when the special-token set is empty (e.g. the tiktoken
87 /// wrapping path): `encode`/`encode_batch` then bypass the cache entirely. The special
88 /// tokens themselves live in the `L1Cache` (its boundary automaton).
89 l1_enabled: bool,
90 /// When true, cache the newly-tokenized suffix on a partial hit so the next turn
91 /// of a growing conversation hits deeper (see [`L1Cache::extend_after_match`]).
92 extend_on_hit: bool,
93 /// Called once after every successful encode while L1 is active.
94 token_observer: Option<CacheTokenUsageFn>,
95}
96
97impl CachedTokenizer {
98 /// Construct a cached tokenizer.
99 ///
100 /// `special_tokens` is the list of atomic special-token strings the inner
101 /// tokenizer recognizes (typically extracted via the HuggingFace tokenizer's
102 /// `get_added_tokens_decoder()` filtering by `special == true`). An empty list
103 /// disables L1 — `encode`/`encode_batch` short-circuit to the inner tokenizer
104 /// without touching the cache or its counters.
105 ///
106 /// `max_memory_bytes` is the L1 cache byte budget.
107 pub fn new(
108 inner: Arc<dyn Tokenizer>,
109 special_tokens: Vec<String>,
110 max_memory_bytes: usize,
111 ) -> Self {
112 let l1_enabled = !special_tokens.is_empty();
113 Self {
114 inner,
115 l1: L1Cache::new(max_memory_bytes, special_tokens),
116 l1_enabled,
117 extend_on_hit: false,
118 token_observer: None,
119 }
120 }
121
122 /// Enable partial-hit extension. When on, a partial cache hit also caches the
123 /// freshly-tokenized suffix at its deepest special-token boundary, so each turn of
124 /// a growing multi-turn conversation hits deeper than the last and per-turn
125 /// tokenization cost stops growing with conversation length. Default off.
126 pub fn with_extend(mut self, enabled: bool) -> Self {
127 self.extend_on_hit = enabled;
128 self
129 }
130
131 /// Install hit/miss callbacks so each L1 lookup pushes an event into the
132 /// supplied closures (e.g. `Prometheus::Counter::inc`). Replaces any
133 /// previously-set observer.
134 pub fn with_observer(mut self, on_hit: CacheEventFn, on_miss: CacheEventFn) -> Self {
135 self.l1.set_observer(on_hit, on_miss);
136 self
137 }
138
139 /// Install a callback that receives exact cached and uncached token counts after each
140 /// successful encode while L1 is active. A partial hit reports both categories, which
141 /// lets consumers maintain token-level cache totals and derive a reuse ratio. Replaces
142 /// any previously-set token observer.
143 ///
144 /// This observer is not called when the special-token set is empty (and L1 is therefore
145 /// disabled) or when encoding returns an error.
146 pub fn with_token_observer(mut self, observer: CacheTokenUsageFn) -> Self {
147 self.token_observer = Some(observer);
148 self
149 }
150
151 fn observe_token_usage(&self, cached_tokens: usize, total_tokens: usize) {
152 if let Some(observer) = &self.token_observer {
153 let uncached_tokens = total_tokens
154 .checked_sub(cached_tokens)
155 .expect("cached token count cannot exceed total token count");
156 observer(CacheTokenUsage {
157 cached_tokens,
158 uncached_tokens,
159 });
160 }
161 }
162
163 /// Snapshot of L1 cache statistics (cumulative hits/misses/entries/memory).
164 pub fn cache_stats(&self) -> L1CacheStats {
165 self.l1.stats()
166 }
167
168 /// Clear all cached entries and reset counters.
169 pub fn clear_cache(&self) {
170 self.l1.clear();
171 }
172
173 /// Access the underlying tokenizer (e.g. for downcasting to a concrete type).
174 pub fn inner(&self) -> &Arc<dyn Tokenizer> {
175 &self.inner
176 }
177}
178
179impl Encoder for CachedTokenizer {
180 fn encode(&self, input: &str) -> Result<Encoding> {
181 // No specials => no boundaries are ever produced. Skip the lookup, miss-counter
182 // bump, and insert attempt entirely — otherwise the tiktoken wrapping path (which
183 // deliberately passes an empty list) pays the cost on every call with no chance
184 // of a hit.
185 if !self.l1_enabled {
186 return self.inner.encode(input);
187 }
188
189 if let Some((prefix_tokens, prefix_len, deepest_boundary)) =
190 self.l1.longest_prefix_match(input)
191 {
192 let cached_tokens = prefix_tokens.len();
193 let suffix = &input[prefix_len..];
194 let encoding = if suffix.is_empty() {
195 Encoding::Sp(prefix_tokens.to_vec())
196 } else if self.extend_on_hit {
197 // Cache the new suffix at its deepest boundary so the next turn hits
198 // deeper, then return the full merged tokens. The deepest boundary was
199 // already found by `longest_prefix_match`, so no rescan is needed here.
200 Encoding::Sp(self.l1.extend_after_match(
201 input,
202 prefix_tokens,
203 prefix_len,
204 deepest_boundary,
205 self.inner.as_ref(),
206 )?)
207 } else {
208 let suffix_enc = self.inner.encode(suffix)?;
209 // Reserve exact capacity so appending the suffix doesn't grow-realloc and
210 // re-copy the (large) cached prefix.
211 let mut merged: Vec<TokenIdType> =
212 Vec::with_capacity(prefix_tokens.len() + suffix_enc.token_ids().len());
213 merged.extend_from_slice(&prefix_tokens);
214 merged.extend_from_slice(suffix_enc.token_ids());
215 Encoding::Sp(merged)
216 };
217 self.observe_token_usage(cached_tokens, encoding.token_ids().len());
218 return Ok(encoding);
219 }
220
221 // Miss path: tokenize once, caching the cumulative prefix at every boundary as we
222 // go. The returned ids equal an uncached encode (special tokens are atomic), so we
223 // avoid the redundant second tokenization a separate full-encode + insert would
224 // cost. Returns Encoding::Sp — consistent with the hit path (see the storage-
225 // normalization note in the module docs).
226 let encoding = Encoding::Sp(self.l1.populate_and_encode(input, self.inner.as_ref())?);
227 self.observe_token_usage(0, encoding.token_ids().len());
228 Ok(encoding)
229 }
230
231 fn encode_batch(&self, inputs: &[&str]) -> Result<Vec<Encoding>> {
232 // True passthrough when L1 is disabled — delegate to the inner's native
233 // batch path (which may be rayon-parallel for HF) instead of falling
234 // through per-item.
235 if !self.l1_enabled {
236 return self.inner.encode_batch(inputs);
237 }
238
239 // Per-item cache lookup — do NOT delegate to inner.encode_batch, which would
240 // bypass the cache. Sequential iteration is fine; if rayon is added later it
241 // belongs here, not inside `encode`.
242 inputs.iter().map(|&i| self.encode(i)).collect()
243 }
244}
245
246impl Decoder for CachedTokenizer {
247 fn decode(&self, token_ids: &[TokenIdType], skip_special_tokens: bool) -> Result<DecodeResult> {
248 // Decode is not cached — passthrough to inner.
249 self.inner.decode(token_ids, skip_special_tokens)
250 }
251}
252
253impl Tokenizer for CachedTokenizer {}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258 use crate::HuggingFaceTokenizer;
259 use std::sync::{Mutex, atomic::AtomicU64, atomic::Ordering};
260
261 struct FailingTokenizer;
262
263 impl Encoder for FailingTokenizer {
264 fn encode(&self, _input: &str) -> Result<Encoding> {
265 Err(anyhow::anyhow!("intentional encode failure"))
266 }
267
268 fn encode_batch(&self, _inputs: &[&str]) -> Result<Vec<Encoding>> {
269 Err(anyhow::anyhow!("intentional encode failure"))
270 }
271 }
272
273 impl Decoder for FailingTokenizer {
274 fn decode(
275 &self,
276 _token_ids: &[TokenIdType],
277 _skip_special_tokens: bool,
278 ) -> Result<DecodeResult> {
279 Err(anyhow::anyhow!("intentional decode failure"))
280 }
281 }
282
283 impl Tokenizer for FailingTokenizer {}
284
285 const TINYLLAMA_PATH: &str = concat!(
286 env!("CARGO_MANIFEST_DIR"),
287 "/tests/data/sample-models/TinyLlama_v1.1/tokenizer.json"
288 );
289
290 fn inner() -> Arc<dyn Tokenizer> {
291 Arc::new(HuggingFaceTokenizer::from_file(TINYLLAMA_PATH).expect("load TinyLlama"))
292 }
293
294 fn specials() -> Vec<String> {
295 vec!["<s>".into(), "</s>".into()]
296 }
297
298 fn collect_token_usage(
299 tokenizer: CachedTokenizer,
300 ) -> (CachedTokenizer, Arc<Mutex<Vec<CacheTokenUsage>>>) {
301 let events = Arc::new(Mutex::new(Vec::new()));
302 let observed = events.clone();
303 let tokenizer = tokenizer.with_token_observer(Arc::new(move |usage| {
304 observed.lock().unwrap().push(usage);
305 }));
306 (tokenizer, events)
307 }
308
309 #[test]
310 fn empty_specials_passes_through_correctly() {
311 // L1 disabled by empty specials list — encode must produce correct ids
312 // AND short-circuit to the inner tokenizer (no miss-counter bump, no
313 // insert attempt). Otherwise the tiktoken integration would log a
314 // miss per request with zero hits forever.
315 let tok = inner();
316 let (cached, events) =
317 collect_token_usage(CachedTokenizer::new(tok.clone(), Vec::new(), 4096));
318 let s = "<s>hello world</s>";
319 let a = cached.encode(s).unwrap();
320 let b = tok.encode(s).unwrap();
321 assert_eq!(a.token_ids(), b.token_ids());
322 let stats = cached.cache_stats();
323 assert_eq!(stats.entries, 0);
324 assert_eq!(stats.misses, 0, "empty specials must not increment misses");
325 assert_eq!(stats.hits, 0);
326 assert!(
327 events.lock().unwrap().is_empty(),
328 "empty specials must not emit token usage"
329 );
330 }
331
332 #[test]
333 fn token_observer_reports_full_miss_and_partial_hit_with_and_without_extension() {
334 for extend_on_hit in [false, true] {
335 let tok = inner();
336 let hits = Arc::new(AtomicU64::new(0));
337 let misses = Arc::new(AtomicU64::new(0));
338 let hit_counter = hits.clone();
339 let miss_counter = misses.clone();
340 let cached = CachedTokenizer::new(tok, specials(), 64 * 1024)
341 .with_extend(extend_on_hit)
342 .with_observer(
343 Arc::new(move || {
344 hit_counter.fetch_add(1, Ordering::Relaxed);
345 }),
346 Arc::new(move || {
347 miss_counter.fetch_add(1, Ordering::Relaxed);
348 }),
349 );
350 let (cached, events) = collect_token_usage(cached);
351
352 let shared = "<s>system\nYou are helpful.</s><s>user\n";
353 let first = format!("{shared}First question?</s>");
354 let second = format!("{shared}Second different prompt entirely.</s>");
355
356 let first_encoding = cached.encode(&first).unwrap();
357 let second_encoding = cached.encode(&second).unwrap();
358
359 let events = events.lock().unwrap();
360 assert_eq!(events.len(), 2);
361 assert_eq!(
362 events[0],
363 CacheTokenUsage {
364 cached_tokens: 0,
365 uncached_tokens: first_encoding.token_ids().len(),
366 }
367 );
368 assert!(events[1].cached_tokens > 0);
369 assert!(events[1].uncached_tokens > 0);
370 assert_eq!(
371 events[1].cached_tokens + events[1].uncached_tokens,
372 second_encoding.token_ids().len()
373 );
374 assert_eq!(hits.load(Ordering::Relaxed), 1);
375 assert_eq!(misses.load(Ordering::Relaxed), 1);
376 }
377 }
378
379 #[test]
380 fn token_observer_does_not_report_failed_encodes() {
381 let tokenizer: Arc<dyn Tokenizer> = Arc::new(FailingTokenizer);
382 let (cached, events) =
383 collect_token_usage(CachedTokenizer::new(tokenizer, specials(), 4096));
384
385 assert!(cached.encode("<s>this fails</s>").is_err());
386 assert!(events.lock().unwrap().is_empty());
387 }
388
389 #[test]
390 fn two_turn_chat_correctness_and_hit() {
391 let tok = inner();
392 let cached = CachedTokenizer::new(tok.clone(), specials(), 64 * 1024);
393
394 let template = "<s>system\nYou are helpful.</s><s>user\n";
395 let first = format!("{template}First question?</s>");
396 let second = format!("{template}Second different prompt entirely.</s>");
397
398 // Warm the cache.
399 let _ = cached.encode(&first).unwrap();
400
401 // Second request: shared prefix → L1 hit, suffix-only fresh encode.
402 let cached_second = cached.encode(&second).unwrap();
403 let plain_second = tok.encode(&second).unwrap();
404 assert_eq!(
405 cached_second.token_ids(),
406 plain_second.token_ids(),
407 "cached encode must equal plain encode for second turn"
408 );
409
410 let stats = cached.cache_stats();
411 assert!(stats.hits >= 1, "expected L1 hit on second request");
412 }
413
414 #[test]
415 fn decode_passes_through() {
416 let tok = inner();
417 let cached = CachedTokenizer::new(tok.clone(), specials(), 4096);
418 let enc = cached.encode("<s>hello</s>").unwrap();
419 let direct = tok.decode(enc.token_ids(), false).unwrap();
420 let through = cached.decode(enc.token_ids(), false).unwrap();
421 assert_eq!(direct, through);
422 }
423
424 #[test]
425 fn encode_batch_uses_cache() {
426 let tok = inner();
427 let (cached, events) =
428 collect_token_usage(CachedTokenizer::new(tok.clone(), specials(), 64 * 1024));
429 let shared = "<s>system\nShared persona.</s><s>user\n";
430 let inputs = [
431 format!("{shared}q1</s>"),
432 format!("{shared}q2</s>"),
433 format!("{shared}q3</s>"),
434 ];
435 let refs: Vec<&str> = inputs.iter().map(String::as_str).collect();
436 let outs = cached.encode_batch(&refs).unwrap();
437 assert_eq!(outs.len(), 3);
438 let events = events.lock().unwrap();
439 assert_eq!(events.len(), outs.len());
440 for (event, output) in events.iter().zip(&outs) {
441 assert_eq!(
442 event.cached_tokens + event.uncached_tokens,
443 output.token_ids().len()
444 );
445 }
446 assert_eq!(events[0].cached_tokens, 0);
447 assert!(events[1..].iter().all(|event| event.cached_tokens > 0));
448 // First call populates, second/third hit.
449 assert!(cached.cache_stats().hits >= 2, "expected hits on q2 and q3");
450 }
451}