betaFeedback

WorksComputer Science

Memorilla: Latent Semantic Memory for LLMs

Abstract

Memory enables large language models (LLMs) to use information beyond their parameters, such as past user conversations, long documents, or an agent's earlier actions. For a frozen LLM, access to this accumulated knowledge is limited to what a memory system places in its context window. However, gathering and combining relevant information needed for each query while keeping the model's context short remains challenging for existing systems. Here we introduce Memorilla, a memory system that gathers information from an entire document collection into a fixed number of query-dependent 'memory tokens' for a frozen LLM. Memorilla encodes documents (such as user chats, book chapters) once into reusable embeddings, then learns to retrieve and place query-specific information in the LLM's input embedding space. Using only 16 memory tokens, Memorilla achieves the best performance against baselines including Mem0 and MemoRAG on five of eight benchmarks spanning personalization, long-document and knowledge-intensive question answering. Notably, on FactKG, it reaches 84.33% accuracy versus 80.43% with full-context inference, while using 108x fewer tokens to represent the source documents. Furthermore, Memorilla can facilitate continual learning in agentic systems where the document count (the agent's past turns) increases throughout the trajectory. In a TextWorld environment, we show that Memorilla reduces the agent's tendency to wander between rooms it has already explored, and improves its average success rate from 18.6% with full-history in-context learning to 24.2%. Overall, Memorilla aids frozen LLMs in accumulating and using knowledge effectively across long-context interactions and takes a step towards building continually learning AI systems.

Introduction

Memory is central to how large language models (LLMs) are used. Personal assistants must recall a user’s history across months of conversations, question-answering systems must reason over documents far longer than the model’s context window, and agents must act on everything they have observed. None of this information exists in the model’s parameters, and a frozen LLM can use it only through its context [20]. A memory system bridges this gap by encoding accumulated information, storing it persistently, and retrieving what each query needs into the context [55]. The central challenge for such a system is to give a frozen LLM access to an entire, growing collection of knowledge while keeping its context short [1, 11].

Existing memory systems address these issues only in part. Agentic memory systems such as MemGPT [38], Mem0 [9] and A-MEM [57] organize past interactions into summaries or structured records, and MemoRAG [40] uses a compressed global memory to guide retrieval, but each ultimately places selected text in the context and inherits the limits of selection. Latent compression methods such as ICAE [14], IC-Former [52], AutoCompressors [8] and ComMer [58] represent documents as a few soft tokens in the LLM embedding space, but they form these tokens without the query, so the same tokens must serve every question. xRAG [7] incorporates query relevance but only by compressing a single retrieved document. Methods that store model-specific hidden or key–value states, such as LongMem [51], MemoryLLM [53], M+ [54], and Cartridges [13], tie the memory to one model and require training the LLM, a side network, or a separate cache for each corpus. What is missing is a memory system that will retrieve query-relevant information from document embeddings directly into the input embedding space of a frozen LLM. Benefits of such an approach would be that the frozen LLM can retain all of its capabilities, and rely on only a few query relevant latent embeddings to answer questions or solve tasks instead of processing long textual contexts in a slow and lossy manner [34]. In essence, improving the speed and quality of LLM responses and also the decision making in LLM agents based on past experiences.

Present work. Here we introduce MEMORILLA, a memory system that learns to retrieve query-relevant information from document embeddings directly into the input embedding space of a frozen LLM (Figure 2). First, a frozen embedding model encodes each document, such as a user conversation or a book chapter, once into a persistent memory store. Next, for each query, a trainable memory module attends to every embedding in the persistent memory store and performs a query conditioned memory readout for the LLM. Unlike RAG which retrieves a subset of documents as textual tokens, MEMORILLA learns to recall what matters from the entire collection for a query, and expresses it as K=16K = 16 latent memory tokens for a frozen LLM, and does not require the documents to enter the context as text. Because the store uses the same embedding as a dense retrieval index, encoding adds no cost over retrieval, and with 512 documents on one H100, MEMORILLA has 27× lower end-to-end latency than full context answer generation (0.74s against 19.9s, Appendix § 17).

MEMORILLA architecture

Figure 2. MEMORILLA architecture. A frozen encoder embeds source documents (User Chats) once into a persistent memory store. For each Query, K query-conditioned slots attend over the store and are projected into the frozen LLM’s embedding space as a memory readout.

Our benchmarks mirror three settings in which deployed LLMs need memory (Figure 1 and Figure 3). In personalization, an assistant must adapt to preferences a user rarely states directly, whether answering questions that depend on traits revealed across past conversations (PersonaMem-v2, PersonalizationV4) or writing in the style of the user’s earlier text (LaMP-4, LaMP-7). Because a user’s preferences rarely share wording with the query, similarity-based retrieval struggles to find and combine relevant information. Notably, on LaMP-4, MEMORILLA reaches 18.15 ROUGE-L against 14.21 for full context while using 474× fewer document tokens. In knowledge-intensive question answering, such as checking a claim against a knowledge base, MEMORILLA outperforms full context on FactKG (84.33% against 80.43%) with 108× fewer document tokens. In long-document understanding, the answer is buried in thousands of tokens of text and often phrased differently from the question, so a system must find and connect relevant content across the entire document. On

Performance versus context length

Figure 1. Performance versus context length. Mean score over eight benchmarks against the geometric mean of document tokens given to a frozen Qwen3-8B decoder. MEMORILLA lies on the Pareto frontier (dashed) with the highest score at 16 memory tokens, 394× fewer than full context.

Eight benchmark plots: (a) FactKG (Acc), (b) TriviaQA (EM), (c) PMv2 (Acc), (d) LaMP-7 (ROUGE-L), (e) LaMP-4 (ROUGE-L), (f) NQA (ROUGE-L), (g) PV4 (Acc), and (h) PubMedQA (Acc)

Figure 3. Per-benchmark performance versus context length. Primary-metric score against mean document tokens per query, with a frozen Qwen3-8B decoder. MEMORILLA lies on the Pareto frontier (dashed) of every benchmark, leads on five and is second on NarrativeQA and PV4.

TriviaQA, whose questions were written independently of their source pages, MEMORILLA reaches the highest exact match (57.00) with 743×\times fewer document tokens than full context.

Beyond answering questions, MEMORILLA allows agents to learn continually from their own experience. In this work, we consider the TextWorld environment [10] where an agent must explore rooms, find and use objects, and complete a multi-step goal within 50 turns, which requires remembering where it has been and what it has already tried. After every turn, MEMORILLA adds that turn to its document store and draws on this experience at the next turn. With our approach, the agent completes 37.5% of held-out games in at least one of three attempts, against 25.0% for the same agent given its full history in context. Overall, MEMORILLA improves the agent’s ability to escape navigation loops and execute action sequences that are crucial to reaching the target.

Memorilla

A persistent latent memory must preserve a document collection across queries while recalling different information for each query. MEMORILLA meets these requirements through three operations: encoding, storage, and retrieval. Given NN document chunks D={d1,…,dN}\mathcal{D} = \{d_1,\ldots,d_N\}, a frozen encoder produces a query-independent representation that is stored once. For instance, D\mathcal{D} can be a collection of NN user-LLM conversations, chapters of a lengthy book, or health records. For each query qq, a trainable memory module reads this store and returns KK query-conditioned soft memory tokens, which a frozen LLM consumes together with the query text. Figure 2 summarizes the architecture.

Encoding and Persistent Storage

A frozen document encoder fencdf_{\mathrm{enc}}^{d} maps each chunk did_i to an embedding zi∈Rhe\mathbf{z}_i \in\mathbb{R}^{h_e}. Stacking these embeddings produces the query-independent document store

ZD=[fencd(d1),…,fencd(dN)]∈RN×he.(1)\mathbf{Z}_{\mathcal{D}} = [f_{\mathrm{enc}}^{d}(d_1), \ldots, f_{\mathrm{enc}}^{d}(d_N)] \in\mathbb{R}^{N \times h_e}. \tag*{(1)}

Because ZD\mathbf{Z}_{\mathcal{D}} does not depend on a query, it is computed once and persisted in memory or on secondary storage. Every subsequent query reuses the same matrix, and only added or changed documents must be re-encoded. A frozen query encoder fencqf_{\mathrm{enc}}^{q} then maps qq to zq=fencq(q)∈Rhe\mathbf{z}_q = f_{\mathrm{enc}}^{q}(q) \in\mathbb{R}^{h_e}. Unlike ZD\mathbf{Z}_{\mathcal{D}}, zq\mathbf{z}_q is computed only for the current query and is not stored as long-term memory.

Query-Conditioned Retrieval

In the next phase, a trainable memory module fmemf_{\mathrm{mem}} uses zq\mathbf{z}_q to select information from ZD\mathbf{Z}_{\mathcal{D}}:

fmem:(ZD,zq)↦M,M∈RK×hL,(2)f_{\mathrm{mem}} : (\mathbf{Z}_{\mathcal{D}}, \mathbf{z}_q) \mapsto\mathbf{M}, \qquad\mathbf{M} \in\mathbb{R}^{K \times h_L}, \tag*{(2)}

where hLh_L is the input-embedding dimension of the frozen LLM and M=[m1;…;mK]\mathbf{M} = [\mathbf{m}_1;\ldots;\mathbf{m}_K] is the output memory matrix. Each row mk∈RhL\mathbf{m}_k \in\mathbb{R}^{h_L} is one soft memory token in the LLM embedding space. The module reads all NN stored document embeddings but always contributes exactly KK memory tokens to the LLM context, and allows significant context compression (over 4000×\times, see Table 11).

TaskMetricClosed bookRAG 1RAG 5RAG 50Full ContextLLM Lingua-2xRAGMem0Memo RAGMEMORILLACompression
PMv2Acc (SA)25.6426.1025.9226.7227.9226.9230.9027.4828.7644.601,974×
PV4Acc (SA)58.3062.2164.9865.7859.1252.1462.6465.0767.8866.653,153×
PV4Acc (SA, Hard)31.9638.0039.2741.9736.57—34.98<u>44.20</u>45.9541.97
PubMedQAAcc21.0034.00<u>67.00</u><u>67.00</u><u>67.00</u>69.0036.0024.0067.0059.0020×
NarrativeQABLEU-17.097.367.858.295.896.8716.867.779.1416.364,212×
NarrativeQAROUGE-111.5413.3215.6018.4519.127.2617.3314.2421.80<u>19.68</u>
NarrativeQAROUGE-L10.7112.4414.5917.2317.997.1816.9213.8020.51<u>19.31</u>
NarrativeQAF1-Score9.8710.5111.6413.2713.505.76<u>15.22</u>11.5815.0316.56
TriviaQAEM36.0051.8055.2055.6052.6042.4047.0044.60<u>56.60</u>57.00743×
TriviaQABLEU-129.1240.2939.0943.0735.5629.2846.5429.0945.0058.66
TriviaQABLEU-43.748.457.5410.949.154.30<u>11.31</u>5.5410.3514.79
TriviaQAF1-Score37.6852.0654.9958.0556.4939.7450.3742.7457.5560.60
FactKGAcc65.9773.9376.9578.39<u>80.43</u>71.6578.9872.7980.3884.33108×
LaMP-4ROUGE-114.2416.1516.9816.9816.2114.98<u>18.12</u>14.7217.0820.30474×
LaMP-4ROUGE-L12.2414.3114.9415.0914.2112.98<u>16.10</u>12.7015.0218.15
LaMP-4F1-Score8.9811.2112.1512.1511.328.71<u>13.46</u>9.0514.1215.54
LaMP-4METEOR7.139.7810.9510.959.856.9910.117.28<u>11.21</u>11.41
LaMP-7ROUGE-148.7349.8049.8049.6549.5749.61<u>52.78</u>49.5849.9254.4029×
LaMP-7ROUGE-L43.1344.1143.8143.7743.7143.73<u>46.84</u>43.6844.0048.37
LaMP-7F1-Score36.1037.2837.2837.2637.1437.17<u>42.99</u>36.8737.5544.96
LaMP-7METEOR32.3133.7033.7833.7333.5533.74<u>38.35</u>33.3034.1240.37

Table 11. Main results across eight benchmarks. All methods use a frozen Qwen3-Embedding-4B encoder and a frozen Qwen3-8B decoder; Mem0 and MemoRAG also use a frozen Qwen3-4B-Instruct-2507 to build their memories. RAG-kk retrieves the top-kk chunks by cosine similarity and Full Context reads the full collection. MEMORILLA uses K=16K=16 memory tokens. Best result per row is bold, second best is underlined. The Compression column reports how many times more document tokens Full Context gives the decoder than the 16 memory tokens of MEMORILLA (Table 10). LLMLingua-2 was not evaluated on the PV4 hard subset.

Stage 1: Memory slot initialization. The module initializes KK memory slots with learned vectors Q0∈RK×he\mathbf{Q}_0 \in\mathbb{R}^{K \times h_e} that are shared across collections and queries. Distinct initial values define a fixed output budget while allowing the slots to capture different information.

Stage 2: Query conditioning. The slots attend to the query embedding:

Qc=LayerNorm⁡(Q0+CrossAttn⁡(Q=Q0,K=zq,V=zq)).(3)\mathbf{Q}_c = \operatorname{LayerNorm}\left(\mathbf{Q}_0 + \operatorname{CrossAttn}(Q=\mathbf{Q}_0, K=\mathbf{z}_q, V=\mathbf{z}_q)\right). \tag*{(3)}

Because the query is represented by one vector, it provides a shared update to all slots; the residual connection preserves the differences among Q0\mathbf{Q}_0. The resulting Qc\mathbf{Q}_c is therefore query-conditioned while retaining distinct slot identities.

Stage 3: Document retrieval. The conditioned slots attend to every document embedding through LrefL_{\mathrm{ref}} cross-attention blocks, following the latent-array design of Perceiver (Jaegle et al., [22]). Let Z‾D=LayerNorm⁡(ZD)\overline{\mathbf{Z}}_D = \operatorname{LayerNorm}(\mathbf{Z}_D) and R0=Qc\mathbf{R}_0 = \mathbf{Q}_c. For block ℓ\ell,

R~ℓ=Rℓ−1+CrossAttn⁡(Q=LayerNorm⁡(Rℓ−1),K=Z‾D,V=Z‾D),Rℓ=R~ℓ+FFN⁡(LayerNorm⁡(R~ℓ)).(4)\begin{aligned} \widetilde{\mathbf{R}}_\ell&= \mathbf{R}_{\ell-1} + \operatorname{CrossAttn}(Q=\operatorname{LayerNorm}(\mathbf{R}_{\ell-1}), K=\overline{\mathbf{Z}}_D, V=\overline{\mathbf{Z}}_D), \\ \mathbf{R}_\ell&= \widetilde{\mathbf{R}}_\ell+ \operatorname{FFN}\left(\operatorname{LayerNorm}(\widetilde{\mathbf{R}}_\ell)\right). \tag*{(4)} \end{aligned}

where FFN is a two-layer feed-forward network with GELU activations (Hendrycks & Gimpel, [18]). Each slot can attend to the full collection, while the query-conditioned slots determine which information is retained. The refinement blocks therefore implement a continuous, query-conditioned read over all stored documents rather than a discrete top-kk selection.

Stage 4: Projection to the LLM embedding space. A learned projection maps the refined slots from the encoder dimension heh_e to the LLM input-embedding dimension hLh_L:

M=LayerNorm⁡(RLref)Wproj,Wproj∈Rhe×hL.(5)\mathbf{M} = \operatorname{LayerNorm}(\mathbf{R}_{L_{\mathrm{ref}}})\mathbf{W}_{\mathrm{proj}}, \qquad\mathbf{W}_{\mathrm{proj}} \in\mathbb{R}^{h_e \times h_L}. \tag*{(5)}

The resulting rows m1,…,mK\mathbf{m}_1,\ldots,\mathbf{m}_K are the soft memory tokens passed to the frozen LLM.

Memory Injection into the Frozen LLM

Finally, the LLM input-embedding layer maps the text query to Pq\mathbf{P}_q, giving

XLLM=[m1,…,mK∣Pq].(6)\mathbf{X}_{\mathrm{LLM}} = [\mathbf{m}_1,\ldots,\mathbf{m}_K \mid\mathbf{P}_q]. \tag*{(6)}

Because mk∈RhL\mathbf{m}_k \in\mathbb{R}^{h_L} has the same dimension as a text token embedding, the LLM processes memory and text in the same input sequence. No LLM layer or attention mechanism is changed. Rotary position embeddings are applied over the combined sequence in the standard way (Su et al., [50]). The frozen LLM can therefore attend to the recalled memory through its existing self-attention layers.

Supervised Training Objective

The frozen LLM generates Yout=(y1,…,yL)\mathbf{Y}_{\mathrm{out}} = (y_1,\ldots,y_L) autoregressively from XLLM\mathbf{X}_{\mathrm{LLM}}, and we minimize the negative log-likelihood of the target answer tokens:

Lsup=−∑i=1Llog⁡P(yi∣y<i,XLLM;θmem),(7)\mathcal{L}_{\mathrm{sup}} = -\sum_{i=1}^{L} \log P(y_i \mid y_{<i}, \mathbf{X}_{\mathrm{LLM}}; \theta_{\mathrm{mem}}), \tag*{(7)}

where θmem\theta_{\mathrm{mem}} includes the memory module and its projection to the LLM embedding space. The loss is applied only to answer positions, not to the prompt or memory positions.

Memorilla with Qwen3

Based on the formalization above, we instantiate Memorilla with fencdf_{\mathrm{enc}}^d and fencqf_{\mathrm{enc}}^q as a frozen Qwen3-Embedding-4B model. Unless stated otherwise, we fix K=16K = 16 throughout the paper and use a Qwen3-8B model as the frozen LLM. This gives us 194,123,776 trainable parameters.

Training Stages

We use a three-stage curriculum that moves from general content preservation to diverse language tasks and then to the evaluation domains. See Appendix § 13.§ 2 for training hyperparameters.

Stage 1 trains the memory module on 1.98 million English Wikipedia paraphrase reconstruction examples. Each passage is divided into document chunks, and the module must preserve enough information in its fixed memory budget for the frozen LLM to generate a paraphrase. This stage provides a general initialization before the module encounters task-specific supervision.

Stage 2 continues training on 1.34 million examples drawn from ten datasets covering reading comprehension, open-domain question answering, and summarization. The variation in source structure and answer format teaches the module to recall different information from the same type of stored representation. Table 1 lists the component datasets and their sizes.

StageSourceCategoryNum. Queries
PretrainingEnWiki ArticlesParaphrase1,979,809
FinetuningSQuAD v2 (Rajpurkar et al., [41])Reading Comprehension86,821
DROP (Dua et al., [12])Reading Comprehension77,400
CoQA (Reddy et al., [44])Reading Comprehension108,647
PubMedQA (Jin et al., [25])Reading Comprehension900
QuAIL (Rogers et al., [45])Reading Comprehension10,246
PwC (Ge et al., [14])Reading Comprehension241,564
CNN/DailyMail (See et al., 2017)Summarization287,113
SamSum (Gliwa et al., [15])Summarization14,731
DialogSum (Chen et al., [6])Summarization12,460
MS MARCO (Bajaj et al., [2])Open-domain QA504,111
Finetuning total1,343,993

Table 1. Training datasets for MEMORILLA. The pretraining corpus is derived from English Wikipedia. The finetuning mixture spans reading comprehension, open-domain question answering, and summarization tasks across 10 sources. Sizes are numbers of training queries.

Stage 3 fine-tunes the resulting module on a unified mixture of the training splits from all eight evaluation benchmarks. One multi-task checkpoint is used directly for FactKG, TriviaQA, NarrativeQA, PubMedQA, LaMP-4, and LaMP-7. PersonaMem-v2 and PersonalizationV4 receive additional benchmark-specific fine-tuning because their validation losses required more epochs to plateau, while the other benchmarks plateaued or began to overfit earlier.

Experiments

Baselines

We compare MEMORILLA against RAG approaches based on cosine similarity, Mem0 (Chhikara et al. [9]), and MemoRAG (Qian et al. [40]). xRAG (Cheng et al. [7]) and ComMer (Zeldes et al. [58]) (via its reported results, Table 12) compress the context into latent input embeddings for the LLM. Finally, we also compare against LLMLingua-2 (Pan et al. [39]), which is a task-agnostic text based prompt compression method. All baselines we run use a frozen Qwen3-Embedding-4B encoder for document embeddings and a frozen Qwen3-8B decoder for generation. Mem0 and MemoRAG additionally use a frozen Qwen3-4B-Instruct-2507 to build their memories, matching the 4B scale of the encoder with which MEMORILLA reads the same collections (Appendix § 14).

MethodTok.LaMP-4 ROUGE-LLaMP-7 ROUGE-L
ComMer12817.5045.00
MEMORILLA (4B)1617.7247.04
MEMORILLA (8B)1618.1548.37
MethodQuery awareParamsPMv2 SA
Global mean-poolno6,566,40028.94
Segmented mean-poolno6,566,40029.68
Segmented, parameter-matchedno190,149,12031.10
Cosine top-16, parameter-matchedyes (hard)190,149,12033.86
Documents onlyno268,856,32034.72
Q-Formeryes (soft)268,856,32043.34
MEMORILLAyes (soft)190,190,08044.04

Table 12. Comparison with ComMer on personalized generation, against ComMer’s reported results. ComMer uses Gemma-2b while MEMORILLA uses Qwen3.

Benchmarks

We evaluate MEMORILLA on eight supervised benchmarks spanning (a) personalization, (b) long-document QA, and (c) knowledge-intensive QA tasks that demand memory. For personalization, we consider PersonaMem-v2 (PMv2) (Jiang et al. [24]), LaMP-4, LaMP-7 (Salemi et al. [46]) and our own PersonalizationV4 (PV4) benchmarks as they require integrating information scattered across a user’s prior chats or writing history to form a coherent user representation. For long-document QA, we choose NarrativeQA (Kočiský et al. [30]) and TriviaQA (Joshi et al. [26]) to test the method’s ability to compress long documents in their entirety into a usable representation for downstream QA. Finally, for knowledge-intensive QA, we consider FactKG (Kim et al. [29]) and PubMedQA (Jin et al. [25]) to test factual grounding from structured or semi-structured evidence of varying quantity and format. Table 10 (Appendix § 15.§ 2) reports how many document tokens each method gives the LLM per query across all the benchmarks.

BenchmarkDocs/qFits 32KRAG 1RAG 5RAG 50Full ContextLLM Lingua-2xRAGMem0Memo RAGMEMORILLA
PMv2116Partial1256529,00931,58725016659,25416
PV4200No2011,02110,83250,455180197811,04616
PubMedQA4Yes69321324†3242901832416
NarrativeQA1,420Partial693543,61267,385596149380016
TriviaQA164Partial512262,35711,888243126930316
FactKG129Yes13645681,727279130057316
LaMP-4172Yes452271,7157,580227125123016
LaMP-718Yes25125435†45929918113516
Geometric mean552731,8086,301278121278416

Table 10. Document tokens per query. Mean number of document-derived tokens in the decoder input, excluding the question and all shared instructions. Mem0, MemoRAG and LLMLingua-2 are counted at the setting reported for each benchmark’s primary metric in Table 11, and truncated inputs are counted as read. Fits 32K reports whether every Full Context prompt fits the enforced 32,768-token limit, and Partial means that YaRN is enabled for the remaining examples. † marks benchmarks where RAG-50 reads the same chunks as Full Context, for every PubMedQA question and 96.7% of LaMP-7 questions.

Evaluation

We use accuracy for classification tasks, exact match and token-level F1 (lowercased, whitespace-tokenized) for short-form QA, and ROUGE, BLEU, F1, and METEOR for open-ended text generation. PMv2 and PV4 are evaluated only on their short-answer questions. The model’s generation is embedded with the frozen encoder and scored as correct if the gold answer is its cosine nearest neighbor among the question’s predefined answer choices, which we report as short-answer accuracy. All supervised LLM evaluations use a decoding temperature of 0. Our serving stack enforces a 32,768-token decoder context and enables YaRN whenever an assembled full-context input exceeds this limit (Appendix § 15).

Quantitative Results

MEMORILLA outperforms all baselines on average while using 394×394 \times, 113×113 \times and 49×49 \times fewer document tokens than full context, RAG-50 and MemoRAG in geometric mean (Figure 1). It also lies on the Pareto frontier of every benchmark, while the compact baselines xRAG, LLMLingua-2 and Mem0 average only 41.92, 40.75 and 38.02 against 49.68. Figure 3 breaks this down by benchmark, where MEMORILLA leads on five and and is second on NarrativeQA and PV4.

Relational evidence. On FactKG (Figure 3a), MEMORILLA reaches 84.33% against 80.43% for full context, 80.38% for MemoRAG and 78.98% for xRAG, with 108×108 \times and 36×36 \times fewer tokens than the first two. Because full context receives every document, the margin cannot stem from discarded evidence, and Section 5 shows that MEMORILLA’s margin over RAG-50 grows with the number of entities and widens overall with the number of composed facts.

Long-document and personalization QA. On TriviaQA (Figure 3b), MEMORILLA reaches 57.00 EM against 56.60 for MemoRAG and 52.60 for full context with 19×19 \times and 743×743 \times fewer document tokens. On PMv2 short-answer (Figure 3c), MEMORILLA reaches 44.60% against 30.90% for xRAG, the strongest baseline. Every other baseline stays within about three points of closed-book (25.64%), including full context, which uses 1,974×1{,}974 \times more document tokens than MEMORILLA. On LaMP-7, every baseline except xRAG (46.84) stays within one ROUGE-L point of the closed-book model, whereas MEMORILLA improves it from 43.13 to 48.37. Finally, MEMORILLA achieves 18.15 ROUGE-L on LaMP-4 (Figure 3e) with 474×474 \times fewer tokens than the full context baseline.

Where memory does not help. On the remaining three benchmarks (Figure 3f–Figure 3h), a baseline leads, but only by supplying the LLM with 18 to 690 times more document tokens. MemoRAG leads NarrativeQA in ROUGE-1 and ROUGE-L (21.80 and 20.51 versus 19.68 and 19.31) with 50×50 \times more document tokens, consistent with its access to verbatim passages, and PV4 (67.88% versus 66.65%) with 690×690 \times more. On PubMedQA, whose four abstracts total only 324 tokens, LLMLingua-2 reaches 69.00% and four other baselines 67.00%, versus 59.00% for MEMORILLA.

Full context is not an upper bound. Full context trails MEMORILLA on every benchmark except PubMedQA and on 20 of 21 metrics in Table 11, and RAG-50 exceeds it on 15, so supplying the entire collection hurts more often than it helps.

NarrativeQA by question type

(a) NarrativeQA by question type

FactKG by entity count

(b) FactKG by entity count

FactKG by composition

(c) FactKG by composition

Figure 4. Per-question breakdowns against RAG-50. (a) NarrativeQA question types are the question’s first word. Conceptual questions (‘Why’, ‘How’, ‘What’) favor MEMORILLA whereas entity-recall questions (‘Which’, ‘Who’) favor RAG. (b) MEMORILLA’s advantage grows with entity count, indicating better capture of multi-entity relational patterns. (c) RAG-50 degrades as more facts are composed, while MEMORILLA remains stable across all depths.

What Does Memorilla Learn?

Conceptual understanding vs. factual recall. Figure 4a breaks down NarrativeQA performance by question type. MEMORILLA outperforms RAG-50 by +4.91 ROUGE-L on “why” questions and +7.02 on “how,” both requiring reasoning about narrative structure and causality. Conversely, RAG-50 leads by +3.45 on “who” and by +2.93 on “which,” where retrieval can locate the entity name verbatim. One explanation is that compression preserves global structure for conceptual reasoning but loses the exact surface tokens that retrieval excels at pinpointing (although question type also varies with answer length and entity frequency). The same trade-off would explain why MemoRAG, which reads selected passages, leads our ROUGE scores on this benchmark while trailing on F1. Figure 6 illustrates the complementary strength in personalization, where MEMORILLA uses semantically relevant medical history despite no lexical overlap with the query.

Personalization case study showing a user query, LLM-only response, RAG response, and memory-based response

Figure 6. Personalization Case Study. On PersonaMem-v2, MEMORILLA personalizes a generic query by leveraging the user’s remembered iron-deficiency anemia history, despite no lexical overlap between the question and the relevant conversation history.

Multi-entity relational reasoning. On FactKG, MEMORILLA’s advantage over RAG-50 grows monotonically with entity count, from +4.23pp at 1 entity to +7.59pp at 4+ (Figure 4b). RAG-50 drops from 78.73 to 51.75 as the number of composed facts increases from 1 to 4, while MEMORILLA remains in the 80–89 range (Figure 4c). Compression encodes relational structure holistically, whereas retrieval degrades when the reasoning chain spans multiple documents. Because 73.5% of FactKG claims have more than 50 chunks, part of this gap reflects evidence RAG-50 never retrieves, but full context, which reads every chunk, still trails MEMORILLA overall (80.43 against 84.33).

MEMORILLA and RAG solve different questions. On FactKG, we observed that 15.9% of questions are answered by MEMORILLA alone against 10.0% by RAG-50 alone, and on PMv2 short-answer the split is 27.1% against 9.2%. In Figure 5, we show that the union of MEMORILLA and RAG (which is an oracle upper bound), could lead to substantial gains in performance than either approach alone, which motivates the design of hybrid retrieval and latent-memory systems as potential future work.

Per-question complementarity between MEMORILLA and RAG-50

Figure 5. Per-question complementarity between MEMORILLA and RAG-50. Share of questions answered by each method alone and by at least one of them (union), an oracle upper bound for a hybrid system. The union exceeds either method on every benchmark. †A question counts as answered when its ROUGE-L is at least max⁡(0.20,m)\max(0.20, m), where mm is MEMORILLA’s median.

What neither method solves. We also examine the questions that both MEMORILLA and RAG-50 answer incorrectly. On PV4, many of these require linking facts that each appear somewhere in the user’s history, which suggests that the remaining errors come from combining information rather than from failing to find it. On FactKG, both methods are biased toward judging claims false. True claims make up 89.5% of the claims both methods get wrong but only 28.7% of those both get right, which points to a miscalibrated decision threshold rather than missing evidence.

Continual Learning with Memorilla

Beyond the supervised learning settings where the document collection can be static, we showcase the potential of MEMORILLA in scenarios where an LLM agent has to continuously learn and adapt from its environment. One such environment is TextWorld (Côté et al. [10]), a suite of partially observable text games in which an agent explores up to 65 rooms, manipulates objects and pursues multi-step goals for at most 50 turns, with reward arriving mainly on a win. After each turn, MEMORILLA stores the completed turn as a new document and condenses the growing document embedding store into K=8K=8 memory tokens placed before the prompt (Figure 7 and Appendix § 18).

Reinforcement-learned memory on TextWorld showing the training loop and comparison of ICL with MEMORILLA

Figure 7. Reinforcement-learned memory on TextWorld. (a) A frozen encoder embeds the trajectory, the trainable memory module compresses it to K=8K=8 latents, and the frozen LLM agent acts; sparse rewards over G=16G=16 rollouts drive a GRPO update to the memory module alone. (b) On a held-out game, ICL loops between explored rooms while (c) MEMORILLA reaches the goal (⋆\star).

Experimental Setup

The agent is a frozen Qwen3-4B-Instruct-2507 decoder paired with the frozen Qwen3-Embedding-4B encoder. Only the memory module is trained, from random initialization and with GRPO on environment reward (see Appendix § 18.§ 1). We compare against two baselines. Full-history in-context learning (ICL) gives the decoder the complete interaction history without memory, and an untrained memory module isolates the contribution of RL. Unlike in the supervised setting, the memory supplements the text rather than replacing it. Every condition keeps the full history under the same input budget (16,000 tokens in training, 4,096 in evaluation), so any improvement reflects what the memory learns to extract, not access to additional information. In the medium and hard games, the history grows from 800 tokens at the first turn to about 3,200 and then levels off, since the median rollout ends at turn 33 and only 5 of 40 rollouts reach turn 50.

Results

Task completion. Training MEMORILLA with GRPO improves avg@3 from 0.186 to 0.242 and pass@3 from 0.250 to 0.375 relative to full-history ICL (Figure 8). Untrained memory instead falls below ICL on both metrics, avg@3 (0.153) and pass@3 (0.225), so the gain comes from learning rather than from the added tokens. The trained memory acts as a compact state that keeps the frozen agent oriented over long trajectories.

Bar chart comparing Random memory, Full-history ICL, and MEMORILLA + GRPO on avg@3, pass@3, and Terminal episodes

Figure 8. MEMORILLA on TextWorld with a frozen Qwen3-4B-Instruct-2507 decoder. Terminal episodes end through the game or the turn limit before the history exceeds the 4,096-token evaluation budget.

MEMORILLA reduces agent loops. The largest behavioral change is termination rather than solve rate. ICL exhausts its 4,096-token budget on 71% of rollouts against 58% for MEMORILLA despite both reading the same trajectory text. Trajectory inspection shows that trained memory helps the agent escape navigation loops and execute keyed action sequences, such as unlocking and then opening a container. Figure 7 illustrates this, with ICL cycling between explored rooms and never reaching the goal, while MEMORILLA advances to the target room. The remaining failures concentrate in the longest games, whose quests approach or exceed the 50-turn limit and require backtracking across many rooms.

Discussion and Conclusion

MEMORILLA separates persistent knowledge storage from the context required for each query. New documents can be added without updating the LLM, while the memory module learns to extract relevant information through a fixed number of latent tokens. This design supports assistants that draw on growing histories without proportionally increasing the decoder’s context. Our analyses suggest that the learned representations capture relationships across documents and recover personal context beyond lexical similarity. In TextWorld, reinforcement learning improves a frozen agent’s decisions even when the interaction history is already available as text. Together, these findings support learned memory as a means of improving how LLMs use accumulated information, with the memory interface optimized through either answer supervision or environment reward.

Conclusion. In this work, we introduced MEMORILLA, a latent semantic memory system that gives frozen LLMs access to query-dependent information from large corpora as ‘soft’ memory tokens. MEMORILLA demonstrates that a frozen LLM can use accumulated knowledge through a learned, query-dependent interface, rather than relying only on retrieved text or an expanding prompt. MEMORILLA leads retrieval, compression and agent memory baselines on average at 20 to 4,212×4{,}212\times fewer document tokens across personalization, long-document QA, and knowledge-intensive tasks. Additionally, MEMORILLA also enables continual learning in agentic RL, where training only the memory module teaches an agent a new environment without overwriting prior knowledge.

Limitations and Future Work. MEMORILLA can lose fine-grained factual details, likely because the document encoder was never trained for memory compression. Future work exploring combinations of latent memory and text retrieval could combine the global structure that memory captures with the exact entities that retrieval recovers. Furthermore, encoders trained specifically for compression could close the remaining gap on fine-grained details. Our experiments pair a Qwen encoder with a Qwen decoder, and testing how well the memory mechanism transfers across model families is also an interesting future area of research. Our evaluation covers personalization, long-document QA and knowledge-intensive QA, so MEMORILLA may not carry over directly to domains such as coding. Nonetheless, for personalization tasks, because the persistent memory store holds only embeddings, a multimodal encoder could extend the same interface to images, audio and video, giving assistants a memory of what a user has seen and heard. Since each user’s memory is a separate store, it can be kept on device or deleted on request, which eases privacy concerns. Finally, because LLM decoding dominates latency, the efficiency gains show up mainly for large collections. Hence one can explore extensions of MEMORILLA where memory modules could share a single persistent store and inject memory tokens across LLMs of varying sizes.

AI USE STATEMENT

We used coding agents to implement and run experiments, and minimally used generative AI tools to polish the writing of the paper. As part of our method, GPT-5 generated the PersonalizationV4 personas, GPT-5.1 generated the question categories, chat topics and questions, and GPT-5-mini generated the dialogues (Appendix § 15.§ 1). We did not use generative AI tools for any other part of this work. The authors reviewed all AI-assisted work and verified the code and experimental results produced with coding agents before reporting them. We take responsibility for the final content of this work, including text, claims and artifacts produced with the aid of generative AI.

ETHICS STATEMENT

MEMORILLA stores and recalls information from user conversations, which raises privacy concerns when deployed on real user data. Because the memory store is external to the LLM, a user’s embeddings can be removed without retraining, but stored embeddings can still encode sensitive information and deployments should obtain user consent and protect them accordingly. PersonalizationV4 consists of synthetic users based on LLM-generated personas and contains no data from real users. All persona profiles follow a single machine template.

REPRODUCIBILITY STATEMENT

§ 2 describes the MEMORILLA architecture, and § 2.6 and § 2.4 describe the training curriculum and objective. Appendix § 13.§ 1 lists the training data, and Appendix § 13.§ 2 reports the model configuration, training hyperparameters, document chunking and evaluation splits. Appendix § 14 describes the implementation of each baseline, and Appendix § 15 describes the benchmarks, the PersonalizationV4 data pipeline and the context budget of each method. Appendix § 18 gives the full TextWorld RL setup. All supervised evaluations use greedy decoding and a fixed random seed. We are releasing the code, the training and evaluation data with precomputed embeddings, and the PersonalizationV4 data on our project website.

ACKNOWLEDGMENTS

We thank Ben Geist, Charilaos Kanatsoulis, Jonas De Schouwer, and Michael Bereket for discussions and feedback on our manuscript, Shayan Talaei for discussions about memory, Victor Li for initial brainstorming of the project, and Olivia Markham for initial experimentation. This work used Marlowe [28], Stanford University’s GPU-based Computational Instrument, supported by Stanford HAI and Stanford Research Computing. We also gratefully acknowledge the support of NSF under Nos. CCF-1918940 (Expeditions), DMS-2327709 (IHBM), IIS-2403318 (III); NIH under No. 1U24NS146314-01, Gates Foundation, Stanford Data Applications Initiative, Wu Tsai Neurosciences Institute, Stanford Institute for Human-Centered AI, Chan Zuckerberg Initiative, Amazon, Genentech, SAP, and SCBX. The content is solely the responsibility of the authors and does not necessarily represent the official views of the funding entities.

Related Work

Textual memory. Textual memory keeps source records readable and retrieves relevant records at inference. RAG [31] and REALM [16] retrieve passages from a document index. Systems built for longer histories retain the same basic interface while organizing the records differently. MemGPT [38] moves information between context tiers, MemoryBank [60] stores conversations and summaries, and Mem0 [9] and A-MEM [57] maintain structured records across sessions. These systems preserve provenance and exact details, but the LLM can reason only over material that retrieval places in its context. Evidence outside the selected set remains unavailable, and widening that set yields limited returns. In-Context RALM [42] finds that most question-answering gains come from the first one or two retrieved documents. MemoRAG [40] uses compressed global memory to generate retrieval clues, but its final generator still reads selected passages. Textual memory is therefore effective when evidence can be localized, while signals distributed across a collection remain constrained by document selection. MEMORILLA instead computes a query-conditioned latent state from the full collection, complementing retrieval when exact evidence is needed.

Latent compression. Latent compression replaces replayed text with compact continuous state. ICAE [14] and IC-Former [52] encode a long input into reusable vectors consumed by frozen target LLMs, while AutoCompressors [8] fine-tune an LLM to produce and consume recursive summary vectors. These representations can be cached because they are computed without a query, but they cannot change what they emphasize for different queries. Gist tokens [36] and 500xCompressor [33] make the same tradeoff using layer-specific key–value states rather than standard input embeddings. xRAG [7] makes the representation query relevant by first selecting a document through retrieval and mapping its embedding to one LLM token, which retains document selection as the access mechanism. A second line improves the alignment between compression and generation. PISCO [35] and COCOM [43] jointly adapt their compressors and generators, while CLaRa [17] learns reusable document vectors before training a query reasoner with the generator. These methods gain a learned latent interface but require an adapted generator. Other methods obtain reuse within a narrower memory domain. TokMem [56] optimizes a separate token for each procedure, while ComMem [58], USER-LLM [37], and Embedding-to-Prefix [21] construct latent state for user histories. MEMORILLA instead accepts unseen document collections without further optimization and converts an LLM-independent store into new query-conditioned input embeddings for a frozen LLM.

Model memory. Model memory stores information in architecture-specific state. Memory-ryLLM [53] maintains a self-updating latent pool, M+ [54] retrieves from long-term storage using the current hidden state, and LongMem [51] retrieves cached key–value states through a trained side network. Their shared internal representation supports query-conditioned recall, but also couples the memory and its reader to a particular model. Other methods preserve state during model execution rather than across an independent document collection. LM2 [27] updates a gated memory matrix during autoregressive inference. Titans [3] combine fixed task-level parameters with a contextual neural memory updated while processing a sequence. MELODI [5] and Activation Beacon [59] compress state across context windows and transformer layers to extend long-sequence processing. Cartridges [13] makes model-specific key–value caches reusable and composable, but requires offline optimization for each new corpus. These approaches demonstrate the value of persistent latent state, while their architecture-specific interfaces limit reuse across models and collections. MEMORILLA instead keeps memory external and supplies it to a frozen LLM as input embeddings.

Additional Details on Training Methodology

Training Datasets

Table 1 details the training data used across the first two stages of the MEMORILLA pipeline. The pretraining corpus consists of approximately 2M paraphrase reconstruction examples derived from English Wikipedia articles. The finetuning mixture aggregates 1.34M queries across 10 sources spanning reading comprehension, open-domain QA, and summarization, exposing the memory module to varied compression demands across different answer types and document structures. PubMedQA contributes only its 900-question training split, which is disjoint from the 100 test questions used for evaluation.

Training Configuration

All MEMORILLA runs use frozen encoder and decoder backbones. Only the memory module is trainable unless otherwise noted. Supervised training stages use bf16 mixed precision on 4 NVIDIA H100 80GB GPUs and random seed 23. Document embeddings are precomputed and cached to amortize encoding cost. Table 2 lists how each benchmark’s collection is split into the chunks did_i that the encoder embeds. The supervised objective follows § 2.4, with loss computed only over answer tokens. A single memory module is trained jointly across all downstream tasks for up to 5 epochs. On PV4 and PMv2 we continue for additional epochs because both were still improving on validation when the other benchmarks had converged. Train and test users are disjoint on both, so one module serves every user and enrolling a new one requires only embedding their chats.

BenchmarkChunk unitTokens per chunk (mean / median)
PMv2One conversation session280 / 262
PV4One chat dialogue252 / 224
PubMedQAOne abstract section84 / 78
TriviaQAEvidence passage, split sentence-greedily at 128 tokens70 / 77
NarrativeQAStory paragraph, split on sentences above ~256 tokens94 / 35
FactKGOne knowledge-graph triple13 / 13
LaMP-4One profile item47 / 44
LaMP-7One profile tweet25 / 25

Table 2. Document chunks per benchmark. Each chunk did_i is embedded once by the frozen encoder. Token counts use the Qwen3 tokenizer.

Additional Details on Baselines

All baselines use the frozen Qwen3-8B as the decoder and the frozen Qwen3-Embedding-4B as the document encoder, and every answer is generated greedily. Baselines that insert text share one prompt template per benchmark and differ only in the context placed before the question.

Closed-book. The decoder receives only the query, which shows how much of each benchmark it answers from parametric knowledge.

RAG and Full Context. RAG-kk ranks the chunks of a collection by the cosine similarity between their embeddings and the query embedding, and places the top kk chunks in the prompt as text, most similar first and separated by blank lines. Full Context places every chunk in its stored order. Inputs longer than the enforced 32,768-token limit use YaRN with a scaling factor of 4, which extends the window to 131,072 tokens and applies to part of PMv2, TriviaQA and NarrativeQA and to all of PV4 (Table 10). For the 10.8% of evaluated NarrativeQA questions whose books exceed this window, the earliest chunks are dropped.

ComponentSettingValue
Memory modulePooling modeAdaptive cross-attention with softmax over documents
Memory slotsK=16K=16
Cross-attention layers2 layers, slots ←\leftarrow documents
Attention heads8
Encoder-side dimension2560
Decoder-side dimension2560 for 4B decoder, 4096 for 8B decoder
Slot initializationXavier uniform
ProjectionLinear encoder-to-decoder projection
RegularizationDropout 0.1 with residual cross-attention
Frozen backbonesDocument encoderQwen3-Embedding-4B, mean-pooled per document
4B decoderQwen3-4B-Instruct-2507
8B decoderQwen3-8B
Trainable parametersMemory module only; 190,190,080 for 4B and 194,123,776 for 8B
GenerationDecodingGreedy decoding with T=0T=0, top-p=1.0p=1.0, top-k=−1k=-1
Short-answer limit8 tokens for classification, 64 tokens for QA and fact-verification tasks
Long-form limit128 tokens for LaMP-4 and LaMP-7; 512 tokens for EnWiki reconstruction

Table 3. Model configuration for MEMORILLA. The memory module maps document representations into a fixed set of learned memory tokens that are inserted into the frozen decoder context.

LLMLingua-2. LLMLingua-2 [39] is a hard prompt compression method that deletes tokens from the context rather than replacing it with latent vectors. We use the released XLM-RoBERTa-large token classifier. Because the classifier never sees the question, each collection is compressed once and reused for every query, similar in principle to MEMORILLA. We concatenate the documents of the Full Context input with blank-line separators and compress them as one block, retaining newlines and question marks. The question, answer-format instruction, system prompt and chat template are copied verbatim, so the prompt differs from Full Context only in the compressed documents. We disable the option to discard whole documents, since document selection is retrieval and is already covered by RAG-kk. We set absolute budgets of 32, 64, 128 and 350 tokens rather than a compression rate, which the method treats only as a soft target, and report the best budget for each metric.

ItemConfiguration
Stage 1 corpus1.98M EnWiki paraphrase reconstruction examples, chunked at approximately 128 tokens with mean 1.73 documents per row
Stage 2 corpusMixed supervision over SQuAD v2, DROP, CoQA, PubMedQA, QuAIL, PwC, CNN/DailyMail, SAMSum, DialogSum, and MS MARCO
Stage 3 corpusUnified concatenation of PV4, PMv2, FactKG, TriviaQA, NarrativeQA, PubMedQA, LaMP-4, and LaMP-7
PV4 and PMv2 specializationAfter multi-task fine-tuning, PV4 and PMv2 are each further fine-tuned for 5 epochs on the corresponding benchmark training split using the same recipe
Other downstream tasksFactKG, TriviaQA, NarrativeQA, PubMedQA, LaMP-4, and LaMP-7 use the multi-task checkpoint directly with no additional task-specific training
Evaluation splitOfficial test split for every task except LaMP-4 and LaMP-7, which use their development splits; TriviaQA, which uses a deterministic seed-23 validation subsample with n=500n=500; and PubMedQA, which uses the 100-example test portion of a 900/100 split derived from PQA-L

Table 5. Downstream training and evaluation details. Stage 3 trains on a unified downstream mixture. PV4 and PMv2 receive additional benchmark-specific fine-tuning, while all other benchmarks use the multi-task checkpoint directly.

xRAG. xRAG [7] maps the embedding of the top retrieved chunk to a single soft token in the input space of the decoder through a trained bridge. We reimplement the bridge in our codebase as a layer normalization followed by a two-layer MLP with a GELU activation, which maps the 2,560-dimensional chunk embedding to the 4,096-dimensional decoder input space with 27,276,288 trainable parameters. The chunk is retrieved by cosine similarity with the shared encoder. Only the bridge is trained, from scratch on each benchmark’s training split with the same answer-token loss as MEMORILLA. We train for 5 epochs with AdamW at a learning rate of 10−410^{-4}, a weight decay of 0.01, a warmup ratio of 0.1, an effective batch size of 16, a maximum sequence length of 8,192 tokens and seed 23.

ComMer. ComMer [58] compresses user-history documents into latent representations with a learned compressor, merges them and passes them to a frozen LLM for personalized generation. We compare against its reported LaMP-4 and LaMP-7 results in Table 12.

Mem0 and MemoRAG. Mem0 [9] extracts and consolidates memories at write time, while MemoRAG [40] forms clue queries from a global memory to guide retrieval. We run the official implementations with the settings in Table 6. Both use a frozen Qwen3-4B-Instruct-2507 to write their memory, as the fact extractor of Mem0 and as the memory model of MemoRAG. This matches the 4B scale of the Qwen3-Embedding-4B encoder with which MEMORILLA reads the same collections, so every method processes the documents with a 4B model and uses the same frozen Qwen3-8B decoder. MemoRAG runs in its supported long-context memory mode, in which the memory model reads the uncompressed collection rather than a compressed version of it. Its retrieval uses each benchmark’s own chunks and the shared encoder, so the clue mechanism is its only difference from RAG-k. We sweep the retrieval depth of Mem0 over k∈{10,30,50}k \in\{10,30,50\} and of MemoRAG over its native setting and caps of 5 and 50 chunks, and report each at its best depth per metric.

SettingMem0MemoRAG
Implementationmem0ai 0.1.118 with its stock prompts and ADD/UPDATE/DELETE/NONE loop, unmodifiedOfficial repository with its prompts unchanged
Memory-writing modelFrozen Qwen3-4B-Instruct-2507 extracts facts and consolidates memoriesFrozen Qwen3-4B-Instruct-2507 reads the collection as its memory
Memory-model decodingGreedy, up to 2,048 tokensGreedy, up to 128 tokens per clue call
Write pathOne add() per document, with each extracted fact reconciled against its 5 nearest stored memoriesCollection read once per entity and cached, front-truncated only where it exceeds the context window (NarrativeQA)
Memory scopeOne Qdrant collection per user (PMv2, PV4), story (NarrativeQA) or question (others)One memory per user, story or question
Retrieval queryThe questionClue spans and surrogate questions longer than 3 words, plus the question
RetrievalTop-kk memories by cosine similarityTop 3 chunks per query, unioned, deduplicated and kept in corpus order
Depths sweptk∈{10,30,50}k \in\{10, 30, 50\} memoriesNative (about 10 to 20 chunks), and capped at 5 and 50 by maximum similarity over queries
Memory-model answerNot applicableNot used (use_memory_answer=False)
RetrieverQwen3-Embedding-4B with 2,560 dimensions and no instruction prefix, over each benchmark’s chunks (Table 2)
GeneratorFrozen Qwen3-8B with the system prompt, chat template, answer-format instruction and maximum new tokens of RAG-kk
DecodingGreedy, with T=0T=0, top-p=1.0p=1.0 and top-k=−1k=-1

Table 6. Mem0 and MemoRAG configuration. Rows below the rule are shared with the RAG-kk baselines, so both methods differ from RAG only in the context given to the decoder.

Additional Details on Benchmarks

Personalization. These benchmarks require combining information spread across a user’s past chats or writing into a picture of the user that no single document provides.

  • PersonaMem-v2 (PMv2, n=5,000n=5{,}000) [24]. Each user has a long history of conversations with an assistant about everyday tasks, and each question asks for a response that fits the user’s preferences. Most preferences are never stated outright but surface indirectly, for instance in an email the user asks to have polished, so the model must infer them from scattered cues across many sessions rather than look them up.

  • PersonalizationV4 (PV4, n=4,237n=4{,}237). Our synthetic benchmark gives each user 200 two-turn conversations that reflect a persona without stating its traits (Appendix § 15.§ 1). Each question places the user in a new scenario and requires combining at least two persona facts, which may

appear in different conversations. A hard subset (n=629n=629) keeps the questions that the untrained Qwen3-4B-Instruct-2507 decoder answers incorrectly without documents or with the top retrieved conversation.

  • LaMP-4 (n=1,925n=1,925), LaMP-7 (n=1,500n=1,500) ([46]). LaMP-4 asks the model to write a headline for a new news article in the style of the author’s earlier articles and headlines, and LaMP-7 asks it to rewrite a tweet in the style of the user’s earlier tweets. The challenge is stylistic rather than factual, since style emerges from the whole writing history rather than a single item.

Long-Document QA. This axis tests whether memory can compress entire long documents into a usable representation for downstream QA.

  • NarrativeQA (NQA, n=10,557n=10,557) ([30]). Questions concern full books and movie scripts and were written from plot summaries without access to the stories, so they target events, motives and relations described across the narrative rather than sentences that can be matched locally. Answers are free-form text, which rewards understanding the plot over copying a passage.

  • TriviaQA (n=500n=500 from the 17,944-question validation split) ([26]). Questions written by trivia enthusiasts are paired with Wikipedia and web documents collected afterwards. Since the questions were not written against these documents, their wording and structure often differ from the passages that answer them, and an answer may require combining facts across sentences.

Knowledge-Intensive QA. These benchmarks test factual grounding from structured or semi-structured evidence of varying quantity and format.

  • FactKG (n=9,041n=9,041) ([29]). Each claim must be labeled as supported or refuted by facts from the DBpedia knowledge graph, through one-hop lookups, conjunctions of several facts, existence checks, multi-hop chains or negations. A multi-hop claim such as “AIDAStella was built by a company in Papenburg” requires chaining two facts, neither of which verifies the claim on its own, and a negated claim requires confirming that a relation is absent.

  • PubMedQA (n=100n=100) ([25]). Each question is a biomedical research question based on an article title, answered yes, no or maybe from the article’s abstract with its conclusion removed. The model must infer the conclusion from the reported methods and results, often by interpreting quantitative findings. The entire source fits easily in the context, which makes PubMedQA a contrast case where condensing the source offers little benefit.

Table 7 summarizes the benchmark datasets evaluated in this work. All datasets use standard train/validation/test splits. For the personalization benchmarks (PV4, PMv2, LaMP-4, LaMP-7), training and evaluation users are strictly disjoint to prevent leakage of user-specific information. We evaluate LaMP-4 and LaMP-7 on their development splits and TriviaQA on the validation split. For PubMedQA we use a 900/100 train/test split derived from the PQA-L source. Table 10 reports how many document tokens each method places in the decoder per query. The serving stack enforces a 32,768-token decoder limit and enables YaRN for every full-context example that exceeds it, which covers part of PMv2, TriviaQA and NQA and all of PV4. Every PubMedQA collection and 96.7% of LaMP-7 collections hold at most 50 chunks, so RAG-50 reads the same chunks as Full Context on them.

DatasetTaskμˉ\bar{\mu} docs/qμˉ\bar{\mu} tok/qTrainValTest
PersonalizationV4 (PV4) (Ours)Personalization SA20050,47615,0581,7554,237
PersonaMem-v2 (PMv2) [24]Personalization SA11631,61818,5212,0595,000
NarrativeQA (NQA) [30]Long-document generative QA1,42076,22532,7473,46110,557
FactKG [29]KG fact verification1291,66586,36713,2669,041
TriviaQA [26]Open-domain factoid QA16411,861138,38417,944—
PubMedQA [25]Biomedical QA4324900—100
LaMP-4 [46]Personalized headline gen.1727,63812,527—1,925
LaMP-7 [46]Personalized tweet paraphrase1846510,437—1,500

Table 7. Benchmark datasets overview. Each row corresponds to an evaluation benchmark. Each data point consists of a textual query paired with a collection of source documents from which the model must produce an answer or generation. μˉ\bar{\mu} docs/q and μˉ\bar{\mu} tok/q report the mean number of source documents and total source tokens per query in the test split.

PersonalizationV4 Data Pipeline

PersonalizationV4 is a synthetic benchmark for evaluating multi-document user modeling. Each user has one LLM-generated persona profile seeded from the Faithful Persona-based Conversational Dataset [23]. The resulting profiles are 10k to 22k characters long (median 15.5k) and describe demographics, personality, work, hobbies, communication style and how preferences change over time. All of the user’s data is derived from this profile through the five steps below, and Table 8 traces one held-out user through each of them.

PersonaName Maya Patel. Age 34. Location Austin, Texas, USA. Occupation Certified Welder & Part-Time CNC Operator at a regional aerospace supplier. … Maya grew up in a multicultural household where her Indian-American parents emphasized discipline, education, and the importance of physical well-being. After completing a two-year technical diploma in welding technology, she entered the workforce in a traditionally male-dominated industry, where she quickly earned a reputation for precision, reliability, and an unflappable calm under pressure. Though she never pursued a university degree, her practical knowledge of metallurgy, robotics-aided fabrication, and safety protocols rivals that of many engineers. …
CategoriesAerospace welding expertise & mental rehearsal habits. Gaming genre preferences & playstyle strategies. Morning mango ritual & mobility routine. … (3 of 10)
Chat topicMaya asks for a list of cooperative building-and-craft games she can play online with classmates after welding class.
User turn… looking for coop building-and-craft games I can jump into with the welding class after tonight’s session. Need stuff that’s accessible for mixed skill levels, supports voice chat, and has meaningful base-building or automation mechanics. Toss me a short list with platform notes and why each one fits.
Assistant turn(seven games with platform notes, from Minecraft to Raft) … Each supports voice via Discord/Steam, scales with mixed experience, and offers clear building goals for group sessions.
QuestionIn a new open-world crafting RPG, players can specialize in one mastery for unique bonuses. Considering Maya’s welding expertise, love for base-building, and ergonomic focus from the Iron Heart project, which specialization best aligns with her likely in-game identity?
Reference answerMaster Builder, optimizing structural stability, workstation placement, and production comfort, because she prefers engineering-style layouts that echo her fabrication and ergonomic design background.
DistractorsArcane Historian, optimizing lore discovery and dialogue outcomes, because she prefers uncovering story fragments over experimenting with materials and structural layouts. Beast Whisperer, optimizing pet behavior and breeding trees, because she prefers managing biological companions over designing durable and efficient physical constructs. Shadow Scavenger, optimizing stealth routes and loot efficiency, because she prefers sneaking past threats over methodically constructing and upgrading comprehensive bases. Combat Tactician, optimizing battlefield formations and ambushes, because she prefers front-line tactics over refining structures, workstations, or long-term infrastructure planning.

Table 8. One held-out PersonalizationV4 user through the pipeline. Excerpts are verbatim apart from abridgement. The question draws on base-building, which appears only in the dialogue shown, and on the Iron Heart project, which appears in 18 other dialogues, so answering requires combining documents. The distractors are never shown to the model and serve only as scoring candidates.

  1. Question categories. GPT-5.1 reads the persona and extracts 10 persona-specific categories that questions can test.

  1. Chat topics. GPT-5.1 writes exactly 200 one-sentence scenarios per user in which the user asks the assistant for help, covering every part of the persona.

  1. Dialogues. GPT-5-mini expands each topic into one two-turn dialogue with one user turn and one assistant turn. The user embodies the persona implicitly without stating its traits. Exactly 200 dialogues are generated per user and all form the collection that the memory module reads; there is no truncation step.

  1. Questions. For each category, GPT-5.1 is asked to write 15 questions from the persona alone. It writes 14 in 1,234 of the 1,490 released category files and 13 to 15 in all but one, which has 5. Each question has a reference answer and four distractors. The instructions in Table 9 require every question to combine at least two persona facts in a new scenario and every distractor to be a plausible preference that matches the reference answer in length, structure and specificity. This gives 133 to 145 questions per user (mean 141.3).

QuestionsEach question must require synthesizing information or understanding nuance from the persona. Questions must require combining two or more facts from the persona profile. Avoid questions that can be answered by recalling a single fact. Embed each question in a specific, realistic scenario that requires applying persona knowledge to a novel situation rather than simple recall. The question stem must not hint at characteristics of the answer.
DistractorsEvery choice (A-E) must be a reasonable, professional, or logical preference for a human. Never use obviously wrong, absurd, or incompetent distractors. Ensure distractors include industry-standard best practices that most people in the persona’s role would choose, but which this specific persona rejects. Use information that is true about the persona but applies it to the wrong situation or frequency. All five choices must have the same word count within a tolerance of two words.

Table 9. Question-generation instructions. Verbatim excerpts from the prompt given to GPT-5.1 for each category, which also contains the full persona profile, the target category and the number of questions to write.

  1. Randomization. The reference answer’s position among its distractors is shuffled with a fixed seed of 42.

Questions are posed without their candidate answers, and the model answers in free text. The reference answer and distractors are used only by the short-answer scorer, which counts a response as correct when its nearest candidate under the Qwen3-Embedding-4B encoder is the reference answer. We release 149 users: 119 training users and 30 held-out evaluation users, none of whom appear in training. One training user whose generated persona was a refusal is withheld from the release. Every question for these held-out users is evaluated: 139 to 143 per user and 4,237 in total, all in the test split. The PersonalizationV4 dataset is linked on our {link}project website. The hard subset (n=629n=629) is defined from the untrained Qwen3-4B-Instruct-2507 decoder’s multiple-choice answers and contains questions it answers incorrectly without documents, with the top-1 retrieved document, or in both settings; 299 of the 629 questions are answered incorrectly in both settings.

Context Budget per Query

Table 10 reports the number of document-derived tokens each method places in the decoder for one query. We exclude the question, the answer-format instruction, the system prompt and the chat template, which are identical across methods. For each text baseline, the count is the length of its prompt minus the length of the closed-book prompt for the same question, measured with the Qwen3-8B tokenizer and averaged over the evaluated questions. Closed-book receives no document tokens, MemorILLa contributes its 16 memory tokens and xRAG a single token. Figure 1 places each method at the geometric mean of these counts over the eight benchmarks, and the compression column of Table 11 divides the Full Context count by the 16 tokens of MemorILLa.

Additional Results and Ablations

Table 11 reports the complete 8B results underlying the main quantitative comparison in Figure 1. Table 12 compares MEMORILLA with ComMer on LaMP-4 and LaMP-7.

Memory Architecture

We port the BLIP-2 bridging module (Li et al., [32]) to document collections and report it as a Q-Former architecture ablation. Table 13 compares methods for constructing 16 memory slots from NN document embeddings on PMv2. Each method is trained from scratch using the hyperparameters in Table 4.

SettingStage 1 EnWiki pretrainStage 2 Multi-task pretrainStage 3 Downstream fine-tune
InitializationRandomWarm-start from Stage 1Warm-start from Stage 2
DataEnWiki paraphrase reconstructionMixed supervision corpusUnified downstream mixture
TasksParaphrase reconstructionReading comprehension, open-domain QA, summarizationPV4, PMv2, FactKG, TriviaQA, NQA, PubMedQA, LaMP-4, LaMP-7
OptimizerAdamWAdamWAdamW
LR schedulerCosine annealing with warmupCosine annealing with warmupCosine annealing with warmup
Peak learning rate3×10−43 \times10^{-4}3×10−43 \times10^{-4}1×10−41 \times10^{-4}
Weight decay1×10−21 \times10^{-2}1×10−21 \times10^{-2}1×10−21 \times10^{-2}
Warmup ratio0.030.030.1
Max decoder length102410242048
Per-device batch size8 for 4B, 4 for 8B8 for 4B, 4 for 8B2
Gradient accumulation4 for 4B, 8 for 8B4 for 4B, 8 for 8B8
Effective batch size12812864
Devices4 GPUs4 GPUs4 GPUs
Epochs115
Checkpoint selectionFinal checkpointFinal checkpointOne shared multi-task checkpoint; best by validation loss only for PV4/PMv2 specialization
Validation interval——0.25 epoch
Random seed232323

Table 4. Training stages for MEMORILLA. Stage 1 pretrains memory on EnWiki paraphrase reconstruction, Stage 2 warm-starts on the mixed supervision corpus in Table 1, and Stage 3 performs downstream multi-task fine-tuning.

Global mean-pool. This baseline averages all document embeddings into one collection vector and copies it into all 16 slots.

Segmented mean-pool. This baseline partitions the ordered sequence of document embeddings into 16 adjacent groups of documents and averages each group to form one slot. The groups contain complete documents rather than subdivisions of individual documents.

Segmented with matched parameters. This method begins with the 16 slots produced by segmented mean-pooling and increases capacity to match MEMORILLA without learned queries or query conditioning.

Cosine top-16 with matched parameters. This method selects the 16 document embeddings with the highest cosine similarity to the question and uses them as the memory slots. Its slot processor matches the parameter budget of MEMORILLA.

Documents only. This Q-Former variant self-attends over its learned latent slots and then cross-attends to all document embeddings without access to the question.

Q-Former. This method self-attends over the learned latent slots and question embedding before the slots cross-attend to all document embeddings.

MEMORILLA. Our method first conditions the learned slots on the question embedding and then uses the conditioned slots to cross-attend to all document embeddings. It does not use self-attention.

Query-independent pooling is weakest and parameters do not fix it, since segmented pooling at matched budget reaches 31.10 on short-answer against 44.04. The Q-Former, which also conditions on the question, nearly matches MEMORILLA on PMv2 (43.34 against 44.04). On FactKG, MEMORILLA also outperforms the Q-Former (82.56 against 80.48), despite the Q-Former using 268,856,320 parameters. The documents-only variant reaches 78.72 on FactKG with 268,856,320 parameters. Replacing every document embedding with Gaussian noise changes the documents-only result by only +0.04 while lowering MEMORILLA by 5.93 and the Q-Former by 5.11. The gain therefore comes from conditioning the slots before they read rather than from either interaction on its own.

Memory Capacity at Training Time

Figure 9 compares models trained from scratch at K=16K=16 and K=128K=128 under otherwise identical settings. All runs use the Qwen3-4B-Instruct-2507 decoder and the same hyperparameters reported in Table 4, with KK as the only changed hyperparameter. Between K=16K=16 and K=128K=128, four of eight benchmarks move by less than a point at eight times the capacity and PMv2 and PV4 drop, so we set K=16K=16 throughout. All runs are trained from scratch, so this concerns capacity rather than the deployed checkpoint.

Bar chart comparing memory-token capacity for K=16 and K=128 across FactKG, TriviaQA, PMv2, LaMP-7, LaMP-4, NQA, PV4 and PubMedQA

Figure 9. Memory-token capacity. All models use a Qwen3-4B-Instruct-2507 decoder and are trained from scratch under identical settings, differing only in the number of memory tokens KK (K=16K=16 is the setting used throughout).

Memory Token Budgets for Inference

Figure 10 varies the number of memory tokens KK at inference time without retraining. Both personalization benchmarks gain most from the last slots. PMv2 stays near its closed-book level through K=4K=4 (26.58 against 25.64) and climbs to 44.60 at K=16K=16, while PV4 starts near its closed-book level (57.66 against 58.30), dips at K=2K=2 and 44, and climbs to 66.65. Neither shows saturation, which reflects slots dropped from a checkpoint trained at K=16K=16 rather than headroom above it, since

Memory token budget at inference across FactKG, TriviaQA, PMv2, LaMP-7, LaMP-4, NQA, PV4, and PubMedQA

Figure 10. Memory token budget at inference. Performance of MEMORILLA with a frozen Qwen3-8B decoder using the first KK memory tokens of the checkpoints trained with the full 16 tokens budget.

training at K=128K=128 does not help. FactKG, TriviaQA and NarrativeQA rise with every doubling. PubMedQA and LaMP-4 remain roughly flat at low KK and improve only from K=8K=8, and LaMP-7 only from K=16K=16. Across all three regimes, the required memory capacity tracks the degree of cross-document integration each task demands.

Frozen vs. LoRA Training

To separate the memory interface from generic adaptation, we train rank-130 LoRA adapters [19] on the Qwen3-4B-Instruct-2507 decoder with 268.4M parameters, comparable to the 194.1M parameters of the memory module paired with the 8B decoder. The adapters use the same training rows as MEMORILLA’s per-task fine-tuning and receive no documents in context. Figure 11 shows that MEMORILLA leads on every primary metric, although the PubMedQA and LaMP-7 gaps are within noise. Together with the noise test above, where MEMORILLA loses 5.93 on FactKG without real documents, this indicates that its gains rely on the stored evidence rather than on adaptation alone. Freezing both backbones keeps the store portable and the decoder untouched, at the cost of an encoder never optimized for compression.

Memory versus comparable-budget adaptation

Figure 11. Memory versus comparable-budget adaptation. MEMORILLA with an 8B decoder and 194.1M trainable parameters against a no-document rank-130 LoRA adapter with a 4B decoder and 268.4M trainable parameters.

Role of Encoder Size

Figure 12 swaps the frozen document encoder from Qwen3-Embedding-4B to Qwen3-Embedding-8B, keeping the Qwen3-8B decoder, memory module and recipe fixed and training from scratch. Every score moves by at most 1.3 except PubMedQA, where the +3.00 gain corresponds to three of 100 questions, so a larger encoder from the same family has minimal effects on performance.

Bar chart comparing Qwen3-Emb-4B and Qwen3-Emb-8B encoder scores across PMv2 Acc (SA), PV4 Acc (SA), PubMedQA Acc, and NQA ROUGE-L

Figure 12. Encoder size. The memory module is trained from scratch with a frozen Qwen3-8B decoder and either encoder; all other settings are fixed.

Computational Analysis of Memorilla

Consider a collection of NN documents serving QQ queries. MEMORILLA pays the encoder once on the write path, producing NN embeddings that persist and are reused by every later query. Dense retrieval builds the same index, so this cost is shared rather than added. The two methods differ on the read path. RAG places the selected text in the decoder, so its prefill grows with retrieval depth, while MEMORILLA runs one cross-attention read over the stored embeddings and always hands the decoder K=16K=16 tokens. Table 14 reports measurements on one H100-80GB at batch size 1 with a Qwen3-8B decoder. Growing the collection by 512×512\times decreases the memory-module forward time by 0.06 ms and MEMORILLA end-to-end latency by 1.9 ms, while full-context decoding grows by 19,184 ms and exceeds the enforced 32,768-token limit, requiring YaRN. Transfer stays under 0.04% of query latency because a 200 document collection is 1 MB, and the store is 7,266×\times smaller than the corresponding KV cache on PV4 (50,455 document tokens at 144 KiB per token for Qwen3-8B in bf16, 6.9 GiB, against 200 embeddings of 2,560 bf16 values). Absolute latency is dominated by decoding rather than by memory, so the benefit is not a faster single query but a serving cost that stays flat as collections grow and amortizes across the QQ queries that read them.

PathQuantityN=1N=1N=512N=512Growth
WriteDocument encoding22.92 ms2,588.84 mslinear in NN
WriteStorage per document5 KB5 KBflat
ReadMemory module forward2.01 ms1.96 ms−0.06 ms
ReadCPU to GPU transfer0.014 ms0.060 ms+0.046 ms
DecoderContext tokens1616flat
DecoderMEMORILLA end to end740 ms739 ms−1.9 ms
DecoderFull Context end to end749 ms19,932 ms+19,184 ms

Table 14. Serving cost as the collection grows. One NVIDIA H100-80GB, batch size 1, bf16, greedy, max_new_tokens=32, 250-token documents; median of 5 timings after 2 warmups. The write path is paid once per document and is shared with dense retrieval; read path and decoder cost are paid per query. Full Context at N=512N=512 is 128,064 context tokens, past the enforced 32,768-token limit, so it uses YaRN (factor 4). Timings use HF transformers generate without a paged KV cache, so Full Context latency depends on the serving stack.

Continual Learning with Memorilla: Additional Details

TextWorld games require an agent to maintain state across a partially observable trajectory, navigate a map, manipulate objects, and execute ordered action sequences. Observations are room descriptions and action outcomes, actions are short text commands, and games span up to 65 rooms. From the second turn on, MEMORILLA embeds each completed turn as one document, holding its observation truncated to 200 characters and its action (74 tokens on average), reads these documents with the current observation as the query, and places the resulting K=8K=8 memory vectors before the prompt. The 20 extreme, huge, long and mega test games instead embed one document per five completed turns with full observations, keep the last four documents, and use the mean document embedding as the query. Figure 13 shows a prompt and the documents compressed into the memory vectors, and § 6.1 reports how the trajectory grows across a rollout.

An example TextWorld prompt showing decoder input, embedded memory documents, and query and action

Figure 13. An example TextWorld prompt. A winning 12-turn rollout on a held-out medium game, at the choice of the turn-6 action; training prompts have the same format. The eight memory vectors sit before the system prompt and are recomputed every turn from one document per completed turn, with the current observation as the query, while the full trajectory stays in the prompt. Line breaks inside the documents are added for width.

We train on 800 prompts and evaluate on held-out validation and test splits of 40 games each (30 distinct, since the five medium and five hard games appear twice). Games come in six tiers (medium, hard, long, mega, huge, extreme) with 15–65 rooms and 6–74-step quests; the 800 training prompts are 202 medium, 558 hard and 10 from each longer tier. Rollouts sample up to 50 environment turns with at most 128 new tokens per turn, and evaluation samples three completions per held-out game at temperature 0.6 using the same SkyRL (Cao et al., [4]) generation harness for every condition. The random-memory baseline uses the MEMORILLA architecture with untrained weights, so it adds eight latents to the same prompt without having learned what to place in them. Table 15 lists the full configuration.

ComponentSettingValue
EnvironmentTask suiteTextWorld held-out games up to 65 rooms
EnvironmentSplits800 train prompts; 40-prompt validation and test splits (30 games each)
EnvironmentAgent stateInitial description plus prior observations/actions
EnvironmentRewardTextWorld game score; no shaping reward
Model interfaceDecoderFrozen Qwen3-4B-Instruct-2507
Model interfaceTrajectory encoderFrozen Qwen3-Embedding-4B
Model interfaceMemory budgetK=8K=8 latent vectors inserted into decoder prompt
Model interfaceMemory architecture8 heads; 1 self-attention layer; 2 cross-attention layers
Model interfaceContext paritySame input budget for every condition: 16,000 tokens in training, 4,096 in evaluation; full history kept for ICL
OptimizationTrainable parametersMemory module only; decoder and encoder frozen
OptimizationInitializationRandom (Xavier-uniform slots); output projection N(0,0.01)\mathcal{N}(0, 0.01); not loaded from the supervised checkpoint
OptimizationRL algorithmGRPO; group size G=16G=16; normalized group advantages
OptimizationPolicy objectivePPO clip 0.2; token-mean loss; no critic/KL/entropy
OptimizationOptimizerAdamW; learning rate 5×10−45 \times10^{-4}; no warmup
RolloutsTraining batch4 prompts/step; 16 sampled rollouts/prompt
RolloutsHorizonUp to 50 environment turns/rollout
RolloutsAction generationUp to 128 new tokens/turn with SkyRL
EvaluationSampling3 samples/held-out game at temperature 0.6
EvaluationMetricsavg@3 mean solve rate; pass@3 any-sample solve rate

Table 15. TextWorld RL configuration. The memory module is the only trainable component, and the full textual history is retained in every condition for a fair comparison.

Reinforcement-Learned Memory Objective

For agentic settings, we train the memory module from environment rewards while keeping the encoder and decoder frozen (Figure 7). At each TextWorld turn, the interaction trajectory is embedded as a document collection, fmemf_{\mathrm{mem}} maps it to memory vectors, and the frozen decoder samples the next action. We optimize only θmem\theta_{\mathrm{mem}} with Group Relative Policy Optimization (GRPO) [49], a critic-free variant of PPO [47]. For each prompt, a group of GG rollouts receives scalar rewards RiR_i from the environment, and advantages are standardized within the group:

Ai=Ri−mean⁡j∈G(Rj)std⁡j∈G(Rj)+ϵ.(8)A_i = \frac{R_i - \operatorname{mean}_{j \in G}(R_j)}{\operatorname{std}_{j \in G}(R_j) + \epsilon}. \tag*{(8)}

The memory policy is then updated with the clipped PPO surrogate over generated action tokens,

LRL(θmem)=−E[min⁡(riAi,clip⁡(ri,1−ϵc,1+ϵc)Ai)],ri=πθmem(ai∣τi)πθold(ai∣τi)(9)\mathcal{L}_{\mathrm{RL}}(\theta_{\mathrm{mem}}) = -\mathbb{E}\left[\min\left(r_i A_i,\operatorname{clip}(r_i,1-\epsilon_c,1+\epsilon_c)A_i\right)\right], \qquad r_i = \frac{\pi_{\theta_{\mathrm{mem}}}(a_i \mid\tau_i)}{\pi_{\theta_{\mathrm{old}}}(a_i \mid\tau_i)} \tag*{(9)}

The reward of each turn is the TextWorld game score after it, without shaping, and a rollout’s return RiR_i sums these over its turns. Most medium and hard games have a single one-point quest and end when it is solved, so they return 1 for a win and 0 otherwise; games in the four longer tiers (long, mega, huge and extreme) have one to three quests and also score as each is completed. The injection mechanism is unchanged from the supervised setting, while the memory module adds one self-attention layer over the trajectory documents before its cross-attention blocks. Memory here supplements the trajectory rather than replacing it, distinguishing it from the compression results in § 4. At turn tt, the decoder input follows Eq. (6) with the query replaced by the trajectory τ(t)\tau^{(t)}, which contains the game description and all prior observations and actions:

XLLM(t)=[m1(t),…,mK(t);Pτ(t)],(10)\mathbf{X}_{\mathrm{LLM}}^{(t)} = [\mathbf{m}_{1}^{(t)}, \ldots, \mathbf{m}_{K}^{(t)}; \mathbf{P}_{\tau^{(t)}}], \tag*{(10)}

where the memory tokens mk(t)\mathbf{m}_{k}^{(t)} are recomputed at every turn after the first from the completed turns of τ(t)\tau^{(t)}, with the current game observation as the query qq (the mean document embedding in the longer games).

References

  1. [1]Chenxin An, Jun Zhang, Ming Zhong, Lei Li, Shansan Gong, Yao Luo, Jingjing Xu, and Lingpeng Kong. Why does the effective context length of LLMs fall short? In The Thirteenth International Conference on Learning Representations, 2025. URL https://openreview.net/forum?id=eoln5WgrPx.arxiv.org/abs/2410.18745
  2. [2]Payal Bajaj, Daniel Campos, Nick Craswell, Li Deng, Jianfeng Gao, Xiaodong Liu, Rangan Majumder, Andrew McNamara, Bhaskar Mitra, Tri Nguyen, Mir Rosenberg, Xia Song, Alina Stoica, Saurabh Tiwary, and Tong Wang. Ms marco: A human generated machine reading comprehension dataset. 2016. doi: 10.48550/arXiv.1611.09268. URL https://arxiv.org/abs/1611.09268.
  3. [3]Ali Behrouz, Peilin Zhong, and Vahab Mirrokni. Titans: Learning to memorize at test time. In The Thirty-ninth Annual Conference on Neural Information Processing Systems, 2025. URL https://openreview.net/forum?id=8GjSf9Rh7Z.arxiv.org/abs/2501.00663
  4. [4]Shivi Cao, Sumanth Hegde, Dacheng Li, Tyler Griggs, Shu Liu, Eric Tang, Jiayi Pan, Xingyao Wang, Akshay Malik, Graham Neubig, Kourosh Hakhamaneshi, Richard Liaw, Philipp Moritz, Matei Zaharia, Joseph E. Gonzalez, and Ion Stoica. Skylr-v0: Train real-world long-horizon agents via reinforcement learning, 2025.
  5. [5]Yinpeng Chen, DeLesley Hutchins, Aren Jansen, Andrey Zhmoginov, David Racz, and Jesper Sparre Andersen. MELODI: Exploring memory compression for long contexts. In The Thirteenth International Conference on Learning Representations, 2025. URL https://openreview.net/forum?id=TvGPP8i18Ss.arxiv.org/abs/2410.03156
  6. [6]Yulong Chen, Yang Liu, Liang Chen, and Yue Zhang. Dialogsum: A real-life scenario dialogue summarization dataset. In Findings of the Association for Computational Linguistics: ACL-IJCNLP 2021, pp. 5062–5074. Association for Computational Linguistics, 2021. doi: 10.18653/v1/2021.findings-acl.449. URL https://aclanthology.org/2021.findings-acl.449.DOI
  7. [7]Xin Cheng, Xun Wang, Xingxing Zhang, Tao Ge, Si-Qing Chen, Furu Wei, Huishuai Zhang, and Dongyan Zhao. xrag: Extreme context compression for retrieval-augmented generation with one token. Advances in Neural Information Processing Systems, 37:109487–109516, 2024.arxiv.org/abs/2405.13792
  8. [8]Alexis Chevalier, Alexander Wettig, Anirudh Ajith, and Danqi Chen. Adapting language models to compress contexts. In Proceedings of the 2023 Conference on Empirical Methods in Natural Language Processing, pp. 3829–3846, 2023.arxiv.org/abs/2305.14788
  9. [9]Prateek Chhikara, Dev Khant, Saket Aryan, Taranjeet Singh, and Deshraj Yadav. Mem0: Building production-ready ai agents with scalable long-term memory. 2025. doi: 10.48550/arXiv.2504.19413. URL https://arxiv.org/abs/2504.19413.
  10. [10]Marc-Alexandre Côté, Ákos Kádár, Xingdi Yuan, Ben Kybartas, Tavian Barnes, Emery Fine, James Moore, Matthew Hausknecht, Layla El Asri, Mahmoud Adada, Wendy Tay, and Adam Trischler. Textworld: A learning environment for text-based games. In Computer Games Workshop at IJCAI, 2018. URL https://arxiv.org/abs/1806.11532.
  11. [11]Yufeng Du, Minyang Tian, Srikanth Ronanki, Subendhu Rongali, Sravan Bodapati, Aram Galstyan, Azton Wells, Roy Schwartz, Eliu A Huerta, and Hao Peng. Context length alone hurts llm performance despite perfect retrieval. arXiv preprint arXiv:2510.05381, 2025.arxiv.org/abs/2510.05381
  12. [12]Dheeru Dua, Yizhong Wang, Pradeep Dasigi, Gabriel Stanovsky, Sameer Singh, and Matt Gardner. Drop: A reading comprehension benchmark requiring discrete reasoning over paragraphs. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pp. 2368–2378. Association for Computational Linguistics, 2019. doi: 10.18653/v1/N19-1246. URL https://aclanthology.org/N19-1246.DOI
  13. [13]Sabri Eyuboglu, Ryan Saul Ehrlich, Simran Arora, Neel Guha, Dylan Zinsley, Emily Ruoyu Liu, Atri Rudra, James Zou, Azalia Mirhoseini, and Christopher Re. Cartridges: Lightweight and general-purpose long context representations via self-study. In The Fourteenth International Conference on Learning Representations, 2026. URL https://openreview.net/forum?id=Ok5w8O0SNg.arxiv.org/abs/2506.06266
  14. [14]Tao Ge, Hu Jing, Lei Wang, Xun Wang, Si-Qing Chen, and Furu Wei. In-context autoencoder for context compression in a large language model. In The Twelfth International Conference on Learning Representations, 2024. URL https://openreview.net/forum?id=uREj4zUGJE.arxiv.org/abs/2307.06945
  15. [15]Bogdan Gliwa, Iwona Mochol, Maciej Biesek, and Aleksander Wawer. Samsum corpus: A human-annotated dialogue dataset for abstractive summarization. In Proceedings of the 2nd Workshop on New Frontiers in Summarization, pp. 70–79. Association for Computational Linguistics, 2019. doi: 10.18653/v1/D19-5409. URL https://aclanthology.org/D19-5409.DOI
  16. [16]Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat, and Ming-Wei Chang. Realm: Retrieval-augmented language model pre-training. 2020. doi: 10.48550/arXiv.2002.08909. URL https://arxiv.org/abs/2002.08909.
  17. [17]Jie He, Richard He Bai, Sinead Williamson, Jeff Z Pan, Navdeep Jaitly, and Yizhe Zhang. Clara: Bridging retrieval and generation with continuous latent reasoning. arXiv preprint arXiv:2511.18659, 2025.arxiv.org/abs/2511.18659
  18. [18]Dan Hendrycks and Kevin Gimpel. Gaussian error linear units (gelus). arXiv preprint arXiv:1606.08415, 2016.
  19. [19]Edward J. Hu, Yelong Shen, Phillip Wallis, Zeyuan Allen-Zhu, Yuanzhi Li, Shean Wang, Lu Wang, and Weizhu Chen. Lora: Low-rank adaptation of large language models, 2021. URL https://arxiv.org/abs/2106.09685.
  20. [20]Yuyang Hu, Shichun Liu, Yanwei Yue, Guibin Zhang, Boyang Liu, Fangyi Zhu, Jiaheng Lin, Honglin Guo, Shihan Dou, Zhiheng Xi, et al. Memory in the age of ai agents. arXiv preprint arXiv:2512.13564, 2025.arxiv.org/abs/2512.13564
  21. [21]Bernd Huber, Ghazal Fazelnia, Andreas Damianou, Sebastian Peleato, Maksym Lefarov, Praveen Ravichandran, Marco De Nadai, Mounia Lalmas-Roelleke, and Paul Bennett. Embedding-to-prefix: Continual personalization with large language models. In AI That Keeps Up: NeurIPS 2025 Workshop on Continual and Compatible Foundation Model Updates, 2025.
  22. [22]Andrew Jaegle, Felix Gimeno, Andrew Brock, Andrew Zisserman, Oriol Vinyals, and Joao Carreira. Perceiver: General perception with iterative attention. 2021. doi: 10.48550/arXiv.2103.03206. URL https://arxiv.org/abs/2103.03206.
  23. [23]Pegah Jandaghi, XiangHai Sheng, Xinyi Bai, Jay Pujara, and Hakim Sidahmed. Faithful persona-based conversational dataset generation with large language models, 2023. URL https://arxiv.org/abs/2312.10007.
  24. [24]Bowen Jiang, Yuan Yuan, Maohao Shen, Zhuoqun Hao, Zhangchen Xu, Zichen Chen, Ziyi Liu, Anvesh Rao Vijjini, Jiashu He, Hanchao Yu, Radha Poovendran, Gregory Wornell, Lyle Ungar, Dan Roth, Sihao Chen, and Camillo Jose Taylor. PersonaM-v2: Towards personalized intelligence via learning implicit user personas and agentic memory. 2025. doi: 10.48550/arXiv.2512.06688. URL https://arxiv.org/abs/2512.06688.
  25. [25]Qiao Jin, Bhuwan Dhingra, Zhengping Liu, William W. Cohen, and Xinghua Lu. Pubmedqa: A dataset for biomedical research question answering, 2019. URL https://arxiv.org/abs/1909.06146.
  26. [26]Mandar Joshi, Eunsol Choi, Daniel S. Weld, and Luke Zettlemoyer. Triviaqa: A large scale distantly supervised challenge dataset for reading comprehension. 2017. doi: 10.48550/arXiv.1705.03551. URL https://arxiv.org/abs/1705.03551.
  27. [27]Jikun Kang, Wenqi Wu, Filippos Christianos, Alex J Chan, Fraser Greenlee, George Thomas, Marvin Purtoarb, and Andy Toulis. Lm2: Large memory models. arXiv preprint arXiv:2502.06049, 2025.arxiv.org/abs/2502.06049
  28. [28]Craig Kapfer, Kurt Stine, Balasubramanian Narasimhan, Christopher Mentzel, and Emmanuel Candès. Marlowe: Stanford's gpu-based computational instrument, 2025. URL https://doi.org/10.5281/zenodo.14751899.
  29. [29]Jiho Kim, Sungjin Park, Yeonsu Kwon, Yohan Jo, James Thorne, and Edward Choi. Factkg: Fact verification via reasoning on knowledge graphs, 2023. doi: 10.48550/arXiv.2305.06590. URL https://arxiv.org/abs/2305.06590.
  30. [30]Tomáš Kočiský, Jonathan Schwarz, Phil Blunsom, Chris Dyer, Karl Moritz Hermann, Gábor Melis, and Edward Grefenstette. The narrativeqa reading comprehension challenge. Transactions of the Association for Computational Linguistics, 6:317–328, 2018.arxiv.org/abs/1712.07040
  31. [31]Patrick Lewis, Ethan Perez, Aleksandra Piktus, Fabio Petroni, Vladimir Karpukhin, Naman Goyal, Heinrich Küttler, Mike Lewis, Wen-tau Yih, Tim Rocktäschel, Sebastian Riedel, and Douwe Kiela. Retrieval-augmented generation for knowledge-intensive nlp tasks. 2020. doi: 10.48550/arXiv.2005.11401. URL https://arxiv.org/abs/2005.11401.
  32. [32]Junnan Li, Dongxu Li, Silvio Savarese, and Steven Hoi. Blip-2: Bootstrapping language-image pre-training with frozen image encoders and large language models, 2023. URL https://arxiv.org/abs/2301.12597.
  33. [33]Zongqian Li, Yixuan Su, and Nigel Collier. 500xcompressor: Generalized prompt compression for large language models. In Proceedings of the 63rd Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), pp. 25081–25091, 2025.arxiv.org/abs/2408.03094
  34. [34]Nelson F Liu, Kevin Lin, John Hewitt, Ashwin Paranjape, Michele Bevilacqua, Fabio Petroni, and Percy Liang. Lost in the middle: How language models use long contexts. Transactions of the association for computational linguistics, 12:157–173, 2024.arxiv.org/abs/2307.03172
  35. [35]Maxime Louis, Hervé Déjean, and Stéphane Clinchant. Pisco: Pretty simple compression for retrieval-augmented generation. In Findings of the Association for Computational Linguistics: ACL 2025, pp. 15506–15521, 2025.
  36. [36]Jesse Mu, Xiang Li, and Noah Goodman. Learning to compress prompts with gist tokens. Advances in Neural Information Processing Systems, 36:19327–19352, 2023.arxiv.org/abs/2304.08467
  37. [37]Lin Ning, Luyang Liu, Jiaxing Wu, Neo Wu, Devora Berlowitz, Sushant Prakash, Bradley Green, Shawn O’Banion, and Jun Xie. User-llm: Efficient llm contextualization with user embeddings. In Companion Proceedings of the ACM on Web Conference 2025, pp. 1219–1223, 2025.arxiv.org/abs/2402.13598
  38. [38]Charles Packer, Sarah Wooders, Kevin Lin, Vivian Fang, Shishir G Patil, Ion Stoica, and Joseph E Gonzalez. Memgpt: Towards llms as operating systems. arXiv preprint arXiv:2310.08560, 2023.arxiv.org/abs/2310.08560
  39. [39]Zhuoshi Pan, Qianhui Wu, Huiqiang Jiang, Menglin Xia, Xufang Luo, Jue Zhang, Qingwei Lin, Victor Rühle, Yuqing Yang, Chin-Yew Lin, H. Vicky Zhao, Lili Qiu, and Dongmei Zhang. Llmlingua-2: Data distillation for efficient and faithful task-agnostic prompt compression, 2024. URL https://arxiv.org/abs/2403.12968.
  40. [40]Hongjin Qian, Zheng Liu, Peitian Zhang, Kelong Mao, Defu Lian, Zhicheng Dou, and Tiejun Huang. Memorag: Boosting long context processing with global memory-enhanced retrieval augmentation. In Proceedings of the ACM on Web Conference 2025, pp. 2366–2377, 2025.arxiv.org/abs/2409.05591
  41. [41]Pranav Rajpurkar, Robin Jia, and Percy Liang. Know what you don’t know: Unanswerable questions for squad. In Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics, pp. 784–789. Association for Computational Linguistics, 2018. doi: 10.18653/v1/P18-2124. URL https://aclanthology.org/P18-2124.DOI
  42. [42]Ori Ram, Yoav Levine, Itay Dalmedigos, Dor Muhlgay, Amnon Shashua, Kevin Leyton-Brown, and Yoav Shoham. In-context retrieval-augmented language models. Transactions of the Association for Computational Linguistics, 11:1316–1331, 2023.arxiv.org/abs/2302.00083
  43. [43]David Rau, Shuai Wang, Hervé Déjean, and Stéphane Clinchant. Context embeddings for efficient answer generation in rag. arXiv preprint arXiv:2407.09252, 2024.arxiv.org/abs/2407.09252
  44. [44]Siva Reddy, Danqi Chen, and Christopher D. Manning. Coqa: A conversational question answering challenge. Transactions of the Association for Computational Linguistics, 7:249–266, 2019. doi: 10.1162/tacl_a_00266. URL https://direct.mit.edu/tacl/article/43511.DOI
  45. [45]Anna Rogers, Olga Kovaleva, Matthew Downey, and Anna Rumshisky. Getting closer to ai complete question answering: A set of prerequisite real tasks. Proceedings of the AAAI Conference on Artificial Intelligence, 34(05):8722–8731, 2020. doi: 10.1609/aaai.v34i05.6398. URL https://ojs.aaai.org/index.php/AAAI/article/view/6398.DOI
  46. [46]Alireza Salemi, Sheshera Mysore, Michael Bendersky, and Hamed Zamani. Lamp: When large language models meet personalization. 2023. doi: 10.48550/arXiv.2304.11406. URL https://arxiv.org/abs/2304.11406.
  47. [47]John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, and Oleg Klimov. Proximal policy optimization algorithms. arXiv preprint arXiv:1707.06347, 2017. URL https://arxiv.org/abs/1707.06347.
  48. [49]Zhihong Shao, Peiyi Wang, Qihao Zhu, Runxin Xu, Junxiao Song, Xiao Bi, Haowei Zhang, Mingchuan Zhang, Y. K. Li, Y. Wu, and Daya Guo. Deepseekmath: Pushing the limits of mathematical reasoning in open language models. arXiv preprint arXiv:2402.03300, 2024. URL https://arxiv.org/abs/2402.03300.
  49. [50]Jianlin Su, Yu Lu, Shengfeng Pan, Ahmed Murtadha, Bo Wen, and Yunfeng Liu. Roformer: Enhanced transformer with rotary position embedding. 2021. doi: 10.48550/arXiv.2104.09864. URL https://arxiv.org/abs/2104.09864.
  50. [51]Weizhi Wang, Li Dong, Hao Cheng, Xiaodong Liu, Xifeng Yan, Jianfeng Gao, and Furu Wei. Augmenting language models with long-term memory. Advances in neural information processing systems, 36:74530–74543, 2023.arxiv.org/abs/2306.07174
  51. [52]Xiangfeng Wang, Zaiyi Chen, Tong Xu, Zheyong Xie, Yongyi He, and Enhong Chen. In-context former: Lightning-fast compressing context for large language model. In Findings of the Association for Computational Linguistics: EMNLP 2024, pp. 2445–2460, 2024a.arxiv.org/abs/2406.13618
  52. [53]Yu Wang, Yifan Gao, Xiusi Chen, Haoming Jiang, Shiyang Li, Jingfeng Yang, Qingyu Yin, Zheng Li, Xian Li, Bing Yin, et al. Memoryllm: Towards self-udaptable large language models. arXiv preprint arXiv:2402.04624, 2024b.arxiv.org/abs/2402.04624
  53. [54]Yu Wang, Dmitry Krotov, Yuanzhe Hu, Yifan Gao, Wangchunshu Zhou, Julian McAuley, Dan Gutfreund, Rogerio Ferris, and Zexue He. M+: Extending memoryLLM with scalable long-term memory. In Forty-second International Conference on Machine Learning, 2025. URL https://openreview.net/forum?id=OcqbkROe8J.arxiv.org/abs/2502.00592
  54. [55]Yaxiong Wu, Sheng Liang, Chen Zhang, Yichao Wang, Yongyue Zhang, Huifeng Guo, Ruiming Tang, and Yong Liu. From human memory to ai memory: A survey on memory mechanisms in the era of llms. arXiv preprint arXiv:2504.15965, 2025.arxiv.org/abs/2504.15965
  55. [56]Zijun Wu, Yongchang Hao, and Lili Mou. Tokmem: One-token procedural memory for large language models. In The Fourteenth International Conference on Learning Representations, 2026. URL https://openreview.net/forum?id=RWjE9P9PdiJ.arxiv.org/abs/2510.00444
  56. [57]Wujiang Xu, Zujie Liang, Kai Mei, Hang Gao, Juntao Tan, and Yongfeng Zhang. A-mem: Agentic memory for llm agents. arXiv preprint arXiv:2502.12110, 2025.arxiv.org/abs/2502.12110
  57. [58]Yoel Zeldes, Amir Zait, Ilia Labzovsky, Danny Karmon, and Efrat Farkash. Commer: a framework for compressing and merging user data for personalization. arXiv preprint arXiv:2501.03276, 2025.arxiv.org/abs/2501.03276
  58. [59]Peitian Zhang, Zheng Liu, Shitao Xiao, Ninglu Shao, Qiwei Ye, and Zhicheng Dou. Long context compression with activation beacon. In The Thirteenth International Conference on Learning Representations, 2025. URL https://openreview.net/forum?id=1eQT9Oz fNQ.arxiv.org/abs/2401.03462
  59. [60]Wanjun Zhong, Lianghong Guo, Qiqi Gao, He Ye, and Yanlin Wang. Memorybank: Enhancing large language models with long-term memory. In Proceedings of the AAAI conference on artificial intelligence, volume 38, pp. 19724–19731, 2024.arxiv.org/abs/2305.10250

Paper details

vlnc:W_zd9wuvnh
Version
v1 · latest
Published
Fresh — added to the Hub within the last 30 days
Added
License
CC BY 4.0
Usage

views · 1

downloads · 0

A view counts once per browser per day, a download each time the PDF is requested.

  • Computer Science

coding agents, GPT (multiple versions)

View statement
Looking for related papers…
Contents