                                              Long Context Modeling with Ranked Memory-Augmented Retrieval
                                                      Ghadir Alselwi1 , Hao Xue1,2,3 , Shoaib Jameel4 , Basem Suleiman1 ,
                                                                       Flora D. Salim1 , Imran Razzak5,1
                                                           1
                                                             University of New South Wales, Sydney, NSW, Australia
                                                       2
                                                         Hong Kong University of Science and Technology (Guangzhou)
                                                             3
                                                               The Hong Kong University of Science and Technology
                                                                 4
                                                                   University of Southampton, Southampton, UK
                                                  5
                                                    Mohamed Bin Zayed University of Artificial Intelligence, Abu Dhabi, UAE
                                                           {g.alselwi,b.suleiman,flora.salim}@unsw.edu.au
                                         haoxue@hkust-gz.edu.cn, M.S.Jameel@southampton.ac.uk, imran.razzak@mbzuai.ac.ae
                                                          Abstract                        ory bank model is a large, non-trainable store
                                                                                                  of past context representations. Instead of re-
                                              Effective long-term memory management is
arXiv:2503.14800v3 [cs.IR] 18 May 2026




                                                                                                  computing representations for all past tokens every
                                              crucial for language models handling extended
                                              contexts. We introduce the Enhanced Ranked          time, these representations are pre-computed and
                                              Memory Augmented Retrieval (ERMAR)                  stored. Given the current context, MemLong re-
                                              framework, which dynamically ranks mem-             trieves relevant segments from the memory bank.
                                              ory entries based on relevance. Unlike prior        It uses a dot product similarity search to find the
                                              models, ERMAR employs a novel relevance             memory entries most related to the current context.
                                              scoring mechanism and a pointwise re-ranking        This allows the model to focus only on the most
                                              model for key-value embeddings, inspired            pertinent past information, rather than processing
                                              by learning-to-rank techniques in informa-
                                                                                                  the entire history. However, its treatment of all
                                              tion retrieval. By integrating historical us-
                                              age patterns and adaptive retrieval, ERMAR          key-value (K-V) pairs with equal weight, regard-
                                              achieves state-of-the-art results on standard       less of their contextual relevance, often leads to
                                              benchmarks, demonstrating superior scalabil-        information overload and reduced retrieval preci-
                                              ity and performance in long-context tasks.          sion. This limitation becomes particularly evident
                                              Code will be released at https://github.            in scenarios requiring context management.
                                              com/cruiseresearchgroup/ERMAR.
                                                                                                     We have developed a novel model that addresses
                                          1   Introduction                                        the aforementioned limitations by building upon
                                                                                                  Memlong (Liu et al., 2024), a publicly available
                                          Large Language Models (LLMs) face a fundamen-           baseline on GitHub1 . Our Enhanced Ranked
                                          tal limitation in processing long-context scenarios     Memory Augmented Retrieval (ERMAR) model
                                          due to the quadratic complexity of attention mecha-     has a novel relevance scoring mechanism that fun-
                                          nisms and increasing memory demands during gen-         damentally improves context retrieval and utiliza-
                                          eration (Vaswani, 2017; Tworkowski et al., 2024).       tion for K-V embeddings. Unlike MemLong, ER-
                                          Consider a scenario in an automated customer ser-       MAR employs multiplication (Cao et al., 2007)
                                          vice system: A customer reports an issue with their     to compute relevance scores, enabling a more nu-
                                          printer, referencing a setup process from a previous    anced and context-aware assessment of semantic
                                          conversation that occurred two hours ago. After         alignment between queries and stored memory. ER-
                                          50 messages of troubleshooting, the customer men-       MAR also incorporates a re-ranking mechanism
                                          tions that the same error from the beginning has        that dynamically reorders K-V embeddings based
                                          resurfaced. Traditional LLMs, constrained by their      on their relevance scores, ensuring that the most
                                          context window, would struggle to access the cru-       pertinent information is prioritized during retrieval.
                                          cial earlier context about the initial setup process,   This re-ranking process, combined with an adaptive
                                          leading to inconsistent or incomplete responses,        retrieval system that integrates historical usage pat-
                                          Figure 1. It is well known that handling extended       terns, allows ERMAR to capture subtle contextual
                                          contexts remains a significant challenge, particu-      relationships better and refine memory prioritiza-
                                          larly in applications requiring document analysis       tion. As shown in Figure 1, ERMAR processes
                                          and sustained dialogue interactions.                    incoming queries and long-context conversations
                                             The recent MemLong (Liu et al., 2024) architec-      through a novel ranking architecture, employing
                                          ture stores and accesses historical context through
                                                                                                     1
                                          basic chunk-level memory operations. The mem-                  https://github.com/Bui1dMySea/MemLong
K-V pairs ranking (K0 -V0 , K1 -V1 ,...,Ki -Vi ) and cor-   Longformer (Beltagy et al., 2020) and BigBird (Za-
responding embeddings to perform semantic search            heer et al., 2020) reduce computational complexity
and ranking of relevant historical information.             while maintaining model capabilities through selec-
   Our novel ERMAR model introduces three key               tive attention patterns. Position encoding adapta-
improvements: (i) A semantic similarity metric              tions like RoPE (Su et al., 2024) and ALiBi (Press
to measure contextual alignment between query               et al., 2022) have enhanced models’ ability to han-
embeddings and key-value pairs; (ii) A weighted             dle longer sequences. YARN (Peng et al., 2023)
scoring function that considers content similarity          further advanced this through dynamic position em-
and contextual relevance; and (iii) Integration of          beddings, demonstrating reliable generalization up
historical usage patterns to refine relevance assess-       to 128k tokens.
ment.
                                                            2.3   Learning-to-Rank and Information
2     Related Work                                                Retrieval
                                                            Our ERMAR framework draws inspiration from
The challenge of enabling language models to ef-            learning-to-rank techniques in information retrieval.
fectively process extended contexts has driven re-          Traditional ranking approaches like BM25 struggle
search across multiple domains. We organize re-             with semantic similarity, leading to neural ranking
lated work into key areas that inform our ERMAR             models using learned representations. Pointwise
framework.                                                  ranking approaches (Cao et al., 2007) predict rel-
                                                            evance scores for query-document pairs, directly
2.1    Memory-Augmented Neural Networks
                                                            inspiring our relevance scoring mechanism. Dense
Early architectures like Neural Turing Ma-                  retrieval methods like DPR (Karpukhin et al., 2020)
chines (Graves et al., 2014) and Differentiable Neu-        and ColBERT (Khattab and Zaharia, 2020) demon-
ral Computers (Graves et al., 2016) introduced ex-          strate the effectiveness of learned dense represen-
ternal memory beyond model parameters. Recent               tations for ranking through similarity scores—a
models for long-context language modeling include           paradigm we adapt for memory entry ranking.
RetroMAE (Xiao et al., 2022), which struggled               BERT-based re-ranking models (Nogueira and Cho,
with semantic coherence, and Memorizing Trans-              2019) show that sophisticated re-ranking signifi-
formers (Wu et al., 2022), which improved cross-            cantly improves retrieval quality. This two-stage
sequence information storage but faced scalability          retrieve-then-rerank paradigm directly influences
limits. MemLong (Liu et al., 2024) stores histor-           our design, where we first retrieve candidate mem-
ical context via chunk-level memory operations,             ory entries and then apply learned re-ranking.
but its uniform treatment of key-value pairs can
cause information overload and reduced retrieval            2.4   Current Limitations and Gaps
precision.                                                  Despite significant progress, current approaches
                                                            face limitations that motivate ERMAR:
2.2    Retrieval-Augmented Generation and                      Static Memory Management: Most ap-
       Long-Context Modeling                                proaches use fixed memory structures that do not
Retrieval-augmented generation (RAG)(Lewis                  adapt to content importance or usage patterns, lead-
et al., 2020) pioneered integrating dense passage           ing to inefficient memory utilization.
retrieval with generative models, while Fusion-in-             Uniform Memory Treatment: Existing meth-
Decoder (FiD)(Izacard and Grave, 2020) improved             ods treat all memory entries equally, lacking mech-
efficiency through independent passage process-             anisms to prioritize more relevant information.
ing. REALM (Guu et al., 2020) introduced end-                  Limited Semantic Understanding: Memory
to-end learning of retrieval and generation, and            systems often rely on simple similarity metrics
DPR (Karpukhin et al., 2020) established dense              without considering contextual nuance or temporal
passage retrieval standards. However, these meth-           relevance.
ods typically focus on static corpora rather than              Scalability Trade-offs: Current approaches face
dynamic context-aware memory management. The                difficult trade-offs between memory capacity, re-
quadratic complexity of attention mechanisms has            trieval accuracy, and computational efficiency.
driven research into efficient long-context archi-             Our ERMAR framework addresses these limita-
tectures. Sparse attention mechanisms such as               tions through dynamic relevance scoring, adaptive
Figure 1: Motivating example of the ERMAR retrieval workflow. Left: A long customer support conversation where
the current query references information from much earlier context. Right: The four-stage workflow — ⃝ 1 Long
Memory Retrieval, ⃝  2 Search, ⃝3 Reranking, ⃝ 4 Memory Fusion Generation. The ERMAR output (top) correctly
references earlier context, whereas the output without reranking (bottom) produces a generic response.


memory management, and sophisticated re-ranking          the model’s output on the most relevant historical
mechanisms inspired by information retrieval tech-       context.
niques, providing a more principled approach to             This design directly addresses the information
long-context memory management.                          dilution problem in long contexts: without rerank-
                                                         ing (bottom of Figure 1), the model produces a
3   Our Novel ERMAR Model                                generic response that fails to reference the earlier
Figure 1 presents a concrete motivating example of       printer setup context; with reranking (ERMAR out-
how ERMAR’s contextual ranking mechanism op-             put, top), the model correctly retrieves and incor-
erates in practice, while Figure 2 illustrates the       porates the relevant earlier information.
overall architecture of the proposed framework.            As shown in Figure 2, the ERMAR architec-
As shown in Figure 1, ERMAR processes a long-           ture consists of three interacting components: a
context query through four sequential stages. First,    frozen lower transformer block, a trainable up-
the Long Memory Retrieval module encodes the            per block with retrieval-augmented attention, and
full input history into chunk-level key–value (KV)      a memory retrieval module with reranking. Input
pairs stored in a memory bank, alongside embed-         text is processed by the frozen lower block (Causal
dings that capture semantic representations of each     Attention and Feed Forward layers), whose hid-
chunk. Second, when a new query arrives, its            den states form the key–value pairs {(Kj , Vj )} ∈
embedding is used to search the memory bank             Rdmodel stored in the Memory Bank. In parallel,
for candidate KV pairs via similarity matching.         the Dense Embedder independently encodes the
Third, the retrieved candidates pass through the        same input into chunk-level retrieval embeddings
Reranking module — the core novelty over Mem-           E1 , . . . , Ei ∈ Rdret , which serve as the semantic
Long — which assigns relevance scores to each KV        index for similarity-based retrieval. The Rerank-
pair and re-orders them by contextual importance,       ing module then scores all stored embeddings and
elevating high-relevance entries (K6 -V6 , ranked)      KV pairs using Equation 2, re-ordering them by
above lower-relevance ones (K0 -V0 , unranked). Fi-     relevance to the current query and isolating the
nally, only the top-ranked KV pairs are passed to       top-ranked subset (right stacks in Figure 2). The
Memory Fusion Generation, which conditions              Retrieval module performs top-K selection over
                                                           with a relevance scoring mechanism,

                                                                    M : |Rd{z  }×R
                                                                            model   dmodel
                                                                                  | {z } × R
                                                                                             dret
                                                                                           |{z} → S ,                    (1)
                                                                            keys       values    embeddings


                                                           where dmodel denotes the transformer hidden di-
                                                           mension, dret the retrieval embedding dimension,
                                                           and S the space of scored memory items (see Ap-
                                                           pendix A.8 for embedding dimensionality analy-
                                                           sis).
                                                              Relevance Score. Given a query embedding
                                                           q ∈ Rdret and a matrix of key embeddings K =
                                                           [k1 , . . . , km ] ∈ Rm×dret , where each row ki ∈ Rdret
                                                           corresponds to a key embedding, the relevance
Figure 2: Architecture of the ERMAR model. The             score is defined as:
frozen lower block (blue dashed, snowflake) produces
                                                                                                    qK⊤
                                                                                                           
hidden states stored as key–value pairs (dmodel ) in the                 α(q, K) = softmax          √           ,        (2)
                                                                                                     dret
Memory Bank, while the Dense Embedder encodes the
input into chunk-level retrieval embeddings (dret ). The          √
                                                           where dret normalizes the similarity scores to pre-
Reranking module scores and ranks all stored entries,
and the Retrieval module injects the top-K ranked pairs
                                                           vent excessively large values.
into the trainable upper block via Retrieval Causal           The resulting vector α(q, K) represents a prob-
Attention (orange arrow) to condition the final out-       ability distribution over the keys, where each en-
put. Frozen and trainable components are marked by         try αi denotes the relative importance (attention
snowflake and flame icons respectively.                    weight) of the i-th key with respect to the query q.
                                                           The final
                                                                 Pm context or weighted output is obtained as
                                                           o = i=1 αi Vi , where Vi denotes the correspond-
                                                           ing value embedding associated with key ki .
this ranked subset and injects the selected KV pairs
                                                              We now introduce the Relevance Scoring with
into the trainable upper block via Retrieval Causal
                                                           Adaptive Retrieval (RSAR) mechanism, which
Attention (orange arrow), producing a context-
                                                           dynamically ranks memory entries according to
enriched representation from which the final output
                                                           their importance to the current query, thereby en-
is generated.
                                                           hancing the retrieval process. The relevance score
   ERMAR maintains consistency through frozen              α(q, K), as defined in Equation 2, is employed to
lower layers and selective parameter updates.              rank the memory entries.
Specifically, ERMAR (i) stores important infor-               RSAR augments the memory module by intro-
mation from earlier parts of the text, (ii) assigns        ducing ranked key–value entries, represented as
relevance scores to stored information based on            (Kj , Vj , sj ), where sj denotes the relevance score
its importance to the current context, and (iii) re-       for each entry. These scores allow the system to pri-
trieves only the most relevant historical information      oritize the most informative content during retrieval
when needed. The relevance scoring mechanism               while maintaining computational efficiency. To op-
is analogous to the attention operation, enabling          timize memory usage, a pruning strategy is applied
the model to focus on salient parts of the mem-            to remove less relevant entries. Specifically, entries
ory. There is also a “loose” pointwise connection:         with scores below a predefined threshold are dis-
while relevance-based reranking acts as an auxil-          carded, preserving only the most critical contextual
iary mechanism that enhances memory retrieval              information.
quality, the primary optimization target remains              The enhanced retrieval mechanism is defined as:
next-token prediction likelihood.
                                                             RRSAR (tq , s) = TopK {sim(E(tq ), e) · maxj sj | e ∈ s},   (3)
  Let V be a finite vocabulary, and x =
(x1 , . . . , xn ) ∈ V n be a token sequence with a        where tq denotes the query token, E(tq ) represents
preceding context x<i . The embedding function             the encoded query, and the operation identifies the
E : V ∗ → Rdret maps sequences to a retrieval space.       top-K relevant entries based on their scores; this
We introduce a memory function M augmented                 mechanism enables efficient retrieval of the most
relevant information, even in extended contexts                      3.1.2   Model Architecture and Configuration
(see Appendix A.6 for the impact of different top-                   We fine-tuned OpenLLaMA-3B, a pre-trained
K values on performance).                                            LLM with rotational position encoding (Su et al.,
   Ranked Key–Value Pairs. Each embedding e                          2024), using LoRA (Hu et al., 2021) for parameter-
maintains a ranked set of key–value pairs:                           efficient adaptation. The model consists of L = 26
                Rranked (e) = {(Kj , Vj , sj )}m
                                               j=1 ,           (4)   transformer layers, H = 32 attention heads, and
                                                                     a hidden dimension of d = 100. The 13th layer
where sj = α(e, Kj ) is the relevance score be-
                                                                     serves as the memory layer where historical con-
tween the embedding e and the key Kj .
                                                                     text is stored, while layers [14, 18, 22, 26] are aug-
   Given a sequence x, the ERMAR objective func-
                                                                     mented with retrieval mechanisms to access stored
tion is formulated as maximizing
                                                                     memories. ERMAR employs a memory capacity
                      n
          L(θ) =
                      X
                             pθ (xi | RRSAR (ti , s), x<i ),   (5)   of 32,768 key–value pairs and utilizes BGE-M3
                       i=1                                           embeddings for semantic similarity computation.
subject to                                                           Complete training hyperparameters and configura-
                                                                     tion details are provided in Appendix A.2.
               si = M(K1:i−1 , V1:i−1 ; E(t1:i−1 )),           (6)
               ti = text(c⌈i/τ ⌉ ),                            (7)   3.1.3   Baseline Models
               αi = α(E(ti ), K1:i−1 ),                        (8)
                                                                     ERMAR was evaluated against state-of-the-art
 where c denotes chunk indices, τ represents the                     models across two parameter scales to ensure com-
chunk size, αi guides key–value pair selection, and                  prehensive comparison. The 7B models include
pθ denotes the model’s probability distribution.                     LLaMA-2-7B (Touvron et al., 2023b) as a standard
  For new content (Kn , Vn ), the memory state is                    transformer baseline, LongLoRA-7B-32k (Chen
updated as:                                                          et al., 2023) which employs sparse attention mech-
               (                                                     anisms for 32k-token contexts, and YARN-128k-
                   M(Kn , Vn ; E(tn )) if |si | < capacity,
      si+1 =                                                   (9)   7B (Peng et al., 2023) featuring dynamic position
                   Mu (si , Kn , Vn , αn ) otherwise,
                                                                     embeddings that support up to 128k tokens.
where capacity is the maximum allowed number                            For the 3B parameter scale, we compared against
of memory entries, Mu prunes the least relevant                      OpenLLaMA-3B (Touvron et al., 2023a) as the
entries based on historical scores by ranking and                    base architecture, LongLLaMA-3B (Tworkowski
removing those with the lowest relevance relative                    et al., 2024) evaluated in two retrieval configu-
to the current context, and subscript n denotes the                  rations (4 and 18 memory entries), MemLong-
new key, value, and relevance score corresponding                    3B (Liu et al., 2024) as our direct baseline
to the latest input.                                                 with chunk-level memory operations, and Phi3-
3.1     Experimental Setup                                           128k (Abdin et al., 2024) which demonstrates
                                                                     strong performance across varying context lengths.
3.1.1 Datasets                                                       This diverse benchmark suite encompasses differ-
We fine-tuned ERMAR on the SlimPajama                                ent long-context strategies including sparse atten-
dataset (Fu et al., 2024), a high-quality, dedupli-                  tion, position encoding extensions, and memory-
cated corpus designed for long-context tasks. It                     augmented architectures, ensuring robust evalua-
contains 84.7K training rows, making it a com-                       tion of ERMAR’s retrieval-based approach against
pact yet effective resource for pre-training and fine-               complementary methodologies.
tuning. The dataset was preprocessed with a sliding
window approach using 512-token strides to ensure                    3.1.4   Evaluation Metrics
comprehensive coverage of long sequences.                            We employ perplexity as the primary metric for
  Performance evaluation was conducted on three                      language modeling performance, computed on the
benchmark datasets: WikiText-103 (Merity et al.,                     final 2048 tokens of each sequence to focus on
2016) (4,358 test rows), PG-19 (Rae et al., 2019)                    long-range dependency modeling. For in-context
(100 test rows), and Proof-Pile (Azerbayev et al.,                   learning tasks, we report accuracy on five natu-
2023) (46.3K test rows). Performance was mea-                        ral language understanding benchmarks: SST-2,
sured across context lengths from (1k-32k) tokens,                   MR, Subj, SST-5, and MPQA, evaluated in both
using perplexity on the last 2048 tokens (Yen et al.,                4-shot and 20-shot settings. Memory efficiency is
2024) following standard evaluation protocols.                       assessed through peak GPU memory usage and to-
kens processed per second, while computational          these are edge cases at the boundary of the training
overhead is measured via inference latency across       distribution (the model was fine-tuned up to 32k
different context lengths.                              tokens): ERMAR maintains consistent improve-
                                                        ments at practical context lengths (1K–4K), where
3.2     Results and Discussion                          memory pressure is highest, and fully recovers at
3.2.1    Long-Context Language Modeling                 32k tokens (Table 2), achieving equal or better per-
Following the experimental strategy adopted in          plexity across all three datasets. The 16k degra-
(Liu et al., 2024), Table 1 reports the mean per-       dation therefore reflects an expected efficiency–
plexity scores of ERMAR across various sequence         benefit trade-off rather than a systematic failure
lengths and datasets. Evaluation was conducted          of the proposed enhancements.
on the test splits of three standard benchmarks:           These findings confirm that ERMAR’s ranked
WikiText-103 (Merity et al., 2016) (4,358 rows),        memory retrieval effectively mitigates informa-
PG-19 (Rae et al., 2019) (100 rows), and Proof-         tion dilution across extended sequences, improv-
Pile (Azerbayev et al., 2023) (46.3k rows).             ing both accuracy and stability over prior memory-
   Among the 7B models, YARN-128k-7B                    augmented models.
achieves the lowest perplexity on shorter contexts,     3.2.2   Scalability to Extended Contexts
whereas LongLoRA-7B-32k scales effectively up
to 16k-token sequences, albeit with mild perfor-        To further assess scalability, we evaluated ER-
mance degradation. This result highlights the trade-    MAR at a 32k-token context length (Table 2). ER-
off between scalability and modeling precision          MAR maintains consistent performance advantages
commonly observed in long-context transformers.         across all datasets, achieving a perplexity of 9.765
   For the 3B parameter models, ERMAR demon-            compared to 9.858 on PG19 (a 0.90% improve-
strates substantial gains in long-context scenarios.    ment) and 7.880 versus 7.938 on WikiText-103 (a
While OpenLLaMA-3B exhibits sharp degradation           0.06% improvement). Both models yield identical
beyond 4k tokens and Phi3-128k maintains moder-         results on Proof-Pile with a perplexity of 3.063.
ate stability, ERMAR achieves consistently com-         These results demonstrate ERMAR’s robustness
petitive performance across all sequence lengths.       and scalability in ultra-long context settings, reflect-
At 2k tokens, ERMAR surpasses MemLong on                ing the effectiveness of its ranked memory retrieval
Proof-Pile (2.98 vs. 3.16) and sustains strong re-      in preserving contextual coherence over extended
sults across the remaining datasets. Its advantage      sequences.
is particularly evident on PG-19, where ERMAR           3.2.3   In-Context Learning Performance
achieves the best performance among 3B mod-
                                                        Table 3 summarizes ERMAR’s performance across
els at 1k and 2k tokens (10.32 and 9.75, respec-
                                                        five natural language understanding tasks under
tively). Notably, ERMAR shows exceptional sta-
                                                        4-shot and 20-shot settings.
bility when scaling to longer contexts, with only
                                                           In the 4-shot configuration, ERMAR achieves
a 0.31% increase in perplexity from 4k to 16k to-
                                                        superior accuracy across all tasks, outperforming
kens on PG-19 (9.78 → 9.81), indicating superior
                                                        OpenLLaMA and other memory-augmented base-
scalability. On WikiText-103, ERMAR consistently
                                                        lines. It performs notably well on challenging
outperforms other 3B models at all evaluated con-
                                                        benchmarks such as SST-5 and MPQA, demonstrat-
text lengths, further validating the effectiveness of
                                                        ing strong generalization even with limited exam-
its relevance-based memory retrieval mechanism
                                                        ples. The consistent results across different mem-
for long-context modeling.
                                                        ory configurations further indicate its robustness in
Overall comparison against MemLong. Across              low-resource scenarios.
all 12 configurations in Table 1 (3 datasets × 4 con-      In the 20-shot setting, ERMAR continues to de-
text lengths), ERMAR outperforms MemLong in             liver leading results, achieving top accuracy on
10 out of 12 settings (83.3%). The two excep-           MPQA and Subj, and establishing a new bench-
tions occur at 16k tokens on PG-19 (9.81 vs. 9.64,      mark on SST-5. Although MemLong marginally
+1.7%) and Proof-Pile (3.18 vs. 2.99, +6.4%),           surpasses ERMAR in isolated tasks, ERMAR main-
where the overhead of the relevance scoring and         tains the highest overall average performance, re-
reranking mechanisms marginally outweighs the           flecting its scalability as the number of in-context
retrieval benefit at very long contexts. Crucially,     examples increases.
                                               PG19                              Proof-pile                       WikiText-103
         Model                    1k      2k      4k        16k        1k     2k       4k      16k       1k      2k     4k       16k
                                                                       7B Model
         YARN-128k-7b             7.22    7.47    7.17      -          3.03   3.29     2.98    -         5.71    6.11   5.71     -
         LongLoRA-7B-32k          9.76    9.71    10.37     7.62       3.68   3.35     3.23    2.60      7.99    7.83   8.39     5.47
         LLaMA-2-7B               10.82   10.06   8.92      -          3.24   3.40     2.72    -         10.82   6.49   5.66     -
                                                                       3B Model
         Phi3-128k                11.31   9.90    9.66      -/9.65     4.25   3.11     2.77    -/3.08    7.54    7.22   7.01     -/7.20
         OpenLLaMA-3B             11.60   9.77    > 103     -          2.96   2.70     > 103   -         10.57   8.08   > 103    -
         LongLLaMA-3B*            10.59   10.02   > 103     -          3.55   3.15     > 103   -         8.88    8.07   > 103    -
         LongLLaMA-3B†            10.59   10.25   9.87      -          3.55   3.22     2.94    -         10.69   8.33   7.84     -
         MemLong-3B*              10.66   10.09   > 103     -          3.58   3.18     > 103   -         8.72    7.93   > 103    -
         w/ 4K MemLong            10.54   9.95    9.89      9.64       3.53   3.16     3.15    2.99      8.53    7.92   7.87     7.99
         w/ 4K ERMAR              10.32   9.75    9.78      9.81       3.24   2.98     3.03    3.18      8.42    7.61   7.62     7.80


Table 1: Perplexity comparison of 7B and 3B models across PG19, Proof-pile, and WikiText-103, using a sliding
window evaluation. "-" denotes Out of Memory (OOM) errors, and "x/y" indicates results from single/dual GPU
setups. Memory-augmented models are tested with varying capacities. All runs use a single GPU.


  Dataset             ERMAR            MemLong           Difference           to 16.61 GB, corresponding to a 30% improvement
  PG19                 9.765            9.858              0.90%
  WikiText-103         7.880            7.938              0.06%              over MemLong. It also maintains lower memory
  Proof-pile           3.063            3.063                 0               consumption per token across all evaluated lengths,
                                                                              demonstrating superior scalability and efficiency
Table 2: Perplexity at 32k context length, evaluated on
                                                                              in memory management. This improvement stems
NVIDIA L40S GPU.
                                                                              from ERMAR’s ranked retrieval and adaptive mem-
                  InC     SST-2     MR     Subj   SST-5    MPQA               ory allocation, which reduce redundancy in long-
 Model                                                               Avg.
                 ,InM     ACC↑     ACC↑   ACC↑    ACC↑     ACC↑               context storage.
 OpenLLaMA       4,N/A    90.7     84.0   58.2    41.0     70.5      68.9
 w./ Rag         4,4      90.9     90.5   61.6    39.2     63.2      69.1
 LongLLaMA       4,4      90.4     83.9   64.3    40.0     64.2      68.6
 MemLong         4,4      91.5     84.5   61.5    41.4     70.2      69.8       Context   Model         Peak Mem    Reserved Mem        Mem/Token
 ERMAR           4,4      93.6     90.8   65.3    45.8     85.2      76.14      Length                  (GB)        (GB)                (MB)
 LongLLaMA       4,18     91.4     87.1   59.1    41.0     64.5      68.7       1024      ERMAR         7.97        8.16                7.97
 MemLong         4,18     91.0     89.6   61.7    43.5     69.4      71.0                 MemLong       8.08        8.49                8.08
 ERMAR           4,18     93.6     90.8   65.3    45.9     85.2      76.16      2048      ERMAR         8.45        8.71                4.22
 OpenLLaMA       20,N/A   93.6     91.2   55.4    38.2     66.4      69.0                 MemLong       8.67        9.38                4.33
 w./ Rag         20,18    92.2     91.3   75.8    39.8     57.6      71.3       4096      ERMAR         9.42        9.87                2.35
 LongLLaMA       20,18    94.1     90.8   64.2    41.4     72.1      72.7                 MemLong       9.72        10.58               2.43
 MemLong         20,18    93.5     93.8   65.8    43.3     70.6      73.4       16384     ERMAR         15.20       16.61               0.95
 ERMAR           20,18    94.7     91.7   82.8    47       86.5      80.54                MemLong       15.60       23.77               0.97
                                                                                32768     ERMAR         22.87       25.56               0.71
                                                                                          MemLong       23.27       26.05               0.72
Table 3: 4-shot and 20-shot ICL accuracy [%] on 5 NLU
tasks (SST-2, MR, Subj, SST-5, MPQA). We compare                             Table 4: Memory efficiency comparison of ERMAR
OpenLLaMA, LongLLaMA, MemLong, and ERMAR.                                    and MemLong across context lengths on WikiText-103.
Note: InC = In-Context, InM = In-Memory.                                     Mem/Token is computed as Peak Memory divided by
                                                                             context length.

   Overall, ERMAR consistently performs well
across varying context lengths and task complexi-                               Memory Pruning Strategy. ERMAR further
ties, effectively leveraging ranked memory retrieval                         improves efficiency through a dynamic memory
to enhance representation quality. Its ability to                            pruning mechanism. The algorithm balances three
scale with more examples and preserve perfor-                                criteria: retaining the most recent 10% of mem-
mance stability across tasks underscores its poten-                          ory, prioritizing the middle 80% based on retrieval
tial as a general-purpose framework for language                             frequency, and discarding the oldest 10% as po-
understanding and long-context modeling.                                     tentially outdated. This hybrid strategy allows
                                                                             ERMAR to adaptively manage memory content
3.2.4    Memory Efficiency Analysis
                                                                             according to actual usage patterns, ensuring that
Table 4 compares the peak and reserved memory                                valuable information is preserved while minimiz-
usage of ERMAR and MemLong across different                                  ing unnecessary memory overhead. Such adaptive
context lengths.                                                             pruning complements the ranked retrieval process,
   As shown in Table 4 and Figure 3, ERMAR ex-                               enhancing memory efficiency especially at longer
hibits clear memory optimization advantages, par-                            context lengths. A systematic validation of these
ticularly beyond 8K tokens. At a 16K context,                                ratios across 11 pruning strategies and five context
ERMAR reduces reserved memory from 23.77 GB                                  lengths is provided in Appendix A.7.
                                                               served on WikiText-103 compared to PG-19 likely
                                                               stems from dataset-specific characteristics and dif-
                                                               ferences in evaluation methodology.
                                                                    Seq          Perplexity     Memory          Throughput     Latency
                                                                    Length                      /Token            (tokens      /Token
                                                                                                 (GB)               /sec)       (ms)
                                                                    1K             8.42           7.13              3125         0.32
                                                                    2K             7.61           3.81              2904         0.35
Figure 3: Memory usage comparison between ERMAR                     4K             7.62           2.14              2109         0.47
                                                                    8K             7.76           1.31              1836         0.54
and MemLong across context lengths (1K–32K tokens),                 16K            7.80           0.90              1727         0.58
showing (left) peak memory and (right) reserved mem-
ory. ERMAR demonstrates 7–30% lower reserved mem-              Table 6: ERMAR’s standalone performance scaling on
ory requirements at longer contexts. Color coding: blue        WikiText-103, showing memory efficiency and through-
bars represent MemLong performance, while orange               put across sequence lengths.
bars show ERMAR improvements.
                                                               3.2.6 Ablation Studies
3.2.5 Latency and Throughput Analysis                          Ablation on Embedders. To investigate the in-
Table 5 compares the latency and throughput of                 fluence of embedding architectures on ERMAR’s
ERMAR and MemLong on the PG-19 dataset.                        performance, we compare BGE and LLM embed-
                                                               ders across five NLU tasks (SST-2, Subj, SST-5,
                                        Latency   Throughput
 Context   Model     Latency            /Token    (tokens/     MPQA, and MR) under various configurations. Ex-
                                        (ms)      sec)         periments examine the effects of Flash versus Ea-
 1024      ERMAR     207.97 ± 53.01     0.203     5135
           MemLong   190.68 ± 154.55    0.186     6803         ger attention modes, different context lengths (0
 2048      ERMAR     423.79 ± 52.56     0.206     4896
           MemLong   323.49 ± 204.89    0.157     7446         and 2048), and varying In-C/In-M demonstration
 4096      ERMAR     1358.36 ± 55.58    0.331     3020         settings. Results are presented in Tables 7 and 8.
           MemLong   1184.16 ± 170.56   0.289     3511
 16384     ERMAR     6862.98 ± 45.65    0.418     2387
           MemLong   6496.00 ± 213.56   0.396     2524           Att      CLen    InC     InM   SST2    Subj     SST5    MPQA MR       Avg
 32768     ERMAR     13679.03 ± 58.76   0.417     2395           Flash    0       4       4     88.07   57.30    41.42   80.04 83.84   70.13
                                                                                  4       18    88.07   57.30    41.42   80.33 83.86   70.20
           MemLong   13449.90 ± 56.22   0.410     2436                            20      18    93.92   50.35    47.05   73.63 91.50   71.69
                                                                 Eager    0       4       4     88.19   51.55    41.42   79.92 83.89   69.59
                                                                                  4       18    88.19   51.55    41.51   80.29 83.92   69.89
Table 5: Latency and throughput comparison on the PG-                             20      18    94.04   82.85    46.96   73.63 91.54   77.80
19 dataset. Latency is reported with standard deviation,         Flash    2048    4       4     88.07   51.55    41.42   80.04 83.84   68.98
                                                                                  4       18    88.07   51.25    41.42   80.33 83.86   68.99
and throughput is measured in tokens per second.                                  20      18    93.92   82.75    47.05   73.63 91.50   77.77
                                                                 Eager    2048    4       4     88.19   51.55    41.51   79.86 83.89   68.96
                                                                                  4       18    88.19   51.55    41.51   79.60 83.92   68.95
                                                                                  20      18    94.04   82.85    46.96   73.63 91.34   77.76
   ERMAR exhibits slightly higher latency (9–35%
relative increase at 1K–4K tokens, narrowing to                Table 7: Performance comparison of the BGE embedder
1.7–5.5% at 16K–32K) while maintaining compet-                 across configurations on five NLU tasks. Accuracy is
itive throughput of approximately 2.4K tokens/s                reported in percentage. Abbreviations: Att = Attention,
at longer contexts. Importantly, ERMAR demon-                  CLen = Context length, Avg = Average.
strates much lower latency variance (±45–59 ms)
compared to MemLong (±154–214 ms), reflecting                    Att      CLen    InC     InM   SST2    Subj     SST5    MPQA MR       Avg
                                                                 Flash    0       4       4     88.07   57.30    41.42   80.04 83.84   70.13
greater runtime stability in long-context settings.                               4       18    88.07   57.30    41.42   80.33 83.86   70.20
                                                                                  20      18    93.92   50.35    47.05   73.63 91.54   71.70
This reduced variance aligns with ERMAR’s adap-                  Eager    0       4       4     88.19   57.30    41.51   79.86 83.89   70.15
                                                                                  4       18    88.19   57.30    41.51   79.60 83.92   70.10
tive ranked retrieval strategy, which streamlines                                 20      18    94.04   50.35    46.96   73.63 91.54   71.70
key–value access and minimizes redundant mem-                    Flash    2048    4
                                                                                  4
                                                                                          4
                                                                                          18
                                                                                                88.07
                                                                                                88.07
                                                                                                        51.55
                                                                                                        51.55
                                                                                                                 41.42
                                                                                                                 41.42
                                                                                                                         80.04 83.84
                                                                                                                         80.33 83.86
                                                                                                                                       68.98
                                                                                                                                       69.05
ory operations.                                                  Eager    2048
                                                                                  20
                                                                                  4
                                                                                          18
                                                                                          4
                                                                                                93.92
                                                                                                88.19
                                                                                                        82.85
                                                                                                        51.25
                                                                                                                 47.05
                                                                                                                 41.51
                                                                                                                         73.63 91.50
                                                                                                                         79.92 83.89
                                                                                                                                       77.79
                                                                                                                                       68.95
                                                                                  4       18    88.19   51.25    41.51   80.29 83.92   69.03
Single-Model Performance Scaling. ERMAR’s                                         20      18    94.04   82.75    46.96   73.63 91.34   77.74

standalone performance across sequence lengths on              Table 8: Performance comparison of the LLM embedder
the WikiText-103 dataset (16K memory capacity) is              across configurations on five NLU tasks. Accuracy is
presented in Table 6.                                          reported in percentage.
   These results highlight ERMAR’s scalability,
achieving an eightfold improvement in per-token                   The results indicate that both BGE and LLM
memory efficiency (7.13 MB → 0.90 MB) while                    embedders yield comparable overall performance,
maintaining stable perplexity across increasing se-            with BGE showing slight advantages under cer-
quence lengths. The slightly higher throughput ob-             tain configurations. Notably, in the 20-shot, 18
in-memory setup with Eager attention and zero                     ity compared to MemLong and maintains stable
context length, BGE achieves a higher average ac-                 performance at 32K-token contexts. In few-shot
curacy (77.80%) compared to LLM (71.70%). The                     in-context learning tasks, ERMAR outperforms
largest gap occurs in the Subj task, where BGE                    baselines by 6.1% on average in 4-shot and 7.1%
reaches 82.85% versus LLM’s 50.35%, suggest-                      in 20-shot settings, including substantial gains on
ing that BGE better captures fine-grained semantic                MPQA (+21%) and Subj (+26%), confirming its
representations. Nevertheless, both embedders re-                 effectiveness in retrieval precision and generaliza-
main broadly consistent, highlighting ERMAR’s                     tion.
adaptability to different embedding backbones.                       ERMAR also exhibits strong computational ef-
                                                                  ficiency, reducing reserved memory by up to 30%
Ablation on Relevance and Re-ranking. We
                                                                  at long contexts and sustaining a throughput of ap-
further evaluate the effect of the Relevance+Re-
                                                                  proximately 2.4K tokens/sec with minimal latency
ranking mechanism on model perplexity across
                                                                  variance. These results establish ERMAR as an ef-
varying context lengths for WikiText-103 and PG-
                                                                  ficient and scalable retrieval-augmented framework
19. Results are shown in Table 9.
                                                                  for long-context modeling. Future work will focus
    Dataset   Context
                              Without               With          on optimizing ERMAR for specialized datasets and
                        Relevance+Reranker   Relevance+Reranker
              Length
                             Perplexity           Perplexity      expanding its applicability to complex reasoning
                1K             8.841                7.919         tasks.
                2K             7.984                7.410
    Wiki        4K             7.438                7.437
               16K             7.267                7.082
               32K             7.938                8.008
                                                                  5   Limitations
                1K            11.451               10.322
                2K            10.412                9.746         While ERMAR improves retrieval efficiency and
    PG19        4K             9.932                9.780
               16K             9.910                9.809         context retention, it has certain limitations. Its re-
               32K             9.858                9.765
                                                                  liance on ranked memory structures increases com-
Table 9: Ablation study on the Relevance+Re-ranking               putational overhead compared to standard LLMs,
mechanism showing perplexity differences for WikiText-            particularly for large-scale retrieval, as discussed
103 and PG-19 across context lengths.                             in Subsections 3.2.4 and 3.2.5, as well as Ap-
                                                                  pendix A.5. Additionally, performance variations
   The relevance scoring mechanism provides                       across different task domains indicate the need for
the greatest improvements at shorter context                      further tuning. The framework’s effectiveness in
lengths—10.4% at 1K and 7.2% at 2K tokens on                      real-world, noisy environments also requires fur-
WikiText-103. The gains taper off beyond 4K to-                   ther validation.
kens and become marginally negative at 32K, sug-
gesting that the computational overhead of ranking                Acknowledgments
may outweigh its benefits when sufficient mem-                    Shoaib Jameel is supported by the Turing’s De-
ory capacity is available. In contrast, PG-19 ex-                 fence and Security programme through a partner-
hibits consistent improvements (1.0–9.9%) across                  ship with the UK government in accordance with
all context lengths, indicating that narrative text               the framework agreement between GCHQ & The
benefits more from semantic ranking, where long-                  Alan Turing Institute. This research is partially sup-
range dependencies and non-sequential references                  ported by the Technology Innovation Institute, Abu
are frequent.                                                     Dhabi, UAE. Computational experiments were con-
                                                                  ducted using the Wolfpack cluster, supported by
4      Conclusion                                                 the School of Computer Science and Engineering
This paper introduced ERMAR, a Ranked                             at UNSW Sydney.
Memory-Augmented Retrieval framework that en-
hances long-context language modeling through dy-
namic relevance scoring and adaptive memory man-                  References
agement. By prioritizing semantically relevant in-                Marah Abdin, Jyoti Aneja, Hany Awadalla, Ahmed
formation during retrieval, ERMAR improves con-                    Awadallah, Ammar Ahmad Awan, Nguyen Bach,
                                                                   Amit Bahree, Arash Bakhtiari, Jianmin Bao, Harkirat
textual reasoning and scalability over extended se-                Behl, et al. 2024. Phi-3 technical report: A highly ca-
quences. Experimental results demonstrate that ER-                 pable language model locally on your phone. arXiv
MAR achieves up to a 3.2% reduction in perplex-                    preprint arXiv:2404.14219.
Zhangir Azerbayev, Edward Ayers, and Bartosz Pi-          Patrick Lewis, Ethan Perez, Aleksandra Piktus, Fabio
  otrowski. 2023. Proofpile: A pre-training dataset         Petroni, Vladimir Karpukhin, Naman Goyal, Hein-
  of mathematical texts.                                    rich Küttler, Mike Lewis, Wen-tau Yih, Tim Rock-
                                                            täschel, et al. 2020. Retrieval-augmented generation
Iz Beltagy, Matthew E Peters, and Arman Cohan. 2020.        for knowledge-intensive nlp tasks. Advances in neu-
   Longformer: The long-document transformer. arXiv         ral information processing systems, 33:9459–9474.
   preprint arXiv:2004.05150.
                                                          Weijie Liu, Zecheng Tang, Juntao Li, Kehai Chen, and
Zhe Cao, Tao Qin, Tie-Yan Liu, Ming-Feng Tsai, and          Min Zhang. 2024. Memlong: Memory-augmented
  Hang Li. 2007. Learning to rank: from pairwise            retrieval for long text modeling. arXiv preprint
  approach to listwise approach. In Proceedings of the      arXiv:2408.16967.
  24th international conference on Machine learning,
  pages 129–136.                                          Stephen Merity, Caiming Xiong, James Bradbury, and
                                                             Richard Socher. 2016. Pointer sentinel mixture mod-
Yukang Chen, Shengju Qian, Haotian Tang, Xin Lai,            els. arXiv preprint arXiv:1609.07843.
  Zhijian Liu, Song Han, and Jiaya Jia. 2023. Longlora:
                                                          Rodrigo Nogueira and Kyunghyun Cho. 2019. Pas-
  Efficient fine-tuning of long-context large language
                                                            sage re-ranking with bert.    arXiv preprint
  models. arXiv preprint arXiv:2309.12307.
                                                            arXiv:1901.04085.
Yao Fu, Rameswar Panda, Xinyao Niu, Xiang Yue, Han-       Bowen Peng, Jeffrey Quesnelle, Honglu Fan, and En-
  naneh Hajishirzi, Yoon Kim, and Hao Peng. 2024.           rico Shippole. 2023. Yarn: Efficient context window
  Data engineering for scaling language models to 128k      extension of large language models. arXiv preprint
  context. arXiv preprint arXiv:2402.10171.                 arXiv:2309.00071.
Alex Graves, Greg Wayne, and Ivo Danihelka.               Ofir Press, Noah A. Smith, and Mike Lewis. 2022.
  2014. Neural turing machines. arXiv preprint              Train short, test long: Attention with linear bi-
  arXiv:1410.5401.                                          ases enables input length extrapolation. Preprint,
                                                            arXiv:2108.12409.
Alex Graves, Greg Wayne, Malcolm Reynolds,
  Tim Harley, Ivo Danihelka, Agnieszka Grabska-           Jack W Rae, Anna Potapenko, Siddhant M Jayakumar,
  Barwińska, Sergio Gómez Colmenarejo, Edward               and Timothy P Lillicrap. 2019. Compressive trans-
  Grefenstette, Tiago Ramalho, John Agapiou, et al.          formers for long-range sequence modelling. arXiv
  2016. Hybrid computing using a neural network with         preprint arXiv:1911.05507.
  dynamic external memory. Nature, 538(7626):471–
  476.                                                    Jianlin Su, Murtadha Ahmed, Yu Lu, Shengfeng Pan,
                                                             Wen Bo, and Yunfeng Liu. 2024. Roformer: En-
Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasu-            hanced transformer with rotary position embedding.
  pat, and Mingwei Chang. 2020. Retrieval augmented          Neurocomputing, 568:127063.
  language model pre-training. In International confer-
  ence on machine learning, pages 3929–3938. PMLR.        Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier
                                                            Martinet, Marie-Anne Lachaux, Timothée Lacroix,
Edward J Hu, Yelong Shen, Phillip Wallis, Zeyuan            Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal
  Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang,               Azhar, et al. 2023a. Llama: Open and effi-
  and Weizhu Chen. 2021. Lora: Low-rank adap-               cient foundation language models. arXiv preprint
  tation of large language models. arXiv preprint           arXiv:2302.13971.
  arXiv:2106.09685.
                                                          Hugo Touvron, Louis Martin, Kevin Stone, Peter Al-
                                                            bert, Amjad Almahairi, Yasmine Babaei, Nikolay
Gautier Izacard and Edouard Grave. 2020. Leverag-
                                                            Bashlykov, Soumya Batra, Prajjwal Bhargava, Shruti
  ing passage retrieval with generative models for
                                                            Bhosale, et al. 2023b. Llama 2: Open founda-
  open domain question answering. arXiv preprint
                                                            tion and fine-tuned chat models. arXiv preprint
  arXiv:2007.01282.
                                                            arXiv:2307.09288.
Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick      Szymon Tworkowski, Konrad Staniszewski, Mikołaj
  Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, and          Pacek, Yuhuai Wu, Henryk Michalewski, and Piotr
  Wen-tau Yih. 2020. Dense passage retrieval for            Miłoś. 2024. Focused transformer: Contrastive train-
  open-domain question answering. arXiv preprint            ing for context scaling. Advances in Neural Informa-
  arXiv:2004.04906.                                         tion Processing Systems, 36.
Omar Khattab and Matei Zaharia. 2020. Colbert: Effi-      A Vaswani. 2017. Attention is all you need. Advances
 cient and effective passage search via contextualized      in Neural Information Processing Systems.
 late interaction over bert. In Proceedings of the 43rd
 International ACM SIGIR conference on research           Yuhuai Wu, Markus N Rabe, DeLesley Hutchins, and
 and development in Information Retrieval, pages 39–        Christian Szegedy. 2022. Memorizing transformers.
 48.                                                        arXiv preprint arXiv:2203.08913.
Shitao Xiao, Zheng Liu, Yingxia Shao, and Zhao Cao.     • Retrieval attention layers: [14, 18, 22, 26]
  2022. Retromae: Pre-training retrieval-oriented
  language models via masked auto-encoder. arXiv        • Memory capacity: 32,768 key-value pairs
  preprint arXiv:2205.12035.
                                                        • Memory group size: 128 tokens per memory
Howard Yen, Tianyu Gao, and Danqi Chen. 2024. Long-
  context language modeling with parallel context en-
                                                          group
  coding. arXiv preprint arXiv:2402.16617.
                                                        • Retrieval group size: 8 (TopK retrieval)
Manzil Zaheer, Guru Guruganesh, Kumar Avinava
 Dubey, Joshua Ainslie, Chris Alberti, Santiago On-     • Gate mechanism: Disabled (use_gate=False)
 tanon, Philip Pham, Anirudh Ravula, Qifan Wang,
 Li Yang, et al. 2020. Big bird: Transformers for       Training Hyperparameters:
 longer sequences. Advances in neural information
 processing systems, 33:17283–17297.                    • Learning rate: 5 × 10−5 with 1,000 warmup
                                                          steps
A     Appendix
                                                        • Weight decay: 1 × 10−4
This appendix supplements the main text with de-
tailed implementation and evaluation specifics for      • Batch size: 1 per device (with gradient accu-
the Enhanced Ranked Memory Augmented Re-                  mulation)
trieval (ERMAR) framework. It includes compre-
hensive descriptions of dataset preprocessing, train-   • Sequence length: 1,024 tokens
ing configurations, hyperparameters, and key ter-       • Last context length: 1,024 tokens
minology, along with extended analyses of context-
length performance and memory efficiency. The           • Training epochs: 1 epoch on SlimPajama 0.5B
provided details ensure reproducibility and offer         subset
deeper insights into ERMAR’s architectural and
                                                        • Training mode: LoRA-freeze (partial parame-
operational nuances.
                                                          ter updates)
A.1    Dataset Preprocessing
                                                        LoRA Configuration:
The SlimPajama dataset, used for fine-tuning ER-
MAR, underwent several preprocessing steps to           • Target modules:     q_proj, k_proj, v_proj,
ensure compatibility with long-context tasks. The         o_proj
dataset was tokenized using the OpenLLaMA tok-
                                                        • Trainable parameters: Layer normalization
enizer, with a maximum sequence length of 32768
                                                          and embeddings
tokens. Duplicate sequences were removed using a
hash-based deduplication algorithm, reducing the        • Frozen layers: Layers 0-13 (up to memory
dataset to 84.7K unique training rows. To handle          layer)
variable context lengths, we applied a sliding win-
dow approach with a stride of 512 tokens, ensuring      • Position encoding: Zero position type for ex-
that the model could process contexts ranging from        tended contexts
1024 to 32768 tokens. Special tokens were added         Embedder Setup:
to denote document boundaries, and padding was
applied to align sequences to the nearest multiple      • Embedder: BAAI/bge-m3 (BGE embedder)
of 128 tokens for efficient batch processing.
                                                        • Embedding dimension: 1,024
A.2    Training Configuration
                                                        • GPU-based similarity search for efficient re-
ERMAR was trained using a two-stage fine-tuning           trieval
approach with the following configuration:
  Model Parameters:                                     Hardware and Infrastructure:

    • Base model: OpenLLaMA-3B-v2 with LoRA             • Primary training: Single NVIDIA 3090 24GB
      adaptations                                         GPU

    • Memory layer: Layer 13 for historical context     • Extended context (32k):       NVIDIA L40S
      storage                                             44.4GB GPU
   • Distributed training: ZeRO-2 optimization            Figure 4 presents detailed perplexity measurements
     with Accelerate                                      across incremental context lengths from 1000 to
                                                          16000 tokens, providing fine-grained insights into
   • Memory optimization: Sequential batching             ERMAR’s scaling behavior. The fine-grained anal-
     and continual fine-tuning                            ysis reveals that WikiText-103 achieves optimal
                                                          performance around 13K-16K tokens (perplexity
A.3   Glossary of Terms
                                                          7.36), while PG-19 maintains consistent perfor-
To aid understanding, we provide definitions for          mance (9.74-9.97) across all context lengths. This
key terms used in the ERMAR framework:                    validates ERMAR’s robustness and suggests that
                                                          factual content benefits more from extended con-
   • Relevance Score (α): A normalized score              text than narrative text.
     computed via softmax over the dot product of
     query and key embeddings, representing the           A.5   Relevance+Reranker Visual Analysis
     contextual importance of a memory entry (see
     Equation 2).

   • Key-Value Pair: A tuple (Kj , Vj ) storing
     contextual information, where Kj is the key
     embedding and Vj is the corresponding value
     embedding in the memory bank.

   • RSAR (Relevance Scoring with Adaptive
     Retrieval): The mechanism that dynamically           Figure 5: Visualization of Table 9, showing the relative
     ranks key-value pairs based on their relevance       impact of the Relevance+Reranker mechanism across
     to the query, incorporating historical usage         context lengths. Color coding highlights: blue bars
     patterns.                                            represent baseline performance, while orange bars show
                                                          improvements with our full mechanism(ERMAR).
   • Memory Bank: A non-trainable storage of
     pre-computed key-value embeddings, used to           Figure 5 provides complementary visual evidence
     retain historical context without recomputa-         for the patterns discussed in Section 3.2.6. The
     tion.                                                stronger improvements at shorter contexts are vi-
                                                          sually apparent through the larger differentials be-
   • TopK Retrieval: The process of selecting the
                                                          tween the orange and blue bars, while differences
     top-K most relevant memory entries based on
                                                          in mechanism effectiveness across datasets are
     their relevance scores for use in the current
                                                          immediately noticeable in the side-by-side com-
     context.
                                                          parisons. Additionally, the 32K edge case on
A.4   Fine-Grained Context Length Analysis                WikiText, where the mechanism underperforms,
                                                          is clearly highlighted in the visualization, under-
                                                          scoring context-length sensitivities of the Rele-
                                                          vance+Reranker mechanism.

                                                          A.6   Impact of Top-K on Performance
                                                          We conducted experiments to examine how varying
                                                          the Top-K retrieval parameter affects system per-
                                                          formance across different sequence lengths on the
                                                          WikiText-103 dataset. The Top-K values (1, 4, 8, 16,
                                                          32) were tested for sequence lengths of 1K–16K
                                                          tokens, measuring latency, throughput, memory
Figure 4: ERMAR perplexity performance across fine-       usage, and perplexity.
grained context lengths for PG-19 and WikiText-103
datasets. The analysis reveals dataset-specific scaling   Results. Table 10 summarizes latency and mem-
patterns and validates performance stability across ex-   ory results across all configurations. Increasing
tended contexts.                                          Top-K consistently reduces latency per token and
improves throughput, particularly between K = 1                               Embedder   In-C,
                                                                                         In-M
                                                                                                 Dim    MPQA    SST2    SST5    SUBJ    MR

and K = 4, with diminishing gains beyond K = 8.                                                  512    88.28   93.00   45.96   94.90   97.15
Memory consumption (both peak and reserved)                                              4,4     1024
                                                                                                 2048
                                                                                                        87.93
                                                                                                        87.99
                                                                                                                91.51
                                                                                                                91.51
                                                                                                                        46.32
                                                                                                                        46.14
                                                                                                                                94.65
                                                                                                                                94.35
                                                                                                                                        97.09
                                                                                                                                        97.08
remains constant for a given sequence length, con-                            BGE                512    88.02   92.89   46.14   94.90   97.11
firming that Top-K selection does not affect model                                       4,18    1024
                                                                                                 2048
                                                                                                        88.11
                                                                                                        88.17
                                                                                                                91.40
                                                                                                                91.40
                                                                                                                        46.32
                                                                                                                        46.14
                                                                                                                                94.65
                                                                                                                                94.35
                                                                                                                                        97.09
                                                                                                                                        97.08
footprint.                                                                                       512    91.23   94.50   52.59   95.55   97.83
                                                                                         20,18   1024   91.26   93.35   49.41   96.60   97.44
                                                                                                 2048   91.29   93.23   49.68   96.75   97.40
 Seq     TopK   Latency/           Latency Throughput     Peak   Reserved
 Len            Token              (s)     (tokens/sec)   Memory Memory                          512    88.65   93.00   46.32   89.05   97.62
                (ms)                                      (GB)   (GB)                    4,4     1024   88.76   92.20   46.32   88.15   96.65
                                                                                                 2048   88.76   92.20   46.32   88.15   96.65
         1      285.38 ± 54.98     0.279    3684.15       7.98      8.19
         4      277.15 ± 60.41     0.271    3810.19       7.98      8.21      LLM                512    88.59   93.00   46.32   89.25   97.62
 1024    8      270.90 ± 57.72     0.265    3893.17       7.98      8.21                 4,18    1024   88.72   92.20   46.32   88.15   96.65
         16     268.60 ± 57.54     0.262    3928.15       7.98      8.21                         2048   88.72   92.20   46.32   88.15   96.65
         32     269.26 ± 56.84     0.263    3915.67       7.98      8.21
                                                                                                 512    90.35   92.78   50.32   95.15   98.08
         1      630.68 ± 49.07     0.308    3264.37       8.46      8.83                 20,18   1024   91.01   93.35   48.14   94.85   98.04
         4      556.76 ± 51.17     0.272    3704.12       8.46      8.81                         2048   91.01   93.35   48.14   94.85   98.04
 2048    8      555.35 ± 51.52     0.271    3714.39       8.46      8.81
         16     549.25 ± 50.81     0.268    3755.02       8.46      8.81
         32     549.17 ± 50.93     0.268    3756.11       8.46      8.81    Table 12: Accuracy results for embedding dimensional-
         1      1873.54 ± 54.43    0.457    2187.96       9.43      9.89    ity experiments across datasets and settings.
         4      1804.90 ± 56.60    0.441    2271.53       9.43      9.91
 4096    8      1759.28 ± 53.03    0.430    2330.24       9.43      9.89
         16     1738.93 ± 44.91    0.425    2356.96       9.43      9.90
         32     1719.64 ± 50.91    0.420    2383.85       9.43      9.90

         1      4264.45 ± 63.90    0.521    1921.41       11.36     12.16   A.7     Pruning Strategy Validation
         4      4116.54 ± 71.41    0.503    1990.60       11.36     12.18
 8192    8      4094.69 ± 79.01    0.500    2001.35       11.36     12.16
         16     4107.60 ± 94.04    0.501    1995.37       11.36     12.16
                                                                            The proportional settings (10% recent, 80% middle,
         32     4098.25 ± 96.92    0.500    2000.00       11.36     12.16   10% oldest) were initially heuristic. We present sys-
         1      9136.22 ± 176.62   0.558    1793.95       15.21     16.69
         4      8965.27 ± 115.76   0.547    1827.79       15.21     16.71   tematic experiments validating these ratios across
 16348   8      8961.31 ± 55.20    0.547    1828.37       15.21     16.69
         16     8945.37 ± 42.26    0.546    1831.60       15.21     16.70
                                                                            context lengths and text genres.
         32     8843.33 ± 48.01    0.540    1852.75       15.21     16.70

                                                                            Setup. We evaluated 11 pruning strategies on
Table 10: Performance metrics across Top-K values and                       WikiText-103 at five context lengths (1K–32K
sequence lengths on WikiText-103.
                                                                            tokens). Baselines: Uniform (equal priority),
                                                                            Recency-only, and Frequency-only. Hybrid
Constant Metrics. Table 11 reports memory-per-                              strategies follow the X-Y -Z format (recent%–
token and perplexity, which remain stable across                            middle%–oldest%): 0-90-10, 5-80-15, 5-85-10, 10-
Top-K variations. This indicates that increasing re-                        80-10 (proposed), 10-85-5, 10-90-0, 15-75-10, and
trieval scope affects efficiency but not model qual-                        20-70-10. All strategies yield identical perplexity
ity.                                                                        per context length (1K: 8.42; 2K: 7.61; 4K: 7.62;
                                                                            16K: 7.80; 32K: 7.86), so results below reflect effi-
  Sequence      Memory/Token               Val            Perplexity        ciency differences only.
  Length           (MB)                 Perplexity
  1024                     7.98             2.13                 8.42       Results. Tables 13 and 14 report efficiency and
  2048                     4.23             2.03                 7.61
  4096                     2.36             2.03                 7.62       latency results respectively for all strategies across
  8192                     1.42             2.05                 7.76       all context lengths. Table 13 shows that hybrid
  16348                    0.95             2.05                 7.80       strategies consistently achieve lower latency per
                                                                            token and higher throughput than baselines, while
Table 11: Constant metrics across Top-K values for each
                                                                            Table 14 reveals that hybrids also exhibit tighter
sequence length.
                                                                            standard deviations, indicating more stable infer-
                                                                            ence. Table 15 summarizes the best-performing
Findings. Increasing Top-K from 1→4 yields the                              strategy per context length regime.
largest latency reduction (e.g., 285.4→277.1 ms at
1K; 9136.2→8965.3 ms at 16K), while further in-                             Findings. (1) Hybrid strategies outperform
creases provide minimal additional gains. Through-                          baselines, yielding 10–45% throughput gains
put improvements are proportional, especially for                           across all lengths (e.g., +45.4% vs. Uniform at
longer sequences (e.g., 2188→2384 tokens/s at                               1K; +17.0% at 32K). (2) Optimal ratios shift
4K). Memory and perplexity remain unaffected.                               with context length: at short contexts (1K–2K),
Thus, K = 4–8 offers the best trade-off between                             5-85-10 dominates by minimising the recent slot
efficiency and computational cost.                                          and maximising the middle; at 4K our proposed
                                     1K                  2K                4K             16K               32K
          Strategy               ms/tok tok/s ms/tok tok/s ms/tok tok/s ms/tok tok/s ms/tok tok/s
          0-90-10                0.285     3619    0.266      3798     0.374    2676   0.444    2253     0.465   2153
          5-80-15                0.259     4023    0.259      3906     0.347    2884   0.441    2269     0.458   2184
          5-85-10                0.206     5069    0.205      4946     0.336    2981   0.416    2404     0.414   2413
          10-80-10 (proposed)    0.262     3981    0.241      4202     0.329    3044   0.453    2209     0.424   2359
          10-85-5                0.259     3979    0.228      4428     0.344    2913   0.424    2358     0.446   2243
          10-90-0                0.308     3512    0.264      3899     0.363    2760   0.452    2213     0.473   2116
          15-75-10               0.283     3875    0.224      4631     0.368    2736   0.417    2400     0.435   2297
          20-70-10               0.254     4067    0.242      4197     0.346    2894   0.432    2316     0.452   2212
          Frequency-only         0.278     3737    0.267      3790     0.372    2688   0.466    2145     0.482   2076
          Recency-only           0.264     3921    0.263      3850     0.360    2779   0.453    2206     0.478   2094
          Uniform                0.295     3486    0.283      3566     0.375    2673   0.469    2133     0.485   2062

Table 13: Latency per token (ms/tok) and throughput (tok/s) for all pruning strategies across context lengths on
WikiText-103. All strategies yield identical perplexity at each context length. Bold denotes the best throughput per
context length. Hybrid strategies are separated from baselines by a horizontal rule.

      Strategy                    1K (s)               2K (s)              4K (s)              16K (s)            32K (s)
      0-90-10             1.39±59.71 544.75±61.74 1533.22±63.16 7273.54±65.57 15222.90±76.59
      5-80-15           265.24±67.89 529.87±60.99 1422.65±58.80 7222.95±134.59 15003.15±76.86
      5-85-10           210.65±54.01 420.44±58.35 1376.97±64.84 6814.59±52.75 13580.93±41.21
      10-80-10 (prop.) 267.94±68.49 492.74±57.10 1348.11±60.15 7419.04±81.91 13894.24±98.75
      10-85-5           265.54±57.85 467.92±57.57 1408.47±57.39 6947.99±53.99 14608.47±81.73
      10-90-0          315.16±121.40 540.34±110.69 1487.03±66.01 7405.31±50.24 15488.75±77.02
      15-75-10         289.29±123.63 458.33±109.72 1506.06±125.70 6826.80±60.86 14264.39±89.72
      20-70-10          260.48±59.69 495.15±69.11 1417.23±57.05 7073.92±47.16 14811.33±64.79
      Frequency-only       284.33±67.71      545.86±61.15        1524.97±44.72 7641.64±127.35 15787.38±72.64
      Recency-only         270.18±62.35      538.19±66.10        1476.49±67.39 7428.95±49.05 15648.46±61.91
      Uniform              302.29±63.34      579.82±62.77        1535.08±71.37 7683.59±87.02 15888.88±85.68

Table 14: Total latency (mean ± std, in seconds) for all pruning strategies across context lengths on WikiText-103.
Lower values and tighter standard deviations indicate more stable inference. Hybrid strategies are separated from
baselines by a horizontal rule.


    Context      Best Strategy    Throughput (tok/s)                 A.8   Sensitivity to Embedding Dimensionality
    1K / 2K           5-85-10            5069 / 4946                       in ICL Retrieval
    4K               10-80-10               3044
    16K / 32K         5-85-10            2404 / 2413
                                                                     We analyzed how embedding dimensionality influ-
                                                                     ences in-context retrieval performance using both
Table 15: Best-performing strategy per context length                BGE and LLM embedders. Experiments were con-
regime.                                                              ducted on MPQA, SST-2, SST-5, SUBJ, and MR
                                                                     datasets with in-context/in-memory settings of (4,
                                                                     4), (4, 18), and (20, 18). Embedding dimensions of
                                                                     512, 1024, and 2048 were evaluated.
                                                                     Results. Table 12 reports results for both em-
                                                                     bedders. Overall, reducing the dimension to 512
                                                                     (via PCA) maintains or slightly improves accuracy
10-80-10 is best; at long contexts (≥16K), 5-85-
                                                                     across most datasets compared to higher dimen-
10 reasserts via aggressive middle-biased pruning.
                                                                     sions, suggesting redundancy in high-dimensional
(3) Quality is unaffected: perplexity is identical
                                                                     embeddings.
across all strategies at each context length, confirm-
ing that pruning ratios govern efficiency only. (4)                  Findings. Reducing dimensionality to 512 pre-
Hybrids are most stable: hybrid configurations                       serves retrieval accuracy while slightly improving
achieve latency variance of ±40–70 ms vs. ±45–                       performance on SST-5 (+3.2 pp) and MPQA (+0.3
127 ms for baselines, making them more reliable                      pp). This indicates that lower dimensions sup-
in deployment.                                                       press noise and redundancy. Dimensional padding
to 2048 introduces negligible changes (<0.5 pp).
Across both embedders, SUBJ shows minor degra-
dation at high dimensionality, whereas MR remains
stable. Overall, 512-dimensional embeddings offer
the best trade-off between accuracy and efficiency.
