Recursive Language Models

Treat a huge prompt as a variable the model reads with code, not as input it must swallow. On 6M to 11M tokens, GPT-5 alone scores 0.0 and an RLM around it scores 91.3.

Pick a task size, then switch between three ways to read it: the model alone, a model that keeps summarizing, and a model that treats the prompt as data. Watch where the prompt lives. Then we build the idea piece by piece: the loop, the code the model writes, the calls it makes to itself, the results, the failures and the training.

You need a rough idea of what a language model is and a little Python. We build the rest from zero.

A reading for lecture 4, Harness Evolution, of MIT MAS.S62 AI4AI (Fall 2026). Paper: “Recursive Language Models” by Alex L. Zhang, Tim Kraska and Omar Khattab, MIT CSAIL, arXiv 2512.24601. Code: github.com/alexzhang13/rlm. Every idea is re-taught here in our own words and devices.

Read a prompt too big for the window

8.3M tokens

Window: 272K tokens, GPT-5 (the paper, Figure 1). Scores are Table 1, GPT-5 with GPT-5-mini sub-calls, for the base model, the compaction agent and the RLM at depth 1: OOLONG-Pairs (F1) 0.1, 0.1, 58.0; OOLONG 44.0, 46.0, 56.0; BrowseComp-Plus 0.0, 70.5, 91.3. The paper tests BrowseComp-Plus at 6M to 11M tokens; 8.3M is one query’s corpus (Appendix E.1). Other lengths show only the fit; the block layout is illustrative.

Chapter 0

A Prompt Too Big to Read

See why a model that can read 272,000 tokens still fails on a task whose prompt is far shorter, and what the paper proposes instead

You give a model a small library: 1,000 documents, about 8.3 million tokens in all. Somewhere inside, a few documents hold clues to one question about a village festival. You ask the question and wait for an answer.

The first problem is size. A token is a small piece of text, about three quarters of a word. A context window is the most tokens a model can read at one time. GPT-5, the model in this paper, has a window of 272,000 tokens. Your library is about 31 windows long. The model cannot even start.

The second problem is quieter. Suppose you cut the library down until it fits. The model still gets worse as the prompt gets longer. The paper calls this context rot: answer quality falls steeply with prompt length, even inside the window. Think of a student handed a 600-page binder one hour before an exam. The binder fits in the bag, yet the student still misses things.

Why the usual fix is not enough

The most popular fix is compaction (also called context condensation). The agent reads until its window is full, asks the model to write a summary, drops the old text and keeps going. It is a student who rereads the binder and only keeps a one-page cheat sheet.

A cheat sheet works when the early pages hold nothing you will need later. The paper says compaction “presumes that some details that appear early in the prompt can safely be forgotten.” Many tasks break that rule. If the answer depends on almost every line, a summary has already thrown some of it away.

A second fix is to let the model hire helpers: sub-agents, other copies of the model that take on part of the job. This helps, but the model must write out each delegation as text, one call at a time. The paper says this is “handicapped by the underlying LLM’s limited output lengths.” A thousand delegations will not fit in one reply.

The paper’s question

Zhang, Kraska and Khattab ask a different question. Do we have to feed the prompt into the neural network at all? Their answer is no. Keep the prompt outside the model, as data the model can look at on demand. Give the model a programming environment. Let it write code that peeks at pieces of the prompt and calls a copy of itself on each piece. They call this a Recursive Language Model, or RLM.

From the outside, an RLM looks like any language model. It takes a string and returns a string. Inside, it is a loop around a normal model. Chapter 2 builds that loop. First we need to see what kind of task each prompt poses.

Hard tasks break earlier

The authors make one careful claim. A model’s effective context window, the length at which it still works well, cannot be separated from the task. A harder task breaks at a shorter length.

They sort tasks by how the needed work grows with the prompt. Look for one fact, a needle in a haystack: the work stays constant, one needle however long the haystack. The benchmark is S-NIAH. Label every line and combine the labels: the work grows in step with the length. That is OOLONG. Compare every pair of lines: the work grows with the square of the length. That is OOLONG-Pairs.

Slide the length below. Count how many items each task makes the model handle.

Count the work in a prompt

Each bar is the number of items the model must handle, on a log scale: every step to the right is ten times more. Drag the prompt length from 8K to 1M tokens.

131K

Illustrative: one entry is 25 tokens. Lengths run 213 to 220, the range of the paper’s Figure 1. The three growth rules (constant, linear, quadratic) are the paper’s own sorting of S-NIAH, OOLONG and OOLONG-Pairs.

At 131K tokens the needle task still means one thing to find. The pair task already means about 13.7 million pairs. A model that coped with the first has no reason to cope with the second. That is exactly the pattern in the paper’s Figure 1: GPT-5 holds up on needles, slips sooner on OOLONG, and slips sooner again on OOLONG-Pairs.

The paper’s result, in one line: an RLM keeps working past 214 tokens where GPT-5 alone drops, and it handles prompts of 10 million tokens and more, over ten times the window.

The road

  1. Four ideas you need first: the window, the REPL, the variable, and recursion.
  2. The prompt becomes a variable: Algorithm 1, line by line.
  3. Three choices that matter: why a look-alike design fails.
  4. What the model actually sees: the real system prompt and the code it writes.
  5. Recursion depth and the call tree: depth 0, 1, 2 and 3.
  6. Reading the results: Table 1, Table 2 and Figure 1.
  7. How models behave as RLMs: trajectories, failures and limits.
  8. Training a native RLM: RLM-Qwen3-8B.
  9. Field guide: numbers, a checklist and the core code.
A task needs the model to compare every pair of lines in a long prompt. Why does it break at a shorter length than a needle search?

Chapter 1

Four Ideas You Need First

Learn a model call, a REPL, a variable and recursion, so that the paper’s loop reads as plain common sense

Imagine an accountant with a tiny desk and a huge filing room. The desk holds one folder at a time. The filing room holds ten thousand. A good accountant does not carry the filing room to the desk. She walks in, finds the right drawer, pulls two pages, and writes a note on the desk.

An RLM treats a language model like that accountant. Four ideas make the picture exact. None is hard. Each is used on every page that follows.

Idea 1: a model call is a string in, a string out

A model call sends text to a language model and gets text back. The text you send is the prompt. The model reads all of it at once, inside its window. Longer prompts cost more tokens and, as Chapter 0 showed, work less well.

In Python, a model call looks like a function: answer = llm_query(prompt). The input is a string. The output is a string. That is the whole interface. Remember it: the paper builds on it without changing it.

Idea 2: a REPL is a notebook that remembers

A REPL is a Read-Eval-Print Loop. You type one line of code. The computer reads it, evaluates it, prints the result and waits for the next line. Python’s interactive prompt is a REPL. A notebook cell is nearly the same thing.

Its key feature is memory. If one line says x = 5, a later line can use x. The values the program keeps are its state. The state lives in the computer’s memory, not on the page you read.

Idea 3: a variable can hold what a prompt cannot

A variable is a name for a stored value. Here the value is a very long string. A computer can hold 30 million characters in a variable without effort. The language model never reads those characters unless a line of code prints some of them.

That is the trick of the whole paper. Pasting a document into a prompt forces the model to read it. Storing the document in a variable lets the model choose what to read. Try it. Run the four lines a model might write against a library of 8.3 million tokens, and watch how little the model’s own history grows.

Peek at a prompt you cannot read

The variable context holds the whole library. Press Run next line to execute each line. The bars compare the library with what the model has seen so far, on a log scale.

Illustrative toy. The library size (8.3M tokens, about 33.2M characters) matches the paper’s Appendix E.1 corpus; the lines, outputs and per-line token counts are made up to show the shape. The 350-token start is a guess for the system prompt plus metadata.

After four lines the model has read about 500 tokens. The library is still 8.3 million. The model read 0.006% of it and found the answer, because code did the searching and the model read only what code printed. The sub-call at line four read a slice of roughly 6,000 characters, which fits any window.

Idea 4: recursion is a job that hands a smaller job to itself

Recursion means a function calls itself on a smaller piece of its input. It needs two parts. A base case is a piece small enough to solve directly. A recursive case splits the job, solves the parts, and joins the answers.

Take a simple job: add up the list [3, 1, 4, 1]. The function total(xs) returns the one number if the list has one item. Otherwise it splits the list in half and adds total of each half.

  1. total([3, 1, 4, 1]) splits into [3, 1] and [4, 1].
  2. total([3, 1]) splits again into [3] and [1]. Each is a base case: 3 and 1. The sum is 4.
  3. total([4, 1]) is the same: 4 and 1 give 5.
  4. The top call adds 4 + 5 = 9.

The calls form a tree two levels deep. The recursion depth is how many levels of calls sit inside calls. In an RLM, the pieces are slices of the prompt and each call is a language model. A sub-call at depth 1 can be a plain model. At depth 2 it can be another RLM that has its own REPL and its own sub-calls. Chapter 5 measures what depth buys.

One word now saves confusion later. The root model is the model the user talks to. A sub-model is any model the root calls from code. In the paper’s main runs, GPT-5 is the root and the cheaper GPT-5-mini is the sub-model.

Why keep the prompt outside: cost, too

A model call is priced by the tokens it reads and writes. If you paste 8.3 million tokens into a prompt, you pay to read all of them, and a long chat pays again on every turn. Code that searches the variable involves no model at all. A regular expression scans 33 million characters quickly and bills nothing per token. The model pays only for the few lines it chooses to read. So keeping the prompt outside helps the window and the bill.

A REPL line can also fail. If a line has a typo, Python prints an error message, and the model sees that message as the output on its next turn. It fixes the line and tries again. This feedback loop is why the paper describes the environment as persistent and interactive: the model learns from what each line did, one turn at a time.

Why can a variable hold a 30-million-character prompt when a model’s window cannot?

Chapter 2

The Prompt Becomes a Variable

Read Algorithm 1 line by line, and see why the root model’s own history stays small however long the prompt is

The accountant from Chapter 1 follows a routine. She walks in with the question and a note about the filing room: how many drawers, what the labels look like. She does not carry any files. She writes an instruction, someone runs it, and a short result comes back. She decides the next step, again and again, until she writes down the final answer.

That routine is the paper’s Algorithm 1. It has seven lines. We will read each one, and we will name every piece of data that moves.

Setting up

A base model M has a maximum window of K tokens. The user gives a prompt P, a string of any length, even far longer than K. The RLM returns a string Y. In the paper’s notation, both P and Y are in Σ*, the set of all strings. An RLM wants unbounded input, unbounded output and an unbounded semantic horizon: the ability to do work proportional to the length of P, or even its square.

python# Algorithm 1, as Python-shaped pseudocode
def rlm(P):
    state = init_repl(context=P)                # P becomes a variable
    state = add_function(state, sub_rlm)       # the model can call itself
    hist  = [metadata(state)]                   # tiny: length, prefix, how to access
    while True:
        code = M(hist)                             # root model writes code
        state, stdout = repl(state, code)          # run it; variables persist
        hist = hist + [code, metadata(stdout)]     # only a short view of the output
        if state.is_set("Final"):
            return state["Final"]

The seven lines, one at a time

  1. init_repl(context=P). Start a Python process. Store the whole prompt in a variable. Nothing is sent to the model yet.
  2. add_function(sub_rlm). Put a function in that process so code can call a model (a sub-model, or another RLM) on any string.
  3. hist = [metadata(state)]. Build the model’s first and only input: a short description, such as the length of P and its first few characters. Its size does not depend on P.
  4. code = M(hist). One model call. Input: a list of strings of at most K tokens. Output: Python code.
  5. repl(state, code). Run the code. It may read context, call sub_rlm, and set variables. Output: new state, and whatever the code printed (stdout).
  6. hist + code + metadata(stdout). Add the code and only a short view of stdout (a prefix and its length) to the history.
  7. if Final is set, return it. When code sets the variable Final, stop and return its value as the response.

Only line 3 and line 6 touch the history, and both add a bounded amount. That is the design. The root model never sees P. It sees descriptions of P, and the results of code it chose to run.

Why trimming stdout is not a detail

The paper adds a footnote that carries a lot of weight. Cutting stdout to a short view “forces M to rely on variables and sub-calls to manage long strings instead of polluting its window.”

It also gives a bound. If each turn adds at most c tokens to the history, the root can run at most K / c turns before its window fills. Each of those turns may start as many sub-calls as it likes.

Nturns
How many times the root model can be called before its history fills the window.
K
The root model’s window, in tokens. For GPT-5, 272,000.
c
The most tokens one turn adds: the code plus the short view of its output.

K = 272,000 and c = 500 give N = 272,000 / 500 = 544 turns, each free to launch many sub-calls.

The authors note this is not a fundamental limit. One could move the root’s own history into a variable too. They keep a cap on iterations at every level of recursion.

Walk through one run

Step through a toy run on the festival question. The top bar is the root model’s history against its 272K window. The middle holds the REPL variables. The bottom shows the line just run.

Step the RLM loop

Press Step to run one turn of the loop. Watch which things grow (the variables) and which stays tiny (the root’s history).

Illustrative toy. The turn sizes (60, 45, 70, 80, 30 tokens) and the 300-token start are made up to show the shape; the loop and the bound K / c are from Algorithm 1 and its footnote 2.

Five turns, 585 tokens, a 31-window library, and a correct answer. Turn 4 shows a habit the paper reports in the best runs: the model checks its answer with fresh sub-calls before it commits.

Now the failure mode. Symptom: a run stops early with an error that the window is full. Measurement: the history grew by thousands of tokens on one turn, because the code ran print(context[:200000]). Fix: the loop shows only a short view of stdout, and the prompt tells the model to feed big slices to llm_query instead of printing them.

What the first message looks like

The paper’s system prompt fills a template for the first turn. It tells the model the type of the context (a string, a list or a dictionary), the total number of characters, and the length of each chunk. For our festival corpus that is a list of 1,000 documents, 33,200,000 characters in all, plus the length of each document. That is a few hundred tokens whether the library holds 1,000 documents or 100,000. The size of the first message does not grow with the prompt.

The root model reads this whole history on every turn, so each extra turn costs a little more than the one before. This is another reason short turns matter. A run of five tight turns is cheap. A run of fifty turns that print big outputs is not.

In Algorithm 1, what does the root model receive as its input on the very first turn?

Chapter 3

Three Choices That Matter

Compare Algorithm 1 with a look-alike scaffold, and find the three design choices that decide whether a long prompt can be handled

A reader may say: “I have seen this before. Coding agents run code. Agents call sub-agents. Agents search files. What is new?” The paper answers with a second algorithm that has all those parts and still fails.

We call it the look-alike scaffold (the paper’s Algorithm 2). It has four actions: Finish, Exec (run code), Search, and a sub-model call. The loop asks the model for an action, runs it, appends the result to the history, and compacts the history when it passes K tokens. It looks close to an RLM. It is not, and the difference is three flaws.

python# Algorithm 2: the look-alike scaffold (what NOT to build)
hist = [metadata(actions), P]            # flaw 1: P goes into the window
while True:
    action, val = M(hist)
    if action == "Finish":
        return val                       # flaw 2: the answer is written token by token
    out = run(action, val)                # flaw 3: a sub-call is one verbalized action
    hist = hist + [(action, val, out)]
    if tok(hist) > K: hist = compact(hist)

Flaw 1: the prompt sits in the window

This scaffold starts by putting P into hist. It inherits the window limit and then falls back on compaction. It can search external data, but its input is bounded by K. An RLM gives the model a symbolic handle, a variable name, so the model can work with P without copying it into the window.

Flaw 2: the answer must be typed out

The look-alike returns whatever the model writes after Finish. A reply cannot be longer than the window, so the output is bounded too. A task like OOLONG-Pairs needs a long list of pairs. An RLM builds the answer in a variable, piece by piece, and returns the variable. The answer can be as long as memory allows.

Flaw 3: sub-calls are written out one at a time

The look-alike has a sub-model action, but the root must say each call in its own text. It can delegate a few jobs. It cannot write a short loop that starts thousands. The paper requires symbolic recursion: code inside the REPL can call the model on slices built by the program, inside loops of any size, and store the results as values.

A worked count shows the gap. Say a call takes about 80 tokens to write out (illustrative). Then a root with a 272K window can write at most 272,000 / 80 = 3,400 calls, and only if it does nothing else. A loop in code writes the call once, about 80 tokens, and runs it 5,000 times.

Try each fix. The first two rows are measured in tokens, the third in calls. Turn on one choice at a time and watch which row turns from red to green.

Fix the look-alike, one flaw at a time

The bar is what the task needs. The tick is what the scaffold allows. A red bar passes its tick. Switch the choices on, and change the task size below.

4M tokens
16K tokens

Illustrative numbers: a slice is 10K tokens, one written-out call costs 80 tokens, the window K is 272K. The three flaws and the choices that fix them are the paper’s (Section 2, Algorithms 1 and 2).

With the defaults, the prompt is 4M tokens and only the first row is red. Make the task quadratic: 410 slices now need 84,000 calls, and the third row joins it. Turn all three choices on and every row turns green. That is the RLM.

The failure mode, as a story. Symptom: an agent with a code tool and a sub-agent tool still scores near zero on OOLONG-Pairs. Measurement: in the paper’s Table 1, CodeAct with sub-calls scores 28.4 where the RLM at depth 1 scores 58.0 (GPT-5), and the base model scores 0.1. Fix: not a better prompt. Move the prompt into the environment, let code build the answer, and let code launch the calls.

Where prior systems fall

The paper places earlier work on this map. Coding agents and retrieval agents treat a file system or a document store as an environment, but they fetch snippets into the window, so they meet the same limit and then compact. Self-delegation systems such as THREAD, ReDel, Context Folding and AgentFold let the model choose when to start sub-calls, but they cannot take an input longer than the base model’s window. DisCIPL writes a program with sub-calls in a single step, so it cannot recover from a mistake. An RLM keeps the prompt outside, runs the program turn by turn, and reads the result of each step before the next.

Three questions to ask any scaffold

  1. Where does P live? If the answer is “in the model’s context,” the input has a ceiling.
  2. Where is the answer built? If the model types it after a Finish action, the output has a ceiling.
  3. Who starts the sub-calls? If the model writes each one as text, the call count has a ceiling. If code starts them in loops, it does not.

A scaffold that passes all three can handle work proportional to the length of the prompt, or to its square. That is the semantic horizon from Chapter 2, now stated as a test you can apply to any system.

A scaffold lets the model run code and call a sub-model, but the sub-model call is a separate action the root must write out each time. Which RLM choice does it miss?

Chapter 4

What the Model Actually Sees

Read the real system prompt, follow one request and reply through the REPL, and learn how big a slice should be

Algorithm 1 says “the model writes code.” Nothing in the model knows how. The behavior comes from a system prompt, the standing instructions placed before every conversation. The paper prints it in full in Appendix C. It is the real implementation of the idea, so we read it closely.

What the prompt tells the model

The prompt first says the task: answer a query about a context, using a REPL that can query sub-models. Then it gives the model three tools.

  1. A context variable. It holds the prompt P. The prompt tells the model to inspect it before answering. Its type changes with the task: a string, a list of strings, or a dictionary. The prompt states the type, the total characters and the length of each chunk.
  2. An llm_query function. It sends a string to a sub-model and returns a string. The prompt says the sub-model can handle about 500,000 characters.
  3. print(). The model sees printed output, but truncated.

It then gives worked examples of strategy: chunk the context and query each chunk, keep a buffer that grows section by section, split by Markdown headers, or feed ten documents to each sub-query. It ends with the stop rule: finish with FINAL(answer) to give the answer directly, or FINAL_VAR(name) to return a variable. Code goes in a fenced block tagged repl.

One round trip, with shapes

Here is what crosses the wire in one turn. The root model receives a list of messages and returns a string. The harness extracts the repl block, runs it, and appends a short result as the next message.

transcript# input to the root: [system prompt, user: query + metadata] -> list[str], well under K
assistant: I will look at the structure first, then split by header.
```repl
sections = re.split(r"### (.+)", context["content"])        # list[str], lives in the REPL
buffers = []
for i in range(1, len(sections), 2):
    buffers.append(llm_query(f"Summarize: {sections[i+1]}"))   # str in, str out
print(len(buffers), buffers[0][:200])
```
user (REPL output, truncated): 14 The authors describe a ...
# next turn: the model reads that short result, and may set FINAL_VAR(final_answer)

The data flow has four types. The root takes list[str] and returns str. The REPL holds anything Python can hold. A sub-call takes str and returns str. The final answer is a str in either case. Everything big stays in the REPL.

How big should a slice be?

Slice size is a real engineering choice. Too small, and the run makes thousands of calls. Too big, and the slice passes the sub-model’s limit, or hits context rot again. The number of sub-calls for one pass over the prompt is simple.

Ncalls
Sub-model calls for one pass: one per slice, plus one to combine the answers.
|P|
The prompt length, in characters.
s
The slice size, in characters.

|P| = 1,000,000 and s = 100,000 give ⌈10⌉ + 1 = 11 calls. One call per 200-character line gives 5,000 calls for the same text.

The paper tuned this by hand. For Qwen3-Coder it added a line: calls are costly, so batch about 200,000 characters per call. With 1,000 lines, make 200 calls of 5 lines, not 1,000 calls of one. Play with the sizes.

Choose a slice size

Drag the prompt length and the slice size. The top bar shows the calls your slice size needs. The second bar shows one call per line. Both are on a log scale.

1.0M chars
100K chars

The 500K-character sub-model limit and the 200K-character advice are in the paper’s Appendix C.1 system prompts. The 200-character line and the calls count are illustrative arithmetic, not measurements.

A failure from the paper, as a story. Symptom: Qwen3-Coder, given the same prompt that worked for GPT-5, made hundreds or thousands of sub-calls on simple tasks. Measurement: the paper’s Appendix E.3 reports hundreds to thousands for one task, where GPT-5 makes about ten; Figure 10 reports about 500 on average for correct OOLONG runs. Fix: one added sentence, be careful, calls are costly, batch as much as you can. The paper also notes that a prompt written for one model can cause “different, undesirable behavior” in another.

Where the code runs, and what it must carry

The paper’s implementation equips the model with a Python REPL in which every tool, including sub-model and sub-RLM calls, is a module. The model’s printed output is truncated so that it cannot flood the window. The prompt also gives two warnings about the execution context. The code runs as written, so each block must include its own imports. Variables persist between blocks, so data built in turn 2 is available in turn 9. Treat each block as a small script that can rely on earlier variables but not on earlier imports.

Choosing between the two stop forms is a real design point. FINAL(answer) is for a short answer the model has typed. FINAL_VAR(name) returns a variable, which is how a long answer, such as a list of pairs, gets out without passing through the model’s own output. The paper reports that the boundary between a final answer and a thought is brittle. In one case the model returned its plan as the final answer.

When a prompt is not a single string, the first message says so. A list of documents can be sliced by index, with ten documents per sub-query as one of the prompt’s examples suggests. A dictionary with a content field can be split by header with a regular expression. The strategies differ, but the data flow is the same: slice in code, call on the slice, store the reply in a buffer, combine at the end.

A prompt has 2,000,000 characters. You use slices of 200,000 characters. How many sub-calls does one pass make, counting the final combining call?

Chapter 5

Recursion Depth and the Call Tree

Count how many levels of model calls an RLM allows, and see which levels earn their cost on which task

A manager gets a thick report to check. She can read it all herself. She can hand each chapter to an assistant. Or she can hand each chapter to an assistant who is allowed to split it again and hire more assistants. The third plan has the most structure and the most things that can go wrong.

The paper names these plans by maximum recursion depth, written RLM(model, depth=N). If the depth is not stated, it is 1.

  1. Depth 0. The model has the REPL and the variable, but no sub-calls. It reads the prompt only through code: search, slice, print.
  2. Depth 1. Code can call a plain language model on a slice. The sub-model has no REPL. It reads a string and answers.
  3. Depth 2 and 3. Code calls rlm_query instead, so a sub-call is itself an RLM, with its own REPL and its own sub-calls, one level further down. The system prompt (Appendix C.1c) adds that function.

The cost of depth is a tree. If the root starts three sub-calls and each of those starts two, six leaves read their slices. A third level of two doubles that again. The number of calls can multiply at every level.

Fan-out 3, 2, 2 (illustrative): depth 1 has 3 sub-calls, depth 2 has 3 + 6 = 9, depth 3 has 3 + 6 + 12 = 21.

The question is what depth buys. The paper ran every depth on four tasks, with two models. Choose a model and a depth and read off the four scores. The small tick on each bar is the plain model with no scaffold.

Turn the depth dial

The tree shows the call structure for the depth you pick. The bars show the paper’s Table 1 scores for that depth. The tick marks the base model.

Scores are the paper’s Table 1 (accuracy, except OOLONG-Pairs which is F1). Base-model ticks: GPT-5 24.0, 0.0, 44.0, 0.1 and Qwen3-Coder 20.0, 0.0, 36.0, 0.1; a 0.0 means the prompt did not fit. The tree’s fan-out of 3, 2, 2 is illustrative; real fan-out depends on the prompt and the model.

What the dial shows

Start with GPT-5 on OOLONG-Pairs, the quadratic task. Depth 0 scores 43.9. Depth 1 scores 58.0, depth 2 scores 65.5 and depth 3 scores 76.0. The base model scored 0.1. Each level of recursion adds points, because the task asks for work on every pair and sub-RLMs can split that work again.

Now flip to CodeQA, a question about a code repository. Depth 0 scores 58.0 and depth 1 scores 62.0. Recursion helps a little and then stops. For Qwen3-Coder it is worse: depth 0 scores 66.0, the best of all its variants. Here one targeted search is enough, and sub-calls only add cost and chances to slip.

The paper reads this as two separate effects. The REPL is what lets a model handle inputs past its window. Depth 0 already beats the plain model on most long tasks. Recursive sub-calls pay off on information-dense inputs, like OOLONG and OOLONG-Pairs, where the model must transform nearly every line.

In the paper’s trajectories, Qwen3-Coder at depth 0 does the semantic work with keyword heuristics, which is weaker. At depth 1 it classifies line by line with sub-calls, which is closer to the task.

The failure mode, as a story. Symptom: Qwen3-Coder gets worse with depth on OOLONG, from 48.0 at depth 1 to 26.0 at depth 2. Measurement: the paper’s Figure 4b counts trajectories with at least one syntax error. Qwen3-Coder has many more than GPT-5, even in correct runs. Cause and fix: a sub-RLM inherits the same weakness, so errors pass down the tree. The remedy is a root that writes cleaner code, which is why the authors later train one (Chapter 8).

A worked comparison on the pair task. From depth 0 to depth 1, GPT-5 goes from 43.9 to 58.0: 58.0 / 43.9 = 1.32, a gain of 32 percent. From depth 1 to depth 3 it goes from 58.0 to 76.0: 76.0 / 58.0 = 1.31, another 31 percent. Each level of recursion lets the model split the quadratic work into smaller jobs that fit one sub-call, so the gains keep coming.

Does depth cost more?

Not always. Table 1 gives the average cost per task. For GPT-5 on OOLONG-Pairs, depth 0 costs $0.69, depth 1 costs $0.33, depth 2 costs $0.33 and depth 3 costs $0.39. The deeper runs are cheaper here, because better-organized work avoids waste. On BrowseComp-Plus, GPT-5 costs $0.44, $0.99, $0.55 and $0.51 at depths 0 to 3.

For Qwen3-Coder on CodeQA the picture changes: depth 0 costs $0.18, depth 1 costs $0.92, depth 2 costs $1.88 and depth 3 costs $1.65. Here depth buys cost and not accuracy. The lesson is to measure per task and per model. A rule of thumb from the paper’s own results: start at depth 1, then try depth 0 if one search should do, and depth 2 only if the work is dense and the root writes clean code.

On CodeQA, Qwen3-Coder with depth 0 (no sub-calls) scores higher than with depth 1, 2 or 3. What is the best reading?

Chapter 6

Reading the Results

Learn how to read Table 1, Table 2 and Figure 1, what each baseline is, and which claims the numbers support

A results table can look like a wall of numbers. Read it like a race. First ask who ran, on what track, and what each runner was allowed to use. Then read the times.

The tracks

The paper uses five tasks, chosen so that the needed work grows differently with length.

  1. S-NIAH. 50 single needle-in-a-haystack tasks. Find one phrase or number in unrelated text. Work is constant in length.
  2. BrowseComp-Plus (1K documents). Multi-hop questions over 1,000 documents, 6M to 11M tokens, 150 questions. The evidence documents are guaranteed to be inside.
  3. OOLONG (trec_coarse). 50 tasks over a list of questions that each need a semantic label, then an aggregate answer. Prompt length 131K tokens. Work is linear.
  4. OOLONG-Pairs. 20 queries that need all pairs of entries meeting a property. Prompt length 32K tokens. Scored with F1, a grade between 0 and 100 that rewards listing the right pairs and punishes both missed pairs and wrong ones. Work is quadratic.
  5. LongBench-v2 CodeQA. Multiple-choice questions about a code repository, 23K to 4.2M tokens.

The runners

Each runner gets the same task-agnostic prompt on every task. Base model: one direct call. CodeAct (with BM25 retrieval, a classic keyword-ranking search that fetches the best-matching snippets, or with sub-calls): a code-running agent that still receives the prompt in its window. Compaction agent: the summarize-when-full loop from Chapter 0. OpenCode and Claude Code: popular coding agents, each tried with the context loaded directly or offloaded to a file. RLM at depths 0 to 3. Models: GPT-5 (root) with GPT-5-mini sub-calls, Qwen3-Coder-480B-A35B, and Claude Opus 4.1 for Claude Code.

An asterisk marks a run where the method sometimes ran into the input limit. A 0.0 with an asterisk means the prompt did not fit at all. Explore the table below.

Explore Table 1

Choose a model and a task. Warm bars are RLM variants; grey bars are the other methods. A red label with a star means the prompt did not fit. The right edge shows average cost per task.

All values are the paper’s Table 1. Scores are accuracy, except OOLONG-Pairs (F1). Costs are average API dollars per task; “n/a” is the paper’s N/A. Claude Code was tried with Claude Opus 4.1 only, so that model has two rows.

What the table says

Observation 1. RLMs scale to the 10M-token range and beat the other task-agnostic methods, by up to 2x, at comparable cost. On BrowseComp-Plus, GPT-5 with an RLM scores 91.3. Compaction scores 70.5 and BM25 retrieval 51.0. The first gain is over 29 percent: 91.3 / 70.5 = 1.295. Read honestly, OpenCode with the corpus offloaded to a file scores 94.0, and Claude Code with offloading scores 84.0. A code agent that holds the data outside the window is already strong. That fits the thesis.

Observation 2. The REPL does most of the work for length. Sub-calls help most when the work is dense.

Observation 3. Figure 1 compares GPT-5 alone with an RLM, from 213 to 220 tokens. The base model drops fastest on the harder tasks. Beyond 214 tokens, the RLM wins consistently.

Observation 4. Cost stays in the same range. The median RLM run is cheaper than the median base run, but the average is higher, because a few runs wander. Cost is long-tailed (the paper’s Figures 11 and 14).

A note on one number. The paper says depth 1 beats the base model on OOLONG by 28.4 percent for GPT-5. The table cell gives 56.0 against 44.0, which is 27.3 percent. The 28.4 matches the depth 2 cell, 56.5 against 44.0. For Qwen3-Coder the paper says 33.3, and 48.0 against 36.0 gives exactly that. Read the table when the text and the cells differ.

Beyond long inputs: Table 2

Observation 5. The authors also test long reasoning on LongCoT-mini, with GPT-5.2. Problems have many linked sub-problems. A plain RLM improves overall from 38.7 to 50.6, but gets worse on MATH and CS. With a decomposition hint that tells the root to plan a graph and delegate each node, the score reaches 65.6.

GPT-5.2 on LongCoT-miniOverallMATHCHEMCSLOGICCHESS
Base model38.726.037.040.453.636.6
RLM, depth 150.65.650.011.086.793.0
RLM + decomposition hints65.632.052.046.099.099.0

The paper’s Table 3 checks the obvious objection: give the base model the same hints. It does worse, 28.6 overall. Without a REPL to keep sub-tasks apart, the hints confuse it. The gain comes from the environment, not from the hint text alone.

The failure mode, as a story. Symptom: the plain RLM scores 5.6 on MATH, below the base model’s 26.0. Measurement: the table shows the drop only on MATH and CS, the splits that need long chains of exact steps. Fix: the hint format in Appendix C.3, which says to orchestrate, not solve: delegate every reasoning step to sub-calls, memoize verified answers in a dictionary, and assemble the answer by lookup.

One more picture explains the trend. In Figure 1, each benchmark is run at lengths from 213 to 220, and the paper also plots the cost of each run (Figure 16). GPT-5 alone drops faster as tasks get harder, and the RLM drops more slowly. The RLM’s cost grows in proportion to the task’s complexity, and stays in the same order of magnitude as GPT-5’s.

In Table 1, a GPT-5 base-model cell on BrowseComp-Plus reads 0.0 with an asterisk. What does that mean?

Chapter 7

How Models Behave as RLMs

Replay four real trajectories, spot the habits that win and the ones that waste money, and read the paper’s own list of limits

Scores say how often an RLM wins. They do not say what it does. The paper’s Section 5 and Appendix E print step-by-step runs. Reading them is like watching a detective at work: first the room is scanned, then one lead is followed, then the lead is checked.

The common pattern: probe, decompose, verify

Across tasks, current models behave in a similar order. They probe the variable: print its length and its first lines to learn the format. They filter with ordinary code, often a regular expression built from what the model already knows. They decompose: split the prompt into slices and start sub-calls. They verify: ask a fresh sub-call to confirm. Then they return.

For long answers, there is a fourth habit. On OOLONG-Pairs the answer is a list of pairs, longer than any reply. The RLM labels the entries with sub-calls, then builds the pair list in code and returns the variable.

Replay four runs. Pick one, then press Step. The chips are the steps the paper describes. Note the cost at the end.

Replay a trajectory

Choose a run, then press Step to move through it. Colours: blue probes the prompt, pink is a sub-call, purple is a check, yellow is a repeat, green is a correct final answer, red is a wrong one.

Steps and costs are the paper’s Appendix E.1 to E.4 (total cost of each trajectory: $0.079, $1.12, $0.38, $0.27). Step wording is condensed from the paper’s own descriptions.

Reading the four runs

Run 1, the clean one. The question is about a festival, and the corpus is 1,000 documents, 8.3M tokens. GPT-5 first tries regular expressions with words from the question. It finds a snippet in chunk 6 and starts one sub-call on it. The answer, Maria Dalmacio, goes into a variable. It checks with two more sub-calls and returns. The whole run costs $0.079. For comparison, a straight-line estimate for GPT-5-mini reading 6M to 11M tokens in one pass is $1.50 to $2.75.

Run 4, divide and join. A 900K-token code repository. GPT-5 splits it into parts, asks one sub-call per part for clues, and a last sub-call joins the clues. It answers correctly for $0.27. The paper adds a caveat: this works when the task is not information dense.

Run 3, the spender. Qwen3-Coder writes a classifier that makes one sub-call per line, then runs it on the full input. That makes thousands of calls. The answer is right, and likely could be reached with far fewer calls. Cost: $0.38.

Run 2, the failure. Qwen3-Coder gets the pair list right in code on step 1. Then it keeps checking. It tries to return the variable with FINAL_VAR, but the answer is not accepted. It repeats the whole build five more times. In the end the root writes an answer from memory. That answer is wrong, and it never returns the correct list sitting in its variable. Cost: $1.12.

The failure mode, in the usual order. Symptom: a correct answer was built, then discarded. Measurement: the trajectory shows 11 or more steps for work that was done in step 1, and a wrong final reply. Fix: the authors point to prompt tuning for each model and to training a model as an RLM, which is Chapter 8. They note that distinguishing a final answer from a thought is brittle: in one trace the model returned its plan as the final answer.

Two sensitivities

Figure 4a changes the examples in the system prompt on OOLONG. The first decomposition the RLM tries gets much better when the prompt includes an in-context example, even an unrelated one. RLMs often recover from a bad first split, but a good one helps overall.

Figure 4b counts trajectories with at least one syntax error. RLM(Qwen3-Coder) has many more than RLM(GPT-5), even in correct runs. That explains why deeper recursion hurts Qwen3-Coder: sub-RLMs repeat the same slips.

What did not work, and what is still open

Appendix B lists negative results. One prompt for all models fails: Qwen3-Coder needed an extra line about sub-call costs. Weak coders struggle: Qwen3-8B without training cannot use the REPL well. Thinking models can run out of output tokens: Qwen3-235B improved from 30 to 38 on OOLONG, but some runs spent their output budget on thinking. Blocking sub-calls are slow: the paper’s sub-calls run one after another, so runtimes are long-tailed.

Section 7 adds the larger limits. Sub-call cost can explode. Better guardrails are an open problem. Harder, more natural long-context tasks are untested. Asynchronous calls and sandboxed REPLs could cut cost and time, but add complexity.

One habit is worth copying. In Run 1, the root checked its answer with two extra sub-calls before it committed. That check cost a few cents and removed a class of mistakes. It is the same idea as checking a sum a second way. The cost of a check is small next to the cost of a wrong answer in a long pipeline.

In the OOLONG-Pairs trajectory by Qwen3-Coder, what went wrong after step 1?

Chapter 8

Training a Native RLM

Follow the paper’s small recipe that turns Qwen3-8B into a better RLM, and see what it did and did not prove

Until now we prompted off-the-shelf models to act as RLMs. They do it, but clumsily: syntax slips, repeated checks, thousands of needless calls. A natural next step is to teach a model to be an RLM. The authors try this at a small scale, and call the result RLM-Qwen3-8B, “the first natively recursive language model.”

The key insight: train only the root

An RLM trajectory can be huge, with thousands of sub-calls. Which part needs training? The authors argue: not the leaves. A leaf sub-call is an ordinary request. “Being an effective sub-call model is roughly similar to being a general purpose reasoning model.” The hard part is being the root: operating the REPL and knowing when a sub-call helps.

So the recipe trains only the root’s behavior. That makes training far cheaper. The root’s job is one turn at a time: read the history, write the next piece of code.

The recipe, step by step

It is rejection fine-tuning: let a strong teacher try, keep only the good attempts, and train a small student to copy them. Slide through the six stages. The funnel on the left narrows as filters apply.

Walk the training recipe

Choose a view. In Recipe, drag the stage slider from 1 to 6. Scores shows Figure 3a. Length shows Figure 3b.

1 of 6

Counts, percentages and compute are the paper’s Appendix A. The scores are read from Figure 3a. The MRCRv2 points (about 0.03, 0.25 and 0.88 at steps 0, 50 and 100, against a dotted Gemini 3.1 Pro line near 0.26) are read off the plot of Figure 3b and are approximate.

  1. Collect. Qwen3-Coder-480B, as an RLM with Qwen3-8B sub-calls, runs on 750 English LongBenchPro tasks, three tries each: 2,250 candidate trajectories. These tasks are unrelated to the four test benchmarks.
  2. Filter. Drop trajectories that score exactly 0.0 or never go past one turn. 1,072 remain.
  3. Split into turns. Each root turn becomes one training example. Input: the full history so far. Output: the code the teacher wrote at that turn.
  4. Cut long inputs. Drop turns whose history exceeds about 100,000 characters, the most Qwen3-8B can take.
  5. Patch template mistakes. The teacher often broke the output rules. 16 percent of turns put a final answer in the wrong form, and 13 percent used a variable name as a final answer. A program finds and repairs these.
  6. Fine-tune. Using the prime-rl library: batch size 64, 300 steps, 48 H100 hours.

The loss, derived

Fine-tuning copies the teacher with the standard next-token loss. For one training example, the model sees the history x and must predict the teacher’s reply y, one token at a time. The loss is the average of how surprised the model is by each teacher token.

L
The loss for one turn. Lower means the student matches the teacher better.
1/T
Average over the T tokens of the teacher’s reply.
log pθ(yt | x, y<t)
The log of the probability that the student, with weights θ, gives the teacher’s token yt, given the history x and the reply so far.

Illustrative: if the student gives each of four teacher tokens probability 0.5, then L = −(4 × ln 0.5) / 4 = 0.693. A perfect copy gives 0.

What it bought

On the four benchmarks, the RLM scaffold around plain Qwen3-8B scores 26.0 on CodeQA, 2.0 on BrowseComp-Plus, 24.0 on OOLONG and 4.26 on OOLONG-Pairs. After training: 32.0, 14.0, 32.04 and 5.17. That is a median gain of 28.3 percent. The trained model is also much cheaper and more than 3 times faster, because it makes fewer mistakes and fewer wasted calls. It approaches vanilla GPT-5 on three of the tasks.

A second experiment tests length. Qwen3-4B-Instruct is trained with reinforcement learning with verifiable rewards (RLVR): it tries, a program scores the answer, and the score trains it. The task is MRCRv2, where the model counts and reproduces instances in a long text. Training uses the 32K to 64K split with two needles, for 150 steps. The test is the 1M-token split with eight needles. The score climbs past a 1M-context frontier model (Gemini 3.1 Pro). Skill learned on short inputs carries to long ones.

The failure mode, in the usual order. Symptom: the student mimics a teacher that mixes FINAL(answer) with FINAL(variable). Measurement: 16 percent and 13 percent of the teacher’s turns break the template. Fix: a patch program before training, which the authors say led to “much better performance.”

Be careful with the scope. It is one small model, a few hundred steps, tasks unrelated to the test, and a single recipe. The authors call for much larger work: more models, more data, and on-policy online rollouts. They hope native RLM training becomes “a new axis of scale.”

Why does the recipe use rejection, and not train on every attempt? A trajectory that scored 0.0 teaches the student the teacher’s mistakes. Dropping those costs data, but it makes each remaining example a demonstration of working behavior. That is the same bet made by earlier methods that bootstrap reasoning from a model’s own successful attempts. The authors suggest that RLM trajectories can be seen as a form of reasoning trace, and so can be trained the same way.

Why does the recipe focus on training the root model’s turns and not the sub-calls?

Chapter 9

Field Guide

Keep the numbers, a decision checklist and the core code of an RLM, then see where the idea sits in the field

You can now rebuild the paper from memory. A prompt too long to read, or too dense for one read, becomes a variable in a REPL. The root model sees only short metadata and the short results of code it writes. Code slices the prompt and calls a model on each slice. Code builds the answer in a variable and sets Final. Three choices separate this from a look-alike scaffold: the prompt lives outside the window, the answer is built outside the window, and recursion is symbolic.

The numbers that matter

WhatNumberWhy it matters
GPT-5 window272K tokensBrowseComp-Plus prompts are 6M to 11M, over 20 windows
BrowseComp-Plus, GPT-5base 0.0*, compaction 70.5, RLM 91.3The base model cannot fit the prompt
OOLONG-Pairs, GPT-5base 0.1, depth 0: 43.9, depth 3: 76.0Recursion helps quadratic work
OOLONG, GPT-5base 44.0, RLM depth 1: 56.0Gain inside the window (text says 28.4%)
CodeQA, Qwen3-Coderdepth 0: 66.0, depth 1: 56.0Sub-calls are not always needed
Abstract, median on GPT-5+26% vs compaction, +130% vs CodeAct with sub-calls, +13% vs Claude CodeThe headline claims
LongCoT-mini, GPT-5.238.7, RLM 50.6, with hints 65.6RLMs also help long reasoning
One clean run$0.079 on 8.3M tokensMedian RLM run is cheap; the tail is not
Training data2,250 to 1,072 trajectories, 300 steps, 48 H100 hoursA very small recipe
RLM-Qwen3-8B vs Qwen3-8B as an RLMmedian +28.3%, over 3x fasterNative training pays

A checklist: should you build an RLM?

Toggle what is true about your task. The advice follows the paper’s own observations. It is guidance, not a measurement.

Pick a starting design

Press each trait that describes your task. The advice below updates.

Rules of thumb drawn from Observations 1 to 3 and Appendix B of the paper: the REPL gives length, sub-calls give density, a built-up variable gives long output, and a capable coding model is needed as the root.

  1. Root model. Pick a strong coder. Weak coders struggled as RLMs. Tune the prompt per model.
  2. Handle. Put P in a variable. Tell the model its type, length and chunk sizes.
  3. View. Show the root a short view of every output. Cap each turn.
  4. Sub-model. Use a cheaper model for leaves. Batch slices to about 200K characters.
  5. Stop rule. Support FINAL and FINAL_VAR. Guard against a plan returned as the answer.
  6. Budget. Cap turns and calls. Time out outliers. Run the REPL in a sandbox.
  7. Depth. Start at 1. Go deeper only when the work is dense and the root writes clean code.

The core, as code

This sketch follows Algorithm 1. M is the root model, sub is the sub-model, and both are functions from a string to a string. Run model-written code only in a sandbox.

pythonimport re, io, contextlib

def rlm(P, query, M, sub, max_turns=20, show=300):
    env  = {"context": P, "llm_query": sub, "re": re}       # P is a variable, not a prompt
    hist = [SYSTEM_PROMPT,
            f"Query: {query}\ncontext: str, {len(P)} chars, starts: {P[:200]!r}"]  # constant-size metadata
    for _ in range(max_turns):
        reply = M(hist)                                  # root: list[str] -> str
        outs = []
        for code in re.findall(r"```repl\n(.*?)```", reply, re.S):
            buf = io.StringIO()
            with contextlib.redirect_stdout(buf):
                try: exec(code, env)                # variables persist in env
                except Exception as e: print("Error:", e)
            out = buf.getvalue()
            outs.append(f"[stdout, {len(out)} chars] " + out[:show])   # only a short view
        hist += [reply] + outs
        m = re.search(r"FINAL_VAR\((\w+)\)", reply)
        if m: return str(env[m.group(1)])       # the answer lives in a variable
        m = re.search(r"FINAL\((.*)\)", reply, re.S)
        if m: return m.group(1)
    return M(hist + ["Give your final answer now."])

Where this sits

Long-context work has two old directions: change the architecture to read longer inputs, or build a scaffold around the model. RLMs take the second. Compaction and memory hierarchies manage the window with fixed rules. In an RLM the model decides what to read. Retrieval picks snippets by similarity before the model starts. An RLM can run a search, but also loops over everything. Sub-agent systems delegate, but must write each delegation as text. An RLM delegates from code, in loops.

It is a harness idea, which is why it belongs to lecture 4. The harness decides where state lives and what the model sees. Harness Evolution traces how that design grew, and this paper pushes it to the limit: the whole prompt moves out of the window.

Keep going

Credit and sources

The paper “Recursive Language Models” is by Alex L. Zhang, Tim Kraska and Omar Khattab of MIT CSAIL, arXiv 2512.24601 (v3, May 2026). The official code is at github.com/alexzhang13/rlm. This lesson re-teaches the paper in our own words and devices. Every score, count and cost comes from the paper’s tables, appendices and figures. Toy numbers are marked as illustrative where they appear. Read the original for the full tables, prompts and trajectories.

The takeaway. A prompt does not have to enter the model to be understood. Keep it in memory, let the model write code that reads it in pieces, and let code call the model again and again on those pieces. The window stops being the limit. The limits become the root model’s skill at writing code, and your budget for calls.
You must answer questions over a 5M-token log, and the answer needs facts from nearly every line. Which design follows the paper?

Now press Present or Teach and explain the loop out loud, from memory: where the prompt lives, what the root sees, how a slice reaches a sub-call, and why the answer is built in a variable. Then go back to the instrument at the top, pick the 8.3M task, and switch between the three readers. You should now be able to say why only one of them can finish.

Recursive Language Models, by Alex L. Zhang, Tim Kraska and Omar Khattab (MIT CSAIL)
Read the paper · Official code · MIT MAS.S62 AI4AI schedule · Lecture 4: Harness Evolution · Back to Gleams