Production engineering · about 20 minutes of study

KV cache

A KV cache stores attention keys and values from previous tokens so decoding need not recompute them for each new token. Its memory grows with workload and model architecture.

Before you start: Review Token cost first. Python-like examples use variables, lists and functions.

Guided concept walkthrough

Follow the mechanism

Prefill

Compute keys and values for input tokens.

1 / 4

A conceptual animation, not a live model trace. Play advances every five seconds and stops at the final stage.

Start with an everyday explanation

Keep earlier calculations on a scratchpad instead of recalculating every line. More simultaneous students and longer worksheets need more scratch space.

See a concrete example

For 32 layers, 32 KV heads, head dimension 128, 4,096 tokens, batch 1 and 2-byte elements, cache size is 2,147,483,648 bytes = 2 GiB. Eight KV heads under the same assumptions use 0.5 GiB.

A claim to question

KV memory is not a universal 0.5 MB per token, and weight size alone cannot establish GPU fit.

Try before revealing the answer

Use the GPU calculator to change KV heads from 32 to 8 and batch from 1 to 4.

Show the worked answer

Heads divided by four reduce the simplified cache fourfold; batch multiplied by four restores the original cache total. Add weights and measured runtime overhead before judging capacity.

Now explain the idea to someone else using your own example. If you cannot explain a stage, revisit it before moving on.

Your explanation and revision notes

Loading local notes…

Read the primary reference

KV cache strategies

Grouped-query attention

The explanation and exercises are original teaching material. The linked source provides background; examples and assumed numbers here are not claims about a particular company.