Hypothetical scenario. Northwind finds several permitted passages after query expansion. Together they exceed the request allowance. Maya needs the exception as well as the general rule; Dev offers a shorter summary, and Priya asks what the summary discarded.
Maya: “A shorter answer is useful only if the condition survives.”
Dev: “We can select passages, extract spans or generate a summary.”
Priya: “Choose what must remain checkable before compressing the evidence.”
You will distinguish evidence selection, extractive compression and generated summaries, then account for context and serving work separately. Meeting an input limit is one condition; preserving the task-relevant source relationship is another.
What must remain when the context gets smaller?
Context compression can select passages, remove tokens or generate a shorter representation. Extractive selection preserves source wording but can remove a necessary qualification; abstractive summarization can introduce unsupported relationships. Jiang and colleagues' LLMLingua paper studies budgeted prompt compression as a concrete mechanism, not a general guarantee that a smaller prompt preserves every task-relevant fact.
Hypothetical scenario. Four permitted passages contain 80 tokens each. Total evidence is 4 × 80 = 320 tokens. With 40 instruction tokens and a 200-token input budget, evidence may occupy 200 − 40 = 160 tokens. Keeping two complete passages fits exactly, while shrinking all four to 40 tokens also totals 160. These alternatives have equal size but different risks. If a policy exception is lost in a generated summary, the size ledger passes while the evidence contract fails. Evaluate preservation of the required rule, exception, identity and effective date.
Hypothetical scenario. Priya proposes sending the entire manual on every question.
In short. Compare full context with selective retrieval. Budget tokens and cache growth together.
The request fits, but the service does not
Hypothetical scenario. A document assistant can accept a long policy collection in one request. Under concurrent use, those requests occupy memory and delay shorter questions. Some answers also miss an exception buried in the middle. The accepted context length establishes neither useful evidence use nor a safe serving policy.
This lesson connects long-context evaluation to prefill, decoding, request state and admission. It extends the local-serving chapter with a mixed-workload decision rather than another weight-file estimate. Scope includes evidence placement, bounded context assembly, scheduling and optimization claims.
Begin by asking why the context is long. The task may genuinely need relationships across many passages, or the application may be forwarding redundant history because it lacks a selection policy. Those situations call for different interventions.
Keep a claim-to-source map when compressing context
Hypothetical scenario. A context selector retains two complete passages while a summarizer shortens four. The token totals can match even though only one representation preserves the exception needed by the question. Record which claims and qualifications each selected unit retains.
| Artifact | Concrete evidence | Decision boundary |
|---|---|---|
| Context unit | source span, claim, qualification | Support coverage |
| Compression result | transform version, source refs | Derived evidence |
| Serving envelope | transform + input + output budgets | Whole-task admission |
Extractive deletion can remove context; abstractive compression can add relationships. Both require task-level checks against the original permitted revision. Compression does not reduce logical uncertainty merely because the prompt becomes smaller. Budget the transform itself, final input, output allowance and live serving state separately. If a source is revoked after a summary is cached, its derived text must follow the disclosure policy even when it no longer contains a recognizable source title.
Input capacity is not evidence comprehension
A model can accept tokens without using every relevant relationship reliably. A simple fact lookup is also different from reconciling exceptions across documents. Evaluate the operation the application actually promises, including correct limitation when the evidence is insufficient.
Lost in the Middle investigates position sensitivity in specific long-context tasks and models. It motivates testing evidence placement; it does not establish that every later model fails identically or that the beginning is always the right location for every passage.
Adding context can increase the number of obsolete, conflicting or malicious passages. Permission and source-version selection still happen before assembly. A larger allowance is not a reason to bypass the evidence contract.
Budget prefill, decoding and retained state separately
Prefill processes the input context; decoding generates subsequent tokens while using retained model state. Their resource patterns differ. A service can schedule them together in several ways, and an optimization that improves one boundary may not improve the complete user task.
FlashAttention changes attention execution through an IO-aware algorithm. PagedAttention addresses serving memory management. These mechanisms solve different resource problems; neither makes arbitrarily long requests free or establishes the application's answer quality.
Some schedulers divide prefill work or admit new sequences as others complete. The concrete implementation and workload determine fairness and efficiency. Inspect the selected runtime rather than assuming every system supports the same scheduling behavior.
Derive context state and a mixed-workload result
Hypothetical scenario. The following architecture, budgets and schedules are chosen teaching examples, not a named model or measured runtime.
Follow the document assistant from the embedding-migration argument: it now retrieves compatible evidence, but that evidence still has to fit an operating request budget. Use a deliberately small fictional architecture so every cache calculation is visible. Let L be eight layers, H be two key/value heads, d be 32 coordinates per head and s be two bytes per coordinate. For these dimensions, each retained position requires 2 × L × H × d × s = 2 × 8 × 2 × 32 × 2 = 2,048 bytes, or 2 KiB. The leading two counts keys and values.
The general payload for this conventional dense layout is 2 × layers × KV heads × head dimension × cached tokens × bytes per element, summed across sequences. KV heads are not necessarily the query-head count. Hugging Face's cache explanation describes reusing earlier keys and values. The formula here counts stored coordinates, excluding weights, workspaces, page metadata, alignment and any padding. Sliding windows, shared prefixes, cache quantization and implementation layout can change what is actually retained.
| Request class | Input + maximum output positions | Raw cache reservation |
|---|---|---|
| Short policy question | 4,096 + 1,024 = 5,120 | 5,120 × 2 KiB = 10 MiB |
| Long policy comparison | 32,768 + 8,192 = 40,960 | 40,960 × 2 KiB = 80 MiB |
Choose a 128 MiB budget solely for these raw cache payloads, with every other resource accounted for separately. One long request plus four short ones reserves 80 + 4 × 10 = 120 MiB. Eight MiB remains. A fifth short request would make 130 MiB, exceeding this chosen budget by 2 MiB. Defer it or use an explicitly smaller task contract; accepting it because its own context is supported does not create the missing capacity.
These are conservative maximum-length reservations. An implementation can instead grow allocations and handle pressure through its documented scheduling and preemption policy. That can use space more flexibly but requires a recovery plan when generation grows. Neither approach turns 128 MiB into a complete device-memory budget.
Now isolate scheduling in a smaller toy example. Two already admitted sequences each need one decode token per iteration for the next three iterations. A pending prompt needs 18 prefill tokens. Choose an iteration allowance of eight processed token positions. Reserve two for decoding; 8 − 2 = 6 remain for prefill.
| Iteration | Decode work | Prefill chunk | Prefill remaining |
|---|---|---|---|
| 1 | 2 positions | 6 positions | 18 − 6 = 12 |
| 2 | 2 positions | 6 positions | 12 − 6 = 6 |
| 3 | 2 positions | 6 positions | 6 − 6 = 0 |
This arrangement gives existing sequences an opportunity to decode in every illustrated iteration while the prompt makes bounded progress. It does not prove a millisecond response target: prefill and decode positions have different costs, and iteration duration depends on the implementation and batch. The vLLM optimization guide documents chunked prefill mixed with decode work. Check the installed version before treating a documented scheduling policy as universal.
Continuous batching concerns admitting and retiring sequences across iterations; chunked prefill concerns splitting input work. Prefix caching reuses eligible compatible prefix state, and PagedAttention organizes cache memory. They can interact, but none substitutes for the others. For the policy assistant, compare short-question waiting, long-task completion and supported answers under the same workload before changing admission or scheduling.
Now choose a toy ten-request workload: nine short requests take one second each and one long request takes ten seconds at the measured boundary of this constructed example. Mean duration is(9 × 1 +10) ÷ 10 = 1.9 seconds, while the long request still takes ten. The mean does not describe every user's wait or establish a percentile service target.
For context evaluation, choose six base questions and place the needed evidence early, centrally and late, yielding 6 × 3 = 18 variants. Add two insufficient-evidence cases for 20 total. The variants are related probes of six questions, not 18 independent user tasks.
Suppose a candidate answers 15 of the 18 positioned variants correctly but answers both insufficient-evidence cases with unsupported conclusions. Reporting 15 ÷ 20 = 0.75 hides the specific limitation failure. Inspect position behavior and required abstention separately before release.
In the wild: Long-Context Systems: When Bigger Windows Help and When They Don’t
Lost in the Middle: Lost in the Middle studies position sensitivity in particular context tasks.
Reuse needs exactly the right equivalence
A prefix cache can reuse compatible processing state for an identical eligible prefix under a runtime's actual rules. A semantic answer cache reuses a final result under a different equivalence claim. Do not treat similar wording as proof that either reuse boundary is valid.
Shared prefixes can contain private instructions or source content. Scope cached state and its metadata to the permitted users and artifacts. Model version, tokenizer and representation compatibility matter as well as text identity.
Quantization, speculative generation and parallel execution can change resource behavior, but their effects require measurement and quality checks. An algorithm name does not establish a universal latency multiplier. Preserve the baseline and compare the complete request path.
Long requests consume the short-request budget
Hypothetical scenario. A team admits every request whose context fits the model limit. Several long requests occupy the available request state and scheduling slots. New short questions wait behind work that will exceed their useful deadline.
Admission needs the relevant occupied-resource budget and task deadline, not only a token-limit check. Separate or prioritize work classes where the product justifies it, and bound waiting. A rejected or deferred request can be more truthful than silently accepting work that cannot finish usefully.
Observe time to first useful output, completion latency, queue age, resource occupancy and accepted task quality separately. Fast initial streaming can conceal a slow or interrupted final answer. Recovery should preserve logical request and attempt identity.
Three long-context misconceptions
“It fits, so the model uses it reliably.” Capacity and task evidence use require separate tests.
“An efficient attention kernel removes request-state growth.” Kernel execution and retained sequence state are different resource dimensions.
“A better mean makes every workload better.” Work classes and tail behavior can worsen while the aggregate improves.
Choose context and serving policy together
Use longer context when the task requires the additional evidence and evaluation supports its use. Use retrieval or selective history when it preserves the required relationships with a smaller request. A combination can be appropriate; there is no universal replacement rule.
Set admission from measured resource behavior under the intended mix of context and output lengths. Evaluate cold starts, cancellations, retries and degraded dependencies. A stable demonstration with one request does not establish multi-user safety.
Reject performance claims inferred from parameter count, a kernel paper or the advertised context limit alone. The architecture decision should explain which boundary improved, which quality constraints held and what workload would invalidate the conclusion.
Limits of Long-Context Systems: When Bigger Windows Help and When They Don’t
Position effects and context capacity depend on the evaluated model and task. Advertised window length does not establish useful evidence coverage or a measured serving improvement. Reserve resources for the complete chosen request and evaluate the quality constraints alongside the runtime.
Test the context unit boundary
The prompt fits after an exception is summarized away. Has the context budget succeeded?
Reveal the design reasoning
The size condition succeeded but the task contract failed. Preserve the exception, choose a different selection or abstain. Evaluate supported outcomes, not only tokens removed.
Decision: Optimize context size only within a preserved evidence and disclosure contract.
Check yourself: review the workload
The model accepts the whole policy collection. What evidence is still needed?
Task-specific support, position and exception handling, permissions and measured resource behavior under the intended workload. Input capacity alone establishes none of them.
The cache budget is 128 MiB. One long task reserves 80 MiB and four short tasks reserve 10 MiB each. Should another short task be admitted?
That would reserve 80 + 5 × 10 = 130 MiB, exceeding the chosen raw-cache budget by 2 MiB. Defer it under this policy. A growth-based allocation policy is an alternative only with a defined pressure/recovery contract; the arithmetic does not establish whole-device capacity.
Mean latency improves but short requests miss their deadline behind long ones. What should change?
Inspect work-class scheduling, admission and bounded waiting against the product requirement. A favorable aggregate does not justify accepting unusable work.
Northwind decision log
Compare full context with selective retrieval.
Budget tokens and cache growth together.
Test evidence use at different context positions.
Go deeper into context evidence and serving
- Book chapter: AI Engineering, chapter 2: Understanding Foundation Models — Chip Huyen. Compare context behavior with the actual inference-resource budget.
- Book chapter: AI Engineering, chapter 9: Inference Optimization — Chip Huyen. Compare context behavior with the actual inference-resource budget.
- Video lecture: Stanford CS336 Language Modeling from Scratch | Spring 2025 | Lecture 1: Overview and Tokenization — Stanford Online. Trace how text becomes a token sequence before budgeting transformed document evidence.
- Primary paper: Lost in the Middle: How Language Models Use Long Contexts — Nelson Liu and colleagues. A concrete study of evidence-position sensitivity to interpret within scope.
- Runtime documentation: Optimization and tuning: Chunked prefill — vLLM contributors. Compare the toy iteration table with the documented scheduler; verify the deployed version.
- Mechanism documentation: How caching works — Hugging Face. Distinguishes retained keys and values from recomputing earlier representations.
Check the mechanism in this lesson
Two compression methods both produce 160 tokens. Is their evidence quality therefore equivalent?
Compare the explanation
No. Equal size says nothing about whether a required exception, date or source relationship survived. Compare the resulting answer and evidence against the task's actual acceptance cases.
Carry the decision forward
Northwind can now inspect what selection removes. Page 17 follows another source of error: a compact, relevant passage can still belong to an obsolete or incompletely published revision.