Skip to content
class

DynamicCache

extendsCache
DynamicCache()

A cache that grows its key/value tensors by concatenation each step.

Holds one key tensor and one value tensor per layer in key_cache and value_cache (see the Attributes section). The first update for a layer seeds the entry; subsequent updates concatenate the new token(s) along the sequence dimension. This is the eager default for autoregressive decoding.

Attributes

key_cachelist[Tensor]
Per-layer accumulated keys, each (B, num_heads, T, head_dim).
value_cachelist[Tensor]
Per-layer accumulated values, same shapes.
_seen_tokensint
Running count of tokens the cache has processed (tracked from layer_idx == 0), exposed via seen_tokens.

Examples

>>> import lucid
>>> from lucid.utils.cache import DynamicCache
>>> cache = DynamicCache()
>>> k = lucid.zeros(1, 2, 3, 4)   # (B, H, T, D)
>>> v = lucid.zeros(1, 2, 3, 4)
>>> ck, cv = cache.update(k, v, layer_idx=0)
>>> cache.get_seq_length()
3

Used by 2

Constructors

1
dunder

__init__

→None
__init__()

Create an empty cache with no layers populated.

Properties

1
prop

seen_tokens

→int
seen_tokens: int

Total number of tokens processed across all update calls.

Class methods

1
cls

from_legacy_cache

→Self
from_legacy_cache(past_key_values: tuple[tuple[Tensor, Tensor], ...] | None = None)

Build a DynamicCache from the legacy tuple format.

past_key_values is a per-layer tuple of (key, value) tensors; None yields an empty cache.

Instance methods

9
fn

batch_repeat_interleave

→None
batch_repeat_interleave(repeats: int)

Repeat every batch row repeats times along the batch dimension (in place) — e.g. to fan one prompt out into repeats samples.

fn

batch_select_indices

→None
batch_select_indices(indices: Tensor)

Keep only the batch rows named by indices along the batch dimension (in place).

fn

crop

→None
crop(max_length: int)

Truncate the cache to at most max_length tokens along the sequence dimension (in place).

A negative max_length drops that many tokens off the end. Useful for rolling the cache back (e.g. rejecting speculative tokens). A max_length at or above the current length is a no-op.

fn

get_max_cache_shape

→int | None
get_max_cache_shape()

Always None — the dynamic cache is unbounded and grows on demand.

fn

get_seq_length

→int
get_seq_length(layer_idx: int = 0)

Number of cached tokens for layer_idx (0 if not yet seeded), read directly from the accumulated tensor's sequence dimension.

fn

reorder_cache

→None
reorder_cache(beam_idx: Tensor)

Reindex every layer's keys/values along the batch dimension with beam_idx (in place) to keep beams aligned after a beam permutation.

fn

reset

→None
reset()

Empty the cache in place so the same object can be reused for a fresh sequence (clears every layer and the token counter).

fn

to_legacy_cache

→tuple[tuple[Tensor, Tensor], ...]
to_legacy_cache()

Convert to the legacy tuple(tuple(key, value), ...) format.

Returns one (key, value) pair per layer, in layer order — the representation older decoder forward signatures consumed before Cache objects existed.

fn

update

→tuple of (Tensor, Tensor)
update(key_states: Tensor, value_states: Tensor, layer_idx: int, cache_kwargs: dict[str, object] | None = None)

Concatenate key_states / value_states onto layer_idx and return the grown key/value tensors.

The first call for a layer seeds the entry; later calls lucid.cat the new token(s) onto the sequence dimension.

Parameters

key_statesTensor
New key projections of shape (B, num_heads, T_new, head_dim).
value_statesTensor
New value projections of the same shape.
layer_idxint
Index of the transformer layer this update belongs to.
cache_kwargsdict or None= None
Accepted for interface parity; unused by the dynamic cache.

Returns

tuple of (Tensor, Tensor)

The accumulated (keys, values) for layer_idx, each of shape (B, num_heads, T_total, head_dim).

Dunder methods

3
dunder

__getitem__

→tuple[Tensor, Tensor]
__getitem__(layer_idx: int)

Return the (keys, values) pair cached for layer_idx.

dunder

__iter__

→Iterator[tuple[Tensor, Tensor]]
__iter__()

Iterate (keys, values) pairs in layer order.

dunder

__len__

→int
__len__()

Number of layers currently held in the cache.