Search

Search papers and lessons

Lost in the Middle: How Language Models Use Long Contexts

Nelson F. Liu, Kevin Lin, John Hewitt et al. · 2023

Liu et al. (2023) show that language models answer best when the relevant passage sits at the start or end of a long prompt, and much worse when it sits in the middle.

On this page

  • Colour = topic mix
  • Neural network basics
  • Calculus
  • Discrete math
  • Linear algebra
  • Probability
  • Architectures
  • ReadReady to readNot yet

TL;DR

Liu and colleagues test how well language models use information placed at different points of a long prompt. Their main result is a U-shaped curve: a model answers best when the passage that contains the answer comes first or last, and its accuracy drops, sometimes below its no-document baseline, when that passage sits in the middle. The effect appears in both retrieval-style question answering and a synthetic key-value lookup, so a long context does not mean the model uses all of it.

Builds on: Transformer, Positional Encoding, Retrieval-Augmented Generation, Instruction Tuning, Encoder-Decoder Architecture · Leads to: the long-context evaluation practice that later model reports follow (no dependents in the graph yet)

Why it mattered

Retrieval-augmented systems put several search results into one prompt and ask the model to answer from them. The paper's test is a close model of that setting. In its experiments the answer passage was one of 10, 20 or 30 documents, and the position of that passage was the only thing that changed. The paper reports that GPT-3.5-Turbo's accuracy can drop by more than 20 percent depending on where the answer sits. With 20 or 30 documents, its worst positions fall below the 56.1 percent it scores with no documents at all. That no-document score is the closed-book baseline; the score with only the answer document is the oracle baseline. Both are explained in the walkthrough below.

The result changed how builders think about long context. A context window of 16K or 100K tokens says how much text fits, not how much the model will use. The paper also shows that a model with a longer window is not automatically better at using a window it already had: GPT-3.5-Turbo and GPT-3.5-Turbo (16K) produce nearly the same curve when both fit the input. Its suggestions, such as moving the most relevant passages to the front, are now common advice for retrieval pipelines.

The problem

A language model reads its whole prompt in one pass and writes an answer. In principle attention lets it reach any token. In practice, nobody had measured, for models with long windows, whether the position of a needed fact changes the answer. Earlier long-context work had measured perplexity or retrieval of synthetic tokens, which is not the same as using a passage to answer a question.

The paper asks two questions. First, does the position of relevant information change task performance when the content is held fixed? Second, if it does, what causes it? It studies two tasks: multi-document question answering, which mirrors retrieval, and a key-value lookup. In the key-value task the prompt is a list of pairs, each a random UUID string (the key) followed by another UUID (its value); the model is given one key and must output its value. Nothing in the task needs world knowledge, so it isolates the act of finding the right item in a long input.

How it works

The walkthrough follows one tiny illustrative prompt through the multi-document setup, then describes what the experiment changes.

  1. Build the prompt. Take a question, such as "Who wrote the play Hamlet?", and five documents. Exactly one document contains the answer. The other four are distractors, passages about other topics. Put the documents in a numbered list and append the question after them. Check: the prompt has one answer passage and four distractors.
  2. Choose the position. Pick where the answer passage goes. Say document 3 of 5, the middle. The other documents keep their relative order. Check: moving the answer changes only where it sits; the content is the same.
  3. Feed the prompt to the model. The model reads all five documents and the question as one token sequence, the way any Language Model does, and writes its answer one token at a time. Check: nothing in the model is changed between runs.
  4. Score the answer. The paper marks an answer correct if any accepted answer string appears in the output. Check: "William Shakespeare" passes, while "Christopher Marlowe" fails.
  5. Repeat over positions and lengths. Move the answer to position 1, then 2, and so on, and repeat for many questions. Then change the number of documents from 10 to 20 to 30. Check: each cell of the table is an accuracy over the same question set.
  6. Read the curve. Plot accuracy against the answer's position. The paper finds high accuracy at position 1 and at the last position, and a clear dip in the middle. Check: the curve has two high ends and a low middle, which is the U shape.

The experiment changes only the order of the same documents, so any change in accuracy comes from position. Table 1 gives the reference points: closed-book accuracy (no documents) and oracle accuracy (only the answer document). Those two numbers mark the range in which the middle-position results must be read.

flowchart LR
  A["Question"] --> D["Prompt: documents in order, answer at position p"]
  B["Answer document"] --> D
  C["Distractor documents"] --> D
  D --> E["Model reads the whole prompt"]
  E --> F["Answer scored: correct or not"]
  F --> G["Accuracy at position p, averaged over questions"]

The math

Let a prompt contain kk documents, d1,…,dkd_1, \dots, d_k, and let p∈{1,…,k}p \in \{1, \dots, k\} be the position of the one document that contains the answer. For a question qq with accepted answers Aq\mathcal{A}_q and model output y^q\hat y_q, the correctness indicator is

cq=1[∃ a∈Aq:a appears in y^q].c_q = \mathbf{1}\left[\exists\, a \in \mathcal{A}_q : a \text{ appears in } \hat y_q\right].

The accuracy at position pp is the average over a question set Q\mathcal{Q}:

Acc(p)=1∣Q∣∑q∈Qcq(p).\mathrm{Acc}(p) = \frac{1}{|\mathcal{Q}|} \sum_{q \in \mathcal{Q}} c_q(p).

In words: Acc(p)\mathrm{Acc}(p) is the fraction of questions answered correctly when the answer sits at position pp, and 1[⋅]\mathbf{1}[\cdot] equals 1 when its condition holds and 0 otherwise. The paper's finding is that Acc(p)\mathrm{Acc}(p) is high at p=1p = 1 and p=kp = k and lower for middle values of pp.

Step 1 in symbols: the prompt

The prompt is the concatenation [d1,…,dk,q][d_1, \dots, d_k, q] with exactly one dpd_p containing an answer to qq. Changing pp permutes the documents and leaves the set unchanged, which is why any difference in Acc(p)\mathrm{Acc}(p) is a position effect.

Step 2 in symbols: the position

pp is a position index, not a token index. Dividing by the document count gives a relative position, p/kp / k, which lets curves for different numbers of documents be drawn on one axis: near 0 at the start of the context and near 1 at the end.

Step 3 and 4 in symbols: the score

cqc_q is 1 or 0 for each question. The paper uses Acc(p)\mathrm{Acc}(p) as its primary measure, so its results are the averages of these indicators.

Step 5 and 6 in symbols: the shape

A U shape means Acc(1)\mathrm{Acc}(1) and Acc(k)\mathrm{Acc}(k) are both larger than Acc(p)\mathrm{Acc}(p) for most middle values pp. The paper also reports the gap between best and worst positions, and it compares that gap with the closed-book and oracle accuracies.

Results

The main evidence is the multi-document question answering experiment with 10, 20 and 30 documents, where only the position of the answer document changes. Accuracy is highest at the start and end of the context and degrades in the middle. For GPT-3.5-Turbo the drop can exceed 20 percent, and in the worst case with 20 or 30 documents it falls below its closed-book accuracy of 56.1 percent. The clearest reference points are for GPT-3.5-Turbo: 56.1 percent closed-book and 88.3 percent oracle, as cited above. The position curve has to be read between those two numbers. Placing the question both before and after the documents (query-aware contextualisation) makes the key-value task much easier for most models, and it changes the multi-document trends only slightly.

In the key-value task, several models lose accuracy as the number of pairs grows, and the paper traces part of this to the same position effects. Other findings in the paper concern base models before instruction tuning, which show the same U shape, and the open-domain setting, where reader accuracy stops improving noticeably after about 20 retrieved documents.

Limits. The main experiments use one question set (NaturalQuestions-Open), greedy decoding, and fixed prompts, and some models are evaluated only on subsets. Accuracy judges whether an accepted answer string appears, which is a proxy for use. The results describe these model versions at the time of testing, not all long-context systems.

Common mistakes and tradeoffs

It is tempting to think a longer context window means the model uses all of the window. In fact the window sets how much text fits, and the paper finds that extended-context versions of a model do no better than the standard version when the input fits both. Use measurements of position, not the window size, to judge a long-context model.

It is tempting to think the U shape is a quirk of retrieval. In fact the paper finds it in the synthetic key-value task too, where the model must match a key to a value, and in base models before instruction tuning. The curve is a property of how these models attend to long inputs, not of one dataset.

It is tempting to think that putting more documents always helps. In fact the paper's open-domain experiments show that extra retrieved documents add little beyond about 20 documents, while latency and cost grow with length. More context is a tradeoff, not a free gain.

It is tempting to think the fix is an encoder-decoder model. In fact the encoder-decoder models studied (Flan-UL2, Flan-T5-XXL) are robust to position only within their trained length; beyond it they show the same curve, so the architecture helps but does not solve the problem.

When to use these findings: when a prompt holds several passages and the answer must come from one of them. Order the most relevant passages first or last, and pass fewer passages when reranking is weak. When not to use them: when the whole input is short enough that position barely matters, or when the task needs many passages to be read together, such as summarising a long document, where a single answer position is not the right measure. Alternatives include reranking before the prompt, truncating the list, and testing position explicitly before choosing a model.

Background and history

Earlier work on sequence models had found position effects in small networks. Khandelwal and colleagues (2018) showed that LSTM language models use context mainly for the most recent words and make only coarse use of earlier ones. Liu and colleagues extended the picture to long windows and to retrieval-style tasks.

The paper's U shape has a name borrowed from psychology: the serial-position effect, in which people recall the first and last items of a list better than the middle ones. The paper draws this link explicitly, while stating that the mechanism in a transformer is a separate question.

The paper appeared on arXiv in 2023 and was later published in Transactions of the Association for Computational Linguistics. It caught on because it turned a vague worry into a simple, reproducible test with a clear control, and because it reported results for the models that builders were already using.

Reading guide

  1. Abstract and Section 1. The claim: models do not robustly use information in long inputs, and the curve is U-shaped. Needs Retrieval-Augmented Generation for the setting the paper mimics.
  2. Section 2, Multi-Document Question Answering. The setup, the three document counts, and Table 1. Needs Open-Domain Question Answering and Language Model.
  3. Section 3, Key-Value Retrieval. The synthetic task and why it isolates retrieval. Needs Attention Mechanism and Subword Tokenization, since the keys are UUID strings.
  4. Section 4, Why the curve appears. Architecture (decoder-only versus encoder-decoder, which needs Encoder-Decoder Architecture), query-aware contextualisation, and instruction tuning (Instruction Tuning). Position effects follow Positional Encoding and Autoregressive Model.
  5. Section 5, Open-domain QA. Retriever recall against reader accuracy. Needs Retrieval-Augmented Generation again.
  6. Appendices. Ambiguity, random distractors, GPT-4 and Llama-2 results. Read after Section 4.

Worked examples and recap

Example
1. Tiny: three documents, one answer

Set-up: three documents, the answer is in one of them, and the model answers correctly only when the answer passage is at position 1 or 3.

  1. Position 1: the model answers correctly. Accuracy for this case: c=1c = 1.
  2. Position 2: the model answers with a distractor. Accuracy: c=0c = 0.
  3. Position 3: the model answers correctly. Accuracy: c=1c = 1.
  4. Over the three positions, the accuracy values are (1,0,1)(1, 0, 1). The average over the three positions is (1+0+1)/3=2/3(1 + 0 + 1) / 3 = 2/3.

Interpretation: a model that uses only the ends of the context scores 2/32/3 here, not 1, and the failure is entirely in the middle position.

Example
2. Standard: a question set with 10 documents

Set-up: 200 questions, each with 10 documents. For the answer at position 1 the model is correct on 150 questions, at position 5 on 90 questions, and at position 10 on 140 questions.

  1. Acc(1)=150/200=0.75\mathrm{Acc}(1) = 150 / 200 = 0.75.
  2. Acc(5)=90/200=0.45\mathrm{Acc}(5) = 90 / 200 = 0.45.
  3. Acc(10)=140/200=0.70\mathrm{Acc}(10) = 140 / 200 = 0.70.
  4. The drop from the best end to the middle is 0.75−0.45=0.300.75 - 0.45 = 0.30, or 30 percentage points.
  5. The end positions are still 5 points apart, so the curve is not symmetric.

Interpretation: the position effect is larger than the gap between the two ends. The same question set would produce the same drop if the documents were reordered, which is the paper's control.

Example
3. Realistic: a retrieval reader with the answer in the middle

Set-up: a retrieval-augmented system passes 20 search results to a model, in order of relevance. On a question set where the paper's GPT-3.5-Turbo scores 56.1 percent closed-book and 88.3 percent with only the answer document (Table 1), suppose the same model scores 52 percent with the answer at position 10 (an illustrative number, not from the paper). The answer is the 10th of 20 results.

  1. The closed-book score is the floor: with no documents the model is right on 56.1 percent of questions by its own memory.
  2. The oracle score is the ceiling: with only the right document, it is right on 88.3 percent.
  3. The middle-position score, 52 percent, is below the floor.
  4. So in this case the extra documents hurt. The model is worse off with the retrieved passages than with no passages at all.
  5. Try it: if the system moves the same passage to position 1, and the score there is 80 percent (also illustrative), what is the gain over the middle position, and what does it say about reranking? Answer: the gain is 80−52=2880 - 52 = 28 points. It says reranking, which moves the most relevant passage to the front, is worth doing even when retrieval itself is unchanged.

Recap

  • A model's answer accuracy depends on where the needed passage sits in a long prompt, even when the content is the same.
  • The curve is U-shaped: high at the start and end, low in the middle. Extended windows do not remove it.
  • The effect appears in multi-document question answering and in synthetic key-value retrieval, and it is present in base models before instruction tuning.
  • Encoder-decoder models are robust only within their trained length; beyond it they show the same curve.
  • Read next: Retrieval-Augmented Generation, which uses the ordering and truncation advice in practice, and In-Context Learning, which depends on the same prompts.

Check yourself

QuestionRecall: what is the U-shaped curve in this paper, in one sentence?Show answer

Accuracy is highest when the answer passage is at the beginning or the end of the context, primacy and recency, and lowest when it is in the middle of a long context, even though the content is the same.

QuestionCompute: a set of 100 questions has the answer at position 1 correct on 62 questions, and at the middle position correct on 40. What are the two accuracies and their difference?Show answer

Acc(1)=62/100=0.62\mathrm{Acc}(1) = 62 / 100 = 0.62 and Acc(middle)=40/100=0.40\mathrm{Acc}(\text{middle}) = 40 / 100 = 0.40. The difference is 0.62−0.40=0.220.62 - 0.40 = 0.22, a drop of 22 percentage points.

QuestionWhy does the paper use a no-document baseline and an oracle baseline alongside the position curves?Show answer

They set the range in which the position results must be read. The closed-book score shows what the model knows without any documents, and the oracle score shows the best it can do with only the answer document. If a middle-position score falls below the closed-book score, the documents actually hurt the answer, which is the paper's worst case.

QuestionApplied: a team puts 25 search results in the prompt, with the most relevant result at position 13. The answer quality is poor, and they propose adding more results to fix it. What would you advise?Show answer

Do not add more results. The paper shows that extra documents add little and that position drives the error. Move the most relevant result to the front or the end, rerank the list, and pass fewer results. Then measure accuracy by position on their own questions before choosing a longer window.

Sources

Read the full paper

Nelson F. Liu, Kevin Lin, John Hewitt et al., 2023. arXiv:2307.03172