Skip to content

[rl] drain mode: wait for the pinned generator instead of re-pinning (3/5) - #5218

Merged
felipemello1 merged 2 commits into
mainfrom
felipemello1/session-kv/3-drain-wait
Oct 12, 2026
Merged

felipemello1 merged 2 commits into
mainfrom
felipemello1/session-kv/3-drain-wait

Conversation

@felipemello1

@felipemello1 felipemello1 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Problem: with hot_swap=False all 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.

real router, 2 generators, 20 sessions:
turn0 {gen0: 10, gen1: 10} | turn1, during sync {gen0: 19} | turn2, after sync {gen0: 19}

Solution: a turn whose session is pinned to a draining generator waits for it (RoutingStrategy.pinned_candidate + the generator's serving event, which replaces the SERVING/SYNCING enum). New sessions still go to any serving generator. With the default reset_kv_cache_on_weight_sync=False, the generator keeps a group's KV across the weight pull, so waiting beats re-prefilling elsewhere.

CPU sim on the real router classes, hot_swap=False, main -> this PR
32 generators:                wall 831 s -> 400 s
4 generators, multi-turn:     prefix hit 0.857 -> 0.898

NOTE: no recipe sets hot_swap=False today.

Test plan
pytest tests/rl/unit_tests/cpu: 433 passed, 5 skipped (main: 432 passed; the 2 test_verifiers_terminal_bench.py failures are on main too). test_sticky_session_assigns_new_generator_when_sticky_target_is_syncing asserted the old re-pin; it is now test_sticky_session_waits_for_its_syncing_generator.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Oct 9, 2026
@felipemello1
felipemello1 added this pull request to stack #5221 October 9, 2026 15:45
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 9, 2026
@felipemello1
felipemello1 force-pushed the felipemello1/session-kv/3-drain-wait branch from 79248f5 to 90ac057 Compare October 9, 2026 16:42
@felipemello1
felipemello1 marked this pull request as ready for review October 9, 2026 23:14
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 9, 2026

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

This PR itself is fine. But since we will wait anyway, we probably should move the hot_swap/drain logic to generator, and remove them from router. Thing should look much simpler. something like #5253

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.

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 drain is short" is not accurate?

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.

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.

@felipemello1
felipemello1 force-pushed the felipemello1/session-kv/3-drain-wait branch from 90ac057 to c25fb30 Compare October 11, 2026 20:01
@felipemello1
felipemello1 removed this pull request from stack #5221 October 11, 2026 20:03
@felipemello1
felipemello1 added this pull request to stack #5293 October 11, 2026 20:03

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

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.

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.

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.

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.

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 routable

If you meant a method on the handle (h.is_serving()), I'm happy to add it.

Comment on lines +158 to +162
h.state = state
if state is _GeneratorState.SERVING:
h.serving.set()
else:
h.serving.clear()

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.

similar -- having both is hard to read

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.

reply from claude: same fix as the :51 thread. _set_serving only touches the Event now.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR and my review

@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

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


Review of #5218 (and @tianyu-l's review)

  • Read the PR diff
  • Read the router and the strategies in full
  • Check tianyu-l's review points
  • Post the 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 state/serving duplication. Details are below.


Answers to your questions

1. "During hot_swap=False, handles will be in syncing status, where the router will re-route to some available generators instead of waiting?"

Yes, before this PR. _pull_one sets SYNCING (inter_generator.py:297). _candidates() then drops that handle. StickySessionRoutingStrategy.choose sees that the pinned handle is not among the candidates, so it falls back to least-loaded and writes the new choice into _sessions for good.

All pulls start together through asyncio.gather (:311), so every generator drains at roughly the same time. Turns that arrive during the sync wait on self._serving. Whichever generator calls _set_state(SERVING) first takes all of them, and they stay re-pinned there. That matches the {gen0: 19} numbers in the PR description. Your read is right, and the change makes sense.

2. "We wouldn't encounter this for hot_swap=True because syncing is never set there?"

Correct. _set_state is only called in the else branch of _pull_one, so with hot swap on, h.serving stays set from __init__ (:134). asyncio.Event.wait() on a set event returns right away without yielding. For hot swap, the new code adds only a dict lookup per request, and behaviour is unchanged.


Your inline comments

:51 and :162, "drop the Enum, check via instance methods": I agree. As written, the same fact is stored twice (h.state and h.serving), and _set_state has to keep them in sync by hand. The enum has only two values and is private: it is used only in this file and in test_inter_generator_router.py. A simpler version:

@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 _GeneratorState / h.state: lines 141, 144, 170, 243, 256, 391–431. They would switch to _set_serving(h, False) and [h.is_serving() for h in ...].

Fix this →


Other findings

1. The :195 comment ("the drain is short") is inaccurate, as pzhan9 pointed out. A drain waits for h.idle. That means every in-flight turn on that generator has to finish, and a long-generation turn can take a while. Only after that does the CPU-to-GPU apply run. Also, "the generator keeps the session's KV" holds only for the default reset_kv_cache_on_weight_sync=False (generator.py:822). It does not hold with True, which batch_invariant requires (generator.py:855).

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 pinned.serving.wait() wakes, the generator could go back to SYNCING before the task runs. That would need a second pull to start right away. In that case choose still re-pins through the fallback path, so nothing breaks or hangs. A comment isn't needed, but this is why choose still has to handle "pinned is not a candidate".

3. Waiting turns don't reserve load, which is correct. _reserve runs after the wait, so a parked turn doesn't keep h.idle cleared and can't stall the drain it is waiting on.

4. Test (test_sticky_session_waits_for_its_syncing_generator). It checks the three things that matter: the pinned turn blocks, a new session isn't blocked, and the turn lands on gen0 afterwards. await asyncio.sleep(0) followed by assert not turn.done() is a somewhat weak check, because one loop tick is enough here. Still, it would catch the old re-pin behaviour, since that version completes in a single tick.

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.

@felipemello1

Copy link
Copy Markdown
Contributor Author

reply from claude:

  • pzhan9: agreed, your drain-in-generator PR is the cleaner end state, and it deletes this wait along with the rest of the router drain. I'd land this one first, because it's small and 5/5 uses pinned_candidate to send each session release to the right generator. Then yours rebases on top and deletes the wait; there's a TODO pointing at it next to the wait. Does that work for you?
  • tianyu-l: yes to both. With hot_swap=False all generators drain in the same weight sync, and a pinned turn used to re-pin to the first one back ({gen0: 19} in the description). With hot_swap=True serving is never cleared, so nothing changes; it costs one Event check per request.

Base automatically changed from felipemello1/session-kv/2-release-routing-session to main October 12, 2026 05:08
Felipe Mello added 2 commits October 12, 2026 01:08
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.
@felipemello1
felipemello1 force-pushed the felipemello1/session-kv/3-drain-wait branch from 2614bac to cd9465f Compare October 12, 2026 05:08
@felipemello1
felipemello1 merged commit 4b0d99d into main Oct 12, 2026
tianyu-l pushed a commit that referenced this pull request Nov 7, 2026
… 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`.
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