---
title: "Build a KV Cache"
description: "Upgrade a generation loop to the cached form every serving system runs, inspect the KV cache tensors and their shapes, and prove the output is unchanged."
canonical_url: "https://fanout.sh/inference-eng/curriculum/03-04"
md_url: "https://fanout.sh/inference-eng/curriculum/03-04.md"
last_updated: "2026-11-11"
access: "public"
---

# Build a KV Cache

Upgrade a generation loop to the cached form every serving system runs, inspect the KV cache tensors and their shapes, and prove the output is unchanged.

The fastest way to trust a mechanism is to drive it yourself. This lesson upgrades the loop from [the generation-loop lesson](/inference-eng/curriculum/02-05) to the cached form every serving system runs, inspects the cache as a live object with real shapes, and proves the upgrade changes the work without changing a single character of output.

## The cache as an object

Ask the model to keep its cache and it returns the object:

Every axis of that shape is something you already know. One batch; 8 KV heads, the grouped-query groups from [the transformer architecture refresher](/inference-eng/curriculum/00-06) in the flesh; 6 positions, one per prompt token with BOS included, because this single prefill pass filled the cache; 128 dims per head. One such tensor for keys and one for values, per layer, 32 layers: the keys and values the lesson on [causal attention](/inference-eng/curriculum/02-02) showed every future step needs from the past, stored instead of recomputed.

## The cached loop

The upgrade to the loop from [the generation-loop lesson](/inference-eng/curriculum/02-05) is three changes: track a cache between trips, branch the forward call, and feed only the newest token plus the cache.

The first branch runs the prefill the lesson on prefill measurement measured: whole prompt in, cache primed. Every later trip is the decode from decode measurement: seq[:, -1:] hands the model exactly one token, past_key_values hands it everything else, and the returned cache has grown by one position. The model's own generate() has run this exact division since running your first LLM; use_cache=True is its default, which means the black box you opened was already built right.

**Inspect this.** Print past.layers[0].keys.shape inside the loop: [1, 8, 6, 128] after prefill, then 7, 8, 9 as decode steps append. The growing third axis is the module's whole subject made visible.

The output is character-identical to the uncached loop's, and [the recomputation lesson](/inference-eng/curriculum/03-01) already measured what the identity cost: nothing. It saved the triangle. The new bill is memory, and who holds that bill, and how much of the GPU it claims, is where the module turns next.

---
This representation contains public Fanout content only. Protected Pro lessons, account data, billing, checkout, and pricing are not included.

Browse the public content map: https://fanout.sh/sitemap.md
