AI Wiki中文/EN

Context windows: what actually fits into one request?

上下文窗口

Budget tokens, reserve output space and audit which evidence survives packing.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A document can fit on disk and still miss the window

You ask for a door code hidden among project notes. The request allows 14 tokens, but four are reserved for the answer and two for instructions and separators. That leaves eight for documents. If a five-token introduction goes first, the four-token answer passage no longer fits. A two-token irrelevant passage does. The request is valid; its evidence is missing.

This chapter uses whitespace-separated words as teaching tokens. A real tokenizer may split a word, merge punctuation or encode Chinese text very differently. Count the actual serialized request with its actual tokenizer. Include role markers, instructions, tool material and other tokens required by that system. There is no universal “characters divided by four” conversion.

A context window is a limit on the token sequence available to a model invocation under a particular configuration. It is separate from information stored in parameters, a retrieval database or a conversation archive. An application can keep an old message while omitting it from the next model input. What the interface displays and what the model receives need not coincide.

Transformer-XL explains how fixed training segments can fragment context and introduces a particular recurrent solution. Lost in the Middle asks a different question: even when relevant evidence is present, how well do evaluated models use it at different positions? First establish inclusion; then measure successful use.

Packing order changes evidence inclusion, while local masking independently limits direct access.
Packing order changes evidence inclusion, while local masking independently limits direct access.

Three limits need three different checks

For a simple shared input-and-output budget, let WW be the total limit, II fixed overhead, DD supplied document tokens and RR reserved output tokens. A conservative planner requires:

I+D+R≤W.I+D+R\le W.

This is our planning convention, not the specification of every service. Some systems expose distinct input and output limits or additional accounting rules. Consult the chosen model and serving implementation before replacing their rules with this inequality. A reservation is an allowance, not a prediction that the model will generate exactly that many tokens.

The document allowance is therefore:

B=W−I−R=14−2−4=8.B=W-I-R=14-2-4=8.

Suppose indivisible document jj has token cost cjc_j and inclusion decision zjz_j in zero or one. Selecting a set must satisfy:

∑jcjzj≤B,zj∈{0,1}.\sum_j c_jz_j\le B,\qquad z_j\in\{0,1\}.

The code uses a simple input-order scan: include a document if it fits; otherwise skip it and continue. This is a non-AI baseline, not a maximum-value selection algorithm. Reordering can change the result even without changing the budget. Splitting documents, scoring them for relevance or solving a knapsack problem are different policies and need separate evaluation.

Capacity also differs from direct attention visibility. For zero-based query position ii, key position jj and a causal local width ww that includes the current position, define:

Mij=1{max⁡(0,i−w+1)≤j≤i}.M_{ij}=\mathbf{1}\{\max(0,i-w+1)\le j\le i\}.

The number of directly visible keys at that position is:

∑jMij=min⁡(w,i+1).\sum_j M_{ij}=\min(w,i+1).

This matrix describes one layer’s direct access. In a multilayer or recurrent architecture, accessible hidden states can carry earlier information indirectly. Do not infer a total information horizon from this row alone. Transformer-XL’s stopped-gradient state reuse is one concrete reason that “segment length” and “all usable history” are different quantities.

Finally, separate the inclusion indicator from answer quality:

V=1{required evidence is included},A=1{answer is correct}.V=\mathbf{1}\{\text{required evidence is included}\},\qquad A=\mathbf{1}\{\text{answer is correct}\}.

V=1V=1 does not imply A=1A=1. Nor does A=1A=1 establish that the evidence was used: a model might already know an answer or guess it. An evidence-dependent test can change the answer-bearing fact between otherwise matched inputs to distinguish those possibilities.

Make the packing decision inspectable

The complete standard-library program prints selected and skipped document IDs, unused space and a six-position visibility matrix. It deliberately keeps documents whole. Two overhead tokens are supplied as a numerical teaching convention; the program does not serialize a production chat template.

"""Original token-budget planner; whitespace tokens are a teaching convention."""
import json


def tokens(text):
    return text.split()


def pack(documents, limit, output_reserve, overhead=0):
    if any(type(x) is not int or x < 0 for x in [limit, output_reserve, overhead]):
        raise ValueError('Budgets must be nonnegative integers')
    budget = limit - output_reserve - overhead
    if budget < 0:
        raise ValueError('Required overhead and output do not fit')
    selected, skipped, used = [], [], 0
    for name, text in documents:
        cost = len(tokens(text))
        if used + cost <= budget:
            selected.append(name)
            used += cost
        else:
            skipped.append(name)
    return dict(selected=selected, skipped=skipped, used=used,
                remaining=budget-used, total_reserved=used+output_reserve+overhead)


def visibility(sequence_length, width):
    if type(sequence_length) is not int or type(width) is not int or sequence_length < 1 or width < 1:
        raise ValueError('Positive integer length and width required')
    return [[int(max(0, i-width+1) <= j <= i) for j in range(sequence_length)]
            for i in range(sequence_length)]


def main():
    docs = [('intro', 'project notes for the review'),
            ('answer', 'door code is seven'), ('noise', 'unrelated text')]
    original = pack(docs, 14, 4, 2)
    ranked = pack([docs[1], docs[0], docs[2]], 14, 4, 2)
    print(json.dumps(dict(original=original, ranked=ranked,
                         mask=visibility(6, 3),
                         answer_visible=[('answer' in x['selected']) for x in [original, ranked]],
                         units='whitespace tokens, including authored overhead convention')))


if __name__ == '__main__':
    main()

The original order selects intro and noise, uses seven document tokens and reserves 13 in total. answer is skipped. Putting the answer first selects answer and noise, uses six document tokens and reserves 12. Both are legal requests; only the second includes the required passage. The selected IDs, rather than an unexplained “success” number, reveal why.

For six positions with width three, visible-key counts are 1, 2, 3, 3, 3, 3. The final row can directly attend only to positions 3, 4 and 5. A width larger than the sequence reduces this example to ordinary full-prefix causal visibility; width zero is rejected instead of silently creating an empty attention distribution.

The planner scans every document and counts its whitespace tokens, taking time proportional to total input text size. It stores selected and skipped IDs. The explicit visibility matrix costs quadratic space in sequence length; it is a teaching display, not an efficient sparse-attention implementation.

A larger allowance can hide a different problem

The answer-first order is an oracle demonstration: we knew where the evidence was. A real relevance ranker must be evaluated without reading reference answers at serving time. Retaining more text can improve evidence coverage while worsening distraction, latency or cost. Lost in the Middle’s position-controlled experiments motivate testing those effects; they do not provide a universal failure curve for every current model.

Keeping documents intact avoids one kind of broken context but wastes leftover space. Arbitrary truncation may sever a negation, table header or attribution. Summarization can save tokens while losing facts. Report which policy was used and retain the IDs or ranges actually delivered to the model so failures can be traced.

This budget model does not cover multimodal token accounting, architecture-specific recurrent memory or a service’s hidden serialization. It also does not show that any particular model supports a stated limit. Those are configuration facts to verify separately. If the task fits a deterministic database lookup, that lookup may be the appropriate baseline rather than a longer model prompt.

Check the request before blaming the answer

  1. Increase the output reservation from four to six while keeping the 14-token limit and two-token overhead. What document budget remains? Answer: Six tokens. The reservation removes two tokens from the previous allowance of eight; no model behavior needs to be assumed.
  2. Why does the original order include noise after skipping answer? Answer: Five tokens are already used, leaving three. The four-token passage fails, but the scan continues and the two-token passage fits. This is a stated policy, not an optimality guarantee.
  3. At position 5 with width 3, which positions are directly visible? Answer: Positions 3, 4 and 5. This includes the current position and excludes all future positions. Earlier information could still be encoded in visible hidden states.
  4. A model answers correctly after the answer passage is removed. Does that prove it read the passage? Answer: No. The result is compatible with memorized knowledge or guessing. Use counterfactual facts, matched prompts and an evidence-sensitive metric to test dependence on supplied information.

From fitting tokens to evaluating access

Transformer-XL addresses fragmentation using cached states from previous segments, with gradients stopped across that memory and positions handled consistently. That is an architectural method, not a free enlargement of any model’s window. Lost in the Middle supplies a complementary evaluation approach: vary evidence location and distractor count while controlling the target question. Neither paper says that an accepted request is necessarily understood.

Continue with long-context evaluation for a controlled positional audit and KV caching for the cost of storing reusable states. These are related but distinct questions: what is supplied, what is used, and what computation can be reused.

Make a prediction, then check

A 14-token limit reserves 4 output tokens and 2 overhead tokens. How many remain for documents?

Choose one answer

Learning objectives

  • Separate token capacity, direct visibility and successful use.
  • Calculate a request budget including overhead and reserved output.
  • Compare document packing policies without silently discarding evidence.

Prerequisites & connections

Explore related knowledge →

References

  1. Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context
    Zihang Dai; Zhilin Yang; Yiming Yang; Jaime Carbonell; Quoc V. Le; Ruslan Salakhutdinov · 2019
  2. Lost in the Middle: How Language Models Use Long Contexts
    Nelson F. Liu; Kevin Lin; John Hewitt; Ashwin Paranjape; Michele Bevilacqua; Fabio Petroni; Percy Liang · 2024

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author read Transformer-XL sections3.1–3.2/opening3.3 and Lost in the Middle PDF2–3. Six paired equations and four explained exercises; original whitespace-token budget planner, exact-fit boundaries, reorder evidence counterexample and local-mask counts. Capacity, direct access and effective use distinguished. No service token-limit or learned-model performance claim.

  • Single AI author read Transformer-XL sections3.1–3.2/opening3.3 and Lost in the Middle PDF2–3. Six paired equations and four explained exercises; original whitespace-token budget planner, exact-fit boundaries, reorder evidence counterexample and local-mask counts. Capacity, direct access and effective use distinguished. No service token-limit or learned-model performance claim.
  • Four computed SVG variants per topic;12 numeric/geometry tests and36 responsive cases passed. Twelve final Chinese-mobile/English-desktop screenshots all directly inspected after revisions. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.