When large language models (LLMs) process long sequences of text, they do not treat all positions equally. Even though modern Transformer architectures can technically accept tens or hundreds of thousands of tokens, their ability to recall and utilize information drops significantly when that information is buried in the middle of a prompt. This phenomenon, widely known as the "lost in the middle" problem, stems from inherent positional biases in Transformer attention mechanisms: specifically, a strong primacy effect (paying attention to the very beginning of a prompt) and an even stronger recency bias (paying attention to the very end of a prompt, closest to the generation target).
Rather than modifying model architectures or undergoing expensive fine-tuning, a prominent line of research focuses on contextual position optimization. By strategically reordering documents, in-context examples, and instructions to occupy these high-attention zones, we can dramatically improve model performance for free.
Mitigating the "Lost in the Middle" Effect via Document Repacking
In Retrieval-Augmented Generation (RAG) systems, a retriever typically fetches a set of relevant documents and concatenates them into the LLM's prompt. Standard practice simply appends them in descending order of their retrieval score. However, this often places moderately relevant documents at the end and pushes highly critical documents into the dead zone in the middle of the context window.
To combat this, researchers have developed document repacking strategies. As demonstrated by Xiaohua Wang et al. in their systematic grid search of RAG configurations, reordering retrieved evidence to place the most pertinent information at the extreme beginning and end of the prompt context significantly mitigates center-context recall degradation (Searching for Best Practices in Retrieval-Augmented Generation).
Standard Order: [Doc 1 (Best)] -> [Doc 2] -> [Doc 3] -> [Doc 4 (Worst)] -> [Query]
^ ^
Buried in the Middle (Low Attention)
Repacked Order: [Doc 1 (Best)] -> [Doc 3] -> [Doc 4 (Worst)] -> [Doc 2 (Good)] -> [Query]
^ ^
Primacy Zone (High Attention) Recency Zone (High Attention)
Several frameworks leverage this structural adjustment to maximize the utility of long-context models:
- Multi-Agent Filtering: Chia-Yuan Chang et al. introduce a training-free framework that uses a committee of agents to filter out irrelevant documents, sorting the remaining high-quality information to the prompt's extremities to prevent the generator from ignoring them (MAIN-RAG: Multi-Agent Filtering Retrieval-Augmented Generation).
- Reinforcement Learning for Ordering: The R4 framework by Dongyang Li et al. treats document ordering as a reinforcement learning problem, dynamically optimizing the placement of key documents at the beginning and end of the context window to maximize factual question-answering performance (R4: Reinforced Retriever-Reorder-Responder for Retrieval-Augmented Large Language Models).
- Prompt Compression and Denoising: Frameworks like LongLLMLingua by Huiqiang Jiang et al. combine token-level compression with relevance reordering, ensuring that compressed, high-salience tokens are placed where the model's attention naturally peaks (LongLLMLingua: Accelerating and Enhancing LLMs in Long Context Scenarios via Prompt Compression). Similarly, Jiwei Tang proposes a training-free framework that uses an auxiliary model to generate sub-questions, guiding the extraction and reordering of critical segments directly to the front of the prompt (Perception Compressor: A Training-Free Prompt Compression Framework in Long Context Scenarios).
- Black-Box Alignment: Lingxi Zhang et al. show that even when dealing with black-box LLMs, teaching a retriever to rank documents based on actual LLM utility—and reordering them during inference to place critical information at the context boundaries—yields substantial accuracy gains (ARL2: Aligning Retrievers with Black-box Large Language Models via Self-guided Adaptive Relevance Labeling).
This positional optimization is not limited to standard text documents. For instance, when reasoning over large tables, Yuxiang Wang et al. found that flattening tables into text causes models to miss information hidden in the middle. By converting tables into graphs, sorting the extracted triples by salience, and placing them at the very beginning of the prompt, they drastically improve reasoning robustness (Beyond Linearization: Attributed Table Graphs for Table Reasoning). Furthermore, Marco Alessio et al. demonstrate that semantically clustering retrieved sentences and sorting these clusters in descending order of query similarity effectively leverages the primacy effect to boost response quality by up to 54% (Improving RAG Systems via Sentence Clustering and Reordering).
Exploiting Recency Bias via Proximity-Based Ordering
While the primacy effect makes the beginning of a prompt valuable, decoder-only Transformer architectures exhibit an even stronger bias toward tokens placed immediately before the generation point. This is because the final tokens are the most recent items in the model's processing buffer, exerting the strongest causal influence on the next-token prediction.
In In-Context Learning (ICL), the order of few-shot demonstrations matters immensely. The authors of the D.Va framework demonstrate that ordering demonstrations by descending informativeness—placing the highest-quality, most relevant examples closest to the end-of-prompt test query—maximizes task performance by capitalizing on this recency bias (D.Va: Validate Your Demonstration First Before You Use It).
This principle of relevance-ordered sequence reversal is highly effective across specialized domains:
- Molecular Chemistry: Jiatong Li argues that reversing the order of retrieved molecular examples to position the most similar data closest to the target query prevents the model from losing focus during complex translation tasks (Large Language Models are In-Context Molecule Learners).
- Repository-Level Code Completion: In software engineering, code completions often depend on context spread across multiple files. Tianyang Liu et al. formalize the proximity-based context ordering principle, showing that placing the most relevant external code snippets at the very end of the input sequence, right next to the generation point, leads to significantly higher accuracy than placing them at the beginning (RepoBench: Benchmarking Repository-Level Code Auto-Completion Systems). This aligns with findings by Qi Lv et al., who utilize semantic reordering to place the most relevant code examples at the end of the prompt to improve robotic perception-planning plans (RoboMP2: A Robotic Multimodal Perception-Planning Framework with Multimodal Large Language Models).
- General RAG Benchmarking: Evaluating these behaviors systematically, Gregor Karetka et al. confirm across diverse NLP tasks that positioning the highest-ranked retrieved examples at the end of the context window, closest to the final instruction, consistently enhances the model's ability to utilize that information (RAGthoven: A Configurable Toolkit for RAG-enabled LLM Experimentation).
Terminal Instruction Placement and Infix Prompting
The structural optimization of prompts extends beyond data documents and few-shot examples; it applies fundamentally to the placement of task instructions themselves.
Traditionally, prompts are structured as [Instruction] -> [Context/Data] -> [Response Target]. However, in long-context scenarios, this causes "instruction forgetting." By the time the model processes thousands of tokens of context data, the initial instruction tokens have suffered severe attention decay.
To solve this, Yijin Liu et al. advocate for Terminal Instruction Placement (or Post-Instruction), where the task command is moved to follow the input data rather than preceding it (Instruction Position Matters in Sequence Generation with Large Language Models). Placing the instruction immediately before the generation point ensures it remains within the model's immediate attention window, yielding massive performance jumps (such as a 9.7 BLEU point increase in zero-shot translation) without any fine-tuning.
Traditional Layout: [Task Instruction] -> [Massive Context Data] -> [Generation Target]
^
Model forgets the instruction
Terminal Layout: [Massive Context Data] -> [Task Instruction] -> [Generation Target]
^
Instruction is fresh in attention buffer
This structural shift manifests across several distinct prompting paradigms:
- Multi-Hop QA: Muhammad Khalifa et al. demonstrate that placing task instructions at the end of a long context window, just before the generation target, guides the model far more effectively than starting with them (Few-shot Reranking for Multi-hop QA via Language Model Prompting).
- Infix Prompting for Math Reasoning: When generating step-by-step plans for math word problems, Mengxue Zhang et al. show that infix prompting—placing instructional prompts after the problem context—maintains the relevance of the problem context within the model's attention mechanism while strictly enforcing the execution plan (Interpretable Math Word Problem Solution Generation via Step-by-step Planning).
- In-Context Vocabulary Acquisition: In probing how models learn novel words during inference, Julian Martin Eisenschlos et al. find that providing a dictionary definition as a suffix after a task sentence leads to significantly better performance than providing it as a prefix, proving that the recency of the definition dictates the model's ability to apply it (WinoDict: Probing language models for in-context word acquisition).
- Prompt Optimization and Security: Even when using LLMs to optimize prompts iteratively, Chengrun Yang et al. sequence previous meta-prompt solutions from lowest to highest score, deliberately placing the highest-scoring examples at the end to bias the model toward refining the most successful strategies (Large Language Models as Optimizers). This principle also acts as a security mechanism: Yulin Chen et al. discover that prompt injection defenses are significantly more effective when defensive "shield instructions" are placed after untrusted user data, exploiting the model's recency bias to ensure the safety directive overrides malicious user text (Defense Against Prompt Injection Attack by Leveraging Attack Techniques).
Ultimately, understanding that Transformers are highly sensitive to information topology allows practitioners to treat prompt design as a spatial optimization problem. By rearranging the layout of data, examples, and instructions to match the natural peaks of the attention mechanism, we can extract significantly higher reasoning capabilities out of frozen language models.