Repository navigation
[rl] Drain inside the generator; the router stops waiting on draining generators - #5905
Conversation
…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.
e513269 to
5b91619
Compare
|
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. |
|
@claude review |
|
Claude finished @tianyu-l's task in 3m 3s —— View job Verdict: Approve (no blocking issues; a maintainer still needs to review) -- see review |
There was a problem hiding this comment.
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 minuspending_engine_requests. Every request is registered in_decide_next_actionwhen 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_messagesin the non-blocking branch is needed. Without it, when the last admitted request finishes inside a step burst, the loop would block onqueue.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
CLOSEbranch fails pending loads, and_release_resourcesfails 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_timeis set inGenerator.generate(generator.py:422), so time spent held back is counted. - Overlapping pulls on one generator would clear
drainingearly (thefinallyatinter_generator.py:214). The controller pulls one at a time, and_set_servinghad the same property onmain, so this is not new. - No stale references remain to
serving,idle,_set_serving, orrouter_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.
| 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 |
There was a problem hiding this comment.
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.
| 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([]), | ||
| ) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
…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.
Summary (human-written)
Address this TODO:
torchtitan/torchtitan/rl/routing/inter_generator.py
Line 171 in c2579f7
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:
Why
Resolves the TODO in
InterGeneratorRouter._route(#5253). Withhot_swap=False, the router drains each generator itself (clears aservingevent, waits for router-sideidle, then callsload_model_state_dict), and every_routecall waits on the pinned generator'sservingevent and a global_servingevent.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):main: where the 20 new sessions goWhat changed
Generator.load_model_state_dict(version, *, drain). Withdrain=True, rank 0 ofEngineLoop._decide_next_actionstops 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 minuspending_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=Falseis unchanged.serving/idleevents,_serving,_candidates,_set_servingand_refresh_serving_statusbecome one_GeneratorHandle.draining: bool, set around the load call in drain mode._routenever waits:main);drain;RequestDispatcher.rank0_has_outstanding_generations()->rank0_num_outstanding_generations();drain=Falseadded to existing engine-loop tests; router tests rewritten for the removed events.strategies.pyandhot_swap(still onInterGeneratorRouter.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
main's no-re-pin behavior.reserved_load: rejected, needs a magic number and tripsrepin_load_ratio, re-pinning every session on the draining generator.hot_swaptoGenerator.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.repin_load_ratiocheck when the drain endsrepin_load_ratiocheckrouter_drain_waittrace spanload_model_state_dictspangenerator/time_to_first_token_ms,generator/inflight_requests_at_completionAPI:
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; adrain=Falseload 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 tomain.Testing
tests/rl/unit_tests/cpu/test_engine_loop.py,test_inter_generator_router.py,test_generator.py,test_intra_generator_router.pypass on each commit. The fulltests/rl/unit_tests/cpusuite matchesmainfile by file; the remaining failures (test_dapo_math,test_model_defaults,test_policy_loss_configs,test_search_r1,test_rdma_microbatch) also fail onmainin this environment (stalerenderers/package versions).test_draining_load_waits_for_admitted_requeststest_hot_swap_load_does_not_wait_for_admitted_requestsdrain=Falseloads starting to waittest_draining_load_applies_after_admitted_requests_and_before_held_back_ones(realEngineLoopthread)test_sticky_session_stays_on_its_draining_generatortest_new_sessions_spread_over_generators_that_all_draintest_drain_marks_generator_draining_for_its_loadtest_drain_clears_draining_on_pull_failure,test_round_robin_skips_draining_generatorsDeleted:
test_drain_excludes_syncing_generator_from_routesandtest_drain_pulls_idle_generators_while_busy_generator_drains(merged intotest_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).EngineLoops with fake engines, random multi-turn sticky sessions and 15 back-to-back pulls passed withhot_swapFalse/True; in drain mode 20-28 of 45 loads per run arrived with requests running, and none was applied with an admitted request.torchtitan_recipes.tests.rl.alphabet_sort.rl_grpo_fsdp2_gen_tp2_no_compile(3 generators x TP2 + FSDP2 trainer), 6-8 steps, withhot_swapFalse and True on this branch and False onmain: all complete. Caveat: the controller pulls when generators are idle in these recipes, so only one load across all runs had ageneratein flight (it finished before the weight copy); drain under load is mainly covered by the CPU tests above.Known issues / follow-ups
StickySessionRoutingStrategy's LRU refresh for that turn (negligible atmax_sessions=262144).hot_swap=False.