The KV Cache Family

A decoder layer computes a key and a value row for every token and reuses them for every later token. The KV cache holds those rows. All variants extend KVCache<T, V> in transformer-core and are assigned to a layer through MultiHeadAttention.kvCache, so the attention module does not know which storage is behind it.

Without compression, one layer stores

2 × positions × nKVHeads × headDim × 4 bytes

The variants differ in how many positions they hold, who owns the storage, and how a row is encoded.

Choosing a variant

Variant Holds Use it for

PositionalKVCache

every position up to maxSeqLen, in a buffer allocated up front

layers that attend to the whole context, read in place without copies

PositionalKVCache(window = N)

the newest N positions, in a ring

sliding-window layers

TurboQuantKVCache

every position, each row compressed

long histories when memory matters more than decode time

OwnerReadOnlyKVCache

nothing of its own; reads another layer’s cache

layers that share K/V with an earlier layer (Gemma 3n, Gemma 4)

AppendKVCache

every position, in tensors that grow by concatenation

the default of the decoder DSL (DecoderKVCacheKind.APPEND); no up-front allocation

SlidingWindowKVCache

the newest window positions, by concatenate and trim

superseded by the ring for eager decoding

SharedKVCache, SharedPositionalKVCache and PaddedSharedPositionalKVCache are older sharing schemes in which followers write into the owner’s storage. New models use OwnerReadOnlyKVCache.

Full history: PositionalKVCache

The cache allocates [nKVHeads, maxSeqLen, headDim] once for keys and once for values and writes position p into row p. The fused attention path reads those buffers in place through a KVBufferView; nothing is copied per token (see Parallel Attention Heads via Schedules). Writing past maxSeqLen is an error.

Ring: PositionalKVCache(window = N)

A layer with slidingWindow = N never reads a key older than N positions. With window = N the cache holds N rows per head and writes position p into row p % N:

window = 4, after 6 positions          rows:  [ 4 | 5 | 2 | 3 ]
                                                        ^ oldest held position
read order (oldest first):             2, 3, 4, 5
  • Memory is 2 × N × nKVHeads × headDim × 4 bytes, independent of maxSeqLen.

  • position still counts every token, so RoPE sees absolute positions.

  • Reads return the positions still held, oldest first. Once the ring has wrapped they sit in two physical runs; the fused kernel walks both in order without copying them together, and its output is the same bits as over a full history.

  • A prefill chunk that pushes out keys its own earlier rows attend to is served from a one-off contiguous copy of the held history plus the chunk.

  • The layer’s slidingWindow must not be wider than the cache’s window. MultiHeadAttention checks this on every forward.

  • OwnerReadOnlyKVCache followers work on a ring owner. The write-through sharing variants reject one.

The Gemma and Gemma 3n network builders give every sliding layer that owns its cache a ring of slidingWindow rows. For Gemma 4 E2B (12 sliding and 3 global cache owners, window 512) at a maxInferenceLen of 4096:

Full history With rings

one sliding layer (head dim 256)

8 MiB

1 MiB

one global layer (head dim 512)

16 MiB

16 MiB

all KV buffers

144 MiB

60 MiB

Shared K/V: OwnerReadOnlyKVCache

In Gemma 3n and Gemma 4 the last layers reuse the K/V of the last earlier layer of the same attention type. Such a follower wraps the owner’s PositionalKVCache, discards its own K/V and returns the owner’s rows. It stores nothing and follows the owner’s position.

Compression: TurboQuantKVCache

TurboQuantKVCache stores every row as a TurboQuant block, produced by the engine’s TurboQuantCodec: a seeded random rotation, scalar quantization to 3, 4 or 8 bits per element with one scale per 32 elements, and bit packing.

flowchart LR
    W[new K/V rows] -->|encode once| B[(blocks<br/>per head and position)]
    B -->|decode history| D[float rows<br/>for this attention call]
    D --> A[fused or general attention]
  • Rows are encoded once, on write. Every read decodes the whole history into fresh arrays, the new rows included, so a position gives the same K/V whether it arrived alone or in a chunk.

  • The decoded arrays live for one attention call. One layer’s history is held as floats at a time; all other layers stay compressed.

  • Decoding costs O(position × headDim) per layer and step. The cache trades time for memory.

  • Attention output differs from an uncompressed cache by the codec’s error.

  • It keeps the full history. Sliding layers are better served by the ring.

  • While recording (StableHLO export) nothing is encoded; the graph carries the computed K/V.

TurboQuantKvPreset names three key/value bit budgets. Keys decide where attention looks, so they tolerate less error than values.

Preset Keys Values Size vs floats Same top token as uncompressed

safe-lowbit

8 bit

4 bit

4.5× smaller

47 of 48 steps

balanced

4 bit

4 bit

6.2× smaller

41 of 48 steps

experimental-max

3 bit

3 bit

7.8× smaller

27 of 48 steps

The last two columns were measured on FunctionGemma 270M (head dim 256) over 48 greedy decode steps with only the three global layers compressed; RealGemmaTurboQuantKvTest reproduces them. A small model reacts strongly to K/V error, so measure on your own model before choosing anything below safe-lowbit. TurboQuant KV Cache — Getting Started shows how.

What lives where

The codec (TurboQuantCodec, TurboQuantConfig) is part of the SKaiNET engine. Everything on this page that knows about layers, heads, positions or attention windows is part of SKaiNET-transformers.