A key-value (KV) cache stores attention key and value vectors during autoregressive generation. Reusing these vectors avoids recomputing the attention context for earlier tokens each time the model generates a new token. section 9.3
At each generation step:
- Compute the query and the key-value pair for the new token. section 9.3
- Append the new key-value pair to the cache and reuse stored pairs from earlier tokens. section 9.3
Figure 9.4 At each step, the query is computed for the new token, while past key and value vectors are cached and reused. This avoids recomputation of the entire attention context, dramatically reducing inference time.
Follow how the query is recomputed while cached keys and values are reused across generation steps. section 9.3
The speedup costs memory: the cache grows with sequence length and the number of transformer layers. Long contexts and large batch sizes can make its memory consumption substantial. Production deployments need careful cache management, including invalidation and opportunities for reuse. section 3.2 section 9.3
Benchmarking generation
A Hugging Face Transformers benchmark generates 256 tokens with Llama 3.2 3B Instruct, comparing model.generate with use_cache enabled and disabled. The reported run took about 8.5 seconds with caching and 17.7 seconds without it. These timings illustrate the trade-off for that benchmark, not a universal speedup. section 9.3
Listing 9.1 Transformer inference with and without KV cache
model_id = "meta-llama/Llama-3.2-3B-Instruct"
device = "cuda" if torch.cuda.is_available() else "cpu"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id).to(device)
model.eval()
prompt = "Why are autoregressive models faster with KV cache?"
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
def measure_inference(use_cache=True, runs=1, max_new_tokens=256): #1
durations = []
for _ in range(runs):
torch.cuda.empty_cache()
start = time.time()
_ = model.generate(input_ids=input_ids,
use_cache=use_cache,
max_new_tokens=max_new_tokens,
do_sample=False) #2
durations.append(time.time() - start) #3
return durations
with_cache = measure_inference(use_cache=True) #4
without_cache = measure_inference(use_cache=False)
print(f"With KV cache: avg = {sum(with_cache)/len(with_cache):.2f}s")
print(f"Without KV cache: avg = {sum(without_cache)/
len(without_cache):.2f}s")
Inspect the benchmark’s use_cache setting and timing loop to compare cached and uncached generation. section 9.3

