MEM1 trains an agent to rewrite one short memory every turn. On a 16-question research task it peaks at 1,040 tokens of context, where a 14B model that keeps its history needs 3,840.
Learn how a language agent can reason and remember in the same breath, and how reinforcement learning teaches it which facts to keep.
Pick how many questions the agent must answer at once, then switch between peak context and right answers. Watch the two systems drift apart. Then we build, piece by piece, how MEM1 does it and how you could train one.
You need a feel for what a chatbot is (you type, it answers) and nothing else. We build the agent loop, the memory problem and the training from zero.
A reading for MIT MMAI, Lecture 13, Multimodal Interaction. Paper: Zijian Zhou, Ao Qu and colleagues, with Paul Pu Liang, “MEM1: Learning to Synergize Memory and Reasoning for Efficient Long-Horizon Agents” (arXiv 2506.15841, 2025). Course: MIT MMAI, Spring 2026. All credit for the method and its numbers belongs to the authors.
The numbers are the paper’s: peak tokens and exact-match (EM) counts for Qwen2.5-14B-Instruct and MEM1-QA, from Table 1 (2, 8 and 16 questions) and Table 3 (1 question, Wikipedia search). Peak tokens leave out the system prompt.
Chapter 0
See why an agent that keeps every turn in its prompt slows down, runs out of room and gets confused
Picture a research assistant that is a language model. You ask it, “What is the evidence for this drug?” It searches the web and reads the results. You ask, “Who published that study?” It searches again. You ask, “Is that source credible?” It searches a third time. Each answer depends on what it found before.
Now ask yourself where the assistant keeps all of that. A person would keep a few notes. A language model usually keeps everything: every thought, every search, every page of results, pasted one after another into the text it reads. After ten turns, that text is huge. This lesson is about one paper that asks whether the assistant could keep notes instead.
An agent is a language model wired into a loop. In each pass of the loop, called a turn, the model reads some text, writes a reply, and sometimes asks the outside world for something. Think of a student at a library desk: read your notes, decide what to look up, look it up, read the result, repeat.
The text the model reads in a turn is its context (also called the prompt). A query is a request the agent sends out, such as a web search. The observation is what comes back, such as ten search snippets. The paper calls it info. The agent repeats this loop until it can write a final answer.
Most agents use the simplest memory rule there is: full-context prompting. At every turn, add the new thought, query and observation to the end of the context. Nothing is ever removed. The paper shows this as the top row of its Figure 1: a line of context that only grows.
The authors name three problems with an ever-growing context. Each one is a real cost, so we take them one at a time.
Here is the first problem, made concrete. Drag the slider and compare how much text a full-history agent holds with how much a MEM1 agent holds.
The yellow line is an agent that keeps everything. The purple line is an agent that rewrites its memory each turn, as MEM1 does. Drag the number of turns.
Illustrative, not from the paper: a 120-token question, then per turn 150 tokens of thought, 20 tokens of query and 500 tokens of search results. MEM1 holds the question, one 150-token state, one query and one result. The paper’s measured numbers are in the hero and in Chapter 6.
Both lines start together, because the first turn has nothing to forget. Then they split. The full-history line climbs by 670 tokens per turn. The MEM1 line stays flat. That flat line is the whole promise of the paper: constant memory over any number of turns.
Two fixes already exist, and the paper says why neither is enough. The first is a long-context model, built to read a very long document. These models mostly target static inputs, such as one big file. An agent’s context is different: it grows turn by turn as the world answers back.
The second is an external memory module: a separate summarizer or a retrieval store that the agent consults. The paper’s complaint is that these modules are usually trained apart from the agent. The agent never learns to use the memory well, and the engineer must run and tune two systems.
Reinforcement-learning agents have a third habit. They learn to search, but they still let the prompt grow. Memory management is left out of what they learn.
The authors ask: can the model learn to write its own notes, as part of thinking? When you reason through a hard problem on paper, your scratch work does two jobs. It helps you think now, and it remembers what you found for later. Psychologists call that working memory: the small mental workspace for holding and using information right now.
MEM1 makes the model’s reasoning and its memory the same text. Each turn the model writes one short block called the internal state. That block is the thought and the memory at once. Then everything else from the earlier turn is thrown away. The model must put what matters into the state, or it will lose it.
How does the model learn what to keep? Not by a rule we write. It learns by trial and reward: if the final answer is right, the notes it kept were good. That is reinforcement learning, which we build in Chapter 4. First, Chapter 1 puts numbers on the cost, because the paper judges itself by three specific measures.
Chapter 1
Count the tokens, the memory and the work that a growing prompt adds, and meet the paper's three measures
You run a small web service. Each time a user’s agent takes a turn, your GPU reads the whole prompt, then writes a few hundred new tokens. On turn 2 the prompt is short. On turn 20 it is long. Your bill, your latency and your memory all follow the prompt. Before we fix the problem, we need to measure it the way the paper does.
The paper judges every method on accuracy and on three efficiency numbers. Each one answers a different question about cost.
Peak tokens and inference time are easy to picture. Dependency length needs a closer look, because it explains why a long prompt costs more than its length suggests.
A transformer writes one token at a time. To write token number j of its output, it looks back at every token before it: the whole prompt, plus the j − 1 tokens it has already written. So a long prompt is paid for again on every single new token.
Add that up over one turn. Let the prompt (the prefix) have np tokens, and let the model write no new tokens (the output). The paper, following an earlier work, sums this over all turns i:
A caution from checking by hand: counting the links by hand gives np no + no(no + 1)/2, which weights the prompt twice as heavily as the printed form. The paper prints the form above (its Appendix A.4.1), and the authors do not discuss the difference. We use the printed form. Either way the lesson is the same: the prompt length np is the term that grows.
Take the toy numbers from the device below (illustrative, not the paper’s). The question is 120 tokens. Each turn the model writes no = 170 tokens (a 150-token thought and a 20-token query), and the world returns 500 tokens of results. Run three turns.
After three turns the gap is small: 1.25 times. The full-history prefix keeps climbing, though, while the MEM1 prefix stays at 790. Drag the slider to watch the gap open.
Each pair of bars is one turn’s cost from the formula. Yellow keeps every old turn in its prefix. Purple keeps one state. Drag the turns, then change how much the world returns.
Illustrative, not from the paper: a 120-token question, 170 tokens written per turn, and the result size you set (tokens returned by the world per turn). The formula is the paper’s printed Dependency formula (Appendix A.4.1). For the real measured values, see Table 1.
Try 16 turns at 500 tokens: the totals come to 7,459,600 for full history and 1,479,850 for MEM1, a gap of about 5 times. Raise the result size and the gap grows, because the pile holds all of it and MEM1 holds only the latest.
The symptom is familiar to anyone who has watched a long agent run: it gets slower and more confused near the end. The measurement is the three numbers above, which the paper reports for every method. The fix is to stop the prefix from growing. The paper’s later tables show the effect: at 16 questions, MEM1 uses 27.1% of the peak tokens and 29.3% of the inference time of Qwen2.5-14B-Instruct.
One honest caution. Peak tokens count one sequence, so they measure the shape of the prompt at its largest, not the total work. That is why the paper also reports dependency length and time. Always read all three together.
Chapter 2
Follow the loop in which the agent thinks, searches, then rewrites everything it knows into one short state
Think of a detective with a single index card. On the desk are the case question and a stack of fresh clues. Each time she reads a new clue, she writes a new card that holds everything she needs, tears up the old card and the clue, and picks the next lead. She never carries a pile of paper. If the card is good, she solves the case.
That is MEM1’s loop. The card is the internal state. This chapter shows what is on the card, what the model reads and writes in each turn, and why the size of its context stops growing.
The paper marks each piece of the loop with an XML-style tag, a label wrapped around text, like <IS> … </IS>. There are four.
One detail to know before you read the code or the appendix. The paper’s figures name the tags <IS>, <query> and <info>. The prompts in Appendix A.3 ask the model to write its summary inside <think> … </think>, its request inside <search> … </search>, and they return results in <information> … </information>. These are the same roles under different names. The internal state is the think block.
Number the turns t = 1, 2, 3 and so on. In turn t, the paper says (Section 3.1):
Write step 4 as a rule. Let x be the original question (it always stays), and let πθ be the model with its weights θ. Then:
The paper states this in words, not as a formula. The line above is my compact way to write what Section 3.1 says. Notice what is missing inside the brackets: no ISt−1, no infot−1. The model cannot look at them.
Here is the loop on a toy task, with two linked questions at once. The names are invented for the toy. Step through it and watch the context.
Each press of Next turn shows what the model reads, then what it writes. Crossed-out blocks are gone from the context. Watch how little it reads at turn 4.
Toy task, invented for this lesson (the company, bridge and people are made up). Token counts are estimated as characters divided by 4. The tags use the paper’s Figure 1 names.
The paper says that at any moment the context holds at most two states, two queries and one info block. The reason is the order inside a turn. While the model writes ISt+1 and queryt+1, the old ISt, queryt and infot are still on the desk. Once it finishes, they are cleared.
So the length of the context at any turn has a ceiling. Let |x| be the length of the question, and LIS, Lq, Linfo the lengths of one state, one query and one result. Then:
|context| ≤ |x| + 2 LIS + 2 Lq + Linfo
There is no t on the right. The ceiling does not depend on the turn number. With my toy numbers (question 40, state 50, query 6, info 25 tokens), the ceiling is 40 + 100 + 12 + 25 = 177 tokens, at turn 10 or turn 1,000. The paper reports the measured effect as a near-flat line: peak tokens of 640, 801 and 1,040 at 2, 8 and 16 questions.
The line is not perfectly flat. The authors say “almost constant” with “a slight increase”. A harder task needs a longer state, because it has more to remember. The ceiling holds the count of blocks fixed, not their lengths.
Why does a model write a good state at all? Because nothing else carries information forward. If the answer to question A sits only in an old info block, and that block is pruned, the model can use it only if it copied the fact into its state. Reward comes from a right final answer. So the habit of copying what matters is what reinforcement learning rewards.
The paper compares this to human skill. People who train their memory with puzzles such as Sudoku learn to pick out what matters and build on it. It makes the same bet for models.
The symptom: a state that forgets something needed. The agent searches for a fact it already found, or answers with a hole. The measurement is accuracy on tasks with many questions, where one dropped fact ruins an answer. The fix is not a rule about which words to keep. It is training: Chapters 4 to 6 show the reward, the masks and the results.
Chapter 3
Read the paper's algorithm as data flow: what goes into the model, what comes out and what the code does with it
Imagine a referee who runs the agent. The referee hands the model its prompt, lets it write until it says “I am done with this step”, then reads what it wrote. If it asked for a search, the referee runs the search, throws away the old pages, and starts the next step. If it wrote an answer, the game ends. If it wrote nonsense, the referee marks the game invalid.
That referee is the rollout: one full run of the agent from the question to the end, used to collect training data. The paper gives it as Algorithm 1 (Appendix A.5). This chapter reads it line by line, with the data that flows through each line.
Algorithm 1 takes four things. The task prompt x holds the instructions and the questions. The policy πθ is the language model. The world model W is whatever answers a query: the paper uses a local Wikipedia index for training, and a web search API for online tests. The last input is the maximum number of turns T.
The prompt matters, so read what it says (Appendix A.3, Prompt 1). It tells the model to do two things each step. First, think, and update a cumulative, concise summary inside the think tags, which “acts as persistent memory and must include all essential information from previous think and information tags”. Second, pick one action: a single search for one question, or, when every question is done, the final answers separated by semicolons. That is how the instruction “your reasoning is your memory” reaches the model: in plain words, in the prompt.
y ← yt with the comment “all previous context removed”. This one line is the whole memory mechanism.Compare line 14 with a normal agent, which would read y ← y + yt. One plus sign is the difference between a pile and a card.
Once old turns are gone, the agent cannot count how long it has been running. It has no way to tell turn 2 from turn 12. So the rollout adds a reminder at the start of each info block: [HINT: YOU HAVE {turns_left} TURNS LEFT]. The paper calls this meta info injection. The turn limit is 6 for tasks of 1 to 4 questions, and 20 for harder ones, to avoid very long runs.
After the model stops, the rollout checks what it wrote. There are three cases (lines 15 to 24).
The device lets you play the referee. Pick a reply and a turn, and see what the rollout does with it.
Choose what the model wrote, and the turn it wrote it on (the limit is T = 6). The panel shows the rule the rollout applies, then what the model reads next.
Rules from Algorithm 1 (Appendix A.5) and the exact-match rules (Appendix A.4.1). The search result and the model’s words are invented for this toy. The “wrong count” reply gives one answer to a two-question task; the rollout accepts it, and the scorer then gives 0.
The fourth button shows a subtle point. The rollout only checks the tags. Whether the answers are right, and whether there are enough of them, is checked later by the scorer (Chapter 5). A reply with one answer to a two-question task passes the referee and then scores zero.
Here is the algorithm as short Python, so you can see how small it is. It is my paraphrase of Algorithm 1, not the authors’ code (theirs is at the repository linked in the credits).
pythondef rollout(policy, env, x, T): y = "" # the block the model sees after the prompt x for t in range(T): y_t = policy.generate(x + y, stop=["</query>", "</answer>", "<eos>"]) y = y_t # all previous context removed (line 14) if "<query>" in y_t: q = parse(y_t, "<query>", "</query>") d = env.search(q) # Wikipedia top 3, or web top 10 hint = f"[HINT: YOU HAVE {T - t} TURNS LEFT]" y = y + f"<info>{hint}{d}</info>" elif "<answer>" in y_t: return x + y_t # finished else: return None # invalid sample return x + y # ran out of turns, no answer
The last line is my reading of the pseudo-code: if the loop ends after T turns without an answer, the run has no answer to score. The paper adds a guard on the last turn, with the comment “prevent the agent from searching further”. It does not describe what happens next, so treat the exact last-turn behaviour as the authors’ code’s business, not ours.
The symptom in early training is that most turns are invalid: the agent breaks the tag format. Appendix C measures it: the ratio of valid actions starts near 0.55. The fix is not a hand-made penalty. The paper found that adding one hurts (Chapter 8). Training itself teaches the format, because an invalid run gets no reward.
Chapter 4
Fix the broken trajectory with two masks so that reinforcement learning can score each token fairly
Imagine a teacher who grades a student’s workbook. The student wrote each page using only the notes on the page before. But the teacher reads the whole workbook at once, and judges every line as if the student had seen all earlier pages. The teacher will credit or blame the student for choices made under the wrong conditions.
That is MEM1’s training problem. During the rollout, each token was written while the model saw a short, rewritten context. If the learner later replays the run with the whole history in view, its numbers no longer match what really happened. This chapter shows how the paper fixes that with two masks.
Reinforcement learning (RL) teaches by trying. The model plays out a whole run, a trajectory, and gets a score at the end: the reward. In MEM1 the reward is 1 point for each right answer. The model then changes its weights so that runs with high rewards become more likely.
To blame or credit single tokens, RL uses an advantage: how much better a token’s outcome was than expected. A second network, the critic, learns to guess the expected reward from any point in the run. The advantage is the real reward minus the critic’s guess, spread back over the tokens.
The paper uses PPO (proximal policy optimization), an RL method that makes only small, safe updates. Its key number is the probability ratio: the new model’s probability of a token divided by the old model’s probability of the same token in the same situation. If the ratio is far from 1, PPO clips it, so no single update jumps too far. The paper chose PPO because it computes token-level advantages, which it says brings stability. A KL penalty keeps the model close to its start. Details of PPO itself are in the sources linked in Chapter 9.
PPO assumes a trajectory is one straight line: token k was written after tokens 1 to k − 1. MEM1 breaks this. When it wrote a token in turn 3, it did not see turn 1. Its context had been cut. Replaying the run as one long sequence would change what the model sees, and so change the very probabilities that the ratio compares. The paper says this disrupts the continuity of the token generation trajectory and complicates the estimation of token-wise advantages.
First, the paper stitches the turns into one long sequence: the question, then (IS1, query1, info1), then (IS2, query2, info2), and so on, ending in (IST, answerT). Now there is one sequence, as PPO expects.
Second, it applies a two-dimensional attention mask. In an ordinary transformer, a token may attend to all earlier tokens: a lower triangle of allowed pairs. Here, token k may attend only to the tokens that were in the context when it was written. The paper’s Figure 3 gives the rule: for ISt+2, only the question, ISt+1, queryt+1 and infot+1 are not masked, plus the tokens of the turn being written.
Now the forward pass reproduces the view the model had during the rollout. The ratio compares like with like. The advantage, the KL penalty and the critic’s value all use the same masked view.
The info blocks come from the search engine, not the model. Training the model to predict a Wikipedia passage would be wrong. So, following the earlier Search-R1 work, the paper adds a one-dimensional information mask over the info tokens during the policy update, for both the actor and the critic. Gradients flow only through tokens that the agent itself wrote.
In symbols (standard PPO, which the paper does not spell out, with the paper’s masked state sk and token ak):
Take a three-turn run with toy sizes (illustrative): question 40 tokens; each state 50 tokens (the last one 40); each query 6; each info 25; the answer 5. Stitched, the sequence has 40 + 2 × (50 + 6 + 25) + 40 + 5 = 247 tokens.
Use the device to move the generating token’s block and flip the mask.
Rows are the blocks being written. Columns are the blocks they may look at. Choose the mask, then slide the row. Crosses are blocks a plain mask would show but MEM1 hides.
Toy block sizes (illustrative): Q 40, IS 50 or 40, query 6, info 25, answer 5 tokens. Which blocks are visible follows the paper’s Figure 3 (bottom right). The row for each info block carries no loss: that is the 1D information mask.
Appendix A.7 notes that the mask does not perfectly recreate the original attention. Position ids, the numbers that tell the model where each token sits, change when old turns vanish. Each state would need two position ids, one as the end of one turn and one as the start of the next. Duplicating every state would make training sequences much longer and slower. The authors skip it and give each state the ids of the earlier turn. They say this acts like adding blank spaces and has no significant impact on the results.
Training setup, for reproduction: started from Qwen2.5-7B Base; veRL framework; 4 H100 or H200 GPUs; batch and mini-batch 64; learning rate 10−6 for the actor and 10−5 for the critic with 50 warmup steps; temperature 1 while training.
Chapter 5
Glue ordinary questions together to build tasks that need many turns, and score them with a plain exact-match reward
Think of an exam. One version has a single question that takes two lookups to answer. Another version glues eight such questions into one paper and gives you a single sheet of notes. The second exam does not need harder questions. It needs more of them at once, and your notes must keep the early answers while you chase the later ones. That is how the paper turns short questions into a long task.
To train an agent that keeps constant memory, you need tasks where memory matters. Public benchmarks do not offer many. HotpotQA, Bamboogle and 2Wiki are called multi-hop: you need to chain facts, such as finding a person and then that person’s birthplace. But the paper notes they typically involve only two information-seeking steps. A full-history agent handles two steps fine. There is nothing to forget.
The authors build a multi-objective QA task. They take N questions from an ordinary dataset and interleave them into one composite query that asks for all N answers. The prompt (Appendix A.3, Prompt 1) tells the agent to search one question at a time, keep a cumulative summary in its state, and, when every question is answered, give the answers separated by semicolons.
Training uses a 2-objective version, built from a mix of HotpotQA and Natural Questions, following the data of Search-R1. Testing goes up to 16 objectives. That gap is the point. The agent is trained on short horizons and tested on horizons eight times longer, and the paper reports that it generalizes.
Why does composing force memory? Because the context is cut every turn. Say the answer to question 1 is found at turn 2. By turn 7, the info block that held it is long gone. The only way to answer question 1 at the end is for every state in between to have carried the fact forward. The task makes forgetting costly.
RL needs a score that a program can compute without a human. This is called a verifiable reward. For QA, the paper uses exact match (EM): the answer inside the answer tags must equal the true answer. The rules (Appendix A.4.1) are short:
The last rule is deliberate. The authors say manual interventions “can interfere with the agent’s learning process”. Chapter 8 shows the experiment behind that claim.
The paper also reports an F1 score for partial credit. F1 compares the words in the guess with the words in the truth. Let c be the number of shared words, l the length of the guess and g the length of the truth. Then precision p = c / l, recall r = c / g, and F1 = 2pr / (p + r). Take the paper’s own example truth, “United States of America” (g = 4), and the guess “United States” (l = 2). Shared words: c = 2. So p = 2/2 = 1, r = 2/4 = 0.5, F1 = 2 × 0.5 / 1.5 = 0.667. EM would give this guess 0. For many questions, the final F1 is the sum over sub-questions.
Try the scorer yourself.
Set how many questions the task asks, how many answers the agent gives, and how many of those are right. Squares are answer slots: green is a point, empty is a miss, a red cross means the count is wrong.
Rules from Appendix A.4.1. The turn limit is the paper’s: 6 for tasks of 1 to 4 questions, 20 for harder ones (Section 4.1). The slider values are illustrative.
Slide “answers given” one below “questions asked” and watch the score fall to zero even when every answer is right. That is harsh, but it is a clean rule a program can check, and it pushes the agent to finish every question.
The symptom of training on single questions is an agent that never learns to carry state: it has no pressure to. The measurement is accuracy as the number of questions grows. The fix is the composed task, which makes carrying state the only route to reward. The paper does not claim composed questions are realistic. It claims they are a scalable way to create long-horizon pressure from existing data.
Chapter 6
Read Table 1 and Figure 4 and see where MEM1 loses, where it ties and where it wins by a wide margin
Picture a race with three courses: a short one of 2 laps, a medium one of 8 and a long one of 16. Seven cars enter. Each car has a speed (how many answers it gets right), a fuel gauge (its peak tokens) and a stopwatch (its inference time). Some cars stall on the long course. This chapter reads the paper’s Table 1 and Figure 4 as that race.
A fair race needs clear entrants. The paper compares MEM1 against six, and each one isolates a different idea.
| Entrant | What it is | What it tests |
|---|---|---|
| Qwen2.5-14B-Instruct | A bigger chat model, with full history | Does size beat memory management? |
| Qwen2.5-7B-Instruct | Same size as MEM1, full history | The plain baseline |
| 7B-Instruct (truncate) | The 7B chat model, run with MEM1’s prompt and rollout | Is the prompt and rollout alone enough, with no RL? |
| 7B-Instruct (A-MEM) | The same, plus A-MEM, an external vector-store memory | Does a separate memory module help? |
| Search-R1 | An RL-trained search agent, trained on 1 question with EM | RL without memory training |
| DeepResearcher | An RL-trained web research agent, trained on 1 question with F1 | The same idea, online search |
| MEM1-QA | Qwen2.5-7B Base trained with the MEM1 recipe on 2 questions | The paper’s method |
Notice the two “truncate” and “A-MEM” rows. They answer an obvious objection: “maybe the trick is only the prompt, or only external memory.” Both use the same prompt and the same cut-off rollout as MEM1, but no RL training of the memory.
The device holds all of Table 1. Choose a course and a measure. Watch where each car lands, and note the ones outlined in red: the paper marks them as collapsed, meaning their performance fell to near zero.
All values are the paper’s Table 1: exact-match count (higher is better), peak tokens (the table’s ×102 column times 100, lower is better) and inference time in seconds (lower is better). Red outlines mark the table’s collapsed entries.
Now the headline arithmetic, with every step. On 16 questions: 1.97 / 0.567 = 3.47, which the abstract rounds to 3.5 times better. Peak tokens: 3,840 / 1,040 = 3.69, rounded to 3.7 times less memory. Time: 8.70 s / 29.7 s = 0.293, the 29.3% the paper quotes. Peak: 1,040 / 3,840 = 0.271, the 27.1%.
Two more details help you read the table without tripping. First, the EM and F1 columns are sums over sub-questions, not shares. A score of 1.97 does not mean 197%. It means about two sub-questions right on average. F1 follows the same rule: MEM1’s F1 at 16 questions is 2.39, against 0.703 for the 14B model, a ratio of 3.4. Second, each time and token entry carries a spread (±) over repeated runs, which the device leaves out for space. The paper reports spreads such as 10.4 ± 0.09 for MEM1’s peak at 16 questions, so the gaps above are far larger than the noise.
MEM1 is not the fastest at 2 questions. Search-R1 takes 4.09 s and DeepResearcher 4.01 s on 2 questions. MEM1 takes 6.49 s. Its advantage in time shows up as the task grows: at 16 questions it takes 8.70 s, while the 14B model takes 29.7 s.
Low tokens can mean failure. Search-R1 holds only 2,090 tokens at 16 questions, fewer than the 14B model. That is not efficiency. Figure 4’s caption says the baselines’ context stops growing at 16 questions because their performance degraded, some collapsed. Always read peak tokens next to accuracy.
An external memory costs time. A-MEM matches MEM1’s idea of keeping context small, and its accuracy at 16 questions (0.730) is the best baseline. But its peak is 1,880 tokens against 1,040, and its time is 91.2 s against 8.70 s. The module adds work on every turn.
The curves in Figure 4 show the same story. Baseline peak tokens rise nearly linearly with the number of objectives. MEM1’s peak stays almost constant, 640 at 2 questions and 1,040 at 16, a rise of 1.6 times while the task grows 8 times. The paper says “slight increase” and we should too.
The symptom: the agent’s accuracy falls apart when the task is longer than anything it saw in training. The measurement: right answers across 2, 8 and 16 questions. The fix the data supports is training the memory, because the same prompt and rollout without RL (the “truncate” row) reaches only 0.396 right at 16 questions, a fifth of MEM1’s 1.97.
Chapter 7
Check WebShop, the unseen web search and the comparison with imitation learning
You ask an assistant: “Find a ginkgo light, 20x20 pillow cover that is hand painted.” It must search the shop, scan a page of results, open a product, check its colour and size, and then press “buy now”. Each page is long. Keep every page in the prompt, and the context swells fast. This chapter checks MEM1 away from question answering, then asks why the paper insists on reinforcement learning.
WebShop is a simulated online store (Yao et al., which the paper cites). The agent sees one web page at a time inside a <state> tag and may type only a few kinds of action: search[keywords], click[item], click[next >], click[description], click[color], click[size] and click[buy now]. Prompt 3 in the appendix lists them.
MEM1 uses the same rollout and the same policy update here, with a prompt that keeps the idea of memory consolidation. One change: WebShop comes with its own reward for each state, so the authors use that reward in place of exact match. The split follows the original: the first 1,000 samples are the test set, 1,000 to 1,500 are validation, and the rest are for training.
Table 2 compares the results. The numbers below are the paper’s, for a few key rows.
| Model | Avg final reward | Peak tokens | Dependency | Time per run (s) |
|---|---|---|---|---|
| GPT-4o | 25.48 | 5,300 | 3.99 M | not reported |
| Qwen2.5-7B-Instruct | 18.42 | 5,640 | 3.38 M | 12.31 |
| AgentLM-7B | 63.60 | 2,240 | 0.28 M | 3.91 |
| AgentLM-13B | 70.80 | 2,360 | 0.30 M | 5.23 |
| MEM1-WebShop | 70.87 | 810 | 0.15 M | 2.61 |
Read the arithmetic against the best same-size baseline, AgentLM-7B. Peak tokens: 2,240 / 810 = 2.8 times. Dependency: 0.28 / 0.15 = 1.9 times. Time: 3.91 / 2.61 = 1.5 times. These are the three factors the paper quotes. On reward, MEM1 (70.87) essentially ties the twice-as-large AgentLM-13B (70.80), and the authors say it “surpasses” it. A 0.07-point gap, with the paper’s spreads, is a tie in practice. GPT-4o, even with truncation or A-MEM, scores far lower (13.82 and 24.50).
MEM1 trained on 2 questions is also tested on plain single-question tasks (Table 3). On Wikipedia search it gets an EM of 0.405, with a peak of 563 tokens against 889 for the 14B model (EM 0.422). Search-R1, which trained on exactly this single-question task, gets 0.445 EM. So MEM1 trades a little accuracy for lighter memory here.
One caution. The paper’s text says MEM1 has the highest EM and best efficiency on all three measures. The table does not fully back that wording: Search-R1 has the best EM, and its time (2.23 s) beats MEM1’s 3.79 s. Trust the table.
The cleaner result is zero-shot transfer to a live web search the agent never trained on (Serper, top 10 results). MEM1 reaches EM 0.397 with 579 peak tokens and 1.84 s. Qwen2.5-7B-Instruct gets 0.334 with 837 tokens and 2.20 s. DeepResearcher, trained on this very task, gets 0.372 EM with 1,027 tokens and 2.87 s.
Supervised fine-tuning (SFT) teaches by example: show the model good runs, and it copies them. The authors tried it. They collected high-quality trajectories from GPT-4o, using MEM1’s rollout, and trained on tasks of 1, 2 and 3 questions. The comparison with RL is Table 4 (Appendix D.1).
Each pair is one task size. Green is the RL-trained MEM1, grey is the SFT copy. Drag along the sizes and watch SFT fall away.
The values are the paper’s Table 4 (exact-match counts, higher is better). Both models trained on 2-objective QA; the SFT model also saw 1 and 3 questions.
SFT is behind at every size, and the collapse is sharp. At 6 questions SFT scores 0.088 against RL’s 1.630. At 16 questions SFT scores 0.000 and RL scores 1.900. One reading, which is mine and not the paper’s, is that imitation copies what good runs look like but gets no signal about which facts later turned out to matter. The paper’s own statement is shorter: RL generalizes better.
Figure 5 of the paper shows eight snippets of the agent’s states and actions. Nobody wrote these as rules. They appear after training.
These behaviours are reported from the authors’ reading of traces, so they are illustrations, not measurements.
Chapter 8
Follow the five phases of training, see why a format reward hurt, and list what the paper does not solve
Think of teaching a child to play a new board game by rewarding only wins. For a while the child plays randomly. Then she finds a safe trick that wins small. Then she gets stuck on that trick. Only later does she learn to play the whole game. The paper’s Appendix C describes MEM1’s training in just that way: a path with five phases, a shortcut and a plateau along it.
The authors plot four curves for the 2-objective QA run (Figure 6): the reward, the entropy loss, the ratio of valid actions, and the number of valid searches. Entropy measures how undecided the model is when it picks tokens: high entropy means wide, random choices. Here is what the appendix says about each phase.
The device draws the four curves as the appendix describes them. Scrub through the run.
Drag the training step. Watch searches dip near step 150 while reward still rises, then recover.
Schematic, not data: the curve shapes are drawn from the words of Appendix C, and the heights are made up. Only the phase boundaries (about steps 50, 150, 200, 250) and the 0.55 starting ratio come from the paper. Real curves are the paper’s Figure 6.
The shortcut is the lesson. A weak reward invites a cheap trick, and the agent found one before it found the real skill. Training that stops at step 150 would give a fast, short-searching, wrong-too-often agent. The run needed to continue past the plateau.
A natural fix for sloppy formats is a format reward: punish bad tags. Many reasoning-agent papers do this. The authors tried it (Appendix D.2): if the agent fails to use the <IS>, <query> and <answer> tags correctly, the turn ends and a penalty of −1 applies.
Choose how the agent was trained. The left bars show right answers on the 2-objective test. The right bars show average peak tokens.
The values are from Appendix D.2: exact match 0.709 against 0.466, and average peak tokens 640 against 514.9, on the 2-objective QA test.
The result runs against habit. The format reward made training converge faster (Figure 7), but the final score was lower: 0.466 against 0.709. The agent with the format reward also wrote shorter responses: 514.9 peak tokens against 640. The authors hypothesize that the format reward “accelerates structural learning but constrains exploration of effective reasoning strategies”. The agent learned to produce short, valid, less useful states. A shorter state meant less memory kept, which meant worse answers. This is why the exact-match reward in Chapter 5 has no other terms.
The authors name one limit. MEM1 assumes environments with well-defined, verifiable rewards. That holds for QA, math and web navigation. Many open-ended tasks have ambiguous, delayed or noisy rewards. The paper leaves them for future work.
Reading the paper closely, I would add these as open points. They are my list, not the authors’.
The authors’ broader claim is hopeful: a model that learns to summarize its own working memory could run long tasks with less compute and less energy. The evidence here is strongest for the narrow claim, memory that stays flat and accuracy that holds, on verifiable search tasks.
The symptom of a young run: a high reward from searching too little. The measurement: the count of valid searches, plotted next to reward. The fix in the paper is patience, plus no extra penalties. Wait past the plateau, and let the outcome reward pull the agent toward longer searching.
Chapter 9
Keep the numbers, the checklist, the core code and the paths onward
You can now rebuild the paper from memory: the problem (a prompt that only grows), the idea (one internal state that is both thought and memory), the loop (replace, never append), the training (outcome reward, a stitched trajectory, two masks), the tasks (composed questions) and the results (flat memory, accuracy that holds out to 16 questions). This page keeps the essentials in one place.
A normal agent pastes every thought, query and result into its prompt, so cost, length and clutter grow with each turn. MEM1 trains a language model, with PPO and a plain exact-match reward, to write one compact internal state each turn that blends reasoning with memory, after which the rollout deletes the old turn. Two masks, a 2D attention mask and a 1D information mask, make the policy gradient correct for the rewritten context. Trained on 2-question tasks and tested on 16, MEM1-7B gets 1.97 right on average with 1,040 peak tokens, where Qwen2.5-14B-Instruct gets 0.567 with 3,840.
| What | Number | Why it matters |
|---|---|---|
| Peak tokens, 16 questions (Table 1) | MEM1 1,040 vs 14B 3,840 (3.7 times less) | Memory stays near flat as the task grows |
| Right answers, 16 questions (Table 1) | 1.97 vs 0.567 (3.5 times more) | Accuracy holds where full history does not |
| Inference time, 16 questions | 8.70 s vs 29.7 s (29.3%) | Shorter prompts mean faster runs |
| Peak tokens at 2, 8, 16 questions | 640, 801, 1,040 | Almost constant, a slight rise |
| Trained on, tested on | 2 questions; up to 16 | Generalizes beyond the training horizon |
| Context ceiling | at most 2 states, 2 queries, 1 info | The size bound does not depend on turn count |
| Turn limit | 6 for 1 to 4 questions; 20 for harder | Hint tells the agent how many turns remain |
| WebShop (Table 2) | reward 70.87; 2.8, 1.9, 1.5 times better than AgentLM-7B on peak, dependency, time | Works beyond question answering |
| Single question, Wikipedia (Table 3) | 563 vs 889 tokens; EM 0.405 vs 0.422 | Lighter memory, a little less accuracy |
| Zero-shot web QA (Table 3) | EM 0.397; 579 tokens; 1.84 s | Transfers to an unseen search tool |
| RL vs SFT, 6 questions (Table 4) | 1.630 vs 0.088 | Imitation collapses on long horizons |
| Format reward (Appendix D.2) | EM 0.466 vs 0.709 | Extra rewards can hurt exploration |
| Training run (Appendix A.1) | 4 H100 or H200, batch 64, lr 1e-6 actor and 1e-5 critic | A modest budget to reproduce |
| Training phases (Appendix C) | about steps 50, 150, 200, 250 | Expect a shortcut and a plateau |
Chapter 3 gave the rollout. This sketch is the other half: the masks and the reward. It is my paraphrase of Sections 3.2 and Appendix A.4.1, not the authors’ code. Running it on Chapter 4’s toy sizes gives 247 tokens, 157 trained, and 121 tokens visible to the first token of the third state.
pythonimport numpy as np, re def build_masks(turn_of, owner, length): # turn_of[b]: 0 for the question, t for blocks of turn t. owner[b]: "agent" or "env". n = sum(length) # stitched sequence length ids = np.repeat(np.arange(len(length)), length) # block id of every token, [n] turn = np.array(turn_of)[ids] # turn of every token, [n] k = np.arange(n) causal = k[None, :] <= k[:, None] # no peeking ahead visible = (turn[None, :] == 0) \ | (turn[None, :] == turn[:, None]) \ | (turn[None, :] == turn[:, None] - 1) # question, this turn, last turn attn = causal & visible # 2D mask, [n, n] loss = np.array(owner)[ids] == "agent" # 1D info mask, [n] return attn, loss def em_reward(text, gold): # Appendix A.4.1 m = re.search(r"<answer>(.*?)</answer>", text, re.S) if not m: return 0 got = [a.strip().lower() for a in m.group(1).split(";")] if len(got) != len(gold): return 0 # wrong count scores 0 return sum(a == g.lower() for a, g in zip(got, gold)) # 1 point per right answer
The text normalization in em_reward (lower case, strip) is my simplification. The paper does not specify it.
A normal ReAct agent appends every thought, action and observation. MemGPT and agentic context engineering manage memory with outside structure. Search-R1 and DeepResearcher train agents with RL but let the prompt grow. A-MEM adds a retrieval memory that is not trained with the agent. MEM1’s one move is to make memory management part of the policy and train it end to end, with the reward the task already gives.
It is a reading for MIT MMAI’s Lecture 13, Multimodal Interaction (course site: MIT MMAI, Spring 2026). Paul Pu Liang, a co-author of the paper, teaches the course.
Credit: this lesson teaches the paper “MEM1: Learning to Synergize Memory and Reasoning for Efficient Long-Horizon Agents” by Zijian Zhou, Ao Qu, Zhaoxuan Wu, Sunghwan Kim, Alok Prakash, Daniela Rus, Jinhua Zhao, Bryan Kian Hsiang Low and Paul Pu Liang (arXiv 2506.15841). The method, the tables and the figures are theirs. The toy examples are ours and labelled as such.
Now press Teach and explain MEM1 from memory: why a growing prompt hurts, what one turn does, how the masks fix the learning signal, and why the format reward lost. Then go back to the instrument at the top, pick 16 questions, and say why the purple bar stays so short.