KV Cache Memory › Worked Example: Hand-Calculating LLaMA 7B Cache
Language AI HandbookAll chapters KV Cache Memory › Worked Example: Hand-Calculating LLaMA 7B CacheOne section · Sections in this chapter4 / 14 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Working through a concrete numerical example cements the formula and builds the intuition you need to estimate cache sizes quickly. Let us trace through the LLaMA 7B calculation step by step, so that every multiplication corresponds to a specific architectural decision.
LLaMA 7B has the following relevant specifications:
- transformer layers
- key-value heads (standard MHA, no GQA in the original LLaMA 7B)
- head dimension
- Inference in FP16:
Step 1: Memory per element. Each floating-point value in the cache occupies 2 bytes in FP16.
Step 2: Elements per head per token. Each head stores one key vector of length and one value vector of length . That gives elements per head per token.
Step 3: Elements across all heads per token per layer. With heads, one layer stores elements per token.
Step 4: Elements across all layers per token. With layers, each token contributes elements to the cache in total.
Step 5: Bytes per token across all layers. Multiplying by 2 bytes per element:
Step 6: Total cache for a sequence of 4,096 tokens. Multiplying by the sequence length:
Step 7: Sanity check using the simplified MHA formula. Recall that for MHA, . For LLaMA 7B, . Plugging into the simplified formula:
Both paths give the same answer, which is reassuring. At 4K tokens with a batch size of 1 in FP16, LLaMA 7B requires exactly 2 GB for its KV cache. This number is small enough to coexist with the model weights (roughly 14 GB in FP16) on a 24 GB GPU. But it doubles with every doubling of context length, and it multiplies linearly with batch size.
Step 8: Scaling to a different batch size. If we want to serve 8 concurrent requests (batch size 8):
Adding 14 GB for model weights and roughly 2 GB for other overhead, this already approaches the 32 GB limit of an A100 40 GB GPU, leaving only a small safety margin. This calculation, which takes under a minute once you know the formula, determines whether a deployment plan is feasible before you ever touch the hardware.