Caching Trades Recalculation for Growing Memory

Compare repeated full-prefix decoding with KV-cached decoding without confusing asymptotic work, implementation overhead, and measured latency. Calculate linear cache-memory growth and state the limits of toy evidence.

Without a cache, each generation step runs the complete growing prefix through every decoder block again. With a cache, each new token reuses earlier keys and values and runs only its own residual path through the blocks.

Calculate Cache Memory

For standard multi-head attention:

NKV=2LBhTdhN_{KV}=2LBhTd_h

stored scalars. The factor 2 represents keys and values.

For the frozen model at B=1B=1, L=2L=2, h=2h=2, and dh=2d_h=2:

NKV=16T.N_{KV}=16T.

At T=4T=4, this is 64 scalars or 64(4)=25664(4)=256 bytes in float32.

Cached lengthScalarsFloat32 payload bytes
11664
232128
348192
464256

These numbers exclude tensor metadata, allocator overhead, model weights, temporary scores, activations for the current token, and framework state.

State What Work Remains

At decode length TT, each new query still compares with TT keys and mixes TT values. Dense cached attention therefore grows linearly per new token. Across a generated sequence, that attention work remains quadratic in total length.

Caching avoids recomputing previous tokens' projections, MLPs, normalizations, and residual updates at every generation step. Under a simple dense-operation count, repeatedly running the full growing sequence incurs cubic total attention work, while cached one-row decode reduces that repeated part to quadratic. Actual latency also depends on kernels, memory bandwidth, batch, hardware, and framework overhead.

Q1. Calculate cache payload

For B=2B=2, L=3L=3, h=4h=4, T=10T=10, dh=8d_h=8, and float16 storage, calculate KV scalars and payload bytes.

Answer it first, then check.

Hint
Use 2LBhTdh2LBhTd_h and multiply by 2 bytes.
Solution
2(3)(2)(4)(10)(8)=38402(3)(2)(4)(10)(8)=3840 scalars and 76807680 bytes.
Not attempted
Review

Not marked done.

Research Boundary

That work analyzes and measures specified large models on TPU v4 systems. It supports careful inference trade-off analysis; its latency and utilization numbers do not describe this tiny CPU Python implementation.

Pause and reflect

In your own words, note what you understood, what remains unclear, or what you want to revisit. The note stays with this lesson.

0 of 1 exercises marked done

Review

Not marked done.

LLM PrimerCaching Trades Recalculation for Growing Memoryhttps://llmprimer.com/transformers/autoregressive-generation-and-efficient-inference/caching-trades-recalculation-for-growing-memory© 2026 LLM Primer