Skip to content

[rl] Store each turn's prompt as a delta on the previous turn (linear-size multi-turn rollouts) (1/2) - #5273

Merged
felipemello1 merged 9 commits into
mainfrom
felipemello1/multiturn/1-delta-prompts
Oct 12, 2026
Merged

felipemello1 merged 9 commits into
mainfrom
felipemello1/multiturn/1-delta-prompts

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

TLDR: each RolloutTurn now stores only the prompt tokens that differ from the previous turn, not its full prompt, so a rollout grows linearly with turns instead of quadratically. On a synthetic 120-ply chess group, the token fields pickle to 17 MB instead of 236 MB and unpickle on the controller in 0.11 s instead of 1.83 s. Today's chess runs (~11 plies) unpickle in under 0.12 s per group, so for chess this is headroom; Terminal-Bench rollouts reach ~45 turns at ~95K-token contexts (not measured here). Packed training batches are bitwise identical.

Problem

  1. Every turn stores its full prompt. RolloutTurn.prompt_token_ids is the whole conversation so far, so K turns hold sum(prompt_k) tokens: O(K^2).
  2. The group crosses a process boundary. The rollout worker pickles each finished RolloutGroup, and the controller unpickles it on its event loop.
  3. Long games pay quadratically. A chess player's prompt grows ~1.7k tokens per turn, so a 120-ply group holds 51.7M list entries where 2.7M would do.
  4. Cost: at 120 plies, 236 MB to pickle and 1.83 s of the controller's event loop to unpickle, per group.

Solution

  1. One delta per turn. prompt_token_ids becomes prompt_prefix_len + prompt_delta_token_ids, where prompt == previous_turn_tokens[:prompt_prefix_len] + prompt_delta_token_ids.
  2. split_prompt(prompt, previous) fills both from the longest common prefix, so a rewritten history (e.g. thinking stripped) also stores only what changed. TokenEnv calls it, since it builds each prompt (TokenEnvOutput.next_prompt_prefix_len), so the rollout loop never handles tokens; the verifiers example calls it too.
  3. The builder rebuilds a new sample's prompt from the last sample's token_ids, and opens samples exactly where it did before.
  4. Unchanged: what the trainer receives, the generator calls, and prompt_messages (still full).
turn  prompt (before: stored in full)   after: stored as (prompt_prefix_len, prompt_delta_token_ids)
0     [P]                               (0, [P])
1     [P, C0, E0]                       (len(P+C0), [E0])
2     [P, C0, E0, C1', E1]              (len(P+C0+E0), [C1', E1])    # thinking stripped from C1

Results

synthetic 16-rollout chess group, 1.1k-token completions, 600-token boards; token fields only; CPU (x86)
                                              before -> after
 60 plies: list entries / pickle / unpickle   13.6M / 63 MB / 0.46 s  ->  1.4M / 8.5 MB / 0.05 s
120 plies: list entries / pickle / unpickle   51.7M / 236 MB / 1.83 s ->  2.7M / 16.9 MB / 0.11 s
packed TrainingMicrobatch, 78 batches x 3 packings, 658 branch samples
(rewrites, resets, every turn rewritten, NaN logprobs):                    bitwise identical

You may ask:

  • Why not a message graph like verifiers v1? Our rollouts are chains, so today it would only share the first prompt across siblings, under 1% of a 120-ply group. A TODO keeps it for turns that fork (subagents, tree search).
  • Why not store the full prompt only on a break? Renderers that strip past thinking break the prefix every turn, which stays O(K^2). The longest common prefix keeps those linear too.

NOTE:

  • With log_tensors=True, the recorder writes prompt_prefix_len + prompt_delta_token_ids instead of prompt_token_ids.
  • RolloutTurn.num_prompt_tokens replaces len(prompt_token_ids) in the rollout metrics.
  • build_from_group drops a rollout whose turn after the first has no completion (e.g. a request aborted before its first token) and counts it in training_sample_builder/num_rollouts_dropped_empty_completion. Before, rollout_to_training_samples raised and stopped the run.
  • A rollouter that builds RolloutTurn by hand must call split_prompt. Otherwise the builder raises: a full prompt stored as the delta would silently open one sample per turn.

Test plan

  • pytest tests/rl/unit_tests/cpu (verifiers 0.3.1 installed): 443 passed, 5 skipped, 2 failed. Main: 432 passed and the same 2 failed (test_verifiers_terminal_bench.py still reads the renamed train_dataset).
  • New: test_delta_prompts_rebuild_the_full_prompt_samples (the real rollout worker and TokenEnv on 20 random multi-turn rollouts vs the full-prompt rule), test_env_returns_each_next_prompt_as_a_delta, test_split_prompt, test_rewrite_that_keeps_a_prefix_branches_then_continues, test_prefix_that_is_not_the_longest_raises, test_verifiers_second_branch_stores_its_prompt_as_a_delta_on_the_first.
  • Bitwise check: the same random groups packed on main and on this branch.
  • Same data as main, end to end: the real TokenEnv + RolloutWorker on 618 rollouts (18 edge cases: empty delta, strict prefix down to an empty prompt, retries, resets, env errors, truncation, abort, NaN logprobs, prompt too long) and VerifiersRollouter.trace_to_rollout_turns on 4,000 random message trees. Every rebuilt prompt, training sample, rollout metric and packed microbatch tensor is identical to main, with and without the stacked TrainingSample-tensor PR. A copy that splits against the prompt without the completion fails the same check.

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 11, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 11, 2026
@felipemello1
felipemello1 added this pull request to stack #5275 October 11, 2026 05:30

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

idea sgtm

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude the idea sgtm, please review and give succinct feedback

@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 7s —— View job


Review: delta prompts (1/2)

I found no correctness bugs. The builder and both rollouters agree on what "previous" means: the rollouter uses the previous turn's prompt + completion, and the builder uses training_samples[-1].token_ids. Those two are always equal, because every turn that isn't skipped is appended to the last sample. The "longest prefix" check catches a full prompt stored as the delta, and it only reads one token, so it's cheap. A few small points:

  1. verifiers/rollouter.py:402-405: element type of token_ids. The old code used list(token_ids[:absolute_start]), and completion_token_ids still wraps its slice in list(...). If branch.token_ids is ever a tuple (verifiers is an external lib), two things happen:

    • split_prompt's fast path (tuple[:n] == list) is always False, so every turn takes the per-token Python loop.
    • prompt_delta_token_ids becomes a tuple, and prev[:k] + delta in the builder (training_sample_builder.py:268-270) raises TypeError.

    I couldn't check the verifiers source in this run. Either confirm it is always a list, or keep list(...), e.g. token_ids = list(branch.token_ids) once per branch.

  2. rollouter.py:470: transient work per turn. previous_token_ids = prompt_token_ids + completion.token_ids, plus the slice in split_prompt's fast path, copy O(context) tokens every turn. Over a rollout that is still O(K^2) CPU work, though not stored memory. That's fine for now; a one-line note would stop someone from "optimizing" it later and thinking storage is still quadratic.

  3. The split_prompt contract is only enforced in the builder. A rollouter that gets it wrong only fails at training-sample build time, away from the cause. That's acceptable. Optionally, add an assert (or the same check) in split_prompt's callers' tests rather than at runtime; no change needed.

  4. rollout_recorder.py:164-165: format break. The log_tensors JSONL schema changes (prompt_token_ids → prompt_prefix_len + prompt_delta_token_ids). Any offline tooling that reads these dumps will break silently. Consider a tiny rebuild_prompts(turns) helper next to split_prompt so readers don't each re-implement the replay; it would also make test assertions shorter.

  5. Nit, types.py:164. The fast path also matches when previous_token_ids == [], so the first turn returns (0, prompt[0:]), which is a full copy. That's correct; just noting it is intentional.

The overall design looks good to me: longest common prefix over break-only, bitwise-identical packing, and the TODO for a graph representation. The rename of train_dataset in test_verifiers_terminal_bench.py is pre-existing on main and outside this PR.

Felipe Mello added 4 commits October 11, 2026 12:23
…-size multi-turn rollouts)

RolloutTurn stored its full prompt every turn, so a rollout held O(num_turns**2) tokens, all pickled
from the rollout worker to the controller. On a 16-rollout chess group at 120 plies that was 236 MB
and 1.83 s to unpickle on the controller's event loop, per group.

RolloutTurn.prompt_token_ids becomes prompt_prefix_len (tokens shared with the previous turn's
prompt + completion) + prompt_delta_token_ids (the rest); split_prompt computes both from the
longest common prefix, so continuing and rewritten histories are both linear. The builder rebuilds
a branch's prompt from the previous turn's tokens and opens samples exactly where it did before;
packed training batches are bitwise identical.
…s not the longest; docstrings

The builder now also raises when a turn claims too few shared tokens (e.g. a full prompt stored as
the delta), so a hand-migrated rollouter fails loudly instead of opening one sample per turn.
prompt_prefix_len's docstring states the longest-prefix rule; split_prompt is a plain loop; the
graph TODO names verifiers v1 and what a graph would add.
RolloutTurn's docstring draws the delta once, including a turn whose history was rewritten
(thinking stripped); the field and Rollout.turns docstrings shrink to one line each. The builder
example no longer claims a compacted prompt shares nothing with the previous turn (BOS and the
system prompt stay). A new test drives the real RolloutWorker._run_single_rollout over 20 random
multi-turn rollouts (continue, strip thinking, shrink to a prefix, reset) and checks the builder
opens and fills samples exactly as the full-prompt rule does.
@felipemello1
felipemello1 force-pushed the felipemello1/multiturn/1-delta-prompts branch from 6930add to c61dfe4 Compare October 11, 2026 19:31
Felipe Mello added 5 commits October 11, 2026 14:52
RolloutTurn shows the rebuild rule as one formula and defines P/Cn/En; split_prompt gets Args and
Returns; the builder's example gets a legend; the prefix check lists its two rejected cases; the
Rollout.turns TODO says what forking from any earlier turn would buy.
RolloutTurn and split_prompt share one example in token ids (prompt [0, 1, 2], completion [3]). The
builder's prefix check becomes two checks with their own example and message: reusing more tokens
than the previous turn has, and could_reuse_one_more (the first new token still matches). Same
logic as before. The rollout_to_training_samples example is back to main's version; the storage
format is explained once, in RolloutTurn.
…checks

TokenEnv builds each prompt, so it now also splits it: TokenEnvOutput.next_prompt_prefix_len (0 on
the first prompt) and the next_prompt_delta_token_ids property. RolloutWorker copies them into
RolloutTurn and no longer handles tokens. The random rollout-worker test drives the real TokenEnv
with a renderer that bridges or re-renders a rewritten history; a TokenEnv test checks the bridge
and re-render cases. The builder's two prefix checks get a blank line each, and the too-many
example says e.g.
next_prompt_prefix_len says it is the longest shared prefix and that a TokenEnv must set it with
split_prompt from the tokens it returns; split_prompt is called with kwargs. The Rollout.turns TODO
says what forking from an earlier turn buys. Tests: the rewriting renderer keeps one list of prompts
and returns copies; the TokenEnv test re-renders a prompt that shares 4 tokens, so a stale previous
prompt would give a different split.
…pping the run

build_from_group used to pass such a rollout to rollout_to_training_samples, which raises and stops
the batcher loop. It now drops the rollout and counts it in
training_sample_builder/num_rollouts_dropped_empty_completion. rollout_to_training_samples still
raises when called directly.
@felipemello1
felipemello1 merged commit c918c08 into main Oct 12, 2026
wwwjn added a commit that referenced this pull request Oct 12, 2026
#5290 added test_compute_rollout_metrics_folds_generator_metrics with
RolloutTurn(prompt_token_ids=...), but #5273/#5274 had replaced that field
with prompt_prefix_len / prompt_delta_token_ids and made the per-token fields
numpy arrays, so the test fails on main with a TypeError.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants