Algorithm Search⌘K

Data structureadvanced

Key-value cache

Also called KV cache.

Store the attention keys and values of past tokens during decoding, so each new token costs attention time linear in the length, not quadratic.

Time
O(L (n^2 d + n d^2)) generateO(L (n d + d^2)) step
Space
O(L n d g / h) extra
Where
L = the number of layers; d = the model width; g = the number of key-value heads; h = the number of query heads; n = the number of positions so far
Properties
not concurrentnot externalnot persistent

A key-value cache stores, for every layer of a decoder-only transformer and every position generated so far, the key and value vectors that attention computed for that position. With a causal mask, these vectors never change once computed, because a position never attends to later ones. So when the decoder appends a token, it computes the query, key and value of the new position only, appends the key and value to the cache, and attends over the cached keys. A step then costs attention time O(Lnd)O(L n d) for nn cached positions, LL layers and width dd, in place of O(Ln2d)O(L n^2 d) to recompute all positions, and generating nn tokens costs O(Ln2d)O(L n^2 d) attention in total in place of O(Ln3d)O(L n^3 d). The price is memory: 2Lnd2 L n d numbers per sequence, or 2Lndg/h2 L n d g / h with gg key-value heads shared by hh query heads. For long contexts and large batches, the cache, not the weights, fills the accelerator memory.

In plain words

To write the next word, the model looks back at every word so far. For each old word it uses two lists of numbers, a key and a value. These lists depend only on that word and the words before it, so they stay the same as the text grows. Without a cache, the model makes them again for every old word at every step, which wastes most of the work. With a cache, it makes them once, keeps them, and at each step only makes the lists for the new word. The cost is the space to keep them all.

The abstract type

For one sequence, the cache is a list of entries per layer l=1…Ll = 1 \ldots L and per key-value head j=1…gj = 1 \ldots g. Each entry is a pair of vectors (key, value) of size dk=d/hd_k = d / h. The operations are:

  • append(l, keys, values): add the keys and values of the next position to layer ll, one pair per head;
  • keys(l, j) and values(l, j): read all stored keys or values of head jj in layer ll, in position order;
  • length: the number of positions stored;
  • release: free the storage of a finished sequence.

Entries are never changed after they are appended. A serving system also needs truncate, to drop the last entries after a rejected draft in speculative decoding, and fork, to share a prefix between sequences, as in beam search or parallel sampling.

Representation

The simple representation keeps, per layer and head, two growable arrays of vectors (dynamic arrays), or one preallocated tensor of shape L×2×g×nmax⁡×dkL \times 2 \times g \times n_{\max} \times d_k per sequence. The tensor form is fast to read, but it reserves memory for the longest possible sequence, and most of it stays unused.

PagedAttention (Kwon et al. 2023) splits the cache into blocks of bb positions. A pool holds the physical blocks, and a free list holds the free ones. Each sequence has a block table that maps its logical block ⌊i/b⌋\lfloor i / b \rfloor to a physical block, and position ii lives in slot i mod bi \bmod b of that block. A sequence takes a new block only when its last block is full, so it wastes at most b−1b - 1 slots, and a finished sequence returns its blocks to the pool. Sequences can share blocks of a common prefix, with a reference count and copy on write.

Operations

One decoding step of a toy transformer with a cache, for a new token at position pospos:

  1. DECODE-STEP(params, token, pos, cache)
  2. 1x ← embedding(token) + position(pos)
  3. 2for l ← 1 to L do
  4. 3q_1 .. q_h ← split(x W_Q), k_1 .. k_g ← split(x W_K), v_1 .. v_g ← split(x W_V)
  5. 4cache.append(l, k_1 .. k_g, v_1 .. v_g)
  6. 5for each query head i: a_i ← attention(q_i, cache.keys(l, j), cache.values(l, j)) with j = the group of i
  7. 6x ← x + concat(a_1 .. a_h) W_O
  8. 7x ← x + FFN(x)
  9. 8return the logits x E^T ▷ E = the embedding matrix

Here attention(q,K,V)=softmax(qKT/dk)V\text{attention}(q, K, V) = \text{softmax}(q K^T / \sqrt{d_k}) V, and query head ii uses key-value head j=⌊i/(h/g)⌋j = \lfloor i / (h / g) \rfloor (numbering from 0). With g=hg = h this is multi-head attention, with g=1g = 1 multi-query attention, and in between grouped-query attention. The toy network has no layer normalization; adding it changes nothing about the cache. To process a prompt, call DECODE-STEP for each prompt token in order (real systems do the prompt in one parallel pass, which fills the same entries), then generate.

Example

A model has L=2L = 2 layers and h=2h = 2 heads. Generate n=4n = 4 positions, one after the other.

Without a cache, step mm (for m=1…4m = 1 \ldots 4) recomputes all mm positions, and position ii attends to ii keys, so step mm computes 1+2+⋯+m=m(m+1)/21 + 2 + \cdots + m = m(m+1)/2 attention scores per head and layer. The four steps compute 1+3+6+10=20=n(n+1)(n+2)/61 + 3 + 6 + 10 = 20 = n(n+1)(n+2)/6 scores per head and layer, 80 in all.

With a cache, step mm computes the new position only, which attends to mm keys: 1+2+3+4=10=n(n+1)/21 + 2 + 3 + 4 = 10 = n(n+1)/2 scores per head and layer, 40 in all. The test counts these scores and checks that the logits of both ways agree within 10−910^{-9}, for g=hg = h, for g=h/2g = h/2 and for g=1g = 1.

For memory, take L=32L = 32 layers, width d=4096d = 4096, h=32h = 32 heads and a context of n=4096n = 4096 tokens. The cache holds 2×32×4096×4096=10737418242 \times 32 \times 4096 \times 4096 = 1073741824 numbers per sequence, which is 2 GiB at 2 bytes per number. With g=8g = 8 key-value heads it holds a quarter of that, 512 MiB. A batch of 16 such sequences needs 32 GiB with full multi-head attention.

A paged pool with blocks of b=4b = 4 positions and 5 blocks serves a sequence of 6 positions (2 blocks) and one of 5 positions (2 blocks), leaving 1 block free. When the first sequence ends, its 2 blocks return to the pool, and a new sequence of 12 positions takes 3 blocks. A thirteenth position finds no free block, and the allocation fails; a real server would then preempt a sequence.

Correctness

The proof is in proofs/correctness.md. It shows, by induction over the positions and the layers, that the key and value of position ii in layer ll depend only on the tokens 1…i1 \ldots i, because of the causal mask. So the values cached when position ii was new are the values that a full recomputation at any later step would produce, and DECODE-STEP returns the same logits as the full forward pass on the whole prefix. The same argument shows that the paged cache returns the same keys and values as the flat one, since the block table is a bijection from positions to slots. In floating point the two ways can round differently, because the sums may run in a different order; the test allows 10−910^{-9}, and the code sums with math.fsum.

Proof: Cached decoding gives the same logits as recomputationfull

We use the notation of the page and the toy network of DECODE-STEP. Tokens t0,t1,…t_0, t_1, \ldots sit at positions 0,1,…0, 1, \ldots. Let xi(0)=embedding(ti)+position(i)x^{(0)}_i = \text{embedding}(t_i) + \text{position}(i), and for layers l=1…Ll = 1 \ldots L let the full forward pass compute, for every position ii,

ki,j(l)=split(xi(l−1)WK)j,vi,j(l)=split(xi(l−1)WV)j,qi,m(l)=split(xi(l−1)WQ)m,k^{(l)}_{i,j} = \text{split}(x^{(l-1)}_i W_K)_j, \quad v^{(l)}_{i,j} = \text{split}(x^{(l-1)}_i W_V)_j, \quad q^{(l)}_{i,m} = \text{split}(x^{(l-1)}_i W_Q)_m,
ai,m(l)=attention(qi,m(l),(ks,j(l))s≤i,(vs,j(l))s≤i) with j=the group of m,a^{(l)}_{i,m} = \text{attention}\big(q^{(l)}_{i,m}, (k^{(l)}_{s,j})_{s \le i}, (v^{(l)}_{s,j})_{s \le i}\big) \text{ with } j = \text{the group of } m,
yi(l)=xi(l−1)+concat(ai,1(l)…ai,h(l))WO,xi(l)=yi(l)+FFN(yi(l)),y^{(l)}_i = x^{(l-1)}_i + \text{concat}(a^{(l)}_{i,1} \ldots a^{(l)}_{i,h}) W_O, \qquad x^{(l)}_i = y^{(l)}_i + \text{FFN}(y^{(l)}_i),

with the weights of layer ll, and the logits xi(L)ETx^{(L)}_i E^T. The causal mask is the condition s≤is \le i. We assume exact arithmetic.

Lemma 1 (dependence on the prefix). For every layer ll and position ii, the vectors xi(l)x^{(l)}_i, ki,j(l+1)k^{(l+1)}_{i,j} and vi,j(l+1)v^{(l+1)}_{i,j} are functions of t0…tit_0 \ldots t_i alone.

Proof. By induction on ll. For l=0l = 0, xi(0)x^{(0)}_i depends on tit_i and ii only. Suppose the claim holds for l−1l - 1. Then qi,m(l)q^{(l)}_{i,m}, ks,j(l)k^{(l)}_{s,j} and vs,j(l)v^{(l)}_{s,j} for s≤is \le i are functions of t0…tst_0 \ldots t_s, hence of t0…tit_0 \ldots t_i. The attention at position ii reads only positions s≤is \le i, so ai,m(l)a^{(l)}_{i,m}, yi(l)y^{(l)}_i and xi(l)x^{(l)}_i are functions of t0…tit_0 \ldots t_i. The keys and values of layer l+1l + 1 are linear maps of xi(l)x^{(l)}_i. □\square

So appending tokens after position ii never changes the keys and values of position ii; they can be computed once and kept.

Theorem 2 (cached decoding is exact). Call DECODE-STEP on t0,t1,…,tnt_0, t_1, \ldots, t_n in order, at positions 0,1,…,n0, 1, \ldots, n, starting from an empty cache. Then, after the call for position ii, the cache of layer ll and head jj holds exactly k0,j(l)…ki,j(l)k^{(l)}_{0,j} \ldots k^{(l)}_{i,j} and v0,j(l)…vi,j(l)v^{(l)}_{0,j} \ldots v^{(l)}_{i,j} in order, and the call returns xi(L)ETx^{(L)}_i E^T.

Proof. By induction on ii, and inside one call by induction on the layer. Assume that before the call for position ii each layer's cache holds the keys and values of positions 0…i−10 \ldots i - 1 (true for i=0i = 0, where the cache is empty). In the call, line L1 sets x=xi(0)x = x^{(0)}_i. Suppose that at the start of the pass for layer ll we have x=xi(l−1)x = x^{(l-1)}_i. Line L3 computes qi,m(l)q^{(l)}_{i,m}, ki,j(l)k^{(l)}_{i,j} and vi,j(l)v^{(l)}_{i,j} from it, and line L4 appends the last two, so the cache of layer ll now holds positions 0…i0 \ldots i. Line L5 attends with qi,m(l)q^{(l)}_{i,m} over exactly the keys and values of positions s≤is \le i of the group of mm, which is ai,m(l)a^{(l)}_{i,m}. Lines L6 and L7 then give yi(l)y^{(l)}_i and xi(l)x^{(l)}_i. After the last layer, line L8 returns xi(L)ETx^{(L)}_i E^T. The stored entries of positions s<is < i were computed in earlier calls from xs(l−1)x^{(l-1)}_s of those calls, which by the induction hypothesis equal the full pass values; by Lemma 1 these do not depend on the tokens after ss, so they are the values of the full forward pass on t0…tnt_0 \ldots t_n as well. □\square

Corollary 3 (greedy generation). Greedy generation with the cache emits the same tokens as greedy generation that recomputes the full forward pass at every step, when both break ties the same way.

Proof. By Theorem 2 the logits at each step are equal, so the argmax is equal; the next token is then the same, and induction on the steps gives the claim. □\square

Lemma 4 (the paged cache). Let the block table of a sequence hold distinct physical blocks B0,B1,…B_0, B_1, \ldots, and store position pp of a layer in slot p mod bp \bmod b of block B⌊p/b⌋B_{\lfloor p / b \rfloor}. Then reading the positions 0…n−10 \ldots n - 1 through the table returns the entries in the order they were appended, and two live sequences never share a slot.

Proof. The map p↦(⌊p/b⌋,p mod b)p \mapsto (\lfloor p / b \rfloor, p \bmod b) is a bijection from the positions to pairs (block index, slot), with inverse (c,r)↦cb+r(c, r) \mapsto c b + r. The table maps block indices to distinct physical blocks, and a block taken from the free list belongs to no live sequence, since a block returns to the free list only on release. So each position has its own slot, and a read of position pp returns what was written for pp. □\square

With Lemma 4, Theorem 2 holds for the paged cache too, since DECODE-STEP only appends and reads keys and values in position order.

Counting. With the cache, the call for position ii (counting from 1) computes ii scores per query head and layer, so nn positions cost ∑i=1ni=n(n+1)/2\sum_{i=1}^{n} i = n(n+1)/2 per head and layer. Without the cache, step mm recomputes positions 1…m1 \ldots m, which costs m(m+1)/2m(m+1)/2, and ∑m=1nm(m+1)/2=n(n+1)(n+2)/6\sum_{m=1}^{n} m(m+1)/2 = n(n+1)(n+2)/6. For n=4n = 4 these are 10 and 20.

Floating point. The cached pass and the full pass compute each entry by the same operations on the same inputs, so in the code, which sums with math.fsum in a fixed order, they agree; a system that batches the full pass differently may round differently, and its results then agree only to within rounding.

Complexity

Time per step. The projections of line L3 and the feed-forward block of line L7 cost O(d2)O(d^2) per layer for the new position (with a feed-forward width of O(d)O(d)). Attention over nn cached positions costs O(ndk)O(n d_k) per query head for the scores and the same for the weighted sum, O(nd)O(n d) over all heads. So a step costs O(L(nd+d2))O(L (n d + d^2)) in the real RAM, plus O(d∣V∣)O(d |V|) for the logits. Without the cache, a step costs O(L(n2d+nd2))O(L (n^2 d + n d^2)). Over nn steps, the attention scores number Lhn(n+1)/2L h n (n+1)/2 with the cache and Lhn(n+1)(n+2)/6L h n (n+1)(n+2)/6 without it.

Memory. 2Lndg/h2 L n d g / h numbers per sequence: 2 for keys and values, LL layers, nn positions, and gg heads of dk=d/hd_k = d / h numbers. For g=hg = h this is 2Lnd2 L n d. A paged cache with blocks of bb positions uses at most b−1b - 1 extra slots per sequence.

Memory traffic. At small batch sizes, a decoding step reads every weight and every cached entry once for a few operations each, so it is limited by memory bandwidth, not arithmetic (see the roofline model). Shrinking the cache by sharing key-value heads reduces this traffic, which is why multi-query and grouped-query attention speed up decoding in practice, a measurement on the hardware of each paper.

Variants

  • Multi-query and grouped-query attention. Share each key-value head among h/gh / g query heads (Shazeer 2019; Ainslie et al. 2023). The cache shrinks by the factor h/gh / g; whether quality drops is a measurement.
  • Paged cache. Fixed blocks with a block table and a free list (Kwon et al. 2023), with prefix sharing between sequences.
  • Quantized cache. Store keys and values in 8 or fewer bits, with a scale per block or per channel.
  • Sliding window. Keep only the last ww positions, as a ring buffer; the memory is then 2Lwdg/h2 L w d g / h, and the model must have been trained to attend within a window.
  • Eviction. Drop the entries that received little attention so far. This changes the model's output, unlike the exact cache.
  • Prefix cache. Keep the cache of a common prompt, such as a system prompt, and start each request from a copy of it.

When to use it

Use a key-value cache in every autoregressive decoder of a transformer; recomputing the past is never cheaper for more than a few tokens. Choose the representation by the workload: a preallocated tensor for one sequence of known length, a paged pool for a server with many requests of unknown length, and grouped-query attention or quantization when the cache does not fit.

Pitfalls

  • Positions. The new token must get its true position, the number of tokens before it, not 0. With rotary embeddings the cached keys already carry their rotation; do not rotate them again.
  • Stale entries. After a rejected draft in speculative decoding, or after a beam is dropped, truncate the cache to the accepted length. Stale entries silently change the output.
  • Beam search copies. When beams reorder, the cache must follow them. Copying the whole cache at each step is slow; share prefixes with a paged cache.
  • Memory planning. Size the cache for the longest sequence times the batch. Running out of memory in the middle of a batch means preempting a sequence and recomputing its cache later.
  • Masks with padding. In a batch of sequences of different lengths, the attention mask must hide the padding slots of the cache.

Implementations

The code builds a toy transformer with seeded random weights, keeps the cache as plain lists, and tests the cached decoder against recomputation; it takes the weights as given and does not train a network. The paged version keeps a block pool with a free list and a block table per sequence.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

key_value_cache.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/key-value-cache/. The authors are listed in prov/JVESYS.jsonl.

"""A key-value cache for the decoding of a decoder-only transformer.

The network is a toy: seeded random weights, model width d, h query heads,
g key-value heads (g divides h; g = h is multi-head attention, g = 1 is
multi-query attention), L layers, sinusoidal positions, a ReLU feed-forward
block, residual connections and no layer normalization. It is not trained;
it only gives the cache real keys and values to store. Vectors are lists of
floats.
"""

import math
import random
from dataclasses import dataclass, field
from typing import Dict, List, Optional

from nlslog import argmax, softmax

Vec = List[float]
Mat = List[List[float]]


@dataclass
class Layer:
    wq: Mat
    wk: Mat
    wv: Mat
    wo: Mat
    w1: Mat
    w2: Mat


@dataclass
class Params:
    emb: Mat
    layers: List[Layer]
    d: int
    heads: int
    kv_heads: int
    counter: Dict[str, int] = field(default_factory=lambda: {"scores": 0})

    @property
    def d_k(self) -> int:
        return self.d // self.heads


def make_params(seed: int, vocab: int = 7, d: int = 8, heads: int = 2, kv_heads: int = 2, layers: int = 2, d_ff: int = 16) -> Params:
    """Return a toy network with weights drawn from random.Random(seed)."""
    if d % heads or heads % kv_heads:
        raise ValueError("heads must divide d and kv_heads must divide heads")
    rng = random.Random(seed)
    d_k = d // heads

    def mat(rows: int, cols: int) -> Mat:
        return [[rng.gauss(0.0, 1.0 / math.sqrt(rows)) for _ in range(cols)] for _ in range(rows)]

    emb = mat(vocab, d)
    ls = [Layer(mat(d, d), mat(d, kv_heads * d_k), mat(d, kv_heads * d_k), mat(d, d), mat(d, d_ff), mat(d_ff, d)) for _ in range(layers)]
    return Params(emb, ls, d, heads, kv_heads)


def matvec(x: Vec, w: Mat) -> Vec:
    cols = len(w[0])
    return [math.fsum(x[i] * w[i][j] for i in range(len(x))) for j in range(cols)]


def position(pos: int, d: int) -> Vec:
    """The sinusoidal position vector of Vaswani et al. 2017."""
    out = []
    for i in range(d):
        angle = pos / 10000 ** (2 * (i // 2) / d)
        out.append(math.sin(angle) if i % 2 == 0 else math.cos(angle))
    return out


def split(x: Vec, parts: int) -> List[Vec]:
    size = len(x) // parts
    return [x[i * size : (i + 1) * size] for i in range(parts)]


def attend(params: Params, q: Vec, keys: List[Vec], values: List[Vec]) -> Vec:
    """softmax(q K^T / sqrt(d_k)) V for one query."""
    params.counter["scores"] += len(keys)
    scale = math.sqrt(len(q))
    weights = softmax([math.fsum(a * b for a, b in zip(q, k)) / scale for k in keys])
    return [math.fsum(w * v[j] for w, v in zip(weights, values)) for j in range(len(values[0]))]


def ffn(layer: Layer, x: Vec) -> Vec:
    hidden = [max(0.0, v) for v in matvec(x, layer.w1)]
    return matvec(hidden, layer.w2)


class KVCache:
    """The keys and values of the past positions, per layer and per key-value head."""

    def __init__(self, layers: int, kv_heads: int, d_k: int) -> None:
        self.layers, self.kv_heads, self.d_k = layers, kv_heads, d_k
        self.k: List[List[List[Vec]]] = [[[] for _ in range(kv_heads)] for _ in range(layers)]
        self.v: List[List[List[Vec]]] = [[[] for _ in range(kv_heads)] for _ in range(layers)]

    def append(self, layer: int, keys: List[Vec], values: List[Vec]) -> None:
        """Store the key and the value of the next position of layer, one per head."""
        for g in range(self.kv_heads):
            self.k[layer][g].append(keys[g])
            self.v[layer][g].append(values[g])

    def keys(self, layer: int, g: int) -> List[Vec]:
        return self.k[layer][g]

    def values(self, layer: int, g: int) -> List[Vec]:
        return self.v[layer][g]

    def __len__(self) -> int:
        return len(self.k[self.layers - 1][0])

    def num_floats(self) -> int:
        """2 * L * n * g * d_k numbers; with g = h this is 2 * L * n * d."""
        return 2 * self.layers * len(self) * self.kv_heads * self.d_k


def decode_step(params: Params, token: int, pos: int, cache) -> Vec:
    """Run one new token at position pos through the network, using and filling the cache.

    Return the logits of the next token (tied output embedding).
    """
    x = [e + p for e, p in zip(params.emb[token], position(pos, params.d))]  # @line L1
    per_group = params.heads // params.kv_heads
    for l, layer in enumerate(params.layers):  # @line L2
        qs = split(matvec(x, layer.wq), params.heads)  # @line L3
        ks = split(matvec(x, layer.wk), params.kv_heads)
        vs = split(matvec(x, layer.wv), params.kv_heads)
        cache.append(l, ks, vs)  # @line L4
        heads = [attend(params, qs[j], cache.keys(l, j // per_group), cache.values(l, j // per_group)) for j in range(params.heads)]  # @line L5
        x = [a + b for a, b in zip(x, matvec([v for hd in heads for v in hd], layer.wo))]  # @line L6
        x = [a + b for a, b in zip(x, ffn(layer, x))]  # @line L7
    return [math.fsum(a * b for a, b in zip(x, e)) for e in params.emb]  # @line L8


def forward_full(params: Params, tokens: List[int]) -> List[Vec]:
    """Recompute every position from scratch with causal attention; return the logits of each."""
    xs = [[e + p for e, p in zip(params.emb[t], position(i, params.d))] for i, t in enumerate(tokens)]
    per_group = params.heads // params.kv_heads
    for layer in params.layers:
        qs = [split(matvec(x, layer.wq), params.heads) for x in xs]
        ks = [split(matvec(x, layer.wk), params.kv_heads) for x in xs]
        vs = [split(matvec(x, layer.wv), params.kv_heads) for x in xs]
        new = []
        for i, x in enumerate(xs):
            heads = []
            for j in range(params.heads):
                g = j // per_group
                heads.append(attend(params, qs[i][j], [ks[t][g] for t in range(i + 1)], [vs[t][g] for t in range(i + 1)]))
            y = [a + b for a, b in zip(x, matvec([v for hd in heads for v in hd], layer.wo))]
            new.append([a + b for a, b in zip(y, ffn(layer, y))])
        xs = new
    return [[math.fsum(a * b for a, b in zip(x, e)) for e in params.emb] for x in xs]


def generate(params: Params, prompt: List[int], steps: int, use_cache: bool = True, cache=None) -> List[int]:
    """Greedy generation of steps new tokens, with the cache or by recomputing each time."""
    tokens = list(prompt)
    if not use_cache:
        for _ in range(steps):
            tokens.append(argmax(forward_full(params, tokens)[-1]))
        return tokens
    if cache is None:
        cache = KVCache(len(params.layers), params.kv_heads, params.d_k)
    logits: Optional[Vec] = None
    for i, t in enumerate(tokens):
        logits = decode_step(params, t, i, cache)
    for s in range(steps):
        tokens.append(argmax(logits))
        if s + 1 < steps:
            logits = decode_step(params, tokens[-1], len(tokens) - 1, cache)
    return tokens


def cache_numbers(layers: int, n: int, d: int, heads: int, kv_heads: int) -> int:
    """The number of stored numbers for one sequence: 2 * layers * n * d * kv_heads / heads."""
    return 2 * layers * n * d * kv_heads // heads


class BlockPool:
    """Fixed size blocks shared by many sequences, as in PagedAttention (Kwon et al. 2023)."""

    def __init__(self, layers: int, kv_heads: int, d_k: int, block_size: int, num_blocks: int) -> None:
        self.layers, self.kv_heads, self.d_k, self.block_size = layers, kv_heads, d_k, block_size
        self.store = [[[[None] * block_size for _ in range(kv_heads)] for _ in range(layers)] for _ in range(num_blocks)]
        self.free = list(range(num_blocks - 1, -1, -1))

    def new_sequence(self) -> "PagedSequence":
        return PagedSequence(self)


class PagedSequence:
    """The cache of one sequence: a block table that maps position // block_size to a block."""

    def __init__(self, pool: BlockPool) -> None:
        self.pool = pool
        self.table: List[int] = []
        self.lengths = [0] * pool.layers

    def append(self, layer: int, keys: List[Vec], values: List[Vec]) -> None:
        pos = self.lengths[layer]
        b = pos // self.pool.block_size
        if b == len(self.table):
            if not self.pool.free:
                raise MemoryError("no free block")
            self.table.append(self.pool.free.pop())
        block = self.pool.store[self.table[b]]
        for g in range(self.pool.kv_heads):
            block[layer][g][pos % self.pool.block_size] = (keys[g], values[g])
        self.lengths[layer] = pos + 1

    def _entries(self, layer: int, g: int):
        bs = self.pool.block_size
        return [self.pool.store[self.table[p // bs]][layer][g][p % bs] for p in range(self.lengths[layer])]

    def keys(self, layer: int, g: int) -> List[Vec]:
        return [kv[0] for kv in self._entries(layer, g)]

    def values(self, layer: int, g: int) -> List[Vec]:
        return [kv[1] for kv in self._entries(layer, g)]

    def __len__(self) -> int:
        return self.lengths[-1]

    def release(self) -> None:
        """Give every block of the sequence back to the pool."""
        for b in reversed(self.table):
            for layer in self.pool.store[b]:
                for slots in layer:
                    for i in range(len(slots)):
                        slots[i] = None
            self.pool.free.append(b)
        self.table = []
        self.lengths = [0] * self.pool.layers
nlslog.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Log-space arithmetic and semirings for the natural-language-and-speech pages.

Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.

The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:

    PROB      probabilities         plus = +        times = *   zero = 0       one = 1
    LOG       log probabilities     plus = log_add  times = +   zero = -inf    one = 0
    VITERBI   log probabilities     plus = max      times = +   zero = -inf    one = 0
    TROPICAL  costs -log p          plus = min      times = +   zero = +inf    one = 0
    LOG_COST  costs -log p          plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
    BOOLEAN   truth values          plus = or       times = and zero = False   one = True
    COUNTING  path counts           plus = +        times = *   zero = 0       one = 1

This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""

import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence

NEG_INF = float("-inf")
POS_INF = float("inf")


def safe_log(p) -> float:
    """Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
    if p < 0:
        raise ValueError("log of a negative number")
    if p == 0:
        return NEG_INF
    return math.log(p)


def log_add(a: float, b: float) -> float:
    """Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).

    log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
    """
    if a < b:
        a, b = b, a
    if b == NEG_INF or a == POS_INF:
        return a
    return a + math.log1p(math.exp(b - a))


def log_sum(xs: Iterable[float]) -> float:
    """Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
    xs = list(xs)
    if not xs:
        return NEG_INF
    m = max(xs)
    if m == NEG_INF or m == POS_INF:
        return m
    return m + math.log(math.fsum(math.exp(x - m) for x in xs))


def log_normalize(xs: Sequence[float]) -> List[float]:
    """Return the list x - log_sum(xs): log values whose exps sum to 1.

    Raise ValueError if every value is NEG_INF (nothing to normalize).
    """
    z = log_sum(xs)
    if z == NEG_INF:
        raise ValueError("every weight is zero")
    return [x - z for x in xs]


def log_softmax(xs: Sequence[float]) -> List[float]:
    """Return log softmax(xs): the logits xs turned into log probabilities."""
    return log_normalize(xs)


def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
    """Return the probabilities exp(x / temperature) / sum, computed stably.

    The temperature must be positive. Logits of NEG_INF get probability 0.
    """
    if not temperature > 0:
        raise ValueError("the temperature must be positive")
    m = max(xs)
    if m == NEG_INF:
        raise ValueError("every logit is -inf")
    es = [math.exp((x - m) / temperature) for x in xs]
    s = math.fsum(es)
    return [e / s for e in es]


def argmax(xs: Sequence[Any]) -> int:
    """Return the first index of a largest value. Raise ValueError if xs is empty."""
    if len(xs) == 0:
        raise ValueError("argmax of an empty sequence")
    best = 0
    for i in range(1, len(xs)):
        if xs[i] > xs[best]:
            best = i
    return best


@dataclass(frozen=True)
class Semiring:
    """A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""

    name: str
    plus: Callable[[Any, Any], Any]
    times: Callable[[Any, Any], Any]
    zero: Any
    one: Any
    idempotent: bool


def _add(a, b):
    return a + b


def _mul(a, b):
    return a * b


def _log_add_cost(a: float, b: float) -> float:
    return -log_add(-a, -b)


PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)


def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring sum of xs, and sr.zero for an empty input."""
    acc = sr.zero
    for x in xs:
        acc = sr.plus(acc, x)
    return acc


def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring product of xs, and sr.one for an empty input."""
    acc = sr.one
    for x in xs:
        acc = sr.times(acc, x)
    return acc
test_key_value_cache.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/key-value-cache/. The authors are listed in prov/JVESYS.jsonl.

import copy
import math
import random

import pytest

from key_value_cache import (
    BlockPool,
    KVCache,
    cache_numbers,
    decode_step,
    forward_full,
    generate,
    make_params,
)

SHAPES = [(8, 2, 2), (8, 4, 2), (8, 4, 1)]  # (d, heads, kv_heads)


def close(a, b, tol=1e-9):
    return all(abs(x - y) <= tol for x, y in zip(a, b)) and len(a) == len(b)


def test_cached_logits_equal_recomputation() -> None:
    for seed in range(4):
        for d, h, g in SHAPES:
            params = make_params(seed, d=d, heads=h, kv_heads=g)
            rng = random.Random(seed)
            tokens = [rng.randrange(7) for _ in range(7)]
            full = forward_full(params, tokens)
            cache = KVCache(2, g, d // h)
            for i, t in enumerate(tokens):
                assert close(decode_step(params, t, i, cache), full[i])
            assert len(cache) == len(tokens)


def test_greedy_generation_is_the_same() -> None:
    for seed in range(3):
        params = make_params(seed, heads=4, kv_heads=2)
        with_cache = generate(params, [1, 2], 6, use_cache=True)
        without = generate(params, [1, 2], 6, use_cache=False)
        assert with_cache == without
        assert len(with_cache) == 8


def test_past_entries_never_change() -> None:
    params = make_params(5)
    cache = KVCache(2, 2, 4)
    snapshots = []
    for i, t in enumerate([3, 1, 4, 1, 5, 2]):
        decode_step(params, t, i, cache)
        snapshots.append(copy.deepcopy(cache.k))
    last = cache.k
    for i, snap in enumerate(snapshots):
        for layer in range(2):
            for g in range(2):
                assert last[layer][g][: i + 1] == snap[layer][g]


def test_score_counts() -> None:
    params = make_params(1, heads=2, kv_heads=2, layers=2)
    n = 4
    # Generating n tokens after a prompt of one token runs positions 0 to n - 1.
    params.counter["scores"] = 0
    generate(params, [0], n, use_cache=True)
    assert params.counter["scores"] == 2 * 2 * n * (n + 1) // 2
    params.counter["scores"] = 0
    generate(params, [0], n, use_cache=False)
    assert params.counter["scores"] == 2 * 2 * n * (n + 1) * (n + 2) // 6
    params.counter["scores"] = 0
    cache = KVCache(2, 2, 4)
    for i, t in enumerate([0, 3, 2, 6]):
        decode_step(params, t, i, cache)
    assert params.counter["scores"] == 2 * 2 * n * (n + 1) // 2  # 10 per head and layer
    params.counter["scores"] = 0
    for m in range(1, n + 1):
        forward_full(params, [0, 3, 2, 6][:m])
    assert params.counter["scores"] == 2 * 2 * n * (n + 1) * (n + 2) // 6  # 20 per head and layer


def test_memory_formula() -> None:
    for d, h, g in SHAPES:
        params = make_params(2, d=d, heads=h, kv_heads=g, layers=3)
        cache = KVCache(3, g, d // h)
        for i, t in enumerate([1, 2, 3, 4, 5]):
            decode_step(params, t, i, cache)
        stored = sum(len(v) for layer in cache.k + cache.v for head in layer for v in head)
        assert stored == cache.num_floats() == cache_numbers(3, 5, d, h, g)
        if g == h:
            assert cache.num_floats() == 2 * 3 * 5 * d
    full = cache_numbers(32, 4096, 4096, 32, 32)
    assert full == 1073741824
    assert full * 2 == 2 * 1024**3
    assert cache_numbers(32, 4096, 4096, 32, 8) * 4 == full


def test_paged_cache_matches_and_reuses_blocks() -> None:
    params = make_params(3, heads=4, kv_heads=2)
    pool = BlockPool(2, 2, 2, block_size=4, num_blocks=5)
    a, b = pool.new_sequence(), pool.new_sequence()
    ta, tb = [1, 2, 3, 4, 5, 6], [6, 5, 4, 3, 2]
    fa, fb = forward_full(params, ta), forward_full(params, tb)
    for i in range(6):
        assert close(decode_step(params, ta[i], i, a), fa[i])
        if i < 5:
            assert close(decode_step(params, tb[i], i, b), fb[i])
    assert len(a.table) == math.ceil(6 / 4) and len(b.table) == math.ceil(5 / 4)
    assert len(pool.free) == 1
    a.release()
    assert len(pool.free) == 3
    c = pool.new_sequence()
    tc = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
    fc = forward_full(params, tc)
    for i, t in enumerate(tc):
        assert close(decode_step(params, t, i, c), fc[i])
    assert len(c.table) == 3 and not pool.free
    with pytest.raises(MemoryError):
        decode_step(params, 1, 12, c)

History

Incremental decoding with stored keys and values goes back to the first transformer implementations, since the causal mask of Vaswani et al. 2017 makes the past keys and values fixed. Shazeer 2019 analyzed its memory traffic and proposed multi-query attention to shrink it, and Ainslie et al. 2023 proposed grouped-query attention as a middle ground. Kwon et al. 2023 brought paging from operating systems to the cache with PagedAttention, in the vLLM serving system.

References

  1. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin, Attention is all you need, NIPS 2017, the decoder with masked self-attention, which makes the keys and values of past positions independent of later tokens
  2. Noam Shazeer, Fast transformer decoding, one write-head is all you need, arXiv 1911.02150, 2019, incremental decoding with stored keys and values, its memory traffic, and multi-query attention
  3. Joshua Ainslie, James Lee-Thorp, Michiel de Jong, Yury Zemlyanskiy, Federico Lebrón and Sumit Sanghai, GQA, training generalized multi-query transformer models from multi-head checkpoints, EMNLP 2023, pages 4895 to 4901, grouped-query attention, with g key-value heads shared by groups of query heads
  4. Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, Lianmin Zheng, Cody Hao Yu, Joseph E. Gonzalez, Hao Zhang and Ion Stoica, Efficient memory management for large language model serving with PagedAttention, SOSP 2023, the block table that maps the logical blocks of a sequence to physical blocks of fixed size

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.generate
  • a full proof of time.step
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/JVESYS/text.yaml