Macalinao StudioLearnAll enriched lessons ↗
High school path · 7 sectionsSwitch to college ↗

High school / LONGER LESSON kv-cache

KV caching: remember the work, budget the memory

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.

Section 01 / 07

Why yesterday’s keys still work

High-school 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.

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.

K_new = concatenate(K_past, k_t); V_new = concatenate(V_past, v_t)

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.

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.

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.

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.

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.

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.

Effective group bits/value = (16 × 4 + 8) / 16 = 4.5

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.

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. What does a KV cache preserve? Option 1: Earlier intermediate keys and values under compatible prefix and model settings. Option 2: All future answers. Option 3: Only the original text, with no computed state.

Pause and choose an answer before continuing.

Reveal worked solution

Option 1 is correct. The cache saves intermediate computation. New queries still use it, and changed prefixes can invalidate it.

LONGER ATTENTION LESSONS

Follow the mechanism in depth

Worked examples, local narration and connected learning modes at your level.

LONGER TRANSFORMER SYSTEMS LESSONS

Follow the mechanism in depth

Worked examples, local narration and connected learning modes at your level.

Continue the learning path

Sources and scope

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.

EXTENDED FIELD NOTES

What stays in memory while a model answers?

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
Two kinds of stored information

A new token reuses cached keys and values; reading that state still costs time and memory.

  1. Weights: learned settings
  2. Prompt: prefill
  3. KV: retained state
  4. 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.

Sources and further investigation

Source review: October 28, 2026. Model-release claims are attributed to their publishers.

Open the focused reading page →

Reset this high school path?

This removes only this path’s notes, progress and experiments from this browser.