Long context: can the model use the middle?
长上下文方法
Design a position-controlled retrieval audit and distinguish capacity from task performance.
long-contextThe answer is present, but the reader misses it
Put a key–value record at the beginning, middle or end of a list. Keep the query and answer unchanged. A reader that scans everything finds it in every position. A reader programmed to inspect only the first two and last two records misses the middle. Both receive the same complete list.
This is an evaluation experiment, not a language-model simulation. The edge reader’s weakness is written into its rule. We use it because the expected outcomes can be checked exactly before asking a costly model to perform a similar controlled task. A benchmark harness should first detect a failure whose cause is known.
Lost in the Middle studies evidence location using actual language models, multi-document question answering and key–value retrieval. Its position-sensitive results apply to the tested models, prompts and tasks. They do not establish that every long-context model must have the same curve. Transformer-XL tackles a different part of the problem: recurrent access across fixed segments. Extending access and using accessible information effectively are separate achievements.
Vary one obstacle at a time
Let be the number of records and the zero-based target position. Represent its relative location by:
For a one-record input, relative position is not defined by this expression; report it as its own case. Our program uses integer positions directly. It moves one unique target while retaining the same other key–value records, preventing content changes from being mistaken for a position effect.
Let be one when reader returns the reference answer. Accuracy across all positions is:
Averages can conceal unusable positions. Record both the worst result and the best-to-worst gap:
For real models, each position normally needs many independently constructed questions, so would be replaced by a per-position estimated accuracy. A single deterministic target per position has no sampling-based confidence claim.
Our edge reader with nonnegative integer width inspects the union:
Overlapping ends are counted once. With one unique target placed uniformly over all positions, its exact accuracy is:
With , lengths 4, 8 and 12 give 1, one half and one third. Full scanning and exact-key retrieval each give 1. At length 8, the edge pattern is 1, 1, 0, 0, 0, 0, 1, 1: a deliberately constructed positional failure, not a measured neural attention distribution.
An operational context criterion must name a task, test grid and threshold. For this grid and a requirement that every position succeeds, define:
This number describes these tests. It does not prove that all lengths below four pass for every task, nor that every untested length above four fails. It is also distinct from Transformer-XL’s paper-specific relative effective context length measure; do not reuse that metric’s name for this simpler criterion.
Three readers and an inspectable failure
The standard-library program creates unique keys, inserts target → violet at each possible location and compares three explicit policies. Exact retrieval filters by the query key before the reader runs. It is a strong non-AI baseline for this particular structured task.
"""Controlled positional retrieval audit of explicit readers, not an LLM benchmark."""
import json
def records(n, target_position):
if type(n) is not int or n < 1 or not 0 <= target_position < n:
raise ValueError('A valid target position is required')
rows = [('key'+str(i), 'value'+str(i)) for i in range(n-1)]
rows.insert(target_position, ('target', 'violet'))
return rows
def lookup(rows, key):
hits = [value for name, value in rows if name == key]
if len(hits) != 1:
return None
return hits[0]
def read(rows, key, edge=None):
if edge is None:
chosen = rows
else:
if type(edge) is not int or edge < 0:
raise ValueError('Nonnegative edge width required')
indices = sorted(set(range(min(edge, len(rows)))) |
set(range(max(0, len(rows)-edge), len(rows))))
chosen = [rows[i] for i in indices]
return lookup(chosen, key)
def evaluate(n, edge=2):
outputs = []
for p in range(n):
rows = records(n, p)
retrieved = [row for row in rows if row[0] == 'target']
outputs.append(dict(position=p, full=int(read(rows, 'target') == 'violet'),
edges=int(read(rows, 'target', edge) == 'violet'),
exact_retrieval=int(read(retrieved, 'target') == 'violet')))
return dict(length=n, cases=outputs,
accuracy={k:sum(r[k] for r in outputs)/n
for k in ['full', 'edges', 'exact_retrieval']},
worst_position=min(r['edges'] for r in outputs))
def main():
print(json.dumps(dict(results=[evaluate(n) for n in [4, 8, 12]],
longest_all_positions_pass=max(n for n in [4, 8, 12]
if evaluate(n)['worst_position'] == 1),
claim='Edge bias is programmed, not discovered in a trained model')))
if __name__ == '__main__':
main()
The output records every case, not just an aggregate score. full and exact_retrieval are correct everywhere; edges is correct at all four positions for length four, four of eight for length eight and four of twelve for length twelve. The longest tested length passing at every position is four.
lookup refuses ambiguous evidence: no match or more than one match returns None. This matters because otherwise a duplicated key with conflicting values could turn a purported position test into a conflict-resolution test. Edge width zero selects nothing; overlapping edges are deduplicated with a set.
The simple full lookup takes linear time in the number of records. Our retrieval baseline also scans linearly rather than using an index. Across every target position, fixture construction and scanning take quadratic time in ; this tiny harness is not designed to evaluate million-record inputs efficiently. Keep the fixture generator separate from measured model latency.
Retrieval is only one long-context skill
Exact-key lookup does not test paraphrase, arithmetic across distant passages, chronological updates, contradiction or long-form synthesis. A system can ace this task and fail those. Add separate task families instead of relabeling a retrieval score as general comprehension.
For model evaluation, fix model version, tokenizer, prompt template, generation settings and scoring rule. Sweep lengths and evidence positions; use multiple questions per cell. Include an oracle input containing only necessary evidence and a no-evidence control. Log truncation or request rejection separately from wrong answers. Where possible, use matched questions across positions so differences are not driven by question difficulty.
The paper’s multi-document setup uses 2,655 NaturalQuestions-Open cases and constructs distractors that do not contain annotated answers, while acknowledging possible answer ambiguity. That detail matters: “the answer was in the input” is not enough if several documents support conflicting plausible answers. Our unique-key fixture removes that ambiguity intentionally; it does not reproduce the paper’s dataset or percentages.
Measure the failure the average hides
- With 12 records and edge width 3, what is accuracy across all target positions? Answer: Six of twelve, or one half. The first and last three do not overlap; the other six positions are never inspected.
- What are worst-position accuracy and the gap for length eight with width two? Answer: Zero and one. Some positions always fail and others always pass, despite average accuracy one half.
- Why does exact retrieval score perfectly here? Answer: The target key is explicit and unique, so exact filtering retains precisely the needed record. This establishes a structured-task baseline, not semantic retrieval quality.
- Can these results show that increasing a real model’s window harms it? Answer: No. The edge policy is hand-coded and fixed. Test an actual model with controlled inputs, versioned settings and repeated questions before making that empirical claim.
Architecture and evaluation should meet
Transformer-XL reuses previous-segment hidden states and stops gradients through the cached memory. Its method changes information paths and positional handling. Lost in the Middle changes the evaluation lens: the location of useful evidence is itself an experimental variable. A long-context claim is stronger when both the mechanism and the position-controlled outcomes are documented.
The author repositories provide model implementations and evaluation/data-generation organization. They are reference points, not code executed by this example. Move from this deterministic harness to a real model only after verifying that the same question, evidence and scoring convention survive each position change. For request budgeting itself, return to context windows.
Make a prediction, then check
Does accepting a longer input prove that the model uses all of it effectively?
Learning objectives
- Control length and evidence position separately.
- Compare full, edge-only and exact-retrieval baselines.
- Report worst-position behavior alongside average accuracy.
Prerequisites & connections
Explore related knowledge →References
- 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 - Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context
Zihang Dai; Zhilin Yang; Yiming Yang; Jaime Carbonell; Quoc V. Le; Ruslan Salakhutdinov · 2019
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author read Lost in the Middle Figure1/section2.1/PDF2–3 and Transformer-XL recurrence. Six paired equations and four explained exercises. Controlled unique-key fixtures, complete position sweep, full/edge/exact-retrieval baselines, missing/ambiguous key behavior and exact accuracy formula. Edge bias intentionally programmed, not an LLM replication or universal failure law.
- Single AI author read Lost in the Middle Figure1/section2.1/PDF2–3 and Transformer-XL recurrence. Six paired equations and four explained exercises. Controlled unique-key fixtures, complete position sweep, full/edge/exact-retrieval baselines, missing/ambiguous key behavior and exact accuracy formula. Edge bias intentionally programmed, not an LLM replication or universal failure law.
- 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:
- Lost in the Middle: How Language Models Use Long Contexts · PDF2–3 visually checked, Figure1 and section2.1: controlled evidence position, 2655 NaturalQuestions-Open cases, distractor construction. Findings concern evaluated models/tasks; our deterministic reader is not a replication.
- Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context · Read sections3.1–3.2 and opening3.3; PDF3 visually checked: fixed segments, stopped-gradient recurrence and contextual states. No training or benchmark reproduced.
Related topics