Foundation Models: Tokens, Attention, And Generation · Lesson 12

How Much Context Can An AI Model Use?

Budget the actual formatted input and output allowance, test how the model uses relevant evidence, and calculate temporary state from the architecture. These records answer different parts of the request’s feasibility and usefulness question.

Study And Save Progress

Watch The Lesson

7 min 30 sec

Read the video transcript

The museum puts a long packet of notices into a request that fits its stated context allowance. The answer still misses an important closure, and another configuration runs short of memory. What did the successful size check actually tell the team? We will budget the input,

test how the evidence is used, and calculate the temporary attention state. Those steps give us different evidence for deciding whether this request can work. Begin by defining the accounting rule. Our hypothetical service has a combined allowance of 16,000 tokens for the input and reserved output.

Set aside 1,000 for instructions, 1,000 for tool definitions, 500 for the current question and 2,000 for output. These are supplied classroom allocations. A real service can define separate limits and different accounting, so its contract and the matched tokenizer must accompany a measurement. Subtract the allocations from the combined allowance.

After instructions and tools, 14,000 remain. The question leaves 13,500, and the output reservation leaves 11,500 for documents and conversation history. Any additional formatting or margin must come from what remains. The output reservation provides room for generation under this convention; it does not

ensure that the answer will use all of it or satisfy the museum task. Now follow the closure notice inside the packet. Finding the relevant passage, associating it with the correct room and date, and reconciling conflicting notices all affect the answer. To investigate use of the evidence,

hold its content fixed while moving it among the other material. Compare beginning, middle and end placements with the same question and scoring rule. Record the model's actual answer and support before deciding whether a longer packet helped. A historical study gives this test a concrete basis.

Liu and colleagues' Lost in the Middle paper, published in February 2024, examined multi-document question answering and key-value retrieval. For the models and settings studied, performance often depended on the position of relevant information and deteriorated when it was in the middle. That finding motivates a controlled placement test.

It supplies no measured outcome for our museum or a universal rule for every later long-context model. The request also needs resources for its computed state. From the generation lesson, a key-value cache retains attention information for processed positions. Its payload depends on how many

positions and requests are retained and on the architecture's layers, key-value heads and coordinates. More available context can therefore create a larger temporary-state requirement even when the saved model weights stay unchanged. Inspect the actual cache convention rather than attach 1 generic memory price to every token.

Use a supplied cache configuration with 32 layers, 8,192 retained positions, 1 request, 8 key-value heads, 128 coordinates per head and 2 bytes per stored value. We count both keys and values, so there are 2 arrays at each relevant position and layer.

The key-value head count is an architectural quantity. It can differ from the number of query heads that use those states. Multiply the 2 arrays by the layers, positions, requests, key-value heads, coordinates and bytes per value. Under these assumptions, the cache

payload is exactly 1 gibibyte, using units based on powers of 1,024. The reading provides the complete byte calculation. This counts the supplied keys and values. Weight storage, other activations, workspace, metadata and allocation effects require additional accounting before estimating the memory of a running service.

Keep every other supplied factor fixed and replace 8 key-value heads with 32. The cache payload becomes 4 gibibytes. Grouped-query attention can let several query heads share a key and value head, which explains why the query-head number alone is insufficient for this calculation. That is a property of

the trained architecture and its implementation. A serving plan needs the actual configuration and supported precision, rather than assume that changing a label resizes an existing model correctly. Sequence length also affects attention's relationships. A full score grid has a query-position axis and a key-position axis.

Doubling both dimensions gives 4 times as many entries in that full grid. A causal mask restricts permitted relationships, and implementations can avoid storing the whole grid. Other computations and the serving arrangement also affect time and memory. Use the pair-count calculation for its stated mathematical comparison; measure an actual service

before assigning it a universal latency multiplier. Pause at the museum's budget. The combined allowance is 16,000 tokens. Instructions use 1,000, tool definitions use 1,000, the current question uses 500, and output reserves 2,000. How much remains for documents and history before additional formatting or margin?

If the packet fits, what further checks would you make before trusting its opening-hours answer? The remaining allowance is 11,500 tokens. Additional formatting and margin still need to fit within the defined total. After that capacity check, verify the applicable notices, the room and date,

source support and treatment of conflicts. Test relevant placements and representative questions, and check that the actual configuration has sufficient resources. A valid length calculation provides 1 part of that service decision. For a separate transfer, the supplied cache payload is 1 gibibyte

with 8 key-value heads and 1 request. Keep the other dimensions and precision fixed, use 32 key-value heads, and retain 2 such requests with their cache payloads stored separately. Calculate the combined cache payload. Would that result guarantee that the complete service fits on a

device with 8 gibibytes of memory? If sequence length doubles, does a 4-fold full-grid entry count establish 4 times the actual response delay? Pause and explain your assumptions. The head-count change multiplies the payload by 4, and the 2 requests multiply it by 2,

giving 8 gibibytes of cache payload. The complete service still needs its weights and other runtime memory under the actual implementation. The device-fit claim therefore needs more evidence. Doubling both axes of the mathematical full score grid gives 4 times its entries; actual delay depends on the computation

and serving conditions, so it requires measurement. The museum can now keep 3 records: its defined token allowance, evidence-use tests, and architecture-specific memory calculation. These explain how a packet can fit a window while a useful, resource-feasible answer remains unresolved. You can reproduce the budget and cache

factors and state what they leave unmeasured. Next we will examine a different architectural count: how a model can store a large collection of parameters while activating only part of its expert computation for a token.

Main Point

Budget the actual formatted input and output allowance, test how the model uses relevant evidence, and calculate temporary state from the architecture. These records answer different parts of the request’s feasibility and usefulness question.

Key Points

1. Budget a defined request

Use a supplied hypothetical combined limit of 16,000 tokens. This is a classroom convention, not a named provider’s specification.

AllocationTokens
Instructions1,000
Tool definitions1,000
Current question500
Reserved output2,000
Remaining documents and history11,500

`16,000 − 1,000 − 1,000 − 500 − 2,000 = 11,500`

The 500 allocation belongs to the current question. Additional formatting and any chosen margin still consume capacity. Count the final representation using the matched tokenizer/version/template and the actual service’s input/output convention. Reserving 2,000 output tokens does not require the model to generate all of them or establish answer quality.

2. Test use of the evidence

The museum’s fictional packet includes a room closure that the answer must associate with the correct date. Keeping the packet within its allowance does not test that association, source support or conflicting notices.

For a controlled placement test, move the same relevant notice among the other supplied material while holding the question and scoring rule fixed. Compare beginning, middle and end placements, then record answers and support. Observed results remain blank until an actual authorized test.

Liu and colleagues’ *Lost in the Middle*, published in February 2024, studied multi-document question answering and key-value retrieval. Its tested models often performed differently as relevant information moved, with weaker use in the middle of long contexts. This motivates a test design; it supplies no result for the museum or every later model. Use representative questions and current applicable evidence when judging the actual task.

3. Define the cache payload

For a simplified retained KV payload:

`bytes = 2 × layers × retained positions × requests × KV heads × head dimension × bytes per stored value`

The 1st factor counts keys and values. The final factor counts bytes for each numerical value. Count the actual retained positions and implementation, rather than assume every reserved output slot has already been processed or allocated in the same way.

The supplied configuration has 32 layers, 8,192 positions, 1 request, 8 KV heads, 128 coordinates per head and 2 bytes per value:

`2 × 32 × 8,192 × 1 × 8 × 128 × 2 = 1,073,741,824 bytes = 1 GiB`

A GiB contains `1,024³` bytes. The same amount is approximately 1.074 GB in decimal units. Keep the unit with the result.

This is KV payload only. Weight storage, other activations, workspace, metadata, padding and allocation effects require additional accounting. No device-fit or runtime measurement is supplied.

4. Inspect the KV heads and sharing assumptions

With every other factor unchanged, 32 KV heads instead of 8 give `32/8=4` times the payload: 4 GiB for 1 request. 2 independently stored such request payloads give 8 GiB. Supported sharing, sharding, replication and precision can change actual physical memory, so record the implementation rather than silently changing assumptions.

Ainslie and colleagues’ 2023 grouped-query attention work describes query-head groups sharing key/value heads. The KV-head factor therefore need not equal the number of query heads. This is an architectural choice associated with a trained configuration. The paper’s conversion/training and performance results are outside this classroom memory calculation.

5. Interpret the full-grid comparison

A mathematical full attention score grid has a query-position axis and a key-position axis. Doubling both lengths multiplies its entries by 4. Causal masks restrict permitted relationships; optimized implementations can avoid storing the full score array, and architectural variants change the work.

The 4× entry count establishes the stated geometric comparison. Actual memory use and latency also depend on kernels, other computation and serving conditions. An end-to-end response-delay claim requires measurement.

6. Use the 3 records together

The token budget tells the museum how much defined material fits. Evidence-use tests examine whether the answer uses the right notice and resolves the task. The cache calculation identifies a temporary-state payload under explicit architecture assumptions. A useful service needs a satisfactory combination of all these conditions.

The next lesson examines another distinction in architectural resource counts: a mixture-of-experts model’s total parameters and the subset active for a token.

7. Learning Checks

Attempt each question before opening its explanation. The worksheet leaves calculations and observations blank.

M14-L12-Q01

A hypothetical combined input-and-reserved-output allowance is 16,000 tokens. Instructions use 1,000, tool definitions use 1,000, the current question uses 500, and output reserves 2,000. How much remains for documents and history before additional formatting or margin? If the packet fits, what further checks are needed before trusting its opening-hours answer?

Your calculation and explanation: ____________________

Show explanation after your attempt

Subtract 1,000+1,000+500+2,000=4,500 from 16,000, leaving 11,500 tokens for documents and history. Additional formatting and margin must still fit under the stated accounting rule. Then inspect applicable evidence, room/date associations, conflicts and source support; test representative questions and evidence placements, and check actual resource availability. Fit addresses capacity while the task and configuration still need evaluation.

M14-L12-P01

A supplied cache payload is 1 GiB for 8 KV heads and 1 request. Keep layers, positions, coordinates and precision fixed, use 32 KV heads, and retain 2 such requests with their cache payloads stored separately. What is the combined payload? Does it guarantee that the complete service fits on an 8 GiB device? If sequence length doubles, does a 4× full-score-grid entry count establish 4× actual response delay? State the assumptions and limits.

Your calculation and explanation: ____________________

Show explanation after your attempt

The head change contributes 32/8=4 and the 2 separately stored request payloads contribute another factor of 2. The combined cache payload is 8 GiB under the supplied assumptions. The service also needs weights, other activations, workspace, metadata and implementation-specific allocation, so device fit requires more evidence. Doubling both dimensions of a mathematical full score grid gives 4× entries. Actual latency depends on permitted/computed relationships, implementation and other serving work; measure it rather than assert that multiplier.

Sources

Learner Materials

Download Lesson 12 Learner Materials

Use the supplied fictional cases and templates for practice.

Practice

Write your answer, compare it with the model answer and decide what to revisit. These written checkpoints are self-assessed.

A hypothetical combined input-and-reserved-output allowance is 16,000 tokens. Instructions use 1,000, tool definitions use 1,000, the current question uses 500, and output reserves 2,000. How much remains for documents and history before additional formatting or margin? If the packet fits, what further checks are needed before trusting its opening-hours answer? Your calculation and explanation: ____________________

Show The Model Answer

Subtract 1,000+1,000+500+2,000=4,500 from 16,000, leaving 11,500 tokens for documents and history. Additional formatting and margin must still fit under the stated accounting rule. Then inspect applicable evidence, room/date associations, conflicts and source support; test representative questions and evidence placements, and check actual resource availability. Fit addresses capacity while the task and configuration still need evaluation.

Compare your reasoning with the model answer. These written checks are self-assessed.

A supplied cache payload is 1 GiB for 8 KV heads and 1 request. Keep layers, positions, coordinates and precision fixed, use 32 KV heads, and retain 2 such requests with their cache payloads stored separately. What is the combined payload? Does it guarantee that the complete service fits on an 8 GiB device? If sequence length doubles, does a 4× full-score-grid entry count establish 4× actual response delay? State the assumptions and limits. Your calculation and explanation: ____________________

Show The Model Answer

The head change contributes 32/8=4 and the 2 separately stored request payloads contribute another factor of 2. The combined cache payload is 8 GiB under the supplied assumptions. The service also needs weights, other activations, workspace, metadata and implementation-specific allocation, so device fit requires more evidence. Doubling both dimensions of a mathematical full score grid gives 4× entries. Actual latency depends on permitted/computed relationships, implementation and other serving work; measure it rather than assert that multiplier.

Compare your reasoning with the model answer. These written checks are self-assessed.

Open Practice And Save Your Work