Trace cache growth, calculate its memory cost, and distinguish exact reuse from approximations.
Preparation: Queries, keys and values; causal masks; multiplication and units.
Plan 25–40 minutes with the activities; this is a study estimate, not a timed requirement. Both paths have complete narration. Your notes and progress are kept separately for each level.
FULL LOCAL NARRATION
Follow the complete explanation.
Narration includes worked solutions. Pause at each practice prompt before continuing. Formula notation has a spoken explanation; all teaching text remains readable.
College path. Trace cache growth, calculate its memory cost, and distinguish exact reuse from approximations. Preparation: Queries, keys and values; causal masks; multiplication and units. Move between Signal Room, Workbench and Field Notes without losing your section. Pause before each worked solution.
Imagine completing a sentence one piece at a time. A causal Transformer cannot let an earlier position inspect a later token. With the same model and prefix, adding a token therefore does not change the earlier positions’ representations. Their keys and values can be kept for the next step. The new token brings a new query, key and value. Its query reads the stored information. A cache is saved intermediate computation, not a permanent knowledge base, a summary of the conversation, or a record of the model’s private reasoning. The distinction matters when deciding what can safely be reused.
At layer l, append k_t = h_t W_K and v_t = h_t W_V to K_<t and V_<t. Evaluate the new query against the allowed cached positions plus its own position. Cache entries are layer-specific. Exact reuse assumes unchanged weights, prefix tokens, positions, masking and deterministic inference semantics; floating-point implementations can still differ slightly. Bidirectional attention generally lacks this append-invariance because adding context can change earlier states.
Worked example. After processing four tokens, each layer has four key rows and four value rows. Processing the fifth adds one row to each cache. Earlier queries are not needed to compute the fifth token’s attention output. If a word near the beginning changes, later cached states may depend on the old word and cannot simply be kept.
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. You replace token two in a five-token prefix. Is keeping the cache for tokens three through five valid?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
Generally no. Their causal representations can depend on token two. Reuse only a verified unchanged prefix under compatible model settings, then recompute the changed suffix.
Section 02 / 07
Prefill, decode and the work that remains
Prefill reads the supplied prompt and constructs its cache. Decode extends the sequence one generated token at a time. Caching prevents repeatedly rebuilding keys and values for the entire prefix. It does not remove the new token’s attention over that prefix, the feed-forward work, or the output prediction. Reading a growing cache can become a bandwidth cost. When comparing two systems, separate the wait for the first output token from the time between later tokens. A fast first response and a fast stream are related but different user experiences.
For ordinary full attention, a decode query attends over N positions, so its attention work grows with N. Across a growing sequence, those interactions still accumulate quadratically. Prefill can process many positions in parallel using a causal mask; decode has a dependency between successive outputs. Operation counts alone cannot predict latency because batch size, kernel implementation and memory movement matter.
Worked example. For prefixes of lengths four, five and six, a naive full-prefix rerun constructs fifteen token positions’ keys and values in total. An incremental path constructs four initially, then one, then one: six. This toy count isolates cache construction; it does not count every attention operation or prove a two-and-a-half-fold wall-clock speedup.
Toy construction counts: 4 + 5 + 6 = 15; cached = 4 + 1 + 1 = 6
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. Does caching make attention to a million previous tokens free?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
No. Exact full attention must still read and combine the allowed stored entries for each new query. Caching removes repeated construction, not all use of the stored information.
Section 03 / 07
Count the bytes before making a hardware claim
A memory budget needs units and dimensions. Count two arrays, one for keys and one for values, then multiply by layers, requests, tokens, key-value heads, head width and bytes per number. In this lesson the key and value widths are equal and every request has the same length. This deliberately simple estimate excludes model weights, temporary tensors, allocation gaps and metadata. It tells you the payload of one kind of cache, not the total memory required to serve a model. Decimal gigabytes and binary gibibytes are different units.
For an uncompressed dense cache, M = 2 L B N H_KV d b bytes. A common per-layer layout is B by H_KV by N by d for each of K and V. Different architectures need a different formula: latent caches, unequal dimensions, sliding windows and cross-layer sharing change the count. Quantized storage also needs scales and sometimes zero points. State assumptions before substituting numbers.
Worked example. Use thirty-two layers, one request, 4,096 tokens, eight key-value heads, width 128 and two bytes per number. Multiplication gives 536,870,912 bytes: 512 mebibytes, or half a gibibyte. Four independent requests need two gibibytes of this payload. In Workbench, doubling tokens or requests doubles the displayed cache count.
M_bytes = 2 × L × B × N × H_KV × d × b
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. If weights occupy eight gibibytes and the estimated cache is two, is ten gibibytes necessarily enough?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
No. Ten is only the sum of those two components. Temporary activations, runtime buffers, fragmentation and other allocations require additional capacity.
Section 04 / 07
Share heads without confusing their questions
Multi-head attention lets several queries examine a token sequence. In ordinary multi-head attention, each query head has its own key-value head. Multi-query attention shares one key-value head among many query heads. Grouped-query attention lies between those choices: groups of queries share keys and values. Fewer stored key-value heads reduce cache payload. They do not mean that every query or output is identical. Changing a trained architecture requires an appropriate model or adaptation; it is not safe to delete heads from a checkpoint and assume the original behavior survives.
For thirty-two query heads and eight key-value heads, four query heads share each key-value head. Holding L, B, N, d and b fixed, the cache ratio relative to thirty-two key-value heads is eight over thirty-two. The attention score shape still includes the query-head count. GQA addresses head sharing, while sparse attention addresses which sequence entries are read; these are distinct design axes.
Worked example. With the previous dimensions, thirty-two key-value heads require two gibibytes for one 4,096-token request. Eight heads require half a gibibyte. One head requires one sixteenth of a gibibyte. These payload calculations are exact under our assumptions, but they do not tell us which model gives the best answers.
Queries per KV head = H_Q / H_KV = 32 / 8 = 4
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. A model has thirty-two query heads and eight key-value heads. How many query heads share each cache head?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
Four. Divide thirty-two by eight. Do not divide the token count or assume that the four queries become the same vector.
Section 05 / 07
Reuse prefixes and manage physical space
Two requests may begin with the same instructions or document. A serving system can reuse a compatible cached prefix rather than compute and store it twice. Similar meaning is not enough: the relevant token prefix and model state must match. Paging is another idea. It divides storage into blocks so growing requests do not each need one large contiguous reservation. Paging changes allocation; it does not by itself compress the numbers. Shared blocks must be treated carefully when requests diverge, so one request cannot overwrite another’s prefix.
With block size S, an unshared sequence of N tokens uses ceil(N/S) blocks, leaving fewer than S unused token slots in the final block. Prefix-sharing systems can use reference counts and copy-on-write. Exact matching must include model/adapters and position semantics, and caches must respect isolation between users. PagedAttention separates logical token order from physical block placement; the mathematical attention result need not change just because storage is paged.
Worked example. A seventeen-token sequence stored in blocks of eight needs three blocks, providing twenty-four slots. Seven are unused. Two requests that share sixteen prefix tokens can share two full blocks if the implementation supports safe reuse. Their divergent suffixes need separate storage. A high hit rate helps only if lookup and management costs do not erase the benefit.
Blocks = ceil(N / S); unused slots = S × ceil(N / S) − N
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. Does reducing wasted allocation prove that the number of bits per cached value decreased?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
No. Allocation waste and numerical precision are separate quantities. Paging can save reserved capacity while every stored value retains the same precision.
Section 06 / 07
Compression, eviction and approximation
A cache can be made smaller by storing fewer bits, keeping fewer positions, sharing representations or moving data to slower memory. Each method has a different tradeoff. Quantization changes numerical precision. A sliding window limits local context. Offloading keeps data elsewhere but adds transfer time. Evicting an entry from a full-attention model can change its output unless it is reconstructed or the model was designed for that policy. The DeepSeek case study combines several methods; its global-cache number should not be substituted into our dense-cache formula without understanding the layout.
Distinguish exact storage transformations from approximations to model state. A block allocator can preserve exact values, whereas lossy quantization changes them. A model trained with sliding-window attention has different allowed dependencies from an otherwise identical full-attention model with arbitrary eviction. Bounded replay in the case study reconstructs approximate local states; validate cache-resumption boundaries rather than claiming mathematical equivalence.
Worked example. Sixteen values at four bits use sixty-four bits. If that group needs one eight-bit scale, the total is seventy-two bits, or nine bytes. The effective payload is four-and-a-half bits per value before alignment. A naive four-bit-only calculation would undercount. This is an illustrative group layout, not a universal quantization format.
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. A cache is half the size after quantization. What else should you measure?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
Measure task quality, numerical error where appropriate, encoding and decoding overhead, actual memory use and latency. Smaller storage is useful evidence, but not a complete evaluation.
Section 07 / 07
Design a cache experiment you can defend
Begin with a claim narrow enough to test. For example, keeping the model, prompts and hardware fixed, does a cache policy reduce memory without harming answers on long documents? Test both cold requests and requests with a reusable prefix. Record prompt length, concurrent requests, precision and whether generated tokens are included in the cache count. Test a changed prefix to catch invalid reuse. Include a distant fact that the model must recover. Keep your prediction in Workbench, then explain what the byte calculator can and cannot establish.
Check cached versus uncached logits under compatible settings with an explicit numerical tolerance, then run task-level evaluations. Report peak allocated and reserved memory separately if the runtime exposes them. Measure time to first token, inter-token latency and throughput, including tail behavior under load. A synthetic payload estimate is a baseline for reasoning, not a substitute for measuring the serving system.
Worked example. In Workbench use 4,096 tokens, one request, eight cache heads and two bytes. Save the half-gibibyte result. Change requests to four and predict two gibibytes before moving the slider. Then halve the head count and explain why the payload halves again. None of these changes predicts answer quality because the calculator does not run a trained model.
Cache estimate + measured overhead + model weights = a fuller memory budget
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. State one conclusion your saved experiment supports and one it cannot support.
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
It supports the linear byte scaling implied by the stated dense-cache dimensions. It cannot establish model quality, real latency or whether a specific device has enough total memory.
Final checkpoint. Which change doubles the dense payload 2 L B N H_KV d b, holding all other factors fixed? Option 1: Doubling query heads while keeping KV heads fixed. Option 2: Doubling concurrent independent requests. Option 3: Doubling the vocabulary alone.
Pause and choose an answer before continuing.
Reveal worked solution
Option 2 is correct. B is a multiplicative factor in this payload estimate. Query-head and vocabulary counts do not appear directly.
WORKBENCH / PREDICT → TEST → EXPLAIN
Inspect exact numerical data
These are computed teaching fixtures. No remote AI model or GPU is called by the experiment.
CHECK YOUR UNDERSTANDING
Commit to an explanation.
Keep your learning record.
LONGER ATTENTION LESSONS
Follow the mechanism in depth
Worked examples, local narration and connected learning modes at your level.
Original worked examples and teaching text, grounded in these primary references. Numerical fixtures explain mechanisms; model quality and hardware performance require separate measurements. Both levels share key examples, with different explanations and checkpoints.
Separate permanent weights from conversation state, and connect memory use to time.
Additional reading · original lesson audio remains unchanged.
Read the full explanation · 579 words + college extension
Two kinds of stored information
WeightsSame learned settings
▪ ▪ ▪ ▪ ▪ ▪
Sequence stateChanges as tokens arrive
▪ ▪ ▪ +
A new token reuses cached keys and values; reading that state still costs time and memory.
Weights: learned settings
Prompt: prefill
KV: retained state
New token: decode
Weights: learned settings
The workshop and the work in progress
A useful way to distinguish model weights from a cache is to imagine a workshop. The tools and their settings are available for many jobs. The current project also occupies space: notes, measurements, and partly completed work. Weights are the learned settings reused across requests. Cached attention state belongs to a particular sequence or reusable prefix. The analogy stops short of literal memory or understanding; it simply separates persistent parameters from temporary computation.
When a decoder processes a prompt, it performs a prefill pass over the input. When it continues the answer, it generates tokens through decoding steps. In ordinary causal attention, earlier token positions cannot attend to later positions. This allows previously computed keys and values to remain useful as the sequence grows. A KV cache stores those representations so the system can reuse them rather than recomputing all earlier projections at every step.
Reusing work is not making it free
A new query still needs to interact with the relevant cached information. Reading the cache takes bandwidth, and a longer sequence can require more attention work. The cache also occupies memory. Caching changes the balance between recomputation and retained state; it does not remove every cost associated with a long conversation. This explains why a model can generate a short answer quickly yet struggle with a very long prompt or many concurrent users.
Suppose a toy model has two layers, two key/value heads per layer, four values per head, and a sequence of one hundred tokens. Storing both keys and values at two bytes per value requires 2 × 2 × 2 × 4 × 100 × 2 = 6,400 bytes. The first factor accounts for keys and values. This deliberately small example ignores allocator overhead and other state. Doubling the sequence length doubles this simple cache estimate; doubling independent sequences does the same.
Architectures change what needs to be retained
Grouped-query attention allows multiple query heads to share fewer key/value heads. That changes the number of cached heads while allowing distinct queries. Latent attention can retain a compact representation and use architecture-specific transformations to recover or compute what attention needs. Sliding windows can limit which recent positions remain relevant to a particular attention layer. These are distinct mechanisms, not interchangeable names for compression.
Do not apply one cache formula to every modern model without checking its architecture. Some systems contain multiple types of attention, shared memory, compressed representations, or other persistent state. A published bytes-per-token figure may cover only one component. Ask whether it includes all layers, scales, local windows, batches, and additional model-specific structures. A precise label such as “global cache component” is more useful than a large unqualified claim about total memory.
Measure the experience, not only a rate
Latency is the time a user waits for an event, such as the first token or the complete answer. Throughput is the amount of work completed over time, often across several requests. Batching can improve aggregate throughput while changing an individual user’s waiting time. Faster arithmetic does not guarantee lower latency when communication, cache reads, or scheduling dominate the workload.
Using the cache calculation above, vary sequence length while keeping other quantities fixed, then vary concurrency. Explain which quantities should change and which should remain constant. Finally, consider an answer that is twice as long. Even if each decoding step has the same cost, more steps take more time. A responsible performance report states the model revision, numerical format, hardware, prompt and output lengths, concurrency, and the metric being measured. Those details turn a speed claim into something another person can interpret and attempt to reproduce.
College extension · make the assumptions explicit
For a conventional cache with uniform layers, an estimate is M = 2LBTHkv db, where L is layer count, B batch size, T retained tokens, Hkv key/value head count, d head dimension and b bytes per element. The result is bytes. It is not a universal equation for latent or heterogeneous architectures. Separate allocated capacity from live occupancy, and separate weight memory from KV state and temporary buffers. Prefix sharing can reduce duplication when supported, but cache validity depends on matching the computation that produced it.
Sources and further investigation
Source review: October 28, 2026. Model-release claims are attributed to their publishers.