Skip to main content

L1Cache

Struct L1Cache 

Source
pub struct L1Cache { /* private fields */ }
Expand description

L1 cache: prefix matching at special-token boundaries, backed by a weighted W-TinyLFU moka cache that owns storage, recency/frequency tracking, and eviction. Hit/miss counts (our notion of a prefix hit) are tracked separately for metrics.

Implementations§

Source§

impl L1Cache

Source

pub fn new(max_memory: usize, special_tokens: Vec<String>) -> Self

special_tokens is the atomic special-token set whose boundaries the cache splits at; an empty set leaves L1 inert (no boundaries, no entries).

Source

pub fn set_observer(&mut self, on_hit: CacheEventFn, on_miss: CacheEventFn)

Install hit/miss callbacks. Replaces any previously-set observers.

Source

pub fn longest_prefix_match( &self, input: &str, ) -> Option<(Arc<[TokenIdType]>, usize, usize)>

Try to find the longest prefix match at a special-token boundary.

Returns (cached_tokens, byte_offset, deepest_boundary) if found. The caller extends the cached tokens with a fresh encode of input[byte_offset..]; deepest_boundary is the deepest special-token boundary in input (end-exclusive), handed back so [extend_after_match] need not rescan the input for it.

Source

pub fn insert_at_boundaries<E: Encoder + ?Sized>( &self, input: &str, tokenizer: &E, ) -> Result<()>

Insert prefix entries at every special-token boundary (e.g. to pre-seed the cache).

Uses incremental hashing and incremental tokenization (per-segment encode of the delta text between adjacent boundaries) so populating N entries costs one full re-tokenize total, split across the segments. The miss path uses Self::populate_and_encode instead, which reuses this same work to also return the full token vector (avoiding a redundant second tokenization).

Source

pub fn populate_and_encode<E: Encoder + ?Sized>( &self, input: &str, tokenizer: &E, ) -> Result<Vec<TokenIdType>>

Miss-path encode: tokenize input exactly once, caching the cumulative prefix at every special-token boundary as we go, and return the full token-id vector. This replaces a separate full encode + Self::insert_at_boundaries, which together tokenized the input ~twice (once for the result, once split across segments).

The concatenation of the per-segment encodes equals an uncached encode(input) because special tokens are atomic in BPE — the same invariant the hit path relies on. Returns token-ids only; the caller wraps them in crate::Encoding::Sp.

Source

pub fn extend_after_match<E: Encoder + ?Sized>( &self, input: &str, prefix_tokens: Arc<[TokenIdType]>, prefix_len: usize, deepest_boundary: usize, tokenizer: &E, ) -> Result<Vec<TokenIdType>>

Extend the cache on a partial hit so the next turn of a growing conversation hits deeper. Given the (prefix_tokens, prefix_len, deepest_boundary) returned by [longest_prefix_match], tokenize the remaining suffix and cache the cumulative prefix at the suffix’s deepest special-token boundary, then return the full merged token vector.

Deepest-only is intentional: in an append-only conversation the next turn always reaches the deepest boundary, so caching it bounds per-turn work to the newest exchange; shallow/branching coverage already comes from the miss path’s [insert_at_boundaries]. Splitting at special-token boundaries is correctness-safe because special tokens are atomic in BPE (tokenize(a) + tokenize(b) == tokenize(a + b)).

Note: unlike the read-only fast path, this writes to the cache on a hit (one insert + possible eviction). It relies on the same best-effort memory accounting as [insert_at_boundaries].

Source

pub fn len(&self) -> usize

Number of live entries. Flushes moka’s deferred maintenance first so the count is exact rather than lagging behind pending inserts/evictions.

Source

pub fn is_empty(&self) -> bool

Source

pub fn stats(&self) -> L1CacheStats

Source

pub fn clear(&self)

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more