Skip to content

[rl] Search-R1: multi-turn retrieval-augmented GRPO - #3602

Merged
yichuan-w merged 57 commits into
pytorch:mainfrom
yichuan-w:yichuan/search-r1-multiturn-rl
Jun 16, 2026
Merged

yichuan-w merged 57 commits into
pytorch:mainfrom
yichuan-w:yichuan/search-r1-multiturn-rl

Conversation

@yichuan-w

@yichuan-w yichuan-w commented Jun 10, 2026 •

Copy link
Copy Markdown
Member

What

Adds a Search-R1 example (multi-turn <search>/<information>/<answer> open-domain
QA RL) to torchtitan/experiments/rl, plus the minimal multi-turn RL infra and the
RL 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_episode rejected >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)

  • Multi-turn controller: batched generate-per-turn loop until each rollout is terminal (trainer.py).
  • Episode flattening + per-token loss_mask masking env-injected (retrieved) tokens (types.py, rollout/utils.py, batcher.py).
  • Generator stop-strings + include_stop_str_in_output (actors/generator.py).
  • TokenEnv.max_num_turns cap (environment/token.py).
  • Fixed held-out eval: Rollouter.reset_validation() so every eval scores the same set (else the iterator advanced and each eval used a different subset).
  • Robustness: GRPOLoss drops tokens with non-finite generator logprobs (vLLM emits occasional NaN logprobs) + log-ratio clamp; batcher clamps grad-accum to available packed rows (no empty-microbatch torch.cat).

RL stabilizers (ported from slime — needed to avoid mode collapse)

  • KL-to-reference penalty (low_var_kl/k3, _compute_kl) + a frozen reference model built in PolicyTrainer when kl_coef>0 (ref_logprobs computed no-grad in forward_backward).
  • clip-higher (asymmetric clamp 1-clip_eps / 1+clip_eps_high).

Result (Qwen3-1.7B, fixed NQ-500 test EM)

EM (baseline → trained) response_length behavior
bare GRPO (no KL) 0.16 → ~0.21 140 → ~30 (collapse) drops <search>, bare <answer> (reward hacking)
+ KL + clip-higher 0.159 → ~0.22 plateau (peak 0.229, +44%) 140 → ~60–130 (no collapse) keeps "After searching, I found …"

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-commit clean.

Requires a running local dense retrieval server + Search-R1 NQ/HotpotQA data; see examples/search_r1/README.md.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 10, 2026
@yichuan-w
yichuan-w requested review from shuhuayu and tianyu-l and removed request for tianyu-l June 10, 2026 03:45
Comment thread torchtitan/experiments/rl/trainer.py Outdated
completion_offset:next_completion_offset
]
completion_offset = next_completion_offset
else:

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.

Where is the if part of this else?

Comment thread torchtitan/experiments/rl/trainer.py Outdated
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(

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.

There seems a barrier between two consecutive turns? So there's no continuous batching across turns.

@shuhuayu

Copy link
Copy Markdown
Contributor

thanks. can you briefly describe why search-r1 is a good example to stay in titan rl?

felipemello1 pushed a commit to felipemello1/torchtitan that referenced this pull request Jun 10, 2026
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.
@yichuan-w

This comment was marked as outdated.

@yichuan-w

Copy link
Copy Markdown
Member Author

Search-R1 multi-turn retrieval GRPO reproduces slime's nq_test EM curve — at two model scales with the same recipe.

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 (low_var_kl, 0.001), AdamW lr 1e-6 constant, temperature 1.0. EM = validation_reward/_mean (slime's eval/nq_test definition: correct / 500, truncated counted as 0).

Qwen3-8B — gen TP=2 + train TP=4 — EM 0.258 → 0.356 (peak @ step 40)

step 0 10 20 30 40 50 55
EM 0.258 0.300 0.320 0.340 0.356 0.342 0.334

Run: https://meta.wandb.io/yichuan/torchtitan/runs/2tusjecg

Qwen3-1.7B — gen TP=4 + train TP=1 — EM 0.144 → ~0.29 plateau (peak 0.308 @ step 185, full 0–270)

step 0 20 40 60 80 100 140 185 270
EM 0.144 0.214 0.238 0.282 0.288 0.292 0.298 0.308 0.284

Run: https://meta.wandb.io/yichuan/torchtitan/runs/52r5ytjc

(slime reference, Qwen2.5-3B: ~0.096 → ~0.28.)

Next step: refactor + rebase onto main.

@yichuan-w

Copy link
Copy Markdown
Member Author
image The curve of 1.7B model

@yichuan-w

Copy link
Copy Markdown
Member Author

Per-step time decomposition (Qwen3-1.7B Search-R1, run m551si0t)

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

phase time % what runs
rollout (generation + retrieval) 24.6 s 50.3% vLLM multi-turn decode + GPU-faiss retrieval between turns
weight sync (trainer → generator) 12.3 s 25.2% TorchStore: push 0.19 s + generator pull/reload 12.1 s
train (fwd / bwd / optim) 11.9 s 24.4% TP=1 policy update + frozen ref model (KL)
total 48.9 s 100% ≈ 4.5K tokens/s

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:

  • Step is rollout-bound (~50%, dominated by vLLM generation, not retrieval).
  • Weight sync is ~25% — almost entirely the generator pulling + reloading weights from TorchStore (push is only 0.19 s); GPUs idle during it, so it's the clearest optimization target.
  • Actual training (fwd/bwd/optim) is only ~24%.

# 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

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.

probably don't need this right now?

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.

remove

max_tokens: int = 100
"""Maximum number of tokens to generate per completion."""

stop: list[str] = field(default_factory=list)

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.

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.

I'm confused. Why would we need both stop_token_ids and stop? Generator only works with tokens not strs.

@yichuan-w yichuan-w Jun 13, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

They're not redundant — different mechanisms:

  • stop_token_ids = the renderer's role-boundary token (<|im_end|>), a single token, filled automatically via renderer.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 as stop_token_ids (single-token match). Hence vLLM's native string stop.

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

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.

Suggested change
self._validation_dataset = self._validation_dataset_config.build()
self._validation_dataset = config.validation_dataset.build()

Comment thread torchtitan/experiments/rl/types.py Resolved
@yichuan-w

Copy link
Copy Markdown
Member Author
image This is the 8B curve

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.
@yichuan-w
yichuan-w force-pushed the yichuan/search-r1-multiturn-rl branch from 26d4071 to 4b183e3 Compare June 12, 2026 17:22
@yichuan-w

Copy link
Copy Markdown
Member Author

Rebased onto main (#3593 continuous-batching multi-turn). EM curves reproduced at both scales — runs linked for checking. Same recipe both: pure-EM 0/1 reward, standard GRPO (group-std-normalized advantage), clip-higher 0.2/0.28, KL-to-reference (low_var_kl, 0.001), AdamW lr 1e-6, temp 1.0, 256 samples/step. EM = validation_reward/_mean (slime eval/nq_test).

Qwen3-8B — rebase n4ds9e4x vs ref 2tusjecg

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.

@yichuan-w
yichuan-w requested a review from tianyu-l June 12, 2026 20:58

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

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

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.

remove

Comment thread .gitignore Resolved
Comment thread torchtitan/experiments/rl/trainer.py Resolved
# 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,

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.

This is also being addressed in #3142
so remove for now

@yichuan-w
yichuan-w requested a review from felipemello1 June 15, 2026 19:05

@felipemello1 felipemello1 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.

please address these last comments. Thanks for the work on this PR!

cc: @tianyu-l in case you have any other comments

Comment thread torchtitan/experiments/rl/trainer.py Resolved
…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.
@yichuan-w

yichuan-w commented Jun 15, 2026 •

Copy link
Copy Markdown
Member Author

Thanks @felipemello1 — addressed the latest round:

  • data.py / 8B config docstrings: applied your suggested wording.
  • rollout_to_episodes now raises if advantage is None — so a Rollouter that forgets to fill it fails loudly instead of silently training on a missing advantage (the safeguard you asked for).
  • AlphabetSort: it already gets the rollouter-side advantage automatically — AlphabetSortRollouter doesn't override run_group_rollouts, so it inherits the advantage step (and the advantage config field, default Dr.GRPO) from the base Rollouter. The new rollout_to_episodes guard protects it too. So nothing example-specific to add there.
  • "is that the filename / did you run it?": yes — data.py calls hf_hub_download(repo_id="PeterJinGo/nq_hotpotqa_train", filename="train.parquet"/"test.parquet"), and those are exactly the files in the repo (['.gitattributes', 'test.parquet', 'train.parquet']). Confirmed with a fresh run on the merged branch: data loads from HF, no crash, and it trains (Step 1 rollout_reward/_max=1.0). wandb: yichuan/titan_rl/ypfkpcpp.

@yichuan-w

Copy link
Copy Markdown
Member Author

final reward curve in search R1: 1.7B
image
and 8B from
image

config.hf_assets_path = "torchtitan/experiments/rl/example_checkpoint/Qwen3-8B"
config.trainer = dataclasses.replace(
config.trainer,
training=TrainingConfig(dtype="bfloat16"),

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.

why dtype bf16?

For memory concern, we should use activation checkpointing.

@felipemello1 felipemello1 Jun 15, 2026 •

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.

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

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.

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

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.

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.

Comment on lines +50 to +51
policy_logprobs: torch.Tensor,
generator_logprobs: torch.Tensor,

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.

nit: both trainer and generator are policies, i would suggest using trainer_logprobs to replace policy_logprobs.

Comment thread torchtitan/experiments/rl/trainer.py Outdated
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

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.

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

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.

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:

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.

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:

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.

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.

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.

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

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

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.

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``;

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.

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.

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.

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]

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.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

the asyncio is order reserved so it might be fine...

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.

good for me if test_env_tool_call_returns_tool_message is not necessary at all.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.
@yichuan-w
yichuan-w requested review from shuhuayu and tianyu-l June 15, 2026 23:57

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

Good job!

Comment on lines +59 to +60
# Standard GRPO (advantage normalized by group reward std). Advantage is a
# post-scoring step on the rollouter; the trainer just consumes it.

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.

Is @felipemello1 suggesting you to remove these?

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.

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.

Comment on lines +72 to +78
**Qwen3-1.7B** — EM ~0.05 → ~0.40 (peak ~0.41):

![Qwen3-1.7B validation EM](./assets/validation_em_1.7b.png)

**Qwen3-8B** — EM ~0.26 → ~0.45 (peak ~0.45):

![Qwen3-8B validation EM](./assets/validation_em_8b.png)

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.

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.

@shuhuayu shuhuayu 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.

Thanks!

…ts commit

Each curve is a snapshot; the link points at the exact config that produced it
(1.7B -> config_registry.py @ e28796e, 8B -> config.py @ 4b183e3) so it's easy to
see/reproduce the recipe behind each number even as the recipe evolves (tianyu-l).
@yichuan-w
yichuan-w merged commit 61c010f into pytorch:main Jun 16, 2026
8 of 12 checks passed
yichuan-w added a commit that referenced this pull request Jun 16, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl ciflow/8gpu 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.

4 participants