Provides common structure and operations for caches that store mappings from layer/block index to cached key-value projections.
Format
An R6::R6Class object.
Details
Layer indices are stored as character strings in the named list kv,
since R lists cannot have integer names that start from 0.
Methods
KVCache$is_populated()
Check if this cache has valid entries.
Returns TRUE when the cache contains data (use_cache mode).
Returns FALSE when the cache is empty (store_cache mode).
KVCache$slice()
Slice all entries along batch dimensions.
Returns a new cache of the same class with sliced entries.
KVCache$to()
Move all entries to the given device and optionally cast dtype.
Returns a new cache of the same class.
KVCache$preallocate()
Pre-allocate entries in this cache based on shapes from a reference.
K/V tensors always have shape (*batch, num_heads, seq_len, head_dim).
This method keeps the last three dimensions from the reference entry and
prepends batch_shape as the leading dimensions.
Examples
if (FALSE) { # \dontrun{
cache <- KVCache$new()
cache$kv[["1"]] <- KVCacheEntry$new(
key = torch_randn(2, 4, 10, 64),
value = torch_randn(2, 4, 10, 64)
)
cache$is_populated()
} # }