Build a KV Cache

The fastest way to trust a mechanism is to drive it yourself. This lesson upgrades the loop from the generation-loop lesson 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 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 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 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 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.