Skip to content

[rl] Drain inside the generator; the router stops waiting on draining generators - #5905

Merged
tianyu-l merged 2 commits into
pytorch:mainfrom
pzhan9:pzhang/drain-in-generator
Nov 7, 2026
Merged

tianyu-l merged 2 commits into
pytorch:mainfrom
pzhan9:pzhang/drain-in-generator

Conversation

@pzhan9

@pzhan9 pzhan9 commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Address this TODO:

# TODO(pytorch/torchtitan#5253): drain inside the generator, so this wait goes away.

Briefly, we move the draining logic to generator, so the router logic stays simpler. But router still needs to maintain the generator draining state (a bool flag), so it can use that flag to decide routing:

  1. A request pinned to a draining generator goes to it and waits there.
  2. every other request goes to a non-draining generator, or, when all drain, to the least-loaded one.

Why

Resolves the TODO in InterGeneratorRouter._route (#5253). With hot_swap=False, the router drains each generator itself (clears a serving event, waits for router-side idle, then calls load_model_state_dict), and every _route call waits on the pinned generator's serving event and a global _serving event.

All generators drain in the same pull, so new sessions block at the router until the first generator finishes its load, then see it as the only candidate and are pinned there by sticky routing.

Example (real router, 4 generators, hot_swap=False, 20 new sessions arriving mid-drain):

Situation main: where the 20 new sessions go This PR
All 4 draining, gen0 comes back first gen0: 20 spread by load, each waits in its generator's queue
gen3 already back, gen0-2 draining gen3: 20 gen3: 20 (unchanged)
main:     route() --await serving--> choose(serving generators) --> generate
this PR:  route() --> choose(...) --> generate --(generator holds it back until its load is applied)

What changed

  • Generator (logic): Generator.load_model_state_dict(version, *, drain). With drain=True, rank 0 of EngineLoop._decide_next_action stops admitting requests, keeps stepping the admitted ones until none is left, applies the load, then admits the held-back requests under the new weights. Admitted = outstanding generations minus pending_engine_requests (requests register with the dispatcher when taken off the queue, so counting held-back ones would deadlock). While a load is pending, the loop decides right away instead of waiting on the queue. drain=False is unchanged.
  • Router (logic): the serving/idle events, _serving, _candidates, _set_serving and _refresh_serving_status become one _GeneratorHandle.draining: bool, set around the load call in drain mode. _route never waits:
    • a turn pinned to a draining generator goes to it, bypassing the strategy (no re-pin while draining, as on main);
    • every other call goes to a generator that isn't draining, or to any of them when all drain.
  • Mechanical, skim: Monarch endpoint passthrough of drain; RequestDispatcher.rank0_has_outstanding_generations() -> rank0_num_outstanding_generations(); drain=False added to existing engine-loop tests; router tests rewritten for the removed events.
  • strategies.py and hot_swap (still on InterGeneratorRouter.Config) are unchanged.

Two commits: the first adds the generator-side drain (the router still drains too, so no behavior change); the second removes the router-side drain.

Alternatives considered

  • Let pinned turns spill over to other generators while theirs drains: rejected, it re-prefills sessions for no reason; this keeps main's no-re-pin behavior.
  • Treat draining as extra load in reserved_load: rejected, needs a magic number and trips repin_load_ratio, re-pinning every session on the draining generator.
  • Move hot_swap to Generator.Config: rejected, the router owns the drain-or-not policy and the generator only implements it.

User-facing changes

Only with hot_swap=False; hot_swap=True (the default, and every recipe) is unchanged.

Before After
Pinned turn, its generator draining waits at the router; repin_load_ratio check when the drain ends waits in the generator's queue; no repin_load_ratio check
New session, some generators serving a serving generator same
New session, all generators draining waits, then all go to the first one back least-loaded over all; waits in that generator's queue
router_drain_wait trace span present removed; the drain wait is inside the generator's load_model_state_dict span
generator/time_to_first_token_ms, generator/inflight_requests_at_completion exclude held-back requests include them (they wait in the generator now)

API: Generator.load_model_state_dict(version) -> load_model_state_dict(version, *, drain) (required).

Numerics / performance

No computation change. hot_swap=True: routing and load timing are logically identical (the flag is never set; a drain=False load is applied at the next decision as before). hot_swap=False: which generator a session lands on can differ, so runs are not bitwise comparable to main.

Testing

  • tests/rl/unit_tests/cpu/test_engine_loop.py, test_inter_generator_router.py, test_generator.py, test_intra_generator_router.py pass on each commit. The full tests/rl/unit_tests/cpu suite matches main file by file; the remaining failures (test_dapo_math, test_model_defaults, test_policy_loss_configs, test_search_r1, test_rdma_microbatch) also fail on main in this environment (stale renderers/package versions).
  • New and changed tests (each verified by mutating the code; failures time out rather than hang):
Test Regression it catches
test_draining_load_waits_for_admitted_requests load applied while an admitted request runs; loop hanging once the last admitted request finishes and no message arrives
test_hot_swap_load_does_not_wait_for_admitted_requests drain=False loads starting to wait
test_draining_load_applies_after_admitted_requests_and_before_held_back_ones (real EngineLoop thread) counting held-back requests (deadlock); admitting a held-back request before the load
test_sticky_session_stays_on_its_draining_generator re-pin while draining, even when the generator looks >1.5x loaded
test_new_sessions_spread_over_generators_that_all_drain missing all-drain fallback
test_drain_marks_generator_draining_for_its_load router waiting on in-flight routes; pulls not concurrent; unpinned calls not avoiding a draining generator
test_drain_clears_draining_on_pull_failure, test_round_robin_skips_draining_generators flag left set after a failed load; exclusion under round robin

Deleted: test_drain_excludes_syncing_generator_from_routes and test_drain_pulls_idle_generators_while_busy_generator_drains (merged into test_drain_marks_generator_draining_for_its_load); test_single_generator_blocks_routes_while_draining (the router no longer blocks; holding back is covered by the engine-loop tests).

  • A scratch harness (not committed) wiring the real router to real EngineLoops with fake engines, random multi-turn sticky sessions and 15 back-to-back pulls passed with hot_swap False/True; in drain mode 20-28 of 45 loads per run arrived with requests running, and none was applied with an admitted request.
  • GPU smoke on 8 GPUs: torchtitan_recipes.tests.rl.alphabet_sort.rl_grpo_fsdp2_gen_tp2_no_compile (3 generators x TP2 + FSDP2 trainer), 6-8 steps, with hot_swap False and True on this branch and False on main: all complete. Caveat: the controller pulls when generators are idle in these recipes, so only one load across all runs had a generate in flight (it finished before the weight copy); drain under load is mainly covered by the CPU tests above.

Known issues / follow-ups

  • A turn pinned to a draining generator skips StickySessionRoutingStrategy's LRU refresh for that turn (negligible at max_sessions=262144).
  • No in-repo recipe sets hot_swap=False.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 6, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 6, 2026
…te dict load

`Generator.load_model_state_dict` takes a required `drain` flag. With
`drain=True`, the engine loop stops admitting requests, keeps stepping the
admitted ones until none is left, applies the load, then admits the requests
that arrived meanwhile under the new weights. With `drain=False` the load is
applied at the next decision, as before ("hot swap").

The router passes `drain=not hot_swap`. It still drains on its side too, so
behavior is unchanged in this commit; the next commit removes the router-side
drain.

Requests are registered with the dispatcher when taken off the queue, before
admission, so the drain counts only admitted ones: outstanding generations
minus those pending admission. Counting the pending ones would deadlock (the
load waits for them; they wait for the load).
Resolves the TODO in `InterGeneratorRouter._route` (pytorch#5253).
With hot_swap=False, the generator now drains itself (previous commit), so the
router no longer clears a `serving` event, waits for the generator to go
idle, or makes `_route` wait on the pinned generator's and the global
`serving` events. It keeps a plain `draining` flag, set around each load call,
that only steers routing:

- a turn pinned to a draining generator still goes to it, bypassing the
  strategy, and waits there: no re-pin while draining, as before. Unlike
  before, such a turn also skips the repin_load_ratio check after the drain,
  since it was already sent to the generator.
- every other call goes to a generator that isn't draining. A draining
  generator holds new work back until its load is applied, which its
  reserved load doesn't reflect. When all generators drain, calls spread over
  them by load, instead of all waiting for, then piling onto, the first one
  to finish its load.

hot_swap=True is unchanged: the flag is never set.

Observability: the router's `router_drain_wait` trace span is gone. In drain
mode, the drain wait now falls inside the generator's `load_model_state_dict`
span, and held-back requests' time to first token includes it.
@pzhan9
pzhan9 force-pushed the pzhang/drain-in-generator branch from e513269 to 5b91619 Compare November 6, 2026 20:54
@pzhan9
pzhan9 marked this pull request as ready for review November 6, 2026 21:39
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 6, 2026
@felipemello1

Copy link
Copy Markdown
Contributor

Reply from claude: optional test idea from #5503 (which this PR supersedes): closing the engine loop while a drain is pending. It passes on this PR's code; it would guard the drain/close interaction.

@tianyu-l

tianyu-l commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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


Verdict: Approve (no blocking issues; a maintainer still needs to review) -- see review

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

Verdict: Approve -- the change resolves the #5253 TODO by moving the drain into the generator's engine loop. That deletes the router's two events and its global wait, and I found no correctness issue in the new drain path. A maintainer still needs to review, since this touches the RL generator's engine loop.

What this PR does. With hot_swap=False, the router used to stop routing to a generator and wait for the router-side idle before calling load_model_state_dict. Now it passes drain=True to the generator. While that load is pending, rank 0 of the engine loop keeps stepping requests that are already admitted, holds back new ones, applies the load once the admitted count reaches zero, and then admits the held-back requests under the new weights. The router keeps only a draining: bool per generator, which it uses for placement. _route no longer waits.

Example. 2 generators, hot_swap=False, a pull is in progress, and session s0 is pinned to gen0:

main:  s0 turn   -> await gen0.serving             (waits at the router)
       new s1    -> await _serving -> first gen back, e.g. gen0 (pile-up)
PR:    s0 turn   -> gen0 (pinned, draining)        -> held in gen0's queue until its load applies
       new s1    -> least-loaded of {gen0, gen1}   -> held in that generator's queue
       gen1 back -> new s2 goes to gen1 (same as main)

Should consider

  • tests/rl/unit_tests/cpu/test_engine_loop.py:388 -- the hot-swap test could fold into the drain test (inline comment).
Details
  • Admitted count (engine_loop.py:495): computed as outstanding minus pending_engine_requests. Every request is registered in _decide_next_action when it comes off the queue, and rejected or failed ones are popped through _rank0_fail_generations. So the difference is exactly the set admitted to an engine on any DP rank, including ones whose peer result hasn't arrived yet. If it were ever wrong, the failure would be safe: the load would apply early. It could not deadlock.
  • Wake-up: the new or pending_load_messages in the non-blocking branch is needed. Without it, when the last admitted request finishes inside a step burst, the loop would block on queue.get() and the load would wait for an unrelated message. The loop never spins with a pending load and nothing admitted, because that case applies the load right away.
  • Close during a drain: the CLOSE branch fails pending loads, and _release_resources fails the held-back generations, which are registered. The optional test from #5503 that felipemello1 mentioned would guard this, but the code already handles it.
  • TTFT note in the description is accurate: arrival_time is set in Generator.generate (generator.py:422), so time spent held back is counted.
  • Overlapping pulls on one generator would clear draining early (the finally at inter_generator.py:214). The controller pulls one at a time, and _set_serving had the same property on main, so this is not new.
  • No stale references remain to serving, idle, _set_serving, or router_drain_wait. No in-repo docs describe the router-side drain.

Not verified: I could not run the CPU tests in this environment (permission denied), and I did not check the GPU smoke runs.

Comment on lines +388 to +391
def test_hot_swap_load_does_not_wait_for_admitted_requests(runner) -> None:
engine_loop = _bare_loop(event_loop=runner.get_loop(), inflight=True)
decision = _decide(runner, engine_loop, [], _load(5))
assert decision.action is LoopAction.LOAD_MODEL_STATE_DICT

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.

Optional: this sets up the same thing as test_draining_load_waits_for_admitted_requests (_bare_loop(inflight=True) plus one load) and checks the other branch. You could fold it into that test, either with @pytest.mark.parametrize("drain", [False, True]) or by adding a two-line drain=False check at the top, so the file doesn't carry a separate test for the case that didn't change.

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

nice

Comment on lines +495 to +507
num_admitted_generations = (
self._request_dispatcher.rank0_num_outstanding_generations()
- len(pending_engine_requests)
)
if (
any(load.drain for load in pending_load_messages)
and num_admitted_generations > 0
):
# Drain: keep stepping the admitted requests, and admit nothing until the load.
decision = LoopDecision(
action=LoopAction.STEP,
requests_per_dp_rank=self._request_dispatcher.rank0_route([]),
)

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.

it took me some time to understand this, but seems correct!

# applied; the strategy would re-pin the session just because it drains.
h = pinned
else:
# Prefer generators that aren't draining: a draining one holds new work

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 know how important this is, because

  • how_swap is by default on
  • even when hot-swap is False, usually all generators are updated together, so they are almost always "all draining" or "none draining", assuming weight sync is reasonably fast

Can leave it as is in this PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I am not sure when the scale is getting very big, how close the generators can finish weight sync together. When there are too many generators, we probably need to stagger them to avoid they all hit the trainer at the same time, unless we have some more sophisticated weight sync scheme.

@tianyu-l
tianyu-l merged commit a9953e7 into pytorch:main Nov 7, 2026
@pzhan9
pzhan9 deleted the pzhang/drain-in-generator branch November 8, 2026 04:07
tianyu-l added a commit that referenced this pull request Nov 26, 2026
…er override; agent self-review; rl/transport (#6407)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why

Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it
approved,
30 then got a formal "request changes" from a maintainer, and about 20
more got
substantive inline asks. In nearly all of them the bot either saw the
problem
and approved anyway, or never asked the questions maintainers ask most
("does
the repo already do this?", "who should own this?"). The opposite
failure, the
bot blocking something a maintainer was fine with, is rare: in the PRs
we
sampled, 2 of its 81 must-fix items were wrong and about a third were
minor
(the empty human-written summary was the biggest source).

**Example** (#6112, controller sizes the rollout worker pool):

```
before: bot approved 10 times; tianyu-l then blocked: "the controller reads
        rollouter.rollouts_per_worker to compute a count it hands back to the
        Rollouter -- violates encapsulation"
after:  same commit, new skill -> Request changes, must-fix #1:
        "controller.py:589 -- wrong owner for the worker count ..."
```

There was also no way for a code owner to overrule the bot except
dismissing
its review in the GitHub UI, and a later `@claude review again` would
block
again.

## What changed

**Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`):
- Verdict rules: Approve only when every remaining item is an edit the
bot
could write itself. Anything the author still owes (a design change, an
unexplained golden change, evidence the PR rests on) is Request changes;
anything only a maintainer can decide is Needs discussion. A hedge like
"a
  maintainer should decide" can't come with Approve.
- Always must-fix: a violated written rule, a silent wrong result, a
second
  definition of an existing concept, a gate finding.
- Design gate: new questions for the existing counterpart, in-repo
ownership,
and the design behind a bug; "ban only what doesn't work on main"; read
the
numbers behind a claim. The overlapping-PR search is mandatory and
reported.
- Re-review covers every commit since the last full review, including
code
taken from the bot's own suggestions. A scoped question gets a
`COMMENT`, not
  a whole-PR verdict.
- The bot fact-checks its own proposed fixes, and cites a source for
claims
  about external tools or marks them unverified (never must-fix).
- An empty "Summary (human-written)" is a one-line "Before merge" note
that
  never affects the verdict.
- Checklist: config ownership direction, general shared wrappers, dead
code the
PR creates, model variants as flavors, a mechanical pass over every new
or
  changed function.

**Code owner override** (`SKILL.md`, `claude-code.yml`,
`CONTRIBUTING.md`): a
code owner comments `@claude override` (optionally `@claude override
2,3:
<reason>`); the bot approves if nothing else is open and doesn't
re-raise the
overridden items. A code owner's GitHub approval or "LGTM" is not an
override,
so a teammate can approve without the bot dropping its findings.
Dismissing the
bot's review still unblocks the PR, but isn't an override: the bot can't
tell
who dismissed it.

**Agent self-review** (`CLAUDE.md`, `pr-description`): an agent
preparing a PR
runs `pr-review` in branch mode first and records unaddressed items in
an
optional "Self-review" section. PRs written without an agent are
unaffected; a
missing section is never a finding.

Where each new rule comes from (maintainer asks the bot missed):

| Change | PRs |
| --- | --- |
| No Approve with open design/evidence items or a "maintainer should
decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 |
| Author waiver can't clear a must-fix | #6201, #6202, #6203 |
| Existing counterpart; one source of truth | #5228, #6169, #5881,
#5823, #5824, #6059, #5812 |
| Responsibility owner; config ownership direction | #6112, #6332,
#5802, #5803, #6325 |
| Fix the design behind the bug; a TODO doesn't justify a workaround |
#5572, #5689, #5657 |
| Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819,
#5543 |
| Re-review covers all new commits; scoped asks don't approve | #5824,
#5842 |
| Mandatory overlap search | #5885, #6248 |
| Ban only what doesn't work on main | #5543 |
| Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868
|

**Rules**: `design.md` gets the one-general-wrapper rule (moved from
`models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the
consumer owning its values; `config.md` gets ownership direction and "a
Config
doesn't read runtime state"; `direction.md` calls all-to-all the MoE
reference
implementation, so a new vendor-specific dispatch path (e.g. #6242)
needs a
reason the existing backends can't serve.

**Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/`
-> d4l3k.

**Mechanical, skim**: `torchtitan/rl/transport/` holds data movement
between RL
actors.
- `rl/model_state_dict_transport.py` ->
`rl/transport/model_state_dict.py`
- `rl/MODEL_STATE_DICT_TRANSPORT.md` ->
`rl/transport/MODEL_STATE_DICT_TRANSPORT.md`
- `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py`
- tests:
`tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py`
->
`tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py`
- imports, READMEs and `scripts/install_rl_env.sh` updated; no code
changes.

## User-facing changes

| Before | After |
| --- | --- |
| Overrule the bot: dismiss its review in the UI, and it blocks again on
the next run | `@claude override [items]: <reason>`; the bot approves
and doesn't re-raise them |
| Empty human-written summary: bot must-fix | One "Before merge" line,
no effect on the verdict |
| `from torchtitan.rl.model_state_dict_transport import ...` | `from
torchtitan.rl.transport.model_state_dict import ...` |
| `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from
torchtitan.rl.transport.rdma_microbatch import ...` |

## Testing

Backtest: the new skill run locally (nothing posted) on each PR at the
commit
and thread state the bot originally saw.

| PR | Bot then | New skill | What the maintainer asked |
| --- | --- | --- | --- |
| #6112 | Approve | Request changes | worker-count ownership (caught) |
| #5837 | Approve | Request changes | apply to `dp_shard` too (caught) |
| #5572 | Approve | Request changes | delete the injection design
(caught) |
| #6201 | Approve after author waived pins | Request changes, waiver
ignored | pins broke GPU tests after merge (caught) |
| #6007 | Approve | Request changes | fold K3.1 into K3 (caught) |
| #5543 | Request changes: "ban it" | Request changes: keep main's path
| don't break gpt-oss + DeepEP (fixed) |
| #6144, #5905 (controls) | Approve | Approve | -- |
| #6137 (control) | Approve | Needs discussion | -- (merge gate on an
upstream API) |

Code owner override, simulated on #6201: override by a code owner lifts
the
named item; `@claude override` from the author changes nothing; a code
owner's
"LGTM" approval followed by "review again" keeps Request changes.

Transport move: 83 RL CPU unit tests pass locally
(`transport/test_model_state_dict.py`, `test_trainer.py`,
`test_engine_loop.py`). `transport/test_rdma_microbatch.py`,
`test_generator.py` and
`test_batcher_actor.py` fail to collect in my env on `origin/main` too
(stale
attention-gym / Monarch), so CI is the check for those.

## Known issues / follow-ups
- Open PRs that edit the moved files rebase cleanly (git follows the
renames),
but new imports of the old module paths will break: #6309 (adds a delta
transport that should live in `rl/transport/`), #6237, #6176, #6177,
#5862,
  and drafts #6127, #6393, #6163, #5764.
- The Actions bot can't read dependency source (e.g. SGLang); follow-up
for the
  workflow.

## Self-review
pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch
mode diffs
against `origin/main` and skips description findings before a
description
exists; the "Config doesn't read runtime state" rule no longer
contradicts
hardware validation; dismissal dropped as an override form (the bot
can't tell
who dismissed); `test_rdma_microbatch.py` added to the transport area.
Not
addressed:
- One concern per PR -- the five changes ship together at the
maintainer's
  request.
- Open PRs touching the moved files -- listed above; the maintainer will
  coordinate.
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.

3 participants