Repository navigation
[rl] drain mode: wait for the pinned generator instead of re-pinning (3/5) - #5218
Conversation
79248f5 to
90ac057
Compare
| return its result. | ||
| """ | ||
| # A turn pinned to a draining generator waits for it instead of re-pinning | ||
| # elsewhere: the drain is short, and the generator keeps the session's KV. |
There was a problem hiding this comment.
"the drain is short" is not accurate?
There was a problem hiding this comment.
reply from claude: right, it isn't. The drain waits for every in-flight turn on that generator. The real reason is the pile-up: all generators drain in the same weight sync, so re-pinning would move every waiting session onto whichever generator serves first. The comment says that now.
90ac057 to
c25fb30
Compare
tianyu-l
left a comment
There was a problem hiding this comment.
Is this PR saying that
- during hot_swap=False, handles will be syncing status, where the router will re-route to some available generators instead of waiting? If so I think the change is legit
- I guess we wouldn't encounter such thing for hot-swap=True because syncing is never set there.
Please address inline comments.
There was a problem hiding this comment.
After you introduce serving to the handle itself, I don't feel we need such Enum anymore -- we should directly check candidates via instance methods.
There was a problem hiding this comment.
reply from claude: agreed, the enum is gone. The serving Event is the only state now: _candidates() checks h.serving.is_set(), and _set_state(h, SYNCING) became _set_serving(h, serving=False).
# before: two fields, kept in sync by _set_state
state: _GeneratorState = _GeneratorState.SERVING
serving: asyncio.Event
# after
serving: asyncio.Event # set while routableIf you meant a method on the handle (h.is_serving()), I'm happy to add it.
| h.state = state | ||
| if state is _GeneratorState.SERVING: | ||
| h.serving.set() | ||
| else: | ||
| h.serving.clear() |
There was a problem hiding this comment.
similar -- having both is hard to read
There was a problem hiding this comment.
reply from claude: same fix as the :51 thread. _set_serving only touches the Event now.
|
@claude review this PR and my review |
|
Claude finished @tianyu-l's task in 1m 17s —— View job Review of #5218 (and @tianyu-l's review)
Verdict: The change is correct and small. I found no bugs. My main suggestion is to make the fix tianyu-l asked for: collapse the Answers to your questions1. "During Yes, before this PR. All pulls start together through 2. "We wouldn't encounter this for Correct. Your inline comments
@dataclass(kw_only=True, slots=True)
class _GeneratorHandle(RoutingCandidate):
...
serving: asyncio.Event = field(default_factory=asyncio.Event)
"""Set while this generator is routable; cleared while it drains for a
weight sync (only when hot-swap is off)."""
def is_serving(self) -> bool:
return self.serving.is_set()
# router
def _candidates(self):
return [h for h in self._generators if h.is_serving()]
def _set_serving(self, h, serving: bool) -> None:
h.serving.set() if serving else h.serving.clear() # or an if/else
self._refresh_serving_status()This would also update these tests, which use Other findings1. The Waiting is still the right choice in both cases, because it also prevents the pile-up on the first generator back. The comment should give the reason that always holds, for example: # A turn pinned to a draining generator waits for it rather than re-pinning:
# every generator drains at once, so re-pinning would move all such sessions
# to whichever comes back first; waiting also reuses the session's KV when
# reset_kv_cache_on_weight_sync=False.2. Race after the wake-up (fine, but worth knowing). After 3. Waiting turns don't reserve load, which is correct. 4. Test ( 5. pzhan9's larger suggestion (#5253, move drain into the generator). Now that the router waits anyway, that refactor looks like the cleaner end state. Doing it as a follow-up seems reasonable; it doesn't need to block this PR in the stack. |
|
reply from claude:
|
With hot_swap=False every generator drains at once, and the first one back used to take every waiting turn and keep those sessions for good. Now a turn whose session is pinned to a draining generator waits for it; new sessions still go to any serving generator.
- Drop _GeneratorState and _GeneratorHandle.state; _candidates reads h.serving and _set_state becomes _set_serving(h, serving). - Reword the pinned-wait comment: all generators drain in the same weight sync, so re-pinning would pile those sessions onto whichever serves first. - TODO to move draining into the generator.
2614bac to
cd9465f
Compare
… generators (#5905) ## Summary (human-written) Address this TODO: https://github.com/pytorch/torchtitan/blob/c2579f7da7539986b2d5d02593957656890ebaf8/torchtitan/rl/routing/inter_generator.py#L171 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. * this is the current behavior. It is avoid pileup on the first undrained generator (see #5218). we just maintain it. 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 `EngineLoop`s 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`.
Problem: with
hot_swap=Falseall generators drain in the same weight sync. Every turn sent while they all drain goes to the first generator back, and the sticky strategy re-pins those sessions there for good.Solution: a turn whose session is pinned to a draining generator waits for it (
RoutingStrategy.pinned_candidate+ the generator'sservingevent, which replaces theSERVING/SYNCINGenum). New sessions still go to any serving generator. With the defaultreset_kv_cache_on_weight_sync=False, the generator keeps a group's KV across the weight pull, so waiting beats re-prefilling elsewhere.NOTE: no recipe sets
hot_swap=Falsetoday.Test plan
pytest tests/rl/unit_tests/cpu: 433 passed, 5 skipped (main: 432 passed; the 2test_verifiers_terminal_bench.pyfailures are on main too).test_sticky_session_assigns_new_generator_when_sticky_target_is_syncingasserted the old re-pin; it is nowtest_sticky_session_waits_for_its_syncing_generator.