generation
generation
¶
GenerationLayerCache
dataclass
¶
Per-layer K/V cache for the main sequence (grows during generation).
Keys and values accumulate along the sequence dimension as new tokens are decoded. Each generation step appends one new position.
Attributes:
| Name | Type | Description |
|---|---|---|
keys |
Tensor
|
Cached keys (B, kv_heads, T, head_dim) where T grows each step. |
values |
Tensor
|
Cached values (B, kv_heads, T, head_dim). |
GenerationCache
dataclass
¶
Multi-layer generation cache for an autoregressive decoder.
Attributes:
| Name | Type | Description |
|---|---|---|
layers |
list[GenerationLayerCache]
|
One GenerationLayerCache per decoder layer. |
key_padding_mask |
Tensor | None
|
Bool mask (B, cache_len), True = masked (do not attend). |
get_length
¶
Get cached sequence length from the first layer.
initialize_generation_cache
¶
initialize_generation_cache(batch_size, num_layers, number_of_heads, head_dimension, device, dtype=float32)
Initialize empty generation cache for all decoder layers.
Pre-allocates empty tensors with zero sequence length for efficiency during autoregressive generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Batch size. |
required |
num_layers
|
int
|
Number of decoder layers. |
required |
number_of_heads
|
int
|
Number of K/V attention heads per layer. |
required |
head_dimension
|
int
|
Dimension per attention head. |
required |
device
|
device | str
|
Device to allocate tensors on. |
required |
dtype
|
dtype
|
Data type for cache tensors. |
float32
|
Returns:
| Type | Description |
|---|---|
list[GenerationLayerCache]
|
List of empty GenerationLayerCache, one per layer. |
Source code in src/versatil/models/layers/transformer/cache/generation.py
update_generation_layer_cache
¶
Append new keys and values to a generation layer cache.
Concatenates along the sequence dimension (dim=2).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache
|
GenerationLayerCache
|
Existing layer cache. |
required |
new_keys
|
Tensor
|
New keys to append (B, number_of_heads, new_len, head_dim). |
required |
new_values
|
Tensor
|
New values to append (B, number_of_heads, new_len, head_dim). |
required |
Returns:
| Type | Description |
|---|---|
GenerationLayerCache
|
New GenerationLayerCache with accumulated K/V. |