Skip to main content

KVCacheManager

Struct KVCacheManager 

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

KV cache manager for all layers in a model

Implementations§

Source§

impl KVCacheManager

Source

pub fn new( num_layers: usize, max_seq_len: usize, quant_type: KVQuantType, ) -> Self

Create a new KV cache manager

Source

pub fn new_paged( num_layers: usize, max_seq_len: usize, pool: Arc<Mutex<BlockPool>>, owner: CacheOwner, ) -> Self

Create a new KV cache manager using paged block storage.

All layers share the same BlockPool for zero-fragmentation memory management.

Source

pub fn with_layer_cache<F, R>(&self, layer_idx: usize, f: F) -> Option<R>
where F: FnOnce(&mut LayerKVCache) -> R,

Get cache for a specific layer with a closure

Source

pub fn layer_cache_ref( &self, layer_idx: usize, ) -> Option<RefMut<'_, usize, LayerKVCache>>

Borrow a layer’s cache directly as a RefMut (for the batched decode path, which needs to hold one mutable layer-cache borrow per sequence across a batched attention call). Each sequence has its own manager, so the borrows never alias. Returns None when caching is disabled or the layer is absent.

Source

pub fn clear_all(&mut self)

Clear all KV tensors together with the metadata that describes them.

cached_token_ids, the SSM snapshot, and its slot-device record only have meaning alongside the layer tensors they were computed with. A cleared cache that retained them would let a later extending prompt claim a prefix_len — or restore a stale snapshot — against KV that no longer exists (e.g. a session turn cancelled before its first prefill: the set-up clear runs at generation setup, and the drop records nothing new).

Source

pub fn ensure_layer_cache(&self, layer_idx: usize)

Insert a fresh cache for layer_idx if none exists yet.

Architectures with auxiliary KV-consuming modules beyond the main decoder layers (the Qwen3.5 MTP draft head, whose slot sits at index num_hidden_layers) call this when a session cache is swapped in: the registry may have created the manager with only the main layer count.

Source

pub fn max_seq_len(&self) -> usize

Maximum sequence length every layer cache is bounded by (LayerKVCache::update errors past it).

Source

pub fn compat_fingerprint(&self) -> Option<KvCompatFingerprint>

The compatibility fingerprint stamped on this cache, or None until the cache is first populated (#1277).

Source

pub fn set_compat_fingerprint(&mut self, fp: KvCompatFingerprint)

Stamp (or re-stamp) the compatibility fingerprint under which this cache’s KV is being produced. Called by the engine at reuse time: a fresh cache is stamped with the current config; an incompatible cache is cleared and re-stamped after its stale KV is discarded.

Source

pub fn apply_reuse_policy( &mut self, expected: Option<KvCompatFingerprint>, ) -> CacheReuseDecision

Apply the fail-closed KV compatibility policy to this real cache.

This is the production state-transition boundary for #1277. A compatible stamped cache is retained. A fresh empty cache is stamped before prefill. Every incompatible or unproven cache has both its token IDs and layer tensors discarded, then is re-stamped only when an authoritative expected fingerprint is available.

Source

pub fn set_enabled(&mut self, enabled: bool)

Enable or disable caching

Source

pub fn memory_usage(&self) -> usize

Get total memory usage in bytes (approximate)

Source

pub fn quant_type(&self) -> KVQuantType

Get the quantization type

Source

pub fn touch(&self)

Update last access timestamp (for LRU eviction)

Source

pub fn last_access(&self) -> u64

Get last access timestamp in milliseconds

Source

pub fn access_count(&self) -> u64

Get access count

Source

pub fn prefix_match_len(&self, new_tokens: &[i64]) -> usize

Find the length of the common prefix between cached tokens and new tokens.

Returns the number of tokens whose KV values can be reused from the cache. A return value of 0 means no prefix match (full recomputation needed).

Source

pub fn set_cached_tokens(&mut self, tokens: Vec<i64>)

Record which tokens this cache was computed for.

Called after generation completes so the next turn can detect prefix overlap. Any prior SSM snapshot is dropped: tokens recorded without a known recurrent state must not resurrect a stale one.

Source

pub fn set_cached_tokens_with_ssm( &mut self, tokens: Vec<i64>, ssm_snapshot: Option<(Vec<Option<Tensor>>, Vec<Option<Tensor>>)>, )

Record which tokens this cache was computed for, together with the recurrent-state (SSM conv/rec) snapshot as of the end of the prefill that produced them (hybrid models only; None for pure attention).

The snapshot is what makes a later prefix hit rewindable for recurrent layers: KV truncates to the matched prefix, the snapshot restores the GDN conv/rec state to the end of the cached sequence.

Source

pub fn ssm_snapshot(&self) -> Option<(Vec<Option<Tensor>>, Vec<Option<Tensor>>)>

Deep-copied SSM snapshot for restore on a prefix hit.

Returns deep copies (same .copy() discipline as Qwen3_5Model::snapshot_ssm_states) so that restoring into the live model state never aliases — and cannot mutate — the stored snapshot.

Source

pub fn cached_token_count(&self) -> usize

Get the cached token IDs (for debugging/metrics).

Source

pub fn truncate_to(&self, pos: usize)

Truncate the cache to a given token position.

Keeps KV values for tokens 0..pos and discards everything after. Used when a prefix matches but the suffix has changed (new turn).

Source

pub fn location(&self) -> CacheLocation

Current storage location of this cache’s tensors.

Source

pub fn offload_to_cpu(&mut self)

Offload all layer caches from GPU to CPU RAM.

Frees GPU memory while preserving the cached data for later restore. Only works for FullPrecision storage — Paged caches free blocks to the pool instead (handled by evict_to_budget), and Quantized data is already partially on CPU.

Source

pub fn restore_to_gpu(&mut self, device: Device)

Restore all layer caches from CPU back to GPU.

Must be called before using the cache for inference.

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
§

impl<T> Any for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

§

fn type_name(&self) -> &'static str

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.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

§

const WITNESS: W = W::MAKE

A constant of the type witness
§

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

§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
§

impl<T> Instrument for T

§

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

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

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
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

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

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

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<T> ServiceExt for T

§

fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>
where Self: Sized,

Apply a transformation to the response body. Read more
§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using HTTP status codes. Read more
§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using gRPC headers. Read more
§

fn follow_redirects(self) -> FollowRedirect<Self>
where Self: Sized,

Follow redirect resposes using the Standard policy. 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.
§

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

impl<T> ErasedDestructor for T
where T: 'static,

§

impl<T> MaybeSend for T
where T: Send,

§

impl<T> MaybeSend for T
where T: Send,