1 of 4

Your RightSignal

How LLMs work · 9 of 141 / 3

KV cache

The concept

Why doesn't a chatbot reread the whole chat for every new word?

A model writes one token at a time, and each new token attends to every token before it. A KV cache stores the keys and values already computed for earlier tokens, so each step computes them only for the newest one.

Take a 1,000-token chat. Without a cache, writing token 1,001 means rerunning all 1,001 tokens through every layer. With one, only the new token runs; its query meets the 1,000 stored keys and mixes their values.

The price is memory. For every token, every layer keeps one key vector and one value vector, so the cache grows in a straight line as the chat gets longer.

What it’s forEstimates how much memory the KV cache needs (the 2 is one key plus one value per token per layer).

size = 2 × L × d × n × b

L
number of layers, e.g. 32
d
length of each key or value vector per layer, e.g. 4,096
n
number of tokens in the conversation so far
b
bytes per number, e.g. 2 for 16-bit numbers

What it givesThe bytes of memory one conversation's cache takes up.

  1. Per token: 2 × 32 × 4,096 × 2 = 524,288 bytes = 0.5 MiB
  2. 4,000 tokens: 4,000 × 0.5 MiB = 2,000 MiB ≈ 2 GiB