kvcache

package
v0.28.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 9 Imported by: 3 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package kvcache implements a flexible key-value (KV) cache for transformer models. It supports rolling (circular) cache, attention sinks (keeping the first N tokens always in the cache), dynamic shape handling (allocating cache with powers-of-two sequence lengths to minimize JIT compilations), and serialization/deserialization of cache nodes and tensors.

Index

Constants

View Source
const (
	// KeySuffix is appended to a layer's scope path to identify its key cache.
	KeySuffix = "/key"
	// ValueSuffix is appended to a layer's scope path to identify its value cache.
	ValueSuffix = "/value"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type KVCache

type KVCache struct {
	// SinkPositions is the number of initial tokens to keep fixed at the start of the cache
	// (also known as attention sinks, e.g. for streaming LLMs).
	SinkPositions int
	// MaxSeqLenPerLayerType defines the maximum sequence length per LayerType.
	// Indexed by attention.LayerType (GlobalLayer=0, LocalLayer=1).
	MaxSeqLenPerLayerType []int
	// MinSeqLenPerLayerType defines the minimum sequence length per LayerType.
	// Indexed by attention.LayerType (GlobalLayer=0, LocalLayer=1).
	MinSeqLenPerLayerType []int
	// OrderedScopes defines the execution order of attention layer scopes.
	// This is required to serialize and deserialize the cache tensors/nodes deterministically.
	OrderedScopes []string
	// LayerTypes maps scope paths (or prefixes) to their attention.LayerType (Global vs Local).
	LayerTypes map[string]attention.LayerType
	// GlobalHeadDim specifies a custom key/value head dimension for global layers if different.
	GlobalHeadDim int
}

KVCache configures and manages the attention Key-Value cache for transformer layers. It supports attention sinks, bucketing sequence lengths (powers-of-two padding) to avoid recompiling graphs for each new sequence length, and sliding-window layouts.

func NewKVCache

func NewKVCache() *KVCache

NewKVCache creates a new KVCache configuration builder with default settings:

  • SinkPositions: 4
  • MaxSeqLenPerLayerType: [64k, 1k] (Global/Local)
  • MinSeqLenPerLayerType: [32, 32]

func (*KVCache) BuildAttentionMask

func (k *KVCache) BuildAttentionMask(scope *model.Scope, cache KVCacheNodes, query *Node, position *Node, useCausalMask bool, slidingWindow int) *Node

BuildAttentionMask constructs the attention mask for the query at the current sequence position. It properly handles causal masking, sliding windows, and rolling cache/attention sinks, returning a boolean mask of shape [batchSize, qSeqLen, cacheSeqLen] where true means attend, false means ignore.

func (*KVCache) CacheSeqLen

func (k *KVCache) CacheSeqLen(lt attention.LayerType, currentSeqLen int) int

CacheSeqLen calculates the rounded-up cache sequence length for a given layer type. It rounds the sequence length up to the next power of 2 (between min and max limits) to reduce JIT graph recompilations.

func (*KVCache) DeserializeNodes

func (k *KVCache) DeserializeNodes(nodes []*Node) KVCacheNodes

DeserializeNodes unpacks a slice of KV cache graph nodes back into a KVCacheNodes map using the ordering defined by OrderedScopes. Panics if the number of nodes is incorrect.

func (*KVCache) DeserializeTensors

func (k *KVCache) DeserializeTensors(tensors []*tensors.Tensor) KVCacheTensors

DeserializeTensors unpacks a slice of KV cache tensors back into a KVCacheTensors map using the ordering defined by OrderedScopes. Panics if the number of tensors is incorrect.

func (*KVCache) Get

func (k *KVCache) Get(cache KVCacheNodes, path string) (key, value *Node)

Get retrieves the key and value nodes for the specified scope path from the cache map.

func (*KVCache) GetLayerType

func (k *KVCache) GetLayerType(scopePath string) attention.LayerType

GetLayerType returns the layer type for the given scope path by finding the longest matching prefix in the configured LayerTypes map. Defaults to attention.GlobalLayer if no prefix matches.

func (*KVCache) InitializeTensors

func (k *KVCache) InitializeTensors(batchSize, numKVHeads, headDim int, dtype dtypes.DType, currentSeqLen int) KVCacheTensors

InitializeTensors allocates and returns a new zero-initialized KVCacheTensors map based on the configuration and current sequence length. Tensors are allocated with shape [batchSize, numKVHeads, cacheSeqLen, headDim].

func (*KVCache) PadTensors

func (k *KVCache) PadTensors(kv KVCacheTensors, currentSeqLen int) (KVCacheTensors, error)

PadTensors pads the sequence length dimension of the KV cache tensors to match the target sequence length calculated by CacheSeqLen. This is used when the sequence length grows past the current bucket size during generation.

func (*KVCache) SerializeNodes

func (k *KVCache) SerializeNodes(kv KVCacheNodes) ([]*Node, error)

SerializeNodes packs the map of KV cache nodes into a slice in a deterministic order defined by OrderedScopes. Returns an error if any scope's key or value node is missing.

func (*KVCache) SerializeTensors

func (k *KVCache) SerializeTensors(kv KVCacheTensors) ([]*tensors.Tensor, error)

SerializeTensors packs the map of KV cache tensors into a slice in a deterministic order defined by OrderedScopes. Returns an error if any scope's key or value tensor is missing.

func (*KVCache) Update

func (k *KVCache) Update(scope *model.Scope, cache KVCacheNodes, nextK, nextV *Node, position *Node)

Update inserts the new key/value nodes (nextK, nextV) into the cache at the specified position. It handles transpose if the layout is different (e.g. BSHD vs BHSD) and implements the rolling cache mechanism with attention sink preservation (SinkPositions) when sequence length exceeds maxSeqLen.

func (*KVCache) WithGlobalHeadDim

func (k *KVCache) WithGlobalHeadDim(dim int) *KVCache

WithGlobalHeadDim configures the key/value head dimension for global layers if different from the default.

func (*KVCache) WithLayerTypes

func (k *KVCache) WithLayerTypes(layerTypes map[string]attention.LayerType) *KVCache

WithLayerTypes configures the mapping from scope prefixes to their attention layer type (Local/Global).

func (*KVCache) WithMaxSeqLenPerLayerType

func (k *KVCache) WithMaxSeqLenPerLayerType(maxLens []int) *KVCache

WithMaxSeqLenPerLayerType sets the maximum sequence lengths per layer type.

func (*KVCache) WithMinSeqLenPerLayerType

func (k *KVCache) WithMinSeqLenPerLayerType(minLens []int) *KVCache

WithMinSeqLenPerLayerType sets the minimum sequence lengths per layer type. The KVCache sequence length grows in powers of two (16, 32, 64, 128, etc.) to minimize JIT compilation costs, from MinSeqLen up to the configured maximum.

func (*KVCache) WithOrderedScopes

func (k *KVCache) WithOrderedScopes(scopes []string) *KVCache

WithOrderedScopes configures the ordered list of scope paths for all layers. This is required for serialization/deserialization to guarantee deterministic ordering.

func (*KVCache) WithSinkPositions

func (k *KVCache) WithSinkPositions(n int) *KVCache

WithSinkPositions configures the number of initial tokens to keep in the cache (attention sinks).

type KVCacheNodes

type KVCacheNodes map[string]*Node

KVCacheNodes maps a scope-specific cache key/value path to its corresponding graph *Node. Keys are formatted as "<scope_path>/key" and "<scope_path>/value".

type KVCacheTensors

type KVCacheTensors map[string]*tensors.Tensor

KVCacheTensors maps a scope-specific cache key/value path to its corresponding concrete *tensors.Tensor. Keys are formatted as "<scope_path>/key" and "<scope_path>/value".

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL