MEM1

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.

Grow the task

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

The Agent That Never Forgets

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.

The words we need

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.

Three things go wrong

The authors name three problems with an ever-growing context. Each one is a real cost, so we take them one at a time.

  1. The cost grows. A transformer compares every token with every earlier token, so the work grows with the square of the length, or linearly with a stored cache. The memory to hold the context grows too. A server must reserve that GPU memory for the whole run, even when most of the text no longer matters.
  2. The length goes past what the model has seen. A model learns from examples of some typical length. A conversation longer than any training example is out of distribution: unfamiliar ground. The model reasons worse there.
  3. The context gets crowded. Old search results that no longer matter sit next to the facts that do. Attention, the model’s way of looking back at earlier text, spreads thin. The right fact can be in the prompt and still get missed.

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.

Watch the context grow, or not

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.

6

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.

Why not just use a bigger window, or a helper?

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 paper’s idea in plain words

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.

The road

  1. What a long context costs: peak tokens, dependency length and inference time.
  2. One internal state per turn: the loop, the tags and what is kept.
  3. The rollout, line by line: Algorithm 1 as data flow, with the turn hint and the stop rules.
  4. Training with a rewritten context: the two masks that make the learning signal correct.
  5. Making long tasks from short ones: multi-objective questions and the exact-match reward.
  6. Reading the scaling results: Table 1 and Figure 4, from 2 to 16 questions.
  7. Shops, transfer and why RL: WebShop, unseen web search and imitation learning.
  8. Training dynamics and limits: five phases, the format reward and what is unsolved.
  9. Field guide: numbers, checklist, code and links.
What does MEM1 change about a normal multi-turn agent?

Chapter 1

What a Long Context Costs

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.

Three measures

The paper judges every method on accuracy and on three efficiency numbers. Each one answers a different question about cost.

  1. Peak token usage. The most tokens in any single sequence during the whole run. The authors count with the GPT-4o-mini tokenizer and leave out the system prompt. It is a stand-in for the memory the GPU must hold.
  2. Dependency length. How much old text each new token leans on, added over the whole run. It stands in for the work of computing the run.
  3. Inference time. The wall-clock seconds to produce the whole run, on one H200 GPU with 10 requests at once, served by vLLM with automatic prefix caching turned on. Prefix caching saves the work already done on the start of a prompt when the next request begins the same way.

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.

Counting what each token leans on

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:

Dependency
The total count of “this token looks back at that token” links over the whole run. Lower means less work.
∑i=1T
Add up the turns, from the first to the last turn T.
(2 no + np) × no / 2
The cost of turn i. np is its prompt length and no is the number of tokens it writes. The prompt term is multiplied by no: every new token pays for the prompt.

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.

A worked example, turn by turn

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.

  1. Turn 1, both agents. Prefix = the question = 120. Cost = (2 × 170 + 120) × 170 / 2 = 460 × 85 = 39,100.
  2. Turn 2, full history. The prefix holds the question, one thought, one query and one result: 120 + 670 = 790. Cost = (340 + 790) × 85 = 96,050.
  3. Turn 3, full history. The prefix now holds two full turns: 120 + 1,340 = 1,460. Cost = (340 + 1,460) × 85 = 153,000.
  4. Turn 3, MEM1. The old turn is gone. The prefix is the question, one state, one query and one result: 790 again. Cost = 96,050.
  5. Totals. Full history: 39,100 + 96,050 + 153,000 = 288,150. MEM1: 39,100 + 96,050 + 96,050 = 231,200.

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.

Add up the dependency

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.

8
500

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.

Symptom, measurement, fix

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.

In the dependency formula, which part makes a long prompt expensive?

Chapter 2

One Internal State per Turn

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 four tags

The paper marks each piece of the loop with an XML-style tag, a label wrapped around text, like <IS> … </IS>. There are four.

  1. <IS>, the internal state. The model’s reasoning and its notes, in one block. It is the only thing carried from one turn to the next.
  2. <query>. A request to the world, such as a search phrase.
  3. <answer>. The final reply, used once the model is done.
  4. <info>. What the world sends back, such as search results. The model does not write it. The environment does.

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.

One turn, step by step

Number the turns t = 1, 2, 3 and so on. In turn t, the paper says (Section 3.1):

  1. The model writes a new state, ISt. It summarizes the past and reasons about what to do next, in one block.
  2. It writes an action: either a queryt to ask the world, or an answert if it is ready.
  3. If it wrote a query, the world replies with infot, which is added to the context.
  4. In turn t + 1, the model reads ISt, queryt and infot, and folds them into a new state ISt+1.
  5. Then all tags of turn t are pruned from the context. Only the new state and the new action remain.

Write step 4 as a rule. Let x be the original question (it always stays), and let πθ be the model with its weights θ. Then:

(ISt+1, at+1)
What the model writes next: a new state, then an action a (a query or an answer). The wavy sign “∼” means “is drawn from”: the model samples its words.
πθ
The policy: the language model, with weights θ. In reinforcement learning, a policy is the rule that picks actions.
x
The task prompt and the original question. It is never pruned.
ISt, queryt, infot
The one turn the model still sees. Anything older than this is gone from its view.

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.

Step through the loop

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.

Why the size stops growing

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.

Reasoning as memory

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 failure, and the fix

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.

At turn 9, an old search result is no longer in MEM1’s context. When can the agent still use a fact from it?

Chapter 3

The Rollout, Line by Line

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.

The inputs

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.

The loop, in the order the data moves

  1. Build the context. Join the prompt x and the current block y (the last state, query and info). Token ids, shape [n], where n has the ceiling from Chapter 2.
  2. Run the model. One forward pass gives scores for the next token, shape [n × V] over the vocabulary size V. Only the last row is used. The agent samples one token (temperature 1 in training, 0.01 at test time, Appendix A.1).
  3. Repeat until the model writes a stop: </query>, </answer> or an end-of-sequence mark. The tokens form the turn’s output yt, a few hundred tokens.
  4. Replace, do not append. Line 14 reads y ← yt with the comment “all previous context removed”. This one line is the whole memory mechanism.
  5. Read the action. A query is parsed out. The world returns text d: for Wikipedia, 3 passages found with an E5 embedding model and a Faiss index; for web search, the top 10 results (titles, snippets, URLs).
  6. Add the hint and the info. Wrap the result in <info> … </info> with a hint in front, then go back to step 1.

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.

The turn hint

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.

Three endings

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.

Referee a reply

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.

1

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.

The same loop as code

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.

Symptom, measurement, fix

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.

Which single line of the rollout makes the context stop growing?

Chapter 4

Training with a Rewritten Context

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, in three plain paragraphs

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.

Why a rewritten context breaks the usual recipe

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.

Fix one: stitch, then mask in two dimensions

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.

Fix two: do not learn from the world’s words

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):

ρk(θ)
The probability ratio for token k. The paper gives this one explicitly, and says it “remains valid and tractable” under the mask.
πθ(ak | sk)
The model being trained: its probability of token ak, given the masked context sk that the 2D mask leaves visible.
πold(ak | sk)
The same, from the model that wrote the rollout. Same token, same view, so the ratio means something.
L
The PPO loss. mk is 1 for tokens the agent wrote and 0 for info tokens (the 1D mask). Ak is the token’s advantage; ε is the clipping width. These last pieces are standard PPO, not the paper’s own.

A worked example with every number

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.

  1. Which tokens train? The agent wrote 50 + 6 + 50 + 6 + 40 + 5 = 157 of them. The 50 info tokens and the 40 question tokens get m = 0. Loss covers 157 of 247.
  2. What does IS3 see? The question (40), IS2 (50), query2 (6), info2 (25), plus its own earlier tokens: 121 tokens before its first word.
  3. What would a plain causal mask let it see? Everything before it: 40 + 81 + 81 = 202 tokens. The 2D mask hides turn 1’s 81 tokens.

Use the device to move the generating token’s block and flip the mask.

Mask the trajectory

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.

IS3

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.

A caveat the authors admit

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.

Why does MEM1 need a 2D attention mask when it trains with PPO?

Chapter 5

Making Long Tasks from Short Ones

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.

The shortage of long tasks

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 paper’s trick: compose questions

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.

The reward: plain exact match

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:

  1. Pull the text between <answer> and </answer>.
  2. If the tags do not match, or the number of answers differs from the number of questions, the score is 0.
  3. Otherwise, give 1 point for each correct answer.
  4. No other rewards. No bonus for format. No penalty for long runs.

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.

Score a composite task

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.

4
4
3

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.

Where it trains and where it is tested

Symptom, measurement, fix

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.

A task asks 3 questions. The agent gives 2 answers, both right. What does the paper’s exact-match scorer give it?

Chapter 6

Reading the Scaling Results

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.

The seven competitors

A fair race needs clear entrants. The paper compares MEM1 against six, and each one isolates a different idea.

EntrantWhat it isWhat it tests
Qwen2.5-14B-InstructA bigger chat model, with full historyDoes size beat memory management?
Qwen2.5-7B-InstructSame size as MEM1, full historyThe plain baseline
7B-Instruct (truncate)The 7B chat model, run with MEM1’s prompt and rolloutIs the prompt and rollout alone enough, with no RL?
7B-Instruct (A-MEM)The same, plus A-MEM, an external vector-store memoryDoes a separate memory module help?
Search-R1An RL-trained search agent, trained on 1 question with EMRL without memory training
DeepResearcherAn RL-trained web research agent, trained on 1 question with F1The same idea, online search
MEM1-QAQwen2.5-7B Base trained with the MEM1 recipe on 2 questionsThe 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.

Read the race yourself

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.

Race the seven systems

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.

What the table says, step by step

  1. 2 questions (the training size). The 14B model leads on right answers: 0.732 against MEM1’s 0.709. Among 7B models, MEM1 is best. But MEM1 holds 640 tokens at peak against 1,560 for the 14B model, 2.4 times fewer.
  2. 8 questions. MEM1 passes the 14B model: 1.87 against 1.55 right, with 801 peak tokens against 4,470. Search-R1 has collapsed to 0.064.
  3. 16 questions. The gap is wide. MEM1 gets 1.97 right. The 14B model gets 0.567. The best other entrant, A-MEM, gets 0.730. Search-R1 (0.009) and DeepResearcher (0.071) have collapsed.

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.

Three honest readings

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.

Symptom, measurement, fix

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.

Search-R1 shows fewer peak tokens than the 14B model at 16 questions. How should you read that?

Chapter 7

Shops, Transfer and Why RL

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: a shop that is a test

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.

ModelAvg final rewardPeak tokensDependencyTime per run (s)
GPT-4o25.485,3003.99 Mnot reported
Qwen2.5-7B-Instruct18.425,6403.38 M12.31
AgentLM-7B63.602,2400.28 M3.91
AgentLM-13B70.802,3600.30 M5.23
MEM1-WebShop70.878100.15 M2.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).

Single questions and an unseen search engine

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.

Why reinforcement learning, not imitation?

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).

Compare RL and imitation

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.

6

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.

Behaviours the agent was never told to learn

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.

The paper compares RL with SFT on trajectories from GPT-4o. What does Table 4 show?

Chapter 8

Training Dynamics and Limits

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 five phases of one training run

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.

  1. Exploration, steps 0 to 50. Reward stays low and entropy is high. The agent behaves at random. The ratio of valid actions is about 0.55: it breaks the tag format almost half the time.
  2. Format acquisition. The valid ratio rises, and reward rises with it. Following the format is the first thing that pays.
  3. The shortcut, around step 150. The number of valid searches drops sharply while reward keeps going up. The authors read this as the agent exploiting the reward: fewer searches mean fewer chances to break the format, so it keeps format fidelity and still scores a little without fully solving the task.
  4. Refined format mastery, steps 150 to 200. The valid ratio keeps climbing but searches stay few. Reward growth slows and entropy flattens. The agent sits in a local optimum: valid but under-informed answers.
  5. Extending the horizon, after step 200. Searches rise again. The agent learns to gather more information and obey the format. Reward climbs more sharply. After step 250 entropy falls steeply: the policy consolidates into a more deterministic, high-reward habit.

The device draws the four curves as the appendix describes them. Scrub through the run.

Scrub through training

Drag the training step. Watch searches dip near step 150 while reward still rises, then recover.

150

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.

The experiment that removed a format reward

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.

Add a format reward

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.

What the paper does not solve

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.

Symptom, measurement, fix

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.

Around step 150 the number of valid searches drops while reward still rises. What do the authors conclude?

Chapter 9

Field Guide

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.

The one-paragraph summary

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.

The numbers that matter

WhatNumberWhy 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 questions8.70 s vs 29.7 s (29.3%)Shorter prompts mean faster runs
Peak tokens at 2, 8, 16 questions640, 801, 1,040Almost constant, a slight rise
Trained on, tested on2 questions; up to 16Generalizes beyond the training horizon
Context ceilingat most 2 states, 2 queries, 1 infoThe size bound does not depend on turn count
Turn limit6 for 1 to 4 questions; 20 for harderHint 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, timeWorks beyond question answering
Single question, Wikipedia (Table 3)563 vs 889 tokens; EM 0.405 vs 0.422Lighter memory, a little less accuracy
Zero-shot web QA (Table 3)EM 0.397; 579 tokens; 1.84 sTransfers to an unseen search tool
RL vs SFT, 6 questions (Table 4)1.630 vs 0.088Imitation collapses on long horizons
Format reward (Appendix D.2)EM 0.466 vs 0.709Extra rewards can hurt exploration
Training run (Appendix A.1)4 H100 or H200, batch 64, lr 1e-6 actor and 1e-5 criticA modest budget to reproduce
Training phases (Appendix C)about steps 50, 150, 200, 250Expect a shortcut and a plateau

The words to keep

A checklist for building a MEM1-style agent

  1. Pick a task whose reward a program can check, such as exact match or an environment score. This is the paper’s main limit.
  2. Make long tasks by composing short ones, and train short (2 questions), test long (up to 16).
  3. Prompt for a cumulative summary inside the think block, then one action.
  4. Roll out with replacement: keep the question and the latest turn only, and inject the turns-left hint.
  5. Stitch the turns, then build the 2D attention mask and the 1D info mask.
  6. Train with PPO (token-level advantages, a critic, a KL penalty), outcome reward only, from a base model.
  7. Watch valid searches next to reward. Do not stop at the first plateau.
  8. Evaluate peak tokens, dependency and time, at lengths longer than training, and flag collapsed baselines.

The core, as code

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.

Where it sits in the field

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.

Keep going

The takeaway. Memory does not have to be a pile. If the reward only arrives for a right final answer, and the context is cut after every turn, a model learns to write the one note that carries what it needs. Its memory then stays the same size however long the task runs.

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.

You want to try a MEM1-style recipe on a new task. What must the task have, according to the paper’s own limitation?

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.

MEM1: Learning to Synergize Memory and Reasoning for Efficient Long-Horizon Agents
Read the paper · Authors’ code · MIT MMAI course · Lecture 13, Multimodal Interaction