Repository navigation
[rl] Search-R1: multi-turn retrieval-augmented GRPO - #3602
Conversation
| completion_offset:next_completion_offset | ||
| ] | ||
| completion_offset = next_completion_offset | ||
| else: |
There was a problem hiding this comment.
Where is the if part of this else?
| prompt_token_ids = [lr.next_prompt_token_ids for lr in active] | ||
| # TODO: pass the remaining budget (max_rollout_tokens - len(prompt)) to the | ||
| # sampling_config, to limit generation length in one turn. | ||
| completions, turn_metrics = self._get_rank_0_value( |
There was a problem hiding this comment.
There seems a barrier between two consecutive turns? So there's no continuous batching across turns.
|
thanks. can you briefly describe why search-r1 is a good example to stay in titan rl? |
Ports the Search-R1 example (upstream pytorch#3602) onto our CB + async + losses stack as `examples/search_r1/`. The model <think>s, emits <search>query</search> (the env injects <information> from a retriever), and finally <answer>s; reward is exact-match + format. Two infra adds the example needs: - `TokenEnv.max_num_turns`: cap assistant turns; end TRUNCATED_LENGTH past it. - `SamplingConfig.stop` / `include_stop_str_in_output`: pass vLLM stop strings so generation halts at </search> / </answer> and keeps the tag for parsing. Example layer (data / env / retrieval / rubric / rollouter) matches our alphabet_sort conventions unchanged; uses DAPO. Config `rl_grpo_qwen3_0_6b_search_r1` (flex, 4 GPUs). A real run needs the Search-R1 dense-retrieval server + NQ/HotpotQA parquet; smoke-tested here with a synthetic parquet + mock retriever (8 steps: multi-turn search->inject->answer flow, stop strings, max-turn truncation, EM reward, async hotswap — all exercised). Tests: test_search_r1.py + suite; 189 passed.
This comment was marked as outdated.
This comment was marked as outdated.
|
Search-R1 multi-turn retrieval GRPO reproduces slime's Shared slime-aligned recipe: pure-EM 0/1 reward, standard GRPO with group-std-normalized advantages, 256 samples/step (32 prompts × group 8, no dynamic sampling), clip-higher (0.2/0.28), KL-to-reference ( Qwen3-8B — gen TP=2 + train TP=4 — EM 0.258 → 0.356 (peak @ step 40)
Qwen3-1.7B — gen TP=4 + train TP=1 — EM 0.144 → ~0.29 plateau (peak 0.308 @ step 185, full 0–270)
(slime reference, Qwen2.5-3B: ~0.096 → ~0.28.) Next step: refactor + rebase onto |
|
Per-step time decomposition (Qwen3-1.7B Search-R1, run Setup: devvm 8×H100 — generator TP=4, trainer TP=1, GPU-faiss retriever sharded on 2 GPUs; 256 samples/step (32 prompts × group 8), seq_len 4096, multi-turn (≤4 search turns). Averaged over steps 61–80 (the three phases are sequential and sum to 100% of the step):
Rollout sub-stats (per step, mean): decode 1.32 s, time-to-first-token 1.02 s, queue 0.87 s, ~35.6K output tokens, response_length ~62, total_length ~863 (prompt+obs+gen across turns). Retrieval is bundled inside rollout and is small — GPU faiss served 32K requests across 80 steps with 0 errors/timeouts (32 concurrent ≈ 1.7 s; the earlier CPU-faiss ~50 s/query bottleneck that caused empty-retrieval reward-hacking is gone). Takeaways:
|
| # Frozen reference model for the KL-to-reference penalty. Only built when | ||
| # kl_coef > 0 (otherwise it would waste a full model's worth of memory). | ||
| # It is the *initial* policy: copy the just-loaded base weights, then freeze. | ||
| self.ref_model = None |
There was a problem hiding this comment.
probably don't need this right now?
| max_tokens: int = 100 | ||
| """Maximum number of tokens to generate per completion.""" | ||
|
|
||
| stop: list[str] = field(default_factory=list) |
There was a problem hiding this comment.
There was a problem hiding this comment.
I'm confused. Why would we need both stop_token_ids and stop? Generator only works with tokens not strs.
There was a problem hiding this comment.
They're not redundant — different mechanisms:
stop_token_ids= the renderer's role-boundary token (<|im_end|>), a single token, filled automatically viarenderer.get_stop_token_ids(). Ends the assistant turn.stop= Search-R1's</search>/</answer>tags, which end a turn mid-message (so the env can retrieve and inject<information>). These are 3 tokens each (</search>→[522, 1836, 29]=['</','search','>'], not in vocab, and context-dependent), so they can't be expressed asstop_token_ids(single-token match). Hence vLLM's native stringstop.
The renderer only knows role boundaries, not these content-level tags. The only token-only alternative is to model search as a tool call (then </tool_call> is a single token and the renderer handles it) — we can have follow up PR on that
| order). Without this the iterator advances across passes, so every eval | ||
| would score a different subset — making the eval trend non-comparable. | ||
| """ | ||
| self._validation_dataset = self._validation_dataset_config.build() |
There was a problem hiding this comment.
| self._validation_dataset = self._validation_dataset_config.build() | |
| self._validation_dataset = config.validation_dataset.build() |
Rework the Search-R1 example to run on main's framework instead of the custom
multi-turn controller from the original PR (#3602):
- Drop the custom multi-turn loop, episode flattening, loss-mask, and batched
generator changes — main's Rollouter._run_single_rollout (continuous batching,
no per-turn barrier) + rollout_to_episodes already provide them.
- examples/search_r1/: env.py now also holds the dense-retrieval client and the
per-rollout turn budget (max_assistant_turns); rubric/data unchanged. Configs
live in examples/search_r1/config.py, imported into config_registry so
--config rl_grpo_qwen3_{1_7b,8b}_search_r1 resolve.
- The slime recipe is added as default-OFF core knobs, set only by the search_r1
config (every other config keeps vanilla GRPO):
* SamplingConfig.stop / include_stop_str_in_output (stop at </search>,</answer>)
* GRPOLoss.clip_eps_high (clip-higher) + kl_coef/kl_loss_type (KL-to-reference,
with a frozen reference model in PolicyTrainer, gated on kl_coef>0)
* RLTrainer.advantage_std_normalization (standard GRPO)
* RLTrainer.validation_freq (periodic eval, to trace the EM curve)
Addresses review feedback: removes the multi-turn-barrier controller, merges
retrieval into env.py, moves configs into the example folder, drops personal
paths from the README. Unit tests (13) + pre-commit all pass.
vLLM cudagraph (the generator default, cudagraph_mode=full) emits degenerate generations + NaN logprobs in this stack (cf. PR #3593 cudagraph-NaN note); the reference 1.7B run ran eager. Set generator.cudagraph.enable=False in the search_r1 config so generation is coherent and matches the reference curve.
Handle vLLM's cudagraph NaN logprobs in the loss instead of running eager: mask out tokens whose importance ratio is non-finite (drop from loss + denominator, cleaner than nan->0 which trains them as on-policy) and clamp |log_ratio| to GRPOLoss.Config.max_log_ratio (10.0). Keep main's generator_logprob_nan_frac metric (now measured against the original response mask). Re-enable the vLLM generator cudagraph in the search_r1 config.
…ion) Two controlled runs (only generator.cudagraph.enable changed) confirm cudagraph 'full' produces degenerate 'locklock' generation at step-0 validation, before any loss runs, so the GRPOLoss NaN-drop cannot fix it (generation corruption is upstream of the loss). Keep eager; matches the reference 1.7B curve. NaN-drop loss stays for robustness; cudagraph re-enable awaits a generator-side root-cause.
…for search_r1 Full cudagraph capture at large batch (search_r1 hits max_num_seqs 256-500) corrupts generation in this vLLM stack (degenerate 'locklock' tokens + NaN logprobs at step-0), while the working alphabet_sort config only captures up to 40. Add a max_capture_size knob (default None = unchanged) that caps capture sizes; batches above it run eager. search_r1 enables cudagraph with cap=64.
…rse outputs don't crash A completion message can carry renderer parse outputs that aren't JSON serializable (e.g. ParsedToolCall in tool_calls when the qwen3 renderer parses a tool-call-like span). The recorder's json.dumps then raises TypeError and kills the run mid-training. Stringify such objects with default=str.
26d4071 to
4b183e3
Compare
|
Rebased onto Qwen3-8B — rebase
|
| step | 0 | 10 | 20 | 30 | 40 | 50 |
|---|---|---|---|---|---|---|
ref 2tusjecg EM |
0.258 | 0.300 | 0.320 | 0.340 | 0.356 | 0.342 |
rebase n4ds9e4x EM |
0.262 | 0.394 | 0.378 | 0.360 | 0.354 | 0.362 |
Rebase reaches EM 0.26 → ~0.43 (peak 0.432) and stays search-based (response_length ~80 throughout) — matches the reference behavior.
Qwen3-1.7B — rebase zq5yq0yn vs ref 52r5ytjc
| step | 0 | 20 | 40 | 60 | 80 | 100 |
|---|---|---|---|---|---|---|
ref 52r5ytjc (EM / resp_len) |
0.144 / 141 | 0.214 / 107 | 0.238 / 96 | 0.282 / 66 | 0.288 / 68 | 0.292 / 81 |
rebase zq5yq0yn (EM / resp_len) |
0.140 / 140 | 0.276 / 85 | 0.300 / 76 | 0.276 / 49 | 0.334 / 15 | 0.358 / 14 |
Rebase EM 0.14 → ~0.40 (matches/exceeds the reference's ~0.29 plateau). One behavioral note for checkers: at 1.7B the greedy-eval response_length drops to ~15 past the plateau — the small model increasingly answers directly from parametric memory rather than searching, so its EM is partly recall-driven. The 8B keeps searching (resp ~80). Same recipe at both scales, so this looks like a small-model + pure-EM effect rather than an implementation difference (the original 1.7B ref 52r5ytjc stayed search-based, so worth a look).
Please check the linked runs.
tianyu-l
left a comment
There was a problem hiding this comment.
I don't think we are interested in taking GRPO with KL penalty. Can we have a "clean" recipe working without it?
| # Frozen reference model for the KL-to-reference penalty. Only built when | ||
| # kl_coef > 0 (otherwise it would waste a full model's worth of memory). | ||
| # It is the *initial* policy: copy the just-loaded base weights, then freeze. | ||
| self.ref_model = None |
| # Some renderer parse outputs (e.g. ParsedToolCall in a completion | ||
| # message's tool_calls) are not JSON-serializable; stringify them so | ||
| # recording never crashes the run. | ||
| default=str, |
There was a problem hiding this comment.
This is also being addressed in #3142
so remove for now
felipemello1
left a comment
There was a problem hiding this comment.
please address these last comments. Thanks for the work on this PR!
cc: @tianyu-l in case you have any other comments
…elipemello1) - data.py / 8B config docstrings: apply Felipe's shorter wording. - rollout_to_episodes: raise if rollout.advantage is None, so a Rollouter that forgets to fill it fails loudly instead of silently training on a bad advantage.
|
Thanks @felipemello1 — addressed the latest round:
|
| config.hf_assets_path = "torchtitan/experiments/rl/example_checkpoint/Qwen3-8B" | ||
| config.trainer = dataclasses.replace( | ||
| config.trainer, | ||
| training=TrainingConfig(dtype="bfloat16"), |
There was a problem hiding this comment.
why dtype bf16?
For memory concern, we should use activation checkpointing.
There was a problem hiding this comment.
are you saying that we should do the training in fp32? That sounds odd to me. What i see commonly in both RL and SFT is training using bf16 (or fp16), or even lower precision
There was a problem hiding this comment.
@felipemello1
I was thinking it should be mixed precision -- master weights and optimizer states should be in fp32, while computation in bf16 -- the same as pretraining and sft.
I'd be very surprised if otherwise.
| _MAX_LOG_RATIO = 10.0 | ||
|
|
||
|
|
||
| class DAPOLoss(Configurable): |
There was a problem hiding this comment.
now that we have a dedicated folder for losses, should we also move the GRPOLoss from trainer to here? In addition, GRPOLoss is a special case of DAPOLoss, we can define grpo loss as a thin layer on top of dapo loss.
| policy_logprobs: torch.Tensor, | ||
| generator_logprobs: torch.Tensor, |
There was a problem hiding this comment.
nit: both trainer and generator are policies, i would suggest using trainer_logprobs to replace policy_logprobs.
| Computes the PPO-style clipped objective at the token level:: | ||
|
|
||
| ratio_t = exp(policy_logprob_t - ref_logprob_t) # π_θ / π_old | ||
| ratio_t = exp(policy_logprob_t - old_logprob_t) # π_θ / π_old |
There was a problem hiding this comment.
nit: both old and generator are used to denote generator logprobs.
|
|
||
| shuffle: bool = True | ||
| """Shuffle row order (with ``seed``), reshuffling on each wrap. Set False for | ||
| validation so the first N rows are a fixed, file-order held-out set.""" |
There was a problem hiding this comment.
this is confusing to me. my understanding is that for different validation runs, use shuffle=False will give us deterministic order of samples for different runs. maybe say 'Set False for validation so the order is deterministic: a given validation step then draws the same samples across runs`.
| async with session.post(url, json=payload) as resp: | ||
| resp.raise_for_status() | ||
| data = await resp.json() | ||
| except Exception: |
There was a problem hiding this comment.
this is not robust. suppose there is a consistent search failure, the model will silently learns from empty output.
| return out | ||
|
|
||
|
|
||
| async def _search(query: str, *, url: str, topk: int, timeout_s: float = 60.0) -> str: |
There was a problem hiding this comment.
how about adding timeout_s into config?
| - ``no_search_penalty`` > 0: a correct answer that never called the search tool | ||
| scores ``score - no_search_penalty``. | ||
| - ``retrieval_score`` > 0: a wrong/missing answer still gets this credit if a | ||
| search surfaced a gold answer. |
There was a problem hiding this comment.
gold answer or golden answer?
pandas was an example-only extra dep; datasets (a core torchtitan dep) both downloads the HF parquet and reads it, so use load_dataset and drop pandas + hf_hub_download. requirements.txt now only needs aiohttp.
The estimator isn't GRPO-specific (search_r1 uses it with DAPO loss), so give it a general name; other advantage schemes can be added under it later.
shuhuayu
left a comment
There was a problem hiding this comment.
Thanks for the great work, left some comments.
| if not isinstance(content, str): | ||
| continue | ||
| normalized = _normalize_answer(content) | ||
| if any(g in normalized for g in normalized_golds): |
There was a problem hiding this comment.
question here, for the case us in bus, is this still legitimate to get retrieval scores?
|
|
||
| class SearchR1Rollouter(Rollouter): | ||
| """Search-R1 rollouter: the QA datasets, the multi-turn search env, and the | ||
| EM/format rubric wired together. All behavior is inherited from ``Rollouter``; |
There was a problem hiding this comment.
no format rubric any more.
| ) | ||
| validation_dataset: SearchR1Dataset.Config = field( | ||
| default_factory=lambda: SearchR1Dataset.Config( | ||
| # Evaluate on the NQ split only; fixed file order for a stable eval set. |
There was a problem hiding this comment.
the same with previous nit: deterministic order so each step draws the same samples across validation runs
| for tc in tool_calls | ||
| ) | ||
| ) | ||
| env_messages: list[Message] = [{"role": "tool", "content": p} for p in passages] |
There was a problem hiding this comment.
there seems to be a bug here to drop too call id if we tend to support multi-call per turn. please check and confirm here, found this from the failed test test_env_tool_call_returns_tool_message.
env_messages = [
{"role": "tool", "content": p, "tool_call_id": tc.id}
for tc, p in zip(tool_calls, passages, strict=True)
]
There was a problem hiding this comment.
the asyncio is order reserved so it might be fine...
There was a problem hiding this comment.
good for me if test_env_tool_call_returns_tool_message is not necessary at all.
There was a problem hiding this comment.
yeah, the tool call is working good now
…e+content only)
The env now builds {role, content} tool messages (matching CalculatorEnv); update
test_env_tool_call_returns_tool_message accordingly. All 10 tests pass.
…iner_logprobs - losses/grpo.py: GRPOLoss(DAPOLoss) exposing a single symmetric clip_eps (= DAPO with ratio_clip_low == ratio_clip_high); removed the duplicated class from trainer.py (shuhuayu). - rename loss arg policy_logprobs -> trainer_logprobs across GRPOLoss/DAPOLoss + callers (both trainer and generator are policies; trainer pairs with generator) and unify the GRPOLoss docstring on trainer/generator (shuhuayu).
- data via datasets only; drop requirements.txt (aiohttp ships with vLLM) + README install step; reword shuffle/validation docstrings (deterministic order). - env: timeout_s now configurable; warn on retrieval failure (not silent). - rubric: retrieval credit matches whole words (no 'us' in 'bus'); 'gold'->'golden' for consistency with the golden_answers field. - README: mention no_search_penalty; 'eval run'->'example run'; rubric docstring covers both anti-reward-hacking levers. - config_registry: drop redundant comments.
Full bf16 has no fp32 master weights; revert to fp32 (default dtype) on TP=4 (the proven split). Added a TODO to move to proper mixed precision (fp32 master + bf16 compute via FSDP + activation checkpointing), which is the memory-efficient way and would let the split stay generator-heavy.
…yu-l) Document why 0.6 (weight-sync GPU-memory spike OOMs at 0.9) and the likely cause (GPU-Direct/RDMA weight transfer on by default; should be configurable + CPU-default, TODO @meetv18). Also note the update isn't landing in place despite expandable_segments, so it allocates rather than updating in place.
| # Standard GRPO (advantage normalized by group reward std). Advantage is a | ||
| # post-scoring step on the rollouter; the trainer just consumes it. |
There was a problem hiding this comment.
Is @felipemello1 suggesting you to remove these?
There was a problem hiding this comment.
in next PR you could help refactor this into examples/alphabet_sort -- note that we have to modify the test code using it as well.
| **Qwen3-1.7B** — EM ~0.05 → ~0.40 (peak ~0.41): | ||
|
|
||
|  | ||
|
|
||
| **Qwen3-8B** — EM ~0.26 → ~0.45 (peak ~0.45): | ||
|
|
||
|  |
There was a problem hiding this comment.
Also, as we updated the actual recipe, these pictures would go outdated.
- One option is to include the pictures only in PR summary, not landing.
- If you think it's helpful to land them, please add timestamp / commit hash around, so people can reproduce.
Follow-up to Tianyu's note in #3602 (comment). `config_registry.py` had collected all the alphabet-sort smoke/debug configs — the 0.6b/1.7b/14b GRPO recipes, the two batch-invariant variants, and the `BatchInvariantFlexConverter` they share. That's example-specific code living in what's supposed to be a generic registry. search_r1 already keeps its configs under `examples/search_r1/config.py` and only re-imports them into `config_registry` so `ConfigManager` can find them via `--config`; this makes alphabet-sort do the same. What changed: - new `examples/alphabet_sort/config.py` holds the six config functions plus the converter/debug helpers - `config_registry.py` is now just two re-import blocks (alphabet-sort + search_r1) - the direct importers (`generate.py`, `test_generator.py`, `test_bitwise_parity.py`) pull the functions from the example module instead of `config_registry` `--config` on the CLI is unchanged: `config_registry` still re-exports the names, so `getattr(config_registry, "rl_grpo_qwen3_0_6b_varlen")` keeps working and the integration tests (`tests/integration_tests.py`) that pass `--config` strings don't need touching. Pure move, no behavior change. Confirmed all six configs are still discoverable through `config_registry` and `pre-commit` is clean.




What
Adds a Search-R1 example (multi-turn
<search>/<information>/<answer>open-domainQA RL) to
torchtitan/experiments/rl, plus the minimal multi-turn RL infra and theRL stabilizers (KL-to-reference + clip-higher) needed to train it without collapse.
Modeled on slime's
examples/search-r1, following PR #3582's example-folder format.Why
The RL controller previously only supported single-turn rollouts and
rollout_to_episoderejected >1 turn. Search-R1 is inherently multi-turn.Core multi-turn infra (single-turn path verified bit-identical: sum_digits loss with
--debug.seed=42 --debug.deterministic)trainer.py).loss_maskmasking env-injected (retrieved) tokens (types.py,rollout/utils.py,batcher.py).include_stop_str_in_output(actors/generator.py).TokenEnv.max_num_turnscap (environment/token.py).Rollouter.reset_validation()so every eval scores the same set (else the iterator advanced and each eval used a different subset).torch.cat).RL stabilizers (ported from slime — needed to avoid mode collapse)
low_var_kl/k3,_compute_kl) + a frozen reference model built inPolicyTrainerwhenkl_coef>0(ref_logprobscomputed no-grad inforward_backward).1-clip_eps/1+clip_eps_high).Result (Qwen3-1.7B, fixed NQ-500 test EM)
<search>, bare<answer>(reward hacking)KL holds the policy near the base model, so EM rises while preserving the search
behavior (genuine Search-R1) instead of collapsing to terse-answer hacking. EM is
noisy (±0.02–0.03); read the plateau over 20 eval passes, not single points.
Tests
tests/test_search_r1.py(rubric + env parsing),tests/test_rollout_to_episode.py(multi-turn flattening + loss-mask).
pre-commitclean.