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

High school / LONGER LESSON 08

Inference: where memory and time go

Separate prefill/decode, calculate KV memory, and evaluate cache trade-offs.

Preparation: Multiplication and units; attention shapes for college.

Plan 20–35 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

Read the prompt, then extend it

High-school path. Separate prefill/decode, calculate KV memory, and evaluate cache trade-offs.

Preparation: Multiplication and units; attention shapes for college. Work through one section at a time. Predict the experiment result before changing its controls, then explain what the example leaves out.

A language model first processes the prompt. This is often called prefill. It then generates additional tokens, commonly one step at a time, called decode. The two phases have different workloads. A long prompt can make the first response slow even if later tokens arrive quickly. Measure time to first token and time per later token separately instead of describing a system with one unexplained speed number.

Worked step 1. Prompt length is 1000 tokens.

Worked step 2. Generation length is 200 additional tokens.

Worked step 3. Report first-token delay separately from the subsequent decode rate.

Try it yourself. Can a single tokens-per-second number fully describe the user experience?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. No. It may hide prompt processing, queuing and first-token delay. State what interval and workload were measured.

Section 02 / 07

Cache old keys and values

Without a cache, generating another token could repeat work on the old prefix. A KV cache stores keys and values already computed for earlier positions. The new query still compares with relevant stored keys and mixes stored values. Keeping notes avoids rewriting them, but you still need to read them. A cache saves repeated projection work; it does not make long-context attention free.

Worked step 1. At context length 1000, the new token adds one key and value per relevant layer/head.

Worked step 2. Its query can still attend over roughly 1001 positions.

Worked step 3. Old projections are reused; their stored information remains part of the computation.

Try it yourself. Does a KV cache mean the new token only attends to itself?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. No. It can attend to the stored prefix. The cache preserves prior keys and values precisely for that use.

Section 03 / 07

Calculate a cache budget

Count two stored objects, keys and values. Multiply by layers, token positions, key-value heads, features per head and bytes per number. Our example has 32 layers, 2048 tokens, eight KV heads, 128 features and two bytes per number. The result is 256 mebibytes for one sequence. Model weights and temporary workspaces are extra. A cache estimate is not the same as total graphics-memory use.

Worked step 1. Two times 32 times 2048 times eight times 128 times two equals 268435456 bytes.

Worked step 2. Divide by 1048576 to obtain 256 MiB.

Worked step 3. Doubling context or batch doubles this simple cache estimate.

bytes=2BLTH_kvD_hs

Multiply two for keys and values by batch, layers, tokens, key-value heads, head width and bytes per element.

Try it yourself. At the same settings, how much cache does a batch of four need?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. 1024 MiB, or one GiB, before overhead. The batch multiplier is four.

Section 04 / 07

Share KV heads carefully

Query heads and stored key-value heads do not always have the same count. Several queries can use the same stored labels and messages. That is the idea behind grouped-query attention. In our example, using eight KV heads instead of 32 cuts the simple KV storage by four. This does not mean all model memory falls by four, or that every architecture can be changed without retraining.

Worked step 1. Keep 32 query heads fixed.

Worked step 2. Compare eight versus 32 KV heads.

Worked step 3. At 2048 tokens, the cache estimate rises from 256 MiB to 1024 MiB.

Try it yourself. Why would using query-head count in every cache estimate overstate some models?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. Grouped-query models store fewer KV heads than query heads. Use the configured KV-head count.

Section 05 / 07

Memory management is not a new attention rule

A system can store cache blocks in a more flexible way to waste less space when requests have different lengths. That helps manage memory, but it does not mean the model suddenly uses a different definition of attention. Likewise, a sliding window keeps fewer old positions, which does change what information is available. Separate a storage improvement from a change in the model's context behavior.

Worked step 1. A block allocator can reuse free cache blocks across requests.

Worked step 2. A sliding window limits how many previous positions remain visible.

Worked step 3. Both may lower memory pressure, but they do so for different reasons.

Try it yourself. Does a lower memory footprint guarantee unchanged outputs?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. No. A pure layout optimization can preserve semantics, while eviction, quantization or changed attention rules may alter results. Test the actual change.

Section 06 / 07

Design an inference measurement

Choose a fixed prompt length, answer length and number of simultaneous requests. Warm up the system consistently and record both delay and memory. Change only one variable at a time. If a larger batch raises total tokens per second but makes each learner wait longer, report both outcomes. The best configuration depends on whether you serve one interactive learner or many offline jobs.

Worked step 1. Measure a short and a long prompt separately.

Worked step 2. Keep generated-token count fixed for the comparison.

Worked step 3. Report cache estimate alongside observed total memory and latency.

Try it yourself. Why might a measured memory peak exceed the cache calculation?

Pause the recording and write your reasoning before continuing. The worked solution follows.

Reveal worked solution

Worked solution. Weights, temporary activations, workspaces, allocator overhead and other runtime state also consume memory.

Section 07 / 07

Mastery and transfer

Bring the pieces together. First answer the checkpoint without the worked solutions. Then explain the mechanism in your own words, using one numerical example from this lesson.

Caching old keys and values… Option 1: Eliminates every old-token read. Option 2: Avoids recomputing them but still supports attending to them. Option 3: Stores only the final word.

Pause here and choose an answer before continuing. The checkpoint explanation follows.

Reveal worked solution

The correct choice is option 2: Avoids recomputing them but still supports attending to them. Reuse does not remove attention over the prefix.

Transfer task. Change one assumption in the worked example. State your prediction, calculate or test it in Workbench, then explain whether the result supports your prediction.

Reveal worked solution

Self-check rubric. Name the changed assumption, keep the other inputs fixed, show at least one intermediate calculation, and distinguish what the toy example guarantees from what would require a trained model or a real measurement.

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.