Open Agent School · Public worked example

KV Cache: meaning and example

Welcome! Take one idea with you today.

A key-value (KV) cache holds intermediate attention tensors for tokens a model has already processed. Keys help a new query locate earlier information; values supply the information to mix. During ordinary causal generation, earlier keys and values can be reused instead of recomputed at every step. They are numerical state, not a dictionary of remembered answers.

Picture it: An invented tailoring assistant serves two conversations, each with 1,024 cached tokens. Its fictional architecture has 32 layers and eight key/value heads of width 128, stored in two-byte elements. You must decide whether doubling conversation length is a harmless change or doubles this part of the memory bill.

What is easy to mix up?

KV state supports attention computation. Exact-prefix prompt caching may reuse compatible state across requests; semantic caching instead reuses a stored answer. These have different correctness and permission boundaries.

Teaching example by Open Agent School. Source: Hugging Face Transformers - How caching works.