Skip to content

[rl] PR2/N — AlphabetSort task; remove SumDigits - #3582

Merged
felipemello1 merged 1 commit into
pytorch:mainfrom
felipemello1:57-pr1-alphabetsort
Jun 10, 2026
Merged

felipemello1 merged 1 commit into
pytorch:mainfrom
felipemello1:57-pr1-alphabetsort

Conversation

@felipemello1

@felipemello1 felipemello1 commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Note: Rebased on top of #3581. It also contains the RolloutLogger because of that.

I added AlphabetSort, a task that works for single or multiturn, where the model is given names on each turn and is asked to sort a list by either first or last name.

This is challenging because the model doesn't see characters. It sees tokens. The rewards start low and gradually grow, which is exactly what we need as a toy task.

Our current 'SumDigits' gets 100% accuracy by qwen before any training. Since it is not helpful, i deleted it.

  {
    "step": 0,
    "is_validation": true,
    "group_id": "step=0/group=3",
    "sample_id": "step=0/group=3/sample=0",
    "turns": [
      {
        "policy_version": 0,
        "prompt_messages": [
          {
            "role": "user",
            "content": "Sort these names in alphabetical order by FIRST name: PietroRigo, LaurentChapon, FedericoLevi, UriLerner\n\nUse exactly this 
  format:\n<alphabetical_sorted>\nName1\nName2\n</alphabetical_sorted>"
          }
        ],
        "completion_message": {
          "role": "assistant",
          "content": "<alphabetical_sorted>\nFedericoLevi\nLaurentChapon\nPietroRigo\nUriLerner\n</alphabetical_sorted>"
        },
        "env_messages": [],
        "env_rewards": {}
      }
    ],
    "status": "completed",
    "reward": 1.0,
    "reward_breakdown": { "RewardAlphabetSort": 1.0 },
    "advantage": null
  }

image

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 9, 2026
@felipemello1
felipemello1 force-pushed the 57-pr1-alphabetsort branch 2 times, most recently from ac7ba50 to 4ccce2e Compare June 10, 2026 00:17
- New `examples/alphabet_sort/` task: sort arXiv author names alphabetically by
  first/last name (the multi-turn task we standardize on; runs single-turn today).
- Delete the `examples/sum_digits/` task and switch every RL config to AlphabetSort.

SumDigits is near-saturated for Qwen3-0.6B, so it shows no learning signal. AlphabetSort
gives a graded sequence-similarity reward that starts low and rises, making it a real
end-to-end RL smoke and the standard task the async PRs build on.

`AlphabetSortRollouter` wires a seeded HF-backed dataset, `AlphabetSortEnv`, and a
`RewardAlphabetSort` (difflib ratio ** similarity_power) rubric. Thinking is disabled for
these configs: the answer is a structured `<alphabetical_sorted>` block, and a reasoning
trace spends the token budget and truncates the list before the closing tag.

The env/dataset/grader are multi-turn-capable (`num_turns`), but default to 1 turn so the
single-turn controller is satisfied (the first `step` returns done); PR2 enables multi-turn.

- Run: `pr1_alphabetsort/runs/pr1_varlen_20step/` (config `rl_grpo_qwen3_0_6b_varlen`, 20
  steps, 6 GPUs). Greedy validation reward 0.184 -> 0.599; is_good_run PASS.
- Unit tests: `tests/test_alphabet_sort.py` (14 passed) — dataset/grader/env/rollouter.

- The multi-turn-capable env/grader kept at `num_turns=1` (single-turn-safe) vs. cutting it.
- `score_sorted_list` difflib ratio ** 4: graded, not 0/1, so reward rises smoothly.
- SumDigits fully removed (grep clean): package, 5 config sites, 2 docstring refs.

- AlphabetSort needs the HF dataset `kalomaze/alphabetic-arxiv-authors-it1` (cached; runs
  set `HF_HUB_OFFLINE=1`).
@felipemello1
felipemello1 force-pushed the 57-pr1-alphabetsort branch from 4ccce2e to 08dbfcb Compare June 10, 2026 00:23
@felipemello1
felipemello1 merged commit 0f929e7 into pytorch:main Jun 10, 2026
8 of 12 checks passed
saforem2 pushed a commit to saforem2/torchtitan that referenced this pull request Jun 10, 2026
**Note**: Rebased on top of
pytorch#3581. It also contains the
`RolloutLogger` because of that.

I added `AlphabetSort`, a task that works for single or multiturn, where
the model is given names on each turn and is asked to sort a list by
either first or last name.

This is challenging because the model doesn't see characters. It sees
tokens. The rewards start low and gradually grow, which is exactly what
we need as a toy task.

Our current 'SumDigits' gets 100% accuracy by qwen before any training.
Since it is not helpful, i deleted it.

```
  {
    "step": 0,
    "is_validation": true,
    "group_id": "step=0/group=3",
    "sample_id": "step=0/group=3/sample=0",
    "turns": [
      {
        "policy_version": 0,
        "prompt_messages": [
          {
            "role": "user",
            "content": "Sort these names in alphabetical order by FIRST name: PietroRigo, LaurentChapon, FedericoLevi, UriLerner\n\nUse exactly this 
  format:\n<alphabetical_sorted>\nName1\nName2\n</alphabetical_sorted>"
          }
        ],
        "completion_message": {
          "role": "assistant",
          "content": "<alphabetical_sorted>\nFedericoLevi\nLaurentChapon\nPietroRigo\nUriLerner\n</alphabetical_sorted>"
        },
        "env_messages": [],
        "env_rewards": {}
      }
    ],
    "status": "completed",
    "reward": 1.0,
    "reward_breakdown": { "RewardAlphabetSort": 1.0 },
    "advantage": null
  }

```

<img width="898" height="559" alt="image"
src="https://github.com/user-attachments/assets/089d3c09-d58e-4dd8-ae33-43a950a71e3c"
/>

Co-authored-by: Felipe Mello <[email protected]>
yichuan-w added a commit that referenced this pull request Jun 16, 2026
## 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`.
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.

2 participants