                                                                 Y OU O NLY U SE R EACTIVE A TTENTION S LICE
                                                                       FOR L ONG C ONTEXT R ETRIEVAL



                                                                   Yun Joon Soh 1 Hanxian Huang 1 Yuandong Tian 2 Jishen Zhao 1


                                                                                              A BSTRACT
                                             Supporting longer context for Large Language Models (LLM) is a promising direction to advance LLMs. As
arXiv:2409.13695v1 [cs.CL] 3 Sep 2024




                                             training a model for a longer context window is computationally expensive, many alternative solutions, such
                                             as Retrieval Augmented Generation (RAG), have been used. However, most existing RAG methods adopt
                                             embedding-based retrieval that falls short on long contexts.
                                             To address such challenges, we propose an attention-based retrieval technique, You Only Use Reactive Attention
                                             slice (YOURA). YOURA leverages a novel retrieval heuristic called reaction score to rank the relevance of each
                                             sentence in the input context with the query sentence. Intuitively, we measure how the per-token attention score
                                             “reacts” to the query and greedily retrieves the most reactive sentences. Internally, YOURA generates a token-
                                             indexed vector (called reaction vector) for the whole input context. To map each sentence to the token-indexed
                                             vector, we propose an Embedding-Agnostic Sentence Yield (EASY), a best-effort token wiggling algorithm.
                                             We evaluate our retrieval technique on three open-source pre-trained LLM models across six LongBench QA
                                             datasets. Our technique achieves up to 30% vLLM inference throughput improvement for serving long-context
                                             queries — with a nearly identical quality score to the simple yet effective truncate-middle approach (Bai et al.,
                                             2023).

                                        1    I NTRODUCTION                                                      a. Input Context & Query           c. Our proposal vs. embeddig-distance based

                                                                                                            C1: A woman is wearing a red dress.         Current             Our Proposal
                                        Pre-trained Large Language Models (LLM) are widely ex-              S2: She is walking on t he st reet .
                                                                                                                                                      Emb. Distance           Reaction Score

                                        plored for various Natural Language Processing (NLP) tasks.         S3: Her name is Mary.
                                                                                                                                                       S1    S2    S3            S1      S2       S3


                                        To enhance the model for more complex tasks, researchers
                                                                                                             Q: Where is Mary?
                                        seek ways to extend the LLM’s context window size via                                                          Retrieve                 Retrieve
                                                                                                                                                    Semantically Close         Most reactive
                                        fine-tuning the pre-trained model (Chen et al., 2023b; Man-               b. Performance Teaser
                                        grulkar et al., 2022), proposing advanced attention mecha-                                                      Augmented               Augmented
                                        nisms (Xiao et al., 2024; Zhang et al., 2023), and improving                 Quality                           Her name is Mary.
                                                                                                                                                        Where is Mary?
                                                                                                                                                                           She is walking on t he st reet .
                                                                                                                                                                                  Where is Mary?
                                                                                                                 +3% / +9% / +11%
                                        Retrieval Augmented Generation (RAG). However, fine-                     Llama2    Llama3     Mistral

                                        tuning requires additional computational power for each                                                         Generated                Generated
                                                                                                                     Inference                        Mar y i s i n t he
                                        pre-trained model and is often targeted for specific tasks                  Throughput                         l i v i ng r oom.
                                                                                                                                                                               On t he St r eet


                                        or datasets. Advanced attention mechanisms conceptually                   +2% / 13% / 31%
                                                                                                                 Llama2    Llama3     Mistral
                                                                                                                                                   Context unaware,
                                                                                                                                                   generates incorrect
                                                                                                                                                                           Correct response
                                                                                                                                                                           with a better
                                        extend the context window by selectively choosing a subse-                                                 responses.              context-awareness

                                        quence of tokens for attention but are susceptible to details
                                        due to the nature of dropping information at the token level.
                                        RAG splits the contextual text into smaller chunks and re-         Figure 1. YOURA improves the retrieval quality and inference
                                        trieves a subset of chunks before inferencing based on the         throughput by retrieving only the “reactive” sentences.
                                        semantical distance to the query in the embedding vector
                                            1
                                              Department of Computer Science and Engineering, Univer-
                                        sity of California, San Diego, San Diego, USA 2 Meta AI (FAIR),    space. RAG’s retrieval nature has many benefits; it reduces
                                        Menlo Park, California, USA. Meta-affiliated author served in
                                        an advisory role and all data processing occurred at the Univer-
                                                                                                           the input size to process, which reduces the computation dur-
                                        sity of California, San Diego. Correspondence to: Jishen Zhao      ing inference (Luo et al., 2024) and improves the accuracy
                                        <jzhao@ucsd.edu>.                                                  by eliminating distracting information (Catav, 2023).
                                                                                                           A high-quality retrieval is crucial for RAG but often suf-
                                                                                                           fers from lower accuracy because (1) the common words
in both the query and text chunk put the semantic distance            returns token indices for each sentence.
closer and (2) the semantically identical, but alphabetically
                                                                      We evaluate (1) how much YOURA improves the answer
different words distance the query and text chunk in the
                                                                      quality for the 6 LongBench QA datasets (Bai et al., 2023),
embedding vector space. For example, the similarity dis-
                                                                      (2) how YOURA reduces the inferencing computation cost
tance between a query (“Where is Mary?”) and a sentence
                                                                      by retrieving fewer, yet sufficient tokens for proper question-
(“Her name is Mary”) may be closer to a sentence (“She is
                                                                      answering, and (3) how well our EASY algorithm maps
at home”) resulting in suboptimal retrieval. 1
                                                                      raw texts to the token-indices. Without any pre-training or
We propose a fine-tuning-free, attention-based retrieval strat-       additional embeddings, YOURA shows a higher retrieval
egy, which can be applied to various off-the-shelf pre-trained        ratio (context token count / retrieved token count) for open-
LLMs to achieve improved text generation quality. Our key             source pre-trained models (Llama2, Llama3, Mistral) by up
insight is that the attention in a pre-trained model already          to ×1.3 and still achieves a higher answer quality than prior
contains information about which tokens are important for             embedding-based retrieval approaches. With the smaller
the given query. Figure 2 illustrates the difference between          number of retrieved tokens, YOURA improves up to 30%
the embedding-based retrieval and our proposal; (a) is a typi-        vLLM serving throughput. Our EASY algorithm shows an
cal embedding-based retrieval where embedding vectors for             average of 93.7% sentence-to-token-index mapping accu-
both the query and context chunk list are generated through           racy.
an embedding layer. Figure 2 (b) is another simple yet effec-
                                                                      We contribute the following.
tive alternative to the embedding distance-based approach,
truncate-middle. Since the introduction and conclusion of                 • We propose You Only Use the Reactive Attention
most documents contain the most important information,                      slice (YOURA) algorithm, a fine-tuning-free, attention-
the truncation approach naively takes out the middle of the                 based retrieval algorithm. YOURA improves QA qual-
context so that the remaining text fits within the LLM’s                    ity by up to 10% while improving inference throughput
context window size. Unlike embedding-based retrieval or                    by up to 30%2 .
truncation, we propose an attention-based retrieval.
                                                                          • We propose an Embedding-Agnostic Sentence Yield
Our proposed technique, You Only Use Reactive Attention                     (EASY) algorithm, which can map individual sen-
slice (YOURA) Figure 2 (c), is a novel attention-based                      tences to their vector slice at 93% accuracy.
retrieval technique. Anonlogically speaking, we use the
attention vector generated without query as the baseline                  • We provide a detailed analysis of YOURA’s QA quality
and measure how each token “reacts” to the query. We                        improvement on LongBench QA datasets.
refer to the “reactiveness” as Reaction Vector, an absolute
difference in attention scores calculated with and without the        2    R ELATED W ORK
query. The per-sentence average of the reaction vector called
reaction score, is a good ranking metric when retrieving              Long-context Language Models. Training LLMs on se-
relevant sentences, as we show in our evaluation.                     quences with a maximum length while still ensuring they
                                                                      infer well on sequences longer than the maximum is chal-
Properly slicing the reaction vector into sentences is cru-
                                                                      lenging. Previous studies proposed techniques such as posi-
cial because YOURA splits the token sequence into chunks
                                                                      tional interpolation (Chen et al., 2023a; Li et al., 2023), posi-
(as opposed to prior works, which split the raw text into
                                                                      tional extrapolation (Press et al., 2021), external emory (Wu
chunks). Such a difference sparks a new challenge: map-
                                                                      et al., 2020; Martins et al., 2021), memory-retrieval augmen-
ping sentences to a token sequence. Merely associating
                                                                      tation strategies (Mohtashami & Jaggi, 2023; Wang et al.,
specific token values (e.g., punctuation token) to a sentence
                                                                      2024) to push the limit of the context window size to 2
boundary is insufficient because different tokenizer uses
                                                                      million and even longer (Ding et al., 2024; Bertsch et al.,
different vocabulary. For example, a tokenizer may encode
                                                                      2024). Although these works improved model accuracy on
 .The (a sentence boundary with a missing white space) as
                                                                      various tasks, the large context window size implies more
two tokens: [ .T , he ]. In such case, .T token becomes               computational and memory costs.
part of the two consecutive sentences. Treating the token be-
fore or after .T token as a sentence boundary would easily            Retrieval-Augmented           Generation. Retrieval-
garble the remaining sentence splits. For this challenge, we          Augmented Generation (RAG) retrieves relevant document
propose the Embedding-Agnostic Sentence Yield (EASY)                  chunks from the external knowledge base. Prior works
— a best-effort token wiggling algorithm — that takes a list          integrate RAG with language models for question an-
of raw sentences and a single token sequence as input and             swering with long documents (Stelmakh et al., 2022)
    1
      Measured with Sentence-Transformer “All-MiniLM-L6-V2”,              2
                                                                            The code has been open-sourced and is available at
scipy.spatial.distance.                                               https://github.com/yjsoh/youra.
                                                                  2
            Context                Query                 Context                Query               Context               Query


     Chunk              ...                        Middle Truncation                                   Transformer


                Embedding                                                                      Reaction Vec.            Emb.
                                                Head Truncated         Tail                                             Agnostic
                                                                                                                        Sentence
   EmbChunk             ...        EmbQ
                                                                                          Chunks              ...       Yield
                                                       Less
                                                       important
       Top-K w/ Cos. Dist.                                                                   Top-K w/ React. Score


       LLM Context Window Size                      LLM Context Window Size                    LLM Context Window Size
     a. Embedding-based Retrieval                  b. Truncate Middle Approach                 c. Our Proposal: YOURA



Figure 2. Comparison of a typical embedding-based retriever (cosine similarity distance), truncation-based approach, and our attention-
based retriever (reaction score). In our evaluation, we show that reaction score is a better retrieval heuristic in terms of quality and
performance. Unlike the embedding-based approach, which splits the raw string context into chunks (e.g., sentences) before retrieval,
YOURA splits the token-indexed vector, reaction-vector in (c), into chunks. Such an approach requires mapping the raw sentences to
token indices. We propose Embedding Agnostic Sentence Yield (EASY) algorithm for the challenge.


and in open-domain (Giorgi et al., 2022). Furthermore,                 served that the small model is capable of identifying the
language models adopted retrieval at various stages such               key relevant information, and devised a way to mitigate the
as pretraining (Wang et al., 2023; Izacard et al., 2023;               “positional bias” due to the positional embeddings by shuf-
Borgeaud et al., 2022), fine-tuning (Jiang et al., 2022;               fling the long context. Unlike their approach, which relies
Zhang et al., 2024) and inference stage (Khandelwal et al.,            on a relatively complex perplexity calculation, our approach
2019).                                                                 merely simply takes the mean within the attention matrix.

Attention Mechanism. Researchers proposed self-                        3      YOU O NLY U SE R EACTIVE ATTENTION
attention alternatives to mitigate its quadratic complexity,                  (YOURA)
which becomes a computational bottleneck for a long
context. These include sparse attention mechanisms with                Limitation of Embedding Vectors — Context-Unaware
pre-defined sparsity patterns (Zhu et al., 2021; Liu et al.,           The limitation of embedding-based retrieval is that the input
2023), recurrence-based method (Bulatov et al., 2022),                 texts are the sole variable when generating the embedding
low-rank projection attention (Zhao et al., 2024), and                 vectors. For example, consider the following two paragraphs
memory-based mechanisms (Lou et al., 2024). However,                   each with two sentences: “Her name is Mary. She is at
these approximate methods introduce inductive bias (e.g.,              home.” and ”Her name is Alice. She is at home.”. In both
pre=defined sparsity) that can fit well for specific domains,          cases, ”She is at home” is embedded into the identical vector,
but may reduce model quality in general LLM training.                  resulting in equal distance to any sentence.

Fine-tuning for Long Context. Recent works (Ding et al.,
2024; Chen et al., 2023b; Peng et al., 2023) show that a
pre-trained LLM context window can be extended by fine-                Attention-Based Retrieval — Context-Aware We pro-
tuning on longer texts. However, fine-tuning approaches                pose an attention-based heuristic for context-aware retrieval.
still require multiple self-attention computations demanding           At a high level, our proposal is measuring how the query sen-
both high-quality training datasets and computational costs.           tence impacts the language model’s attention distribution.
Our approach does not require fine-tuning.                             We observe that attention values of relevant information
                                                                       change more drastically than irrelevant information. From
Context Compression. LongLLMLingua (Jiang et al.,                      this observation, we introduce reaction vector to quantify
2023) is one of the closest approaches to ours; they ob-               the attention shift caused by the query sentence.
                                                                   3
Design Overview Figure 3 illustrates the overview of our                Reaction Score Given the reaction vector, we define the
proposed design. The left portion of the figure depicts how             reaction score (rs) as follows for a vector slice represented
a reaction vector is calculated and the right portion depicts           with left-right index, [l, r):
how a reaction vector is used for the retrieval and how the
language model leverages the retrieved sentences to answer                ReactionScore(ReactionVector, l, r)
the query.
                                                                                                 = avg(ReactionVector[l : r]) (6)
3.1   Problem Statement & Definitions
Annotations We annotate ZC ∈ Rd×c , ZQ ∈ Rd×q as                        Problem Statement We define the retrieval task as finding
the continuous representation of the context and question,              a set of non-overlapping chunks S = {(li , ri ) | 0 ≤ li ≤
respectively, and d is the pre-trained model’s hidden dimen-            ri ≤ |Zctxt |, ri ≤ li+1 }, such that
sion, c is the context token count and q is the question token
count.
                                                                          argmaxS AnsQuality(LLMInference(concat(S , q))) (7)
Reaction Vector We define the reaction vector as follows:
                                                                        where:
                      C   Q
  ReactionVector(Z , Z )
= abs AttnVec(ZC ) − AttnVec(concat(ZC , ZQ ))1:c
                                                        
                                                              (1)          • concat(S , q) denotes the concatenation of the chunks
                                                                             in S with the query q.
where
                                                                           • LLMInference is the function that processes the con-
        AttnVec(Z) = Meancol (AttnMatrix(Q, K))               (2)            catenated chunks and the query using a language
                                                                             model.
AttnMatrix is the dense attention function before multiply-
ing the value projection and Q, K are the query and key                    • AnsQuality measures the quality (e.g., F1 Score) of
projection of Z, respectively, similar to the description in                 the answer produced by the inference function.
the “Attention is all you need” paper (Vaswani et al., 2023):
                                           QK T                         3.2   Embedding-Agnostic Sentence Yield (EASY)
                                                
         AttnMatrix(Q, K) = softmax         √                                 Algorithm
                                              d
                                                          (3)
                           Q = Z × WQ                                   Challenge Given a token sequence, finding the token in-
                           K =Z×W        K                              dex of sentence boundary is non-trivial for two reasons: (1)
                                                                        the embedding model for sentence split task (e.g., stanza) is
                                                                        different from the model’s embedding, and (2) embedding
Meancol takes the attention matrix and returns a per-column
                                                                        models with huge dictionary may result in an impossible
mean vector (note the subscription 1 : c to indicate trunca-
                                                                        token sequence to achieve a perfect sentence split. For ex-
tion from 1 to c-th column):
                                                                        ample, widely known sentence-splitting algorithms (e.g.,
                                                                        Stanza (Qi et al., 2020)) use a different dictionary from the
                               d         d              d
                                                               !
                           1 X          X              X
 Meancol ([aij ]d×n )1:c =        ai1 ,     ai2 , ...,     aic          LLM models (e.g., Llama3-8B-Instruct). Thus, the total
                           d i=1        i=1            i=1              token count varies across the embedding models (Table 1).
                               d
                                      !c
                           1 X                                          Another challenge is that some models prefer huge dictio-
                         =        aij
                           d i=1                                        naries resulting in a token sequence with an impossible case
                                         j=1
                                                              (4)       to articulate a sentence boundary. For example, llama-3
                                                                        treats .T as a single token. Although it may be useful in
For multi-head attention, the reaction vector is a mean across          code generation, a missing whitespace between a punctua-
heads:                                                                  tion period and a subsequent sentence that starts with the
                                       H         d
                                                       !c               word “The” would result in an impossible case. In other
                    h
                                   1 X 1X h
 Meancol,heads [aij ]d×n 1:c =                      a                   words, Stanza would create a token sequence ( . - The ),
                                   H         d i=1 ij
                                      h=1                j=1            whereas Llama3 tokenizer would output ( .T - he ). In
                                         H       d
                                                       !c               such a case, an exact sentence boundary for Llama3 cannot
                                    1   X    1  X
                                =                   ah                  be expressed as a token index. For these reasons, finding
                                   H         d i=1 ij                   the sentence boundary token index across the embedding
                                         h=1                j=1
                                                              (5)       model is non-trivial.
                                                                    4
      Our Proposal - You Only Use Reactive Attention (YOURA)                                 Section 3.3 Embedding-Agnostic Sentence Yield (EASY)
                                                                                             : Maps raw sentence text to index of token sequence

     Context Only Attention Matrix                 Context + Query Attention Matrix                                     Retrieval
            I                                                                                               Token                   Reaction Score
                                                                                              Sentence
        am                                                                                                  Index              : mean of reaction vector slice
                                                                                                                                 (higher = relevant to query)
          an                                                                                   I am an
   amazing                                                                                               [ 0, 7 ) Mean (                                            )
                                                                                               amazing
 researcher                                                                                  researcher.                             Reaction              Ignore
            .
                                                                                                                                    Vector Slice
            I                                                                                   I like
        like                                                                                               [ 7, 11 ) Mean (                                         )
                                                                                                LLM.
       LLM
            .                                                                                Retrieved! (? higher reaction score)
                                               Who
                                                am                                                                   Augmented
                                                  I                                           Query: "Who am I?"
                                                 ?                                            Prompt: "Answer the question. {Retrieved Context} {Q}"

                                                                                                         Augmented Prompt

   Reaction Vector                                                                                                    Generation
                                                                                Ignore
  = abs (                                      -                                         )        Language Models
                                                                                               Llama2, Llama3, Mistral
                                                                                                                                          Answer:
                                                                                                                                     Amazing researcher!
                 Attention Vec w/o Query                 Attention Vec w/ Query
                = Meancol (Attention Matrix)            = Meancol (Attention Matrix)




Figure 3. Overview of YOURA and where it is used in the Retrieval Augmented Generation (RAG) with an example (example context: ”I
am an amazing researcher. I like LLM.”, example query: ”Who am I?”). The first step is calculating the reaction vector, an absolute
difference between the attention vector with and without the query (left side of the figure). The highlighted cells in the attention matrix
indicate that the token pair exhibits a relatively high value (e.g., Who vs. I). Once the reaction vector has been calculated, each sentence is
assigned a reaction score, the mean of a corresponding reaction vector slice. To map each sentence to a token sequence, we propose
Embedding-Agnostic Sentence Yield (EASY) algorithm (Section 3.2). The retriever passes on the sentences with high reaction scores to
the augmentor. The pre-trained LLM models generate answers using the augmented text, which includes the task-specific prompt, the
retrieved context, and the question.
                                    researcher


                                           like
                                          LLM
                                      amazing
                                               I
                                           am



                                               .
                                               I


                                               .
                                             an




Embedding-Agnostic Sentence Yield (EASY) To re-                                3.3     Retrieval using Reaction Score — End-to-end
solve the problem, we propose the Embedding-Agnostic
                                                                               The retrieval algorithm starts with calculating the reaction
                                                                       researcher


                                                                              like
                                                                             LLM
                                                                         amazing




                                                                                 ?
                                                                             Who
                                                                                  I
                                                                              am



                                                                                  .
                                                                                  I


                                                                                  .

                                                                              am
                                                                                  I
                                                                                an




Sentence Yield (EASY) algorithm. The input to the algo-
                                                                               vector. If the input context is longer than the model’s context
rithm is a single token sequence and a list of sentence strings
                                                                               window size, we calculate the attention vector for each
acquired from the LLM tokenizer and the sentence splitting
                                                                               chunk of context window size and concatenate them before
NLP models (e.g., Stanza (Qi et al., 2020)), respectively.
                                                                               returning. At this point, we have the reaction vector whose
The EASY algorithm is a repetition of guessing the sen-                        length equals the input context’s token sequence.
tence boundary and making best efforts adjustments. First,
                                                                               To slice the reaction vector for each sentence, we apply
EASY estimates a candidate index as the encoded length of
                                                                               the Embedding-Agnostic Sentence Yield (EASY) algorithm
sentences that are already processed (Algorithm 1 line 7).
                                                                               (Section 3.2). Then the retriever slices the reaction vector
EASY decodes the token subsequence between the most-
                                                                               and calculates the geometric mean of the reaction vector
recently confirmed boundary index (m in Algorithm 1)
                                                                               slice using the output of the EASY algorithm, a list of
and the current candidate and compares it against the
                                                                               sentence boundary indices. At this point, we have a list of
target sentence (Algorithm 1 line 16). Based on the compar-
                                                                               sentences and their associated reaction scores, which will
ison outcome (MATCH, INCLUDED, NO-MATCH), EASY
                                                                               be used as a retrieval heuristic.
wiggles (+1 or -1) the candidate index until the decoded
subsequence matches the target or a termination condition                      For the actual retrieval, we greedily add sentences starting
is met (lines 17-23). Lastly, EASY returns the list of inte-                   with the highest reaction score until the retrieval token bud-
gers, where each value is a token index corresponding to a                     get is depleted or the sentence count threshold is reached
sentence boundary. If for some reason, the best effort fails,                  (80% of total sentence count). The retrieved sentences are
EASY restores the initial candidate index and appends to the                   reordered according to their original position as the final
boundary list. This retains the one-to-one mapping between                     cleanup step.
the target sentence and the boundary token index.
                                                                           5
             Dataset                ID    Source                      Avg # Tokens                 Metric    # Data
                                                                Llama2 Llama3 Mistral
             Single-Document QA
             NarrativeQA            1-1   Literature, Film          35937      29777     35937       F1        200
             Qasper                 1-2   Science                    5603       4922      5517       F1        200
             MultiFieldQA-en        1-3   Multi-field                8046       6889      7877       F1        150
             Multi-Document QA
             HotpotQA               2-1   Wikipedia                 15244      12780     14890       F1        200
             2WikiMultihopQA        2-2   Wikipedia                  8381       7096      8281       F1        200
             MuSiQue                2-3   Wikipedia                 18459      15544     18069       F1        200

                                               Table 1. Evaluated dataset details.


4    E XPERIMENTS                                                          chunks. We measure the cosine similarity between
                                                                           each chunk’s embedding vector generated by the
We evaluate how the YOURA improves the answering per-                      “paraphrase-MiniLM-L6-v2” model3 .
formance of 5 pre-trained models on LongBench (Bai et al.,
2023) single-doc and multi-doc QA datasets.                             • with Truncation We use LongBench’s prompt along
                                                                          with its context truncation approach: the whole context,
Datasets We evaluate YOURA on the single and multi-                       if it fits within the pre-trained model’s context window
document QA (Table 1).                                                    size, or the concatenation of the context head and tail
                                                                          with an equal context window budget, otherwise.
Models We used three different open-sourced LLM mod-
els: LLama2-7B, Llama3-8B, and Mistralv0.2-7B, where                    • with YOURA Our proposed system as described in
each model has a context window size of 4K, 8K, and 32K,                  Section 3.
respectively.
                                                                     4.1    Longbench QA Result
Inference Setup For inference, we used the vLLM (Kwon
et al., 2023). We used the LongBench (Bai et al., 2023) code         How does YOURA impact the output quality? From Ta-
to evaluate the generated answers.                                   ble 2, which shows the answer quality using three different
                                                                     open-sourced models (Llama2, Llama3, and Mistralv0.2),
Machine Setup We measured the vLLM (Kwon et al.,                     we make the following observations. (1) We observe that
2023) inference performance by slightly modifying the                YOURA showed better overall answer quality than all of the
vLLM’s throughput benchmark (v0.5.3) code on a single                retrieval approaches (BM25 and embedding-based, except
NVIDIA H100-80G GPU. We used the default vLLM set-                   for Llama2 w/ B50 70) at a higher retrieval ratio — i.e.,
tings except for changing the ignore eos to false .                  retrieving less information from the long context. (2) When
                                                                     compared to the truncate-middle approach, YOURA shows
Experiment Setup We compare the following scenarios                  better overall quality for Llama2 and Llama3, and slightly
to evaluate how the YOURA improves the output quality                less (-0.15) for Mistral.
or performance. For each setup, as done with the Long-               (2-1) When broken down into dataset types, we observe
Bench (Bai et al., 2023), we equalize the retrieval budget to        that YOURA is better at multi-document QA than single-
3500, 7500, and 31500 for models with 4K, 8K, and 32K                document QA for Llama2 and Llama3. We claim that Trunc.
context window sizes, respectively.                                  truncates the key information to correctly answer multi-
                                                                     document QAs, but the head and tail of a single document
    • Model without context No context is passed to the              include key information in many cases. As for YOURA,
      LLM.                                                           the key information is retrieved properly for both the single-
                                                                     doc and multi-doc QAs resulting in a comparable answer
    • with BM25 Retrieval Bx y indicates chunking at                 quality. For YOURA’s lower single-document score, we
      roughly x tokens and retrieving the top y chunks.              conjecture that the retrieval budget (4k, and 8k for Llama2
    • with Embedding Retrieval Ex y indicates chunk-                   3
                                                                         https://huggingface.co/sentence-transformers/paraphrase-
      ing at roughly x tokens and retrieving the top y               MiniLM-L6-v2
                                                                6
Algorithm 1 EASY Algorithm                                              Setup             Retr. Ratio     SDOC        MDoc       Overall
Require: seq - Encoded token sequence                                                        Avg            Avg        Avg         Avg
Require: T S - Target Sentences generated by NLP models
Require: tol ← 30 - Max wiggling tries                                  LLaMA2                INF           13.65      19.30       16.47
 1: P ← [] {Processed sentences}                                        w/ B500 7             3.28          22.82      20.17       21.49
 2: B ← [] {Sentence boundary indices}                                  w/ B50 70             3.28          23.86      23.25       23.56
 3: i, m ← 0 {Initialize indices}                                       w/ E500 7             3.28          17.13      19.57       18.35
 4: while P ̸= T S do                                                   w/ E50 70             3.28          24.15      22.87       23.51
 5:    APPEND T S[i] to P                                               w/ Trunc.             3.28          25.74      22.34       24.04
 6:    c ← Length(Encode(Concat(P ))) {Candidate}                       w/ YOURA              3.39          23.22      25.17       24.20
 7:    saved ← c
                                                                        LLaMA3                INF           11.59      23.16       17.37
 8:    visited ← ∅
                                                                        w/ B500 15            1.57          34.07      33.27       33.73
 9:    while true do
                                                                        w/ B50 150            1.57          32.92      35.83       34.17
10:      if c ∈ visited or c > |seq| or |c − saved| > tol
                                                                        w/ E500 15            1.57          33.33      30.82       32.08
         then
                                                                        w/ E50 150            1.57          31.50      35.70       33.60
11:         c ← saved
                                                                        w/ Trunc.             1.57          36.83      34.72       35.93
12:         break
                                                                        w/ YOURA              1.76          36.57      36.44       36.50
13:      end if
14:      ADD c to visited                                               Mistralv0.2           INF            7.02      11.47        9.25
15:      s ← Decode(seq[m : c])                                         w/ B500 63            1.04          32.29      24.66       29.02
16:      if s == T S[i] then                                            w/ B50 630            1.04          29.14      23.28       26.63
17:         break                                                       w/ E500 63            1.04          26.79      22.06       24.76
18:      else if s is substring of T S[i] then                          w/ E50 630            1.04          29.14      23.28       26.63
19:         c←c+1                                                       w/ Trunc.             1.04          32.65      26.62       29.64
20:      else                                                           w/ YOURA              1.33          33.14      25.84       29.49
21:         c←c−1
22:      end if
                                                                       Table 2. Answer quality comparison for LongBench’s single-
23:    end while
                                                                       document and multi-document QA datasets. YOURA shows better
24:    APPEND c to B
                                                                       quality with a higher retrieval ratio — i.e., retrieved fewer tokens.
25:    m←c                                                             All retrieval scenarios use the maximal budget (4K, 8K, and 32K
26:    i←i+1                                                           tokens depending on the model) except for without-context setup
27: end while                                                          and “YOURA”. The retrieval ratio (second column) is the average
28: return B                                                           of the total token count divided by the retrieved token count.



and Llama3, respectively) is insufficient to retrieve all of the
relevant information. As a supporting fact, the quality differ-
                                                                       From the observations, we conclude that the balance be-
ence between Trunc. and YOURA decreases significantly
                                                                       tween the pre-trained model’s context window size and the
from -2.52 to -0.26. Experiment results for a pre-trained
                                                                       retrieval ratio is important for long context QA.
model with a 16k context window size would be useful for
proving/disproving the conjecture but no solid 16k model is            How does YOURA’s higher retrieval ratio improve in-
available at the time of the publication.                              ference performance? Table 3 shows the average vllm
                                                                       inference throughput (requests per second) assuming offline
(2-2) For Mistral, which has a large context window size
                                                                       truncation/retrieval. We make the following observations.
of 32k, truncation rarely happens (as shown in the small
                                                                       First, YOURA improves the overall inference throughput,
retrieval ratio). Without truncation, distractful information
                                                                       especially for models with larger context window sizes. This
is included as part of the augmented context resulting in
                                                                       is because the relative retrieval ratio is larger for models
worse single-document answer quality than YOURA. 4 Our
                                                                       with larger context window sizes. Second, the retrieval ra-
explanation for multi-document QA using Mistral, where
                                                                       tio is a good relative throughput estimator. The relative
YOURA showed a slightly worse quality (-0.78), is sim-
                                                                       throughput improvements (+2%, +13%, +31%) are on par
ilar to the explanation in (2-1); YOURA’s relatively high
                                                                       with the relative retrieval ratio (+3%, +12%, +28%). We
retrieval ratio resulted in leaving out some key information.
                                                                       conclude that the performance of LLM serving platforms
   4
     The impact of distractful information on output quality is        such as vLLM is sensitive to the retrieved context size and
observed in other work (Catav, 2023) as well.                          underscores the importance of good information retrieval.
                                                                   7
  Mod     Retrieval    SDOC      MDOC        Overall Avg              Mod       1-1     1-2      1-3     2-1      2-2      2-3     Avg
  L2       Trunc.       5.25       5.76         5.50                     L2    94.1     83.1    93.5     98.4    98.8     97.8    94.3
  L2      YOURA         5.43       5.78      5.60 (+2%)                  L3    99.9     99.6    96.5     86.5    86.9     85.6    92.5
  L3       Trunc.       3.23       2.79          3.01                    M     94.0     83.1    93.5     98.4    98.8     97.8    94.3
  L3      YOURA         3.76       3.03      3.39 (+13%)                 Avg   96.0     88.6    94.5     94.4    94.8     93.7    93.7
  M        Trunc.       1.97       1.36          1.66                          L2: Llama2-7B, L3: Llama3-8B, M: Mistralv0.2
  M       YOURA         2.54       1.82      2.18 (+31%)
                                                                     Table 4. Evaluation of EASY algorithm’s average sentence match
Table 3. vLLM Serving performance (request per second, higher        rate (exact match / total # of sentences) for each model and dataset
the better) for LongBench’s single-document and multi-document       (Table 1) pairs.
QA datasets with respect to Truncation and YOURA. YOURA
retrieved fewer tokens resulting in up to 30% higher inference
throughput.                                                           Mod       1-1     1-2      1-3     2-1      2-2      2-3     Avg
                                                                      L2       3.26     3.48    2.54     2.61    2.36     2.67    2.82
                                                                      NZ       5.40     4.80    4.35     4.22    4.13     4.31    4.54
4.2    EASY Sentence Splitter Accuracy
                                                                      L3       1.71     3.45    2.77     3.16    2.80     3.23    2.85
How well can the EASY algorithm split tokens into sen-                NZ       3.70     4.76    4.52     4.53    4.29     4.64    4.41
tences? Table 4 shows the quality of our EASY sentence                M        3.54     3.52    2.56     2.65    2.38     2.71    2.89
splitting algorithm. We used Stanza (Qi et al., 2020), an             NZ       5.52     4.85    4.40     4.29    4.17     4.38    4.60
open-sourced NLP toolkit, to split raw text into sentences.
Then we ran the EASY algorithm for each tokenizer model                        L2: Llama2-7B, L3: Llama3-8B, M: Mistralv0.2
to identify the sentence boundary within a token sequence.                     NZ* (Non-Zero): average of non-zero distances.
After decoding each token segment (delimited by the sen-
tence boundary index), it is a match if the Stanza’s sentence        Table 5. Average Levenshtein distance between the target sentence
(namely target sentence) matches exactly after the cleanup           and EASY algorithm’s sentence split. A smaller number indicates
(e.g., trailing whitespace). We report the average match rate        fewer character edits (insert, remove, replace) to transform the
                                                                     EASY output sentence to the target sentence, and thus a better
for each model and dataset pair.
                                                                     quality split.
We make the following observations. Overall the EASY
algorithm can identify the sentence boundary for models
with varying dictionary sizes: Llama2, Llama3, and Mis-              The NZ row in Table 5 is the average Levenshtein distance
tralv0.2 tokenizers with 32000, 128256, and 32000 words,             of unmatched sentences. From these rows, we conclude
respectively. Llama2 and Mistral showed almost identical             that the EASY algorithm is resilient to incorrect split and
match ratios, as both models’ tokenizers are based on simi-          its cascading effect.
lar vocabulary. Llama3 uses roughly ×4 more vocabulary
resulting in fewer total token counts as shown in Table 1            5     C ONCLUSION
(e.g., .T into a single token). Due to the rich vocabulary, a
typo easily blurred sentence boundaries causing many im-             We propose a simple, yet effective attention-based retrieval
perfect matches and thus the smallest overall match quality          algorithm. We show that attention vectors are useful re-
as in the 2-1, 2-2, and 2-3 datasets. For 1-1, 1-2, and 1-3,         trieval and propose novel retrieval heuristics called reaction
datasets, the rich vocabulary worked in favor. Many atypical         scores. Our fine-tuning approach improves the output qual-
char sequences (e.g., <b>, math formula) were present in             ity or the inference performance of off-the-shelf models for
these datasets, which were properly represented with tokens          long-context QA tasks.
using Llama3.


How resilient is the EASY algorithm from edge cases?
To quantify the resilience despite typos and overly represen-
tative dictionaries, we measured the Levenshtein distance
between the target sentence and the sentence yielded by
our EASY algorithm (Table 5). On average, one needs less
than 3 character edits (insert, remove, replace) to the EASY
output sentences to match the target sentences.
                                                                 8
R EFERENCES                                                         Jiang, Z., Gao, L., Araki, J., Ding, H., Wang, Z., Callan,
                                                                       J., and Neubig, G. Retrieval as attention: End-to-end
Bai, Y., Lv, X., Zhang, J., Lyu, H., Tang, J., Huang, Z., Du,
                                                                       learning of retrieval and reading within a single trans-
  Z., Liu, X., Zeng, A., Hou, L., Dong, Y., Tang, J., and Li,
                                                                       former, 2022. URL https://arxiv.org/abs/
  J. Longbench: A bilingual, multitask benchmark for long
                                                                       2212.02027.
  context understanding, 2023.
                                                                    Khandelwal, U., Levy, O., Jurafsky, D., Zettlemoyer, L.,
Bertsch, A., Alon, U., Neubig, G., and Gormley, M. Unlim-             and Lewis, M. Generalization through memorization:
  iformer: Long-range transformers with unlimited length              Nearest neighbor language models. arXiv preprint
  input. Advances in Neural Information Processing Sys-               arXiv:1911.00172, 2019.
  tems, 36, 2024.
                                                                    Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu,
Borgeaud, S., Mensch, A., Hoffmann, J., Cai, T., Rutherford,         C. H., Gonzalez, J. E., Zhang, H., and Stoica, I. Efficient
  E., Millican, K., Van Den Driessche, G. B., Lespiau, J.-B.,        memory management for large language model serving
  Damoc, B., Clark, A., et al. Improving language models             with pagedattention. In Proceedings of the ACM SIGOPS
  by retrieving from trillions of tokens. In International           29th Symposium on Operating Systems Principles, 2023.
  conference on machine learning, pp. 2206–2240. PMLR,
  2022.                                                             Li, S., You, C., Guruganesh, G., Ainslie, J., Ontanon, S.,
                                                                      Zaheer, M., Sanghai, S., Yang, Y., Kumar, S., and Bho-
Bulatov, A., Kuratov, Y., and Burtsev, M. Recurrent memory            janapalli, S. Functional interpolation for relative posi-
  transformer. Advances in Neural Information Processing              tions improves long context transformers. arXiv preprint
  Systems, 35:11079–11091, 2022.                                      arXiv:2310.04418, 2023.

Catav, A.  Less is more: Why use retrieval in- Liu, Z., Wang, J., Dao, T., Zhou, T., Yuan, B., Song, Z.,
  stead of larger context windows, Jul 2023.     Shrivastava, A., Zhang, C., Tian, Y., Re, C., et al. Deja
  URL      https://www.pinecone.io/blog/         vu: Contextual sparsity for efficient llms at inference time.
  why-use-retrieval-instead-of-larger-context/.  In International Conference on Machine Learning, pp.
                                                 22137–22176. PMLR, 2023.
Chen, S., Wong, S., Chen, L., and Tian, Y. Extending                Lou, C., Jia, Z., Zheng, Z., and Tu, K. Sparser is faster and
  context window of large language models via positional              less is more: Efficient sparse attention for long-range
  interpolation. arXiv preprint arXiv:2306.15595, 2023a.              transformers, 2024. URL https://arxiv.org/
                                                                      abs/2406.16747.
Chen, Y., Qian, S., Tang, H., Lai, X., Liu, Z., Han, S., and
  Jia, J. Longlora: Efficient fine-tuning of long-context           Luo, K., Liu, Z., Xiao, S., and Liu, K. Bge landmark embed-
  large language models. arXiv preprint arXiv:2309.12307,             ding: A chunking-free embedding method for retrieval
  2023b.                                                              augmented long-context large language models, 2024.

Ding, Y., Zhang, L. L., Zhang, C., Xu, Y., Shang, N., Xu,           Mangrulkar, S., Gugger, S., Debut, L., Belkada, Y., Paul,
  J., Yang, F., and Yang, M. Longrope: Extending llm                 S., and Bossan, B. Peft: State-of-the-art parameter-
  context window beyond 2 million tokens. arXiv preprint             efficient fine-tuning methods. https://github.
  arXiv:2402.13753, 2024.                                            com/huggingface/peft, 2022.

Giorgi, J., Soldaini, L., Wang, B., Bader, G., Lo, K.,              Martins, P. H., Marinho, Z., and Martins, A. F. ∞-
  Wang, L. L., and Cohan, A. Exploring the challenges                former: Infinite memory transformer. arXiv preprint
  of open domain multi-document summarization. ArXiv,                arXiv:2109.00301, 2021.
  abs/2212.10526, 2022.
                                                                    Mohtashami, A. and Jaggi, M. Landmark attention:
                                                                     Random-access infinite context length for transformers.
Izacard, G., Lewis, P., Lomeli, M., Hosseini, L., Petroni,
                                                                     arXiv preprint arXiv:2305.16300, 2023.
  F., Schick, T., Dwivedi-Yu, J., Joulin, A., Riedel, S., and
  Grave, E. Atlas: Few-shot learning with retrieval aug-            Peng, B., Quesnelle, J., Fan, H., and Shippole, E. Yarn:
  mented language models. Journal of Machine Learning                 Efficient context window extension of large language
  Research, 24(251):1–43, 2023.                                       models. arXiv preprint arXiv:2309.00071, 2023.

Jiang, H., Wu, Q., Luo, X., Li, D., Lin, C.-Y., Yang, Y., and       Press, O., Smith, N. A., and Lewis, M. Train short, test
   Qiu, L. Longllmlingua: Accelerating and enhancing llms             long: Attention with linear biases enables input length
   in long context scenarios via prompt compression, 2023.            extrapolation. arXiv preprint arXiv:2108.12409, 2021.
                                                                9
Qi, P., Zhang, Y., Zhang, Y., Bolton, J., and Manning, C. D.
  Stanza: A python natural language processing toolkit for
  many human languages, 2020.
Stelmakh, I., Luan, Y., Dhingra, B., and Chang, M.-W.
  Asqa: Factoid questions meet long-form answers. arXiv
  preprint arXiv:2204.06092, 2022.

Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones,
  L., Gomez, A. N., Kaiser, L., and Polosukhin, I. Attention
  is all you need, 2023.
Wang, B., Ping, W., Xu, P., McAfee, L., Liu, Z., Shoeybi,
 M., Dong, Y., Kuchaiev, O., Li, B., Xiao, C., et al.
 Shall we pretrain autoregressive language models with
 retrieval? a comprehensive study. arXiv preprint
 arXiv:2304.06762, 2023.
Wang, W., Dong, L., Cheng, H., Liu, X., Yan, X., Gao, J.,
 and Wei, F. Augmenting language models with long-term
 memory. Advances in Neural Information Processing
 Systems, 36, 2024.
Wu, Q., Lan, Z., Qian, K., Gu, J., Geramifard, A., and Yu,
 Z. Memformer: A memory-augmented transformer for
 sequence modeling. arXiv preprint arXiv:2010.06891,
 2020.

Xiao, G., Tian, Y., Chen, B., Han, S., and Lewis, M. Ef-
  ficient streaming language models with attention sinks,
  2024.
Zhang, T., Patil, S. G., Jain, N., Shen, S., Zaharia, M., Stoica,
  I., and Gonzalez, J. E. Raft: Adapting language model
  to domain specific rag, 2024. URL https://arxiv.
  org/abs/2403.10131.
Zhang, Z., Sheng, Y., Zhou, T., Chen, T., Zheng, L., Cai,
  R., Song, Z., Tian, Y., Ré, C., Barrett, C., Wang, Z., and
  Chen, B. H2 o: Heavy-hitter oracle for efficient generative
  inference of large language models, 2023.
Zhao, J., Zhang, Z., Chen, B., Wang, Z., Anandkumar,
  A., and Tian, Y. Galore: Memory-efficient llm train-
  ing by gradient low-rank projection. arXiv preprint
  arXiv:2403.03507, 2024.

Zhu, C., Ping, W., Xiao, C., Shoeybi, M., Goldstein, T.,
  Anandkumar, A., and Catanzaro, B. Long-short trans-
  former: Efficient transformers for language and vision.
  Advances in neural information processing systems, 34:
  17723–17736, 2021.




                                                                10
A    D ETAILED R ESULTS
Table 6, Table 7 are the detailed version of Table 2 and
Table 3, respectively.




                                                           11
       Setup           Retr. Rate      Single-Document QA           SDoc       Multi-Document QA         MDoc       Overall
                         Avg            1-1     1-2    1-3           Avg        2-1    2-2     2-3        Avg         Avg
       LLaMA2             INF          8.89    13.87      18.19     13.65     23.05   25.67       9.17   19.30        16.47
       w/ B500 7          3.28        12.59    21.44      34.42     22.82     25.92   27.47       7.11   20.17        21.49
       w/ B50 70          3.28        16.37    21.51      33.71     23.86     27.48   28.62      13.64   23.25        23.56
       w/ E500 7          3.28        12.85    16.08      22.47     17.13     25.51   24.84       8.35   19.57        18.35
       w/ E50 70          3.28        17.15    20.12      35.18     24.15     28.80   27.15      12.66   22.87        23.51
       w/ Trunc.          3.28        18.84    21.71      36.68     25.74     27.55   31.08       8.40   22.34        24.04
       w/ YOURA           3.39        15.48    23.41      30.77     23.22     29.55   31.11      14.86   25.17        24.20
       LLaMA3             INF          9.62    14.38      10.78     11.59     28.43   30.46      10.60   23.16        17.37
       w/ B500            1.57        18.27    40.21      43.72     34.07     41.75   41.18      16.88   33.27        33.73
       w/ B50             1.57        19.86    36.51      42.39     32.92     47.04   40.58      19.86   35.83        34.17
       w/ E500            1.57        16.38    39.85      43.76     33.33     42.28   34.93      15.25   30.82        32.08
       w/ E50             1.57        19.05    35.44      40.02     31.50     48.05   36.85      22.19   35.70        33.60
       w/ Trunc.          1.57        21.54    44.21      44.75     36.83     46.43   36.23      21.50   34.72        35.93
       w/ YOURA           1.76        21.47    42.39      45.85     36.57     50.78   34.24      24.29   36.44        36.50
       Mistralv0.2        INF          7.24     7.69       6.13      7.02     16.41   11.87       6.13   11.47         9.25
       w/ B500 63         1.04        20.74    29.22      46.91     32.29     34.26   22.26      17.47   24.66        29.02
       w/ B50 630         1.04        18.84    25.08      43.50     29.14     32.85   18.66      18.32   23.28        26.63
       w/ E500 63         1.04        14.02    24.14      42.22     26.79     32.81   17.55      15.82   22.06        24.76
       w/ E50 630         1.04        18.84    25.08      43.50     29.14     32.85   18.66      18.32   23.28        26.63
       w/ Trunc.          1.04        20.80    29.23      47.92     32.65     37.28   21.72      20.86   26.62        29.64
       w/ YOURA           1.33        22.37    30.17      46.88     33.14     36.11   21.45      19.95   25.84        29.49
                                                     The bold score indicates the best score for each pre-trained model.

Table 6. Detailed experiment results for LongBench’s single-document and multi-document QA datasets. YOURA shows better quality
with a higher retrieval ratio — i.e., retrieved fewer tokens. All retrieval scenarios use the maximal budget (4K, 8K, and 32K tokens
depending on model) except for without-context setup and “YOURA”. Retrieval ratio (second column) is an average of the total token
count divided by the retrieved token count.




                 Model           Retrieval    Single-Document QA            Multi-Document QA       Overall Avg
                                 Method       1-1    1-2    1-3             2-1    2-2   2-3         Req./Sec
                 LLaMA2           Trunc.      5.58     4.68       5.50      5.71   5.87   5.68         5.50
                 LLaMA2          YOURA        5.70     4.88       5.72      5.70   6.00   5.63      5.60 (+2%)
                 LLaMA3           Trunc.      2.50     3.95       3.23      2.63   3.23   2.52          3.01
                 LLaMA3          YOURA        2.60     4.87       3.82      2.72   3.83   2.53      3.39 (+13%)
                 Mistralv0.2      Trunc.      0.55     3.17       2.19      1.08   2.14   0.86          1.66
                 Mistralv0.2     YOURA        0.64     4.02       2.97      1.45   2.85   1.15      2.18 (+31%)

Table 7. vLLM Serving performance (request per second, higher the better) for LongBench’s single-document and multi-document QA
datasets with respect to Truncation and YOURA. YOURA retrieved fewer tokens resulting in upto 30% higher inference throughput.



                                                                  12
