betaFeedback

WorksComputer Science

Reasoning with Context Management and External Memory

Abstract

Reasoning models maintain information about the status of their reasoning process through in-context memory. Complex problems require larger context windows and memory requirements. In this scenario, context management without caching risks discarding useful information for reasoning. We propose RCMEM, an approach that extends context management with an external memory to maintain additional information without burdening the reasoning model with additional context. RCMEM significantly reduces computation time on problems that require repeated computation of intermediate steps, while achieving better performance on complex problems. We demonstrate our approach on a few mathematics problems using model sizes ranging from 0.4 to 25 million parameters, and GPT-2.

Introduction

Current work in reasoning models arose from Chain-of-Thought (CoT) style approaches [23] (Wei et al. 2022). By iteratively appending generated output to the context, a reasoning model can work through the steps to solve the problem. A limitation of this approach is that the required memory grows linearly with the computation. Longer context windows also come with attention limitations in terms of both efficiency [10] and accuracy [12]. More sophisticated approaches use an agentic paradigm where information is passed between different models and tools [11]. Even with agentic approaches, it still remains a challenge to determine how much information to retain in the contextual memory of any one model.

Context memory management has recently become a topic of interest for LLMs [19, 20, 14]. As an LLM reasons by adding additional information to the context window, it will eventually run out of memory. At that point information begins to be removed from the context based on age, that can cause important information, e.g., instructions, to no longer be available and lead to catastrophic failures in the reasoning process. Approaches to contextual memory management address the problem by proactively compress, summarize, and remove information in the context before memory issues arise.

A major limitation in contextual memory management alone is that the information disappears after summarization. This presents two key challenges. The first is in the case of a mistake or contradiction. If the model reaches a faulty conclusion, it is impossible to backtrack its reasoning process to discover and recover from the issue. The second case is related to repeated subproblems. In order to solve some complex problems, it is required to solve subproblems multiple times (e.g., the recursive solution to the Fibonacci sequence). The worst-case time complexity without caching those intermediate solutions could increase exponentially. To overcome these problems, recent works extend contextual memory management with external memory, providing theoretical proofs and applications to reinforcement learning.

We specifically address the challenge of repeated computation of subproblems by extending contextual memory management with an external memory to supervised training. Starting from the PENCIL proposed by Yang et al. [20] that applies reduction rules on the reasoning traces, we introduce special tokens that allow the model to read and write to an external memory. Our contributions are as follows: (1) We introduce RCMEM that integrates context management and external memory with reduction rules. (2) We show that the computation required for a model with external memory scales significantly slower for problems that require repeated computation. (3) We verify our model’s performance experimentally on several mathematical problems on supervised and fine-tuned models.

Related Work

Contextual memory management Standard CoT approaches Wei et al., 2022 manage contextual memory by appending to the context. Improvements to attention computation like Flash Attention Dao et al., [5], or approximations like Linformer Wang et al., [18] and Longformer Beltagy et al., [2] allow for longer contexts without significantly increasing computation per token. However, there are still issues with memory and model confusion Liu et al., [12]. Contextual memory management compresses the information in the context to prevent memory issues. Inftythink Yan et al., [19] uses instruction fine-tuning to adapt an LLM to iteratively summarize the existing context during the reasoning process. PENCIL Yang et al., [20] introduces special tokens and trains the LLM end-to-end to summarize intermediate reasoning steps. SUPO Lu et al., [14] also trains a model to summarize intermediate reasoning steps, but uses an reinforcement learning (RL) approach. The summarization is part of the objective function and does not require training data with contextual memory summaries.

External memory An alternative approach is to offload contextual memory externally. For instance, retrieval-augmented generation (RAG, Guu et al. [7]) gives the LLM access to information far beyond what can be stored in context, though selection of what to include in the context window is still a challenge Barnett et al., [1]. For reasoning models, there is the additional challenge of deciding what information to offload to external memory. Early work simply wrote information to an external scratchpad Nye et al., [17]. Since then, memory has been found to be critical to the performance of agentic systems Zhang et al., [24]. Recent approaches have added native memory lookup beyond contextual memory, such as fine-tuning an LLM to produce memory access commands Modarressi et al., [15, 16], replaced feed-forward layers with locality-sensitive hashing Zeng et al., [21]. Modern commercial LLMs have multiple layers of memory with agentic workflows to manage the flow of information Lei et al., [11]. Engram Cheng et al., [4] uses a modern n-gram lookup for phrase-level caching. MeKi Ding et al., [6] uses a static memory at the token level to inject knowledge into the hidden layers of the network.

Illustration of how memory access is introduced on top of reduction rule in RCMEM

Figure 1. Illustration of how memory access is introduced on top of reduction rule in RCMEM

LLM reasoning with context compression and external memory Recent attempts in combining context management with external memory has been made. Neural Paging Chen and Liu, [3] provides a formal definition of the external memory concept in LLMs and offered theoretical analysis of complexity. Multiple possible realizations are tested, for example, Unified Memory Agent (UMA, Zhang et al. [22]) uses a dual architecture of compact core summary plus a structured Memory Bank with CRUD (create, read, update, and delete) operations trained end-to-end with RL. Dep-Search Liu et al., [13] combines dependency-aware reasoning traces with persistent memory using GRPO (Group Relative Policy Optimization) training.

Proposed methodology

Our implementation is built on the reduction mechanism in PENCIL architecture, which offers a way to purge redundant information in the intermediate reasoning steps in CoT supervised training. This reduction mechanism complements the memory eviction in external memory by other reinforcement learning methods—clearing out expired reasoning traces that could lead to context burden in future computation. The combination of the two mechanisms, reduction of intermediate information in reasoning, and access to external memory, are the main originality of our approach.

Context management - PENCIL

The original PENCIL Yang et al., [20] approach introduces a reduction mechanism to the LLM autoregressive generation process, where intermediate thoughts are summarized recursively during inference. The reduction mechanism is achieved by adding three new tokens: [CALL], [SEP] and [RETURN] to the CoT process, which separate the CoT sequence into context (CC), thoughts (TT), and answer (AA). The process can be thought of as simulating a call stack, with the reduction rule illustrated as follows:

C [CALL] T [SEP] A [RETURN] ⇒C A(1)C\ [\mathrm{CALL}]\ T\ [\mathrm{SEP}]\ A\ [\mathrm{RETURN}]\ \Rightarrow C\ A \tag*{(1)}

Once a computation is completed (marked by [RETURN]), the reduction rule removes all intermediate reasoning steps TT (between [CALL] and [SEP]) and keeps only AA (between [SEP] and [RETURN]) as the remaining answer. This allows the model to reason recursively, and enables the LLM to perform more complex and longer reasoning with limited context length. It outperforms the standard CoT approach in complex reasoning problems like Einstein’s puzzles.

External memory - RCMEM

We extend this work by introducing an external memory with read and write access. In the remainder of the work we refer to the extension as RCMEM. Four additional tokens are introduced: [READ], [/READ], [WRITE], and [/WRITE]. The model is trained to generate the additional tokens just as the original PENCIL model. The reduction rule operates identically to the PENCIL model.

Given a memory mm with index ii and value vv, we read a value from the memory by calling an additional computation.

[CALL] [READ] m[i] [/READ][\mathrm{CALL}]\ [\mathrm{READ}]\ m[i]\ [/ \mathrm{READ}]
[SEP] v [RETURN](2)[\mathrm{SEP}]\ v\ [\mathrm{RETURN}] \tag*{(2)}

The value vv between [SEP] and [RETURN] is recalled with the value stored in memory, and is kept for future computation after reduction. We write a new value to the memory by calling:

[WRITE] m[i]=v [/WRITE](3)[\mathrm{WRITE}]\ m[i] = v\ [/ \mathrm{WRITE}] \tag*{(3)}

Whenever the [/READ] or [/WRITE] tokens are generated, our memory access operation is invoked and the context is modified accordingly. Both memory access operations exist within the intermediate reasoning steps TT, which are removed after the computation.

Computational improvements from external memory

The PENCIL model itself “can perform universal space-efficient computation for solving any task (Yang et al., [20]).” The introduction of an external memory does not fundamentally change the class of problems the model can solve. What it provides is a more efficient approach to compute solution when problems are structured in a manner where repeated computation is required.

More formally, assume we have a problem that requires a search through every vertex in a directed acyclic graph (DAG). If every vertex only has a single parent, then the PENCIL approach can perform the optimal search through the graph (which would be a tree). If, instead, the DAG is more general and each vertex can have multiple parents, then a vertex can be visited multiple times. As the PENCIL approach provides no history of computation, every path through the DAG will be visited. Our extension with an external memory gives the model the ability to save the solutions to sub-graphs within the DAG.

Define a DAG as G=(V,E)G = (V, E), where VV is the set of vertices and EE is the set of edges. Our model can evaluate GG in time polynomial in ∣V∣+∣E∣|V| + |E| with an external memory of size ∣V∣|V|. This is because every edge and every vertex must be visited once and the result of each visit to a vertex will be stored in memory. The original PENCIL approach requires exponential time with respect to the size of the critical path in GG in the worst case.

Connecting to the knapsack problem in our experiments in § 4, we can think of the solution as a DAG. Each vertex is an entry in the DP matrix that represents the solution for the first nn items with a total weight of ww. Each edge is any valid connection between those entries, i.e., what other vertices are required in order to know the solution to the given subproblem. The root node of the graph is the final solution using all NN items and the total weight WW.

Invalid memory access at inference

One constraint in the design of our memory access is that the read and write operations require a specific syntax. During inference, especially in early stages of training, it is possible for the model to generate output that is syntactically incorrect or to attempt to read from a memory location that does not exist. We handle those scenarios as follows. If the syntax is incorrect, then the memory access is skipped. If the model attempts to read from null content, we remove the read operation and allow the model to continue processing by generating the solution. For details of these design decisions, please refer to Appendix § 8.

Experiments

Problems Selection

To demonstrate the capabilities of our model, we explore three problems - the knapsack problem, longest common subsequence (LCS) and graph shortest path (GSP). We train the model to solve both knapsack and LCS using a recursive approach, while GSP is solved with dynamic programming (DP). Each time the answer to a subproblem is discovered, the result is saved to an external memory. When the solution to that subproblem is required, it is read from memory instead of being recomputed.

The pseudocode for generating the training traces are presented in Appendix § 11. Note that both LCS and GSP are more straightforward problems, where neighboring values are accessed in every iteration. The purpose is to understand the model’s behaviors without running exhaustive experiments. The main experimental focus will be on the knapsack problem where the complexity of the problem and constraints require the model to learn effective access to the memory under specific conditions.

Knapsack Problem: We consider specifically the 0-1 version with integer weights and capacity; This kind of problem requires solving repeated subproblems where RCMEM is designed to handle. We have a knapsack with a maximum capacity in terms of weight (WW). We also have a set of NN items, each with a value and a weight. The goal is to find the optimal set of items that fit within the knapsack and maximize the value. An exhaustive search is exponential in the number of items, with time complexity of O(2N)O(2^N). We train the models with N∈[4,5,..,10]N \in[4, 5, .., 10] items. For a sample with NN items, item weights and prices are randomly selected integers from [1,N][1, N], while the knapsack capacity WW is randomly chosen from [6,30][6, 30].

Longest Common Subsequence (LCS): This is a simpler problem, where given two equal length sequences randomly constructed of ‘A’, ‘C’, ‘G’, ‘T’, the goal is to find the length of their longest common subsequence. A subsequence is a string generated from the original string by removing zero or more characters without changing the relative order of the remaining characters. For simplicity, the length LL is the only variable in this experiment. Both sequence lengths must be the same. The time complexity of the recursive solution is O(22L)O(2^{2L}). We trained the model on length L=4,5,6,7L = 4, 5, 6, 7.

Graph Shortest Path (GSP): Additionally, to understand if RCMEM brings any benefit over PENCIL on dynamic programming (DP) solutions, we also experimented using the Floyd Warshall Algorithm in finding the shortest path in a graph. We compute the shortest paths between all pairs of vertices in a weighted graph. The graph is a 2D matrix of size V×VV \times V. The algorithm exhaustively looks for intermediate nodes within the vertices that return the smallest total weight. The time complexity is O(V3)O(V^3) with a space complexity of O(V2)O(V^2). We trained the model on graphs with a number of vertices V=4,5,6V = 4, 5, 6, and graph weights randomly initialized from [−1,6][-1, 6].

Training Data

For each problem instance, we generate a solution trace by applying the iterative process described in § 4.1. From these traces, we create training samples consisting of the problem definition, constraints, the CoT reasoning, and the full solution trace. For PENCIL, we formulate the reasoning process as solving a chain of equations recursively. The equation is stored as an intermediate thought, while the answer is kept after the computation. For example, in Knapsack:

[CALL] P(n,w)=v^ [SEP] v^ [RETURN](4)[\mathrm{CALL}]\ P(n,w)=\hat{v}\ [\mathrm{SEP}]\ \hat{v}\ [\mathrm{RETURN}] \tag*{(4)}

where n∈[1,N]n \in[1, N], w∈[0,W]w \in[0, W], and v^\hat{v} is the optimal value for the set (n,w)(n, w). For RCMEM, an additional read operation is inserted when an equation’s value is already available in memory, and a write operation is used when a calculated answer is ready to store. All other parts of the reasoning trace are identical to PENCIL. The pseudocode for generating the training traces are in Appendix § 11.

Analysis on the problem complexity

To evaluate the solution complexity between the original PENCIL approach and our proposed modification, we measured the number of tokens in each solution. Identical problem sets are generated for the PENCIL model, but with no external memory access. Some of the reasoning process is repeated for recursive solutions.

Knapsack: In theory the time complexity of recursion without memory access is O(2N)O(2^N), while having memory storage reduces the time complexity to O(NW)O(NW). Figure 4a shows the average number of tokens in the training set. We observed that for smaller problem sizes the number of tokens from RCMEM is slightly larger than PENCIL until reaching a problem size of 7 items. After 7 items, the problem size grows exponentially as the number of items increases. We also measure the number of [CALL], [READ] and [WRITE] tokens to evaluate the effect of memory access in solving the problem in Figure 4b. The number of [CALL] tokens measures the number of iterative CoT operations and the number of [READ], [WRITE] tokens measures the number of memory access operations. We observed that as the problem size grows larger, there is a significant reduction in CoT operations with increasing memory access in RCMEM. This shows that the inherent complexity of the problem solution grows significantly slower when using external memory for intermediate computation.

GSP training-set token and special-token counts

Figure 4. (a) Average number of tokens and (b) special tokens for GSP problem training sets. The number of tokens and iterations are much larger on RCMEM.

LCS training-set token and special-token counts

Figure 3. (a) Average number of tokens and (b) special tokens for LCS problem training sets. The number of tokens and iterations are much larger on PENCIL.

Longest Common Subsequence: Similar to knapsack, in theory the time complexity of the recursive approach is O(22L)O(2^{2L}), while having memory storage reduces the time complexity to O((2L)2)O((2L)^2). As the problem size grows larger, the number of tokens and iterations grows exponentially. In all problem sizes generated, the number of tokens and iterations of RCMEM is consistently at least an order of magnitude smaller than PENCIL.

Graph Shortest Path: Since the Floyd Warshall algorithm is a DP solution that reads the weights of the connecting vertices and calculates the updated weight of the target vertex, memory access does not simplify the reasoning process. Instead, RCMEM takes an extra two read operations (and iterations) to access the stored value, and one write operation to write into the memory. This tripled the number of iterations, and doubled the number of tokens for RCMEM compared to PENCIL. The only benefit of RCMEM over PENCIL is the ability to access values in the memory that are calculated earlier, instead of relying solely on the model’s reasoning process. It evaluates whether memory itself, without the advantage of bypassing recursive computation, can still bring a benefit to the reasoning process.

Model Training

As with PENCIL, we adopt the learning setting where models train until convergence with unconstrained data access. This mirrors the common scenarios in language model training where data can be effectively infinite [8]. The sequence is truncated to the maximal context window that fits the model if it exceeds the model’s capacity. All hyperparameter settings are the same in all experiments, with the learning rate of 1e-3 decaying to 1e-4 in 20k steps with adam optimizer. Depending on the problem and model size, the model runs on 1-2 A6000 GPUs. For each problem size, we generate 5 copies of the training, validation, and test set to train the models. The results are then averaged over the 5 runs. The model checkpoint that gives the highest accuracy on the validation set is used to score the test set. In addition to our proposed model, we also trained the PENCIL models with the same set of architectures. They are trained with PENCIL style data without access to the external memory.

Knapsack Problem

For the knapsack problem, we explore various model sizes and training setups. The models are trained from scratch, and validated and tested on 100 samples each. We trained the models on N=4N = 4 to 10, and experimented with various model sizes:

  • 0.4M parameters model: Transformer with 2 layers, 2 heads, embedding size of 128.

  • 3.17M parameters model: Transformer with 4 layers, 4 heads, embedding size of 256.

  • 25.2M parameters model: Transformer with 8 layers, 8 heads, embedding size of 512.

For each model, we experimented with context windows of 256 and 512 tokens. We also experimented fine-tuning a pretrained GPT-2 model (124M, 2048 context length) using nanoGPT [9] with knapsack RCMEM data, to understand if the proposed method is applicable to LLM fine-tuning.

On a side note, CoT—which PENCIL and RCMEM are built on top of—is excluded from the analysis because it was already shown that PENCIL outperforms CoT in long reasoning tasks [20], which applies to the Knapsack problem. We also conducted a small experiment on CoT to validate this assumption in Appendix § 9.

Longest Common Subsequence

For LCS, we only experiment on one model size. The model is trained from scratch and validated and tested on 100 samples each. We trained the model on sequences of L=6L = 6 to 9 with each configuration.

  • 0.4M parameters model: Transformer with 2 layers, 2 heads, embedding size of 128. Context length of 512.

Graph Shortest Path

The models are trained from scratch and validated and tested on 100 samples each. We trained the models on graph sizes of V=4V = 4 to 6, and experimented with two model sizes:

  • 3.17M parameters model: Transformer with 4 layers, 4 heads, embedding size of 256. Context length of 512.

  • 25.2M parameters model: Transformer with 8 layers, 8 heads, embedding size of 512. Context length of 1024.

Evaluation Metrics

For all tasks, we measure the accuracy, which measures if the predicted answer matches ground truth.

y=y^y = \hat{y}

with yy denoting the actual answer, and y^\hat{y} the predicted answer. We also measure the average sample generation time at inference to evaluate the efficiency of the models.

Analysis

We compared the performance of PENCIL and RCMEM with memory access on the Knapsack problem. The PENCIL approach uses the traditional recursive method to solve the Knapsack and the LCS problems, and the DP method on GSP. RCMEM creates an external memory that stores and updates the values. If the value is stored in memory, then the value is read from the memory instead of repeating the computation.

Knapsack Problem

Accuracy

Figure 5 shows the average accuracy of PENCIL and RCMEM on the knapsack problem. Considering all models, the performance of the small model (0.4M) drops steadily as the problem size increases, with a 40% degradation across problem sizes of 4 to 10. For larger models (3.17M and 25.2M) the performance drop is mild—with < 5% and < 10% degradation, respectively. RCMEM outperforms PENCIL as problem complexity increases, regardless of context length. For the 3.17M model, RCMEM’s advantage only becomes apparent with eight or more items, aligning with our complexity analysis in § 4.3. For the 25.2M model, RCMEM performance drops only marginally as complexity increases, whereas PENCIL shows a clear degradation. This suggests that larger models are better suited to learning additional memory access operations. Finally, the 0.4M model consistently maintains a 10-point lead from seven items onward with 512 context tokens. In resource-constrained environments (256 context tokens), RCMEM achieves double the accuracy of PENCIL at 10 items. Our results suggests that for simpler problems, RCMEM gains no advantage from external memory access. However, for more complex problems, the benefits of memory access outweigh the increased operational complexity.

Accuracy of PENCIL and RCMEM on Knapsack across 3 model sizes

Figure 5. Accuracy of PENCIL and RCMEM on Knapsack across 3 model sizes.

Sample generation time

Figure 6 shows the average sample generation time at inference for models with context lengths of 256 and 512. The average generation time increases exponentially for PENCIL, while RCMEM increases at a lower rate with problem size. PENCIL outperforms RCMEM for simpler problems (N<7N < 7). At N≥8N \ge8, the RCMEM generation time becomes much shorter (only half of PENCIL for 10 items). This aligns with our analysis in Figure 2 that the iterative process of RCMEM decreases exponentially compared to PENCIL after N=7N = 7, due to the benefit of external memory access. Fewer tokens means a faster response time of the model to an answer.

Knapsack training-set token and special-token counts

Figure 2. (a) Average number of tokens and (b) special tokens for the Knapsack problem training sets. Note the number of tokens and [CALL] (iterations) of PENCIL exceed RCMEM at N=7N = 7 and N=6N = 6 respectively.

Average generation time for a sample at inference, on 256 and 512 context lengths

Figure 6. Average generation time for a sample at inference, on 256 and 512 context lengths.

Fine-tune GPT-2 model

We compare the convergence rate of one set of the seed dataset on the four models: 0.4M, 3.17M, 25.2M and GPT-2. The first three models are trained from scratch with the same architecture defined in § 4.4.1, with 512 context length. The GPT-2 model is a pre-trained 1024M model with 2048 context length. The purpose of this experiment is to investigate the feasibility of applying RCMEM to fine-tune a pre-existing LLM that is trained on different data.

We compare the accuracy of the optimal models trained on 25k, 50k, 75k, and 100k training samples, presented in Figure 7. Results show that although it takes more time to converge to the performance that other supervised models in the first 25k samples, GPT-2 is able to converge faster and outperform other smaller models with fine-tuning.

Knapsack - Accuracy of 0.4M, 3.17M, 25.2M and GPT-2 on 25k, 50k, 75k and 100k training samples

Figure 7. Knapsack - Accuracy of 0.4M, 3.17M, 25.2M and GPT-2 on 25k, 50k, 75k and 100k training samples.

Accuracy and sample generation time of PENCIL and RCMEM on GSP tasks

Figure 9. Accuracy and sample generation time of PENCIL and RCMEM on GSP tasks.

For more complex problems (N=8N = 8), GPT-2 needs more training to outperform other models. This shows RCMEM is transferable to LLM and there is a benefit to fine-tuning from a pretrained LLM for faster convergence.

Longest Common Subsequence

Accuracy

Both PENCIL and RCMEM achieve 100% accuracy after training on sufficient data on the 0.4M model. This shows that this is a much easier problem than Knapsack. So we analyze the amount of data they need to converge to an optimal solution. We present the accuracy of the models trained on 25k, 50k, 75k and 100k samples in Figure 8. RCMEM coverages to 100% accuracy much earlier than PENCIL. When LL increases, PENCIL needs more training samples to reach 100% accuracy, while RCMEM can easily achieve and maintain such performance with only 25k or less training samples.

Accuracy and sample generation time of PENCIL and RCMEM on LCS tasks

Figure 8. Accuracy and sample generation time of PENCIL and RCMEM on LCS tasks. The accuracy are broken down to accuracy per batch of training samples to understand how fast the models are trained.

Sample generation time

The sample generation time for PENCIL grows exponentially when the problem size increases. The time ratio difference with RCMEM matches with the number of tokens and iterations discussed in Figure 4.

Graph Shortest Path

Accuracy

When the model size is small (3.17M with 256 context length), PENCIL consistently outperforms RCMEM. However, on a larger model (25.2M) with longer context length of 1024, RCMEM is able to outperform PENCIL on V=4V = 4, and has similar performance at V=6V = 6. We also notice the accuracy of the larger model is lower than that of a smaller model for V=4V = 4, but becomes better at V=6V = 6. This suggests that for a simpler problem, a large model might struggle from overfitting. In those scenarios, the ability to access the memory to correct a miscalculated answer from the model could help improve the performance. Also, even though the training data is more complex for RCMEM, it does not hurt the performance compared to PENCIL to use a smaller model when computation resource is limited.

Sample generation time

The sample generation time for RCMEM is consistently roughly three times of PENCIL, regardless of the model size. This matches the ratio of the number of iterations discussed in Figure 4.

Conclusion

We have introduced RCMEM, a model that extends the context management capabilities of PENCIL with an external memory for supervised training. Our experiments have demonstrated that the external memory provides the ability for the model to remember previous computations without resorting to storing all intermediate steps in context. On problems that can be represented as a directed acyclic graph, RCMEM requires a number of steps that is linear in the number of nodes and edges. A reasoning model that relies on context management alone can require reasoning steps that are exponential in the length of the critical path of the graph. Our experiments confirm that the time required grows slower for a model with external memory. The proposed methodology is transferable to a small LLM—GPT-2. Even on problems with dynamic programming solution, external memory can still benefit the reasoning process on large models.

Limitations

More work could be done to train the model to access external memory more effectively. In our experiments, we kept the setup comparable to PENCIL, with external-memory access as the sole computational difference with PENCIL. With the current design, it is difficult for the model to learn when to access memory just by learning the pattern through token predictions. Future work on training specialized agentic AIs or applying the reduction rule to reinforcement learning to master the underlying procedural logic of memory access is needed.

As with PENCIL, RCMEM requires training data explicitly annotated with special tokens for effective memory access and resource management. While it is easy for deterministic algorithms like the Knapsack problem, developing automatic formation of reasoning processes is important in order to scale for complex, open-ended reasoning tasks. Future work will expand its use to real-world applications where the reasoning steps are more complex—for example, resource allocation and logistics planning under computational constraints.

Design decision of handling invalid memory access

We experimented various design in handling invalid memory access during inference of the generated tokens, as listed:

  1. No memory access

    • This basically works as training the PENCIL model. For analysis purpose, the memory rate from PENCIL is inferred by extracting the intermediate solution at each trace stack on the generated text.

  1. No invalid memory handle

    • The read and write access are operated as it is. If invalid answer is read, the error propagates in the training.

  1. Handle read only

    • When the generated text tries to read from a non-existing memory, either if the weight exceeds the size of the memory, or the value of the item has not been written before (i.e. “P(item, weight) = -1”). We reduce the text to exclude the [SEP] and [RETURN] tokens associate to the read operation to force the model to regenerate a valid answer.

  1. Bypass invalid READ memory access

    • After the invalid memory access, the model stops trying to access the memory until reduction happens. The reason is to only access the memory again when the model might update the generated text and fix the issue after reduction.

  1. Handle both read and write, Bypass invalid memory access

    • In addition to (4), we implement the same handling to write operation. If the model tries to access from a non-existing memory, i.e. the weight exceeds the size of the memory. We reduce the text to exclude the [SEP] and [RETURN] tokens associate to the write operation. However, in theory it has less effect to the training process, due to the result of writing to the invalid memory is usually a chain effect of multiple wrong operations.

We ran the setup on 0.4M model with 512 contextual tokens on knapsack, because of the observable degradation with N=4N = 4 to 6 makes the experiments more manageable. We trained and tested the models for 5 times and took the average on the accuracy.

Besides accuracy, we also evaluate the performance of the models with trace rate and memory rate. With xx denotes the ground-truth reasoning trace, and x^\hat{x} the model generated reasoning trace, mm denotes the ground truth memory and m^\hat{m} the model induced memory. The metrics are calculated as follows:

  • Trace rate: Same metric used in [20], measures how the predicted tokens match with ground truth.

∑i=1min⁡{∣x∣,∣x^∣}(xi=x^i)max⁡{∣x∣,∣x^∣}\frac{\sum_{i=1}^{\min\{|x|,|\hat{x}|\}}(x_i=\hat{x}_i)}{\max\{|x|,|\hat{x}|\}}
  • Memory correct rate: Measures how the external memory, after read and write operations, matches with the ground truth. We only evaluate the memory that has been accessed.

∑n=1,w=1i≤N,j≤W(mn,w=m^n,w)NW\frac{\sum_{n=1,w=1}^{i\leq N,j\leq W}(m_{n,w}=\hat{m}_{n,w})}{NW}

The average accuracy, memory correct rate and trace rate are presented in Table 1. Actual memory correct rate is the accuracy of values in the memory actually access by the model. From the results, we observe the best accuracy and memory correct rate is obtained by just handling invalid read operations, with slight gain with early stopping on more items. Handling invalid write operations or not handling read operations hurt the performance in more complex problems.

# of ItemNo memoryMemoryFix READFix READ b.p.Fix R&W b.p.
Accuracy
40.8160.740.860.8240.832
50.7420.5460.7320.7580.702
60.5840.2840.680.70.55
Memory Correct Rate
40.7620.8910.9750.9760.967
50.5700.9010.9540.9580.842
60.4470.5090.9340.9430.862
Trace Rate
40.7810.7890.7520.7700.785
50.5760.6070.5640.5680.562
60.4440.4410.4300.4050.421

Table 1. Knapsack - Average accuracy and actual memory correct rate on 0.4M model with 512 content length, with different memory handle methods. R&W - READ and WRITE, b.p. - bypass invalid memory access

Performance on Chain-of-Thought

PENCIL significantly outperforming CoT has been discussed and proved on several reasoning tasks in [20]. We believe it outperforms CoT in knapsack problem as well due to the nature of the problem. As a sanity check we also trained a 3.17M with 512 and 256 content length on CoT and compare with PENCIL and RCMEM. The training data of PENCIL is used to make sure the only different of CoT to PENCIL is the introduction of reduction rule. Results presented in Table 2.

Model Size 3.17M
Context 512
# itemsCoTPENCILRCMEM
40.7760.9840.988
50.3540.9840.976
60.2220.9760.974
70.0860.9560.956
80.0560.9260.956
Context 256
# itemsCoTPENCILRCMEM
40.2120.9840.976
50.0480.9780.972
60.0280.9740.972
70.0080.9860.952
80.0010.9340.963

Table 2. Knapsack - Accuracy of 3.17M on CoT, PENCIL and RCMEM, with 512 and 256 context tokens.

Training PENCIL on RCMEM data

To verify the gain of the RCMEM is from the access to external memory, not primarily due to the shortened token size in the datasets, we trained the PENCIL model with the RCMEM datasets. We experiment on the 3.17M model with 512 contextual tokens, on knapsack with N=4N = 4 to 10. Since the PENCIL approach does not have access to external memory, the read and write operations are not invoked. Instead, the PENCIL model must predict the values that would have been read from memory. This is possible because the versions of the model trained on the RCMEM data are trained to make those predictions; they are just not used when the model has access to external memory. We independently performed training and inference 5 times and present the average accuracy and generation time for a sample, presented in Table 3. The results show consistent gain in RCMEM over PENCIL, with the accuracy gap increasing as more items are introduced. This further proves the gain to the model with memory access.

PENCILRCMEM
ItemsAccTimeTrace RateAccTimeTrace Rate
40.9841.1240.9320.9880.8960.938
50.9662.3030.8390.9761.3220.833
60.9382.2670.7340.9742.4380.670
70.8443.2960.5870.9562.9800.578
80.7944.2380.5500.9565.9860.462
90.6845.2990.4830.9439.6130.410
100.6385.8480.3980.9186.9720.337

Table 3. Knapsack - Accuracy, time (in seconds) and trace rate of PENCIL and RCMEM, trained on the same RCMEM data.

We also observe that the trace rate of the model with no memory access (the PENCIL method on the RCMEM datasets) is similar to other RCMEM variants, especially on small problems. The difference begins to increase on larger problems, where the example generation time of RCMEM also exceeds that of PENCIL. This is due to memory access operations in RCMEM that increases the computation time. This confirms that the drop in trace rate is not caused by memory access itself. A possible reason is that the introduction of READ and WRITE operations that increases the complexity of the learning process for the model.

PseudoCode of RCMEM Implementation of the problems

The pseudocodes of the RCMEM and PENCIL implementation of the 3 problems investigated in this work are presented in Table 4, 5, 6.

def knapsackRec(item, W, msg, RCMEM=True):
    if (W > 0 and still_has_item):
        msg += " [CALL] P(item, W) = "
        if mem[item][W] exist: # directly read from memory
            msg = msg + "[CALL] [READ] P(item, W) [/READ] "
            value = mem[item][W]
            msg = msg + ‘ ‘ [SEP] value [RETURN]"
            return value, msg
        else:
            msg = msg + " P( item , W}) = "
            max_value = 0
            if W < weight_of_item:
                msg = msg + "[CALL] "
                max_value, msg = knapsackRec(item_next, W, msg)
                # RCMEM only
                if RCMEM:
                    msg += f" [WRITE] P( item , W ) = max_value [/WRITE]"
                    mem[item][W] = max_value
                msg += " [SEP] max_value [RETURN]"
            else:
                msg += "Max( [CALL]"
                value, msg = knapsackRec(item, W, msg)
                msg += " [CALL] "
                value2, msg = knapsackRec(item, W−weight_of_item, msg)
                max_value = np.max((value, value2 + value_of_item))
                msg += "+value_of_item"
                #RCMEM only
                if RCMEM:
                    msg += " [WRITE] P( item , W ) = max_value [/WRITE]"
                    mem[item][W] = max_value
                msg += " [SEP] max_value [RETURN]"
        return max_value, msg

# Create problem set
item_names = N items
item_weights = random.choices([1..N], k=N)
item = {item_names, item_weights}
max_weight = random.randint(6, 30)

# Create memory table
mem = create_table(num_of_items, item_weights, max_weight)

# Start solving problem
msg = "[CALL] "
final_answer, final_msg = knapsackRec(item, max_weight, msg)

Table 4. Pseudocode of generating training traces for Knapsack problem

Detail accuracy and sample generation time for all models and context lengths

For the knapsack problem, we present the detailed mean and standard deviation accuracy of the PENCIL and RCMEM results in Table 7, and the average sample generation time and its standard deviation for all models at all context lengths in Table 8.

Model Size 25.2M
Context 512Context 256
PENCILRCMEMPENCILRCMEM
Nmeanstdmeanstdmeanstdmeanstd
40.960.000.980.000.960.000.960.00
50.940.000.990.010.970.000.980.00
60.960.010.980.000.950.010.970.00
70.910.000.980.000.920.000.980.00
80.890.010.960.000.890.010.980.00
90.750.020.970.000.840.020.970.01
100.740.010.970.000.660.010.960.01
Model Size 3.17M
Context 512Context 256
PENCILRCMEMPENCILRCMEM
Nmeanstdmeanstdmeanstdmeanstd
40.980.000.990.000.980.000.980.00
50.980.000.980.000.980.000.970.00
60.980.000.970.000.970.000.970.00
70.960.000.960.000.990.000.950.00
80.930.010.960.000.930.010.960.01
90.860.010.940.010.860.010.920.00
100.740.010.920.000.800.010.910.01
Model Size 0.4M
Context 512Context 256
PENCILRCMEMPENCILRCMEM
Nmeanstdmeanstdmeanstdmeanstd
40.890.010.860.010.890.010.840.01
50.730.020.730.010.790.010.750.01
60.700.020.680.020.660.010.660.01
70.460.050.580.040.570.070.580.01
80.390.030.570.020.460.030.500.01
90.310.060.410.020.340.040.360.02
100.280.020.380.020.190.040.400.03

Table 7. Average accuracy and standard deviation of PENCIL and RCMEM, on 3 model sizes and 2 context lengths.

Model Size 25.2M
Context 512Context 256
PENCILRCMEMPENCILRCMEM
Nmeanstdmeanstdmeanstdmeanstd
41.20.31.50.51.40.21.90.2
52.40.43.50.12.40.43.10.7
64.11.14.40.83.90.84.61.1
76.71.57.40.96.61.17.51.2
8122.682.213.208.31.9
915.93.78.4218.54.912.11.8
1024.62.410.21.126.78.412.55.1
Model Size 3.17M
Context 512Context 256
PENCILRCMEMPENCILRCMEM
Nmeanstdmeanstdmeanstdmeanstd
40.70.11.10.10.9010.2
51.30.31.40.31.50.11.40.2
62.20.42.80.32.70.23.10.2
740.63.50.84.60.34.40.2
87.90.65.11.16.71.460.4
97.80.35.14.18.91.96.81.1
1016.13.78.90.514.84.57.71.8
Model Size 0.4M
Context 512Context 256
PENCILRCMEMPENCILRCMEM
Nmeanstdmeanstdmeanstdmeanstd
40.501.92.60.50.10.50.1
50.90.11.20.10.90.20.90.3
61.60.132.22.70.31.80.1
72.50.43.30.330.43.32.4
83.90.94.62.63.638.72.1
95.825.12.35.21.86.40.9
107.91.56.52.68.31.85.92

Table 8. Average generation time and standard deviation (in seconds) for a sample at inference, on 3 model sizes and 2 context lengths.

def LCSRec(s1, s2, m, n, msg, RCMEM=True):
    if (m <=0) or (n <= 0):
        if mem[item][W] exist: # directly read from memory
            msg += "[CALL] P(m, n) [SEP] 0 [RETURN]"
            return value, msg
    msg = msg + " P(m, n) = "
    if s1[m−1] == s2[n−1]:
        msg += "P(m−1, n−1) + 1="
        # RCMEM only and value in memory
        if RCMEM and (mem[m−1][n−1] != −1):
            max_value = mem[m−1][n−1]
            msg += f"[CALL] [READ] P(m−1, n−1) [/READ]"
            msg += "[SEP] max_value [RETURN]"
        else:
            max_value, msg = LCSRec(s1, s2, m−1, n−1, msg)
            msg += "= max_value + 1"
            max_value += 1
        msg += "= max_value"
        #RCMEM only
        if RCMEM:
            msg += "[WRITE] P(m,n) = max_value [/WRITE]"
            mem[m][n] = max_value
            msg += "[SEP] max_value [RETURN]"
    else:
        msg += "Max("
        value1, msg = LCSRec(s1, s2, m, n−1, msg)
        msg += ", "
        value2, msg = LCSRec(s1, s2, m−1, n, msg)
        max_value = np.max(value1, value2)
        msg += ") = max_value "
        #RCMEM only
        if RCMEM:
            msg += "[WRITE] P(m,n) = max_value [/WRITE]"
            mem[m][n] = max_value
            msg += "[SEP] {max_value} [RETURN]"
    return max_value, msg

# Create problem set
alphabet = ['A', 'C', 'G', 'T']
s1 = "".join(random.choice(alphabet) for _ in range(L))
s2 = "".join(random.choice(alphabet) for _ in range(L))

# Create memory table
mem = create_table(L)

# Start solving problem
msg = "[CALL]"
final_answer, final_msg = LCSRec(item, W, msg)
final_msg += f"[SEP] Final LCS is {final_answer} [RETURN]"

Table 5. Pseudocode of generating training traces for Longest Common Subsequence problem

def FloydWarshall(graph, msg, RCMEM=True):
    V = len(graph)
    for k, i, j in zip(range(V), range(V), range(V)):
        if ((graph[i][j] == -1) and (graph[k][j] != -1 and graph[i][k] != -1)) \
        or ((graph[i][j] > (graph[i][k] + graph[k][j])) \
        and (graph[k][j] != -1 and graph[i][k] != -1)):
            msg += " [CALL] graph[i][j] = graph[i][k] + graph[k][j] = "
            if RCMEM:
                msg += f"[CALL] [READ] graph [{i}] [{k}] [/READ] "
                value = graph[i][k]
                msg += f"[SEP] value [RETURN] + "
                msg += f"[CALL] [READ] graph [{k}] [{j}] [/READ] "
                value = graph[k][j]
                msg += f"[SEP] value [RETURN] "
            graph[i][j] = graph[i][k] + graph[k][j]
            value = graph[i][j]
            if RCMEM:
                msg += " [WRITE] graph[i][j] = value [/WRITE] "
            msg += " [SEP] value [RETURN] \n"
    return graph, msg

# Create memory table
graph = np.random.randint(-1, 6, size=(V, V))
# Start solving problem
msg = "[CALL]"
final_answer, final_msg = FloydWarshall(graph, msg, RCMEM = True)

Table 6. Pseudocode of generating training traces for Graph Shortest Path problem

References

  1. [1]Scott Barnett, Stefanus Kurniawan, Srikanth Thudumu, Zach Brannelly, and Mohamed Abdelrazek. 2024. Seven failure points when engineering a retrieval augmented generation system. In Proceedings of the IEEE/ACM 3rd International Conference on AI Engineering-Software Engineering for AI, pages 194–199.arxiv.org/abs/2401.05856
  2. [2]Iz Beltagy, Matthew E Peters, and Arman Cohan. 2020. Longformer: The long-document transformer. arXiv preprint arXiv:2004.05150.arxiv.org/abs/2004.05150
  3. [3]Liang Chen and Qi Liu. 2026. Neural paging: Learning context management policies for turing-complete agents. arXiv preprint arXiv:2603.02228.arxiv.org/abs/2603.02228
  4. [4]Xin Cheng, Wangding Zeng, Damai Dai, Qinyu Chen, Bingxuan Wang, Zhenda Xie, Kezhao Huang, Xingkai Yu, Zhewen Hao, Yukun Li, and 1 others. 2026. Conditional memory via scalable lookup: A new axis of sparsity for large language models. arXiv preprint arXiv:2601.07372.arxiv.org/abs/2601.07372
  5. [5]Tri Dao, Dan Fu, Stefano Ermon, Atri Rudra, and Christopher Ré. 2022. Flashattention: Fast and memory-efficient exact attention with io-awareness. Advances in Neural Information Processing Systems, 35:16344–16359.arxiv.org/abs/2205.14135
  6. [6]Ning Ding, Fangcheng Liu, Kyungrae Kim, Linji Hao, Kyeng-Hun Lee, Hyeonmok Ko, and Yehui Tang. 2026. Meki: Memory-based expert knowledge injection for efficient llm scaling. arXiv preprint arXiv:2602.03359.arxiv.org/abs/2602.03359
  7. [7]Kelvin Guu, Kenton Lee, Zora Tung, Panupong Pasupat, and Mingwei Chang. 2020. Retrieval augmented language model pre-training. In International Conference on Machine Learning, pages 3929–3938. PMLR.
  8. [8]Jordan Hoffmann, Sebastian Borgeaud, Arthur Mensch, Elena Buchatskaya, Trevor Cai, Eliza Rutherford, Diego de Las Casas, Lisa Anne Hendricks, Johannes Welbl, Aidan Clark, and 1 others. 2022. Training compute-optimal large language models. arXiv preprint arXiv:2203.15556.arxiv.org/abs/2203.15556
  9. [9]Andrej Karpathy. 2022. nanoGPT: The simplest, fastest repository for training/finetuning medium-sized gpts.
  10. [10]Feyza Duman Keles, Pruthuvi Mahesakya Wijewardena, and Chinmay Hegde. 2023. On the computational complexity of self-attention. In International conference on algorithmic learning theory, pages 597–619. PMLR.arxiv.org/abs/2209.04881
  11. [11]Haodong Lei, Junming Liu, Yirong Chen, Ding Wang, and Hongsong Wang. 2026. Memcot: Test-time scaling through memory-driven chain-of-thought. arXiv preprint arXiv:2604.08216.arxiv.org/abs/2604.08216
  12. [12]Nelson F Liu, Kevin Lin, John Hewitt, Ashwin Paranjiape, Michele Bevilacqua, Fabio Petroni, and Percy Liang. 2023. Lost in the middle: How language models use long contexts, 2023. URL https://arxiv.org/abs/2307.03172, 2.
  13. [13]Yanming Liu, Xinyue Peng, Zixuan Yan, Yanxin Shen, Wenjie Xu, Yufeng Huang, Xinyi Wang, Jiannan Cao, Jianwei Yin, and Xuhong Zhang. 2026. Dep-search: Learning dependency-aware reasoning traces with persistent memory. arXiv preprint arXiv:2601.18771.arxiv.org/abs/2601.18771
  14. [14]Miao Lu, Weiwei Sun, Weihua Du, Zhan Ling, Xuesong Yao, Kang Liu, and Jiecao Chen. 2025. Scaling llm multi-turn rl with end-to-end summarization-based context management. arXiv preprint arXiv:2510.06727.arxiv.org/abs/2510.06727
  15. [15]Ali Modarressi, Ayyoob Imani, Mohsen Fayyaz, and Hinrich Schütze. 2023. Ret-llm: Towards a general read-write memory for large language models. arXiv preprint arXiv:2305.14322.arxiv.org/abs/2305.14322
  16. [16]Ali Modarressi, Abdullatif Köksal, Ayyoob Imani, Mohsen Fayyaz, and Hinrich Schütze. 2024. Memllm: Finetuning llms to use an explicit read-write memory. arXiv preprint arXiv:2404.11672.arxiv.org/abs/2404.11672
  17. [17]Maxwell Nye, Anders Johan Andreassen, Guy Gur-Ari, Henryk Michalewski, Jacob Austin, David Bieber, David Dohan, Aitor Lewkowycz, Maarten Bosma, David Luan, and 1 others. 2021. Show your work: Scratchpads for intermediate computation with language models.arxiv.org/abs/2112.00114
  18. [18]Sinong Wang, Belinda Z Li, Madian Khabsa, Han Fang, and Hao Ma. 2020. Linformer: Self-attention with linear complexity. arXiv preprint arXiv:2006.04768. Jason Wei, Xuezhi Wang, Dale Schuurmans, Maarten Bosma, Fei Xia, Ed Chi, Quoc V Le, Denny Zhou, and 1 others. 2022. Chain-of-thought prompting elicits reasoning in large language models. Advances in neural information processing systems, 35:24824–24837.
  19. [19]Yuchen Yan, Yongliang Shen, Yang Liu, Jin Jiang, Mengdi Zhang, Jian Shao, and Yueting Zhuang. 2025. Inftythink: Breaking the length limits of long-context reasoning in large language models. arXiv preprint arXiv:2503.06692.arxiv.org/abs/2503.06692
  20. [20]Chenxiao Yang, Nathan Srebro, David McAllester, and Zhiyuan Li. 2025. Pencil: Long thoughts with short memory. arXiv preprint arXiv:2503.14337.arxiv.org/abs/2503.14337
  21. [21]Zhanpeng Zeng, Michael Davies, Pranav Pulijala, Karthikeyan Sankaralingam, and Vikas Singh. 2023. Lookupffn: making transformers compute-lite for cpu inference. In International Conference on Machine Learning, pages 40707–40718. PMLR.arxiv.org/abs/2403.07221
  22. [22]Kehao Zhang, Shangtong Gui, Sheng Yang, Wei Chen, and Yang Feng. 2026. Learning to remember: End-to-end training of memory agents for long-context reasoning. arXiv preprint arXiv:2602.18493.arxiv.org/abs/2602.18493
  23. [23]Xuan Zhang, Chao Du, Tianyu Pang, Qian Liu, Wei Gao, and Min Lin. 2024. Chain of preference optimization: Improving chain-of-thought reasoning in llms. Advances in Neural Information Processing Systems, 37:333–356.arxiv.org/abs/2406.09136
  24. [24]Zeyu Zhang, Quanyu Dai, Xiaohe Bo, Chen Ma, Rui Li, Xu Chen, Jieming Zhu, Zhenhua Dong, and Ji-Rong Wen. 2025. A survey on the memory mechanism of large language model-based agents. ACM Transactions on Information Systems, 43(6):1–47.

Paper details

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

views · 4

downloads · 0

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

  • Computer Science

Not recorded for this paper

View statement
Looking for related papers…
Contents