Skip to content

[rl] Look-aside generator routing: the router reserves, the caller generates - #5990

Merged
pzhan9 merged 3 commits into
pytorch:mainfrom
pzhan9:pzhang/look_aside_router
Nov 13, 2026
Merged

pzhan9 merged 3 commits into
pytorch:mainfrom
pzhan9:pzhang/look_aside_router

Conversation

@pzhan9

@pzhan9 pzhan9 commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

It is more performant to skip the extra hop through router.

Why

InterGeneratorRouter.generate proxies every generate call through the singleton router actor. Each prompt and each Completion (token ids + logprobs) is unpickled and repickled in the router process and crosses the network twice. Routing only needs the request id and the routing session. Pickling plus unpickling a 16K-token prompt alone costs ~320 us of router CPU per call, before the completion.

Example.

before (proxy):      caller --prompt--> router --prompt--> generator
                     caller <--completion-- router <--completion-- generator

after (look-aside):  caller --reserve(request_id, session)-------> router   (picks, load += 1)
                     caller <---------- generator rank-0 handle -- router
                     caller --prompt----------------------------------> generator
                     caller <--completion------------------------------ generator
                     caller --release_reservation(request_id)----> router   (load -= 1)

What changed

  • routing/inter_generator.py: generate/_route/_reserve/_release replaced by reserve(request_id, *, routing_session_id) -> rank-0 handle and release_reservation(request_id), like IntraGeneratorRouter's reserve/release (renamed so it isn't confused with release_session and release_groups, which free KV on a generator). Generator selection (strategy, draining, sticky pinning) is moved unchanged. The router keeps the request_id -> generator map. TODOs record that one load unit per call ignores request size and KV held between turns, and that returning an index instead of the handle is cheaper if the router becomes a bottleneck.
  • actors/monarch/router.py: the generate endpoint is replaced by reserve/release_reservation endpoints.
  • controller.py::_make_generate_fn: reserve, call generate on the returned handle, then await release_reservation in a finally.
  • routing/types.py: RoutingContext.estimated_cost removed. Its only writer (the proxy, always 1) and only reader are gone.
  • Docs (skimmable): rl/README.md, actors/monarch/README.md, the rollouter.py close docstring, the terminal_bench diagram.
  • Tests: test_inter_generator_router.py ported from router._route("generate", ...) to reserve/release_reservation. The tests are now synchronous; net -250 lines.

Trade-offs and alternatives

  • Each turn now makes two small router round trips (reserve, release_reservation; ~0.4-0.6 ms each on one host) around the direct generate call. The returned handle is ~2.8 KB and costs ~46 us to pickle on the router. All micro-numbers here were measured with Monarch 0.6.0 CPU actors in separate processes on one devgpu host.
  • Generate and load_model_state_dict no longer come from the same sender, so they are no longer ordered. With hot_swap=False, a call reserved just before a load can reach the generator after the drain starts and wait for the load. This costs latency only; before, the router's own send order put it ahead of the load.
  • release_reservation is an awaited call_one, not broadcast: a broadcast to a @concurrent_endpoint drops its exceptions (@concurrent_endpoint silently swallows exceptions from .broadcast() calls meta-pytorch/monarch#5277), which would hide a broken release.
  • Rejected: returning a generator index instead of the handle. It saves ~45 us per call on each side, but callers would then need the generator handle list.
  • Rejected: having the generator call router.release_reservation itself. Generators would need a router handle (circular at spawn) and would be coupled to routing.
  • Known limitation (TODO in _make_generate_fn): a cancelled caller releases early, and a caller that dies never releases. Nothing in-tree cancels a GenerateFn call, and a dead rollout worker fails the run (Monarch root-client supervision exits the controller).

Numerics / performance

This is not a computation change. Least-loaded/sticky routing was already timing-dependent, so runs are not bitwise-comparable. GPU smoke test (Qwen3-0.6B, FSDP2 trainer + 3 TP2 generators, 8 GPUs, temperature 2 for long rollouts, 10 steps), main (98a8ce0) vs this branch:

Config main this PR
hot_swap=False (drain) 10 steps, 0 failed rollouts, 8.30K tok/s, ITL 4.38 ms 10 steps, 0 failed rollouts, 8.45K tok/s, ITL 4.34 ms
hot_swap=True 10 steps, 0 failed rollouts, 8.33K tok/s, ITL 4.36 ms 10 steps, 0 failed rollouts, 8.34K tok/s, ITL 4.33 ms

At this scale the router is not a bottleneck, so this run shows no regression, not the win. No large-scale router-CPU benchmark yet.

Testing

  • pytest tests/rl/unit_tests/cpu/{test_inter_generator_router,test_async_controller,test_shutdown,test_intra_generator_router,test_trainer_loop,test_generator,test_engine_loop}.py: all pass.
  • New test_generate_fn_forwards_the_session_and_releases_on_failure: catches a failed generate call that never releases its load unit (silently skewing routing), a release that runs before the generate call finishes, and routing_session_id not reaching both routing layers.
  • test_sticky_session_respects_max_sessions and the merged test_release_session_unpins_it_and_frees_its_kv_on_its_generator now set repin_load_ratio=None. Before, default repinning moved the session anyway, so they passed with eviction/release disabled; now they fail (checked by mutation).

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 9, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 9, 2026
@pzhan9
pzhan9 force-pushed the pzhang/look_aside_router branch from 1ae3ade to e3de0f9 Compare November 10, 2026 00:00
@pzhan9
pzhan9 marked this pull request as ready for review November 10, 2026 16:05
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 10, 2026
@felipemello1

Copy link
Copy Markdown
Contributor

from claude to felipe: a TLDR image of this PR, drawn from its diff at e3de0f947.

Before, every prompt and completion went through the one router actor (about 320 µs of router CPU for a 16K-token prompt); now the router only reserves a generator and hands back a 2.8 KB handle, and the rollout worker sends the generate call straight to that generator.

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

thanks! I left a few comments.

Its neat that you only had to make changes to the router while keeping the generator/workers the same.

Comment thread torchtitan/rl/controller/controller.py Resolved
Comment thread torchtitan/rl/actors/monarch/router.py Resolved
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve: please first address felipemello1's three requests that aren't in the code yet (rename release, add a TODO on the load unit, add a comment on returning the handle vs. an index). 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 -- please address the items below before merging. The look-aside design is right: the router only needs (request_id, session), and generator selection moves over unchanged. What's left is three small edits that @felipemello1 asked for and that aren't in HEAD (e3de0f9) yet.

What this PR does. InterGeneratorRouter.generate no longer proxies prompts and completions. reserve(request_id, routing_session_id=...) picks a generator, adds one unit of load and returns its rank-0 handle. The caller calls generate on that handle directly, then calls release(request_id) in a finally. This mirrors IntraGeneratorRouter's existing reserve/release. RoutingContext.estimated_cost is deleted because it was always 1 and had no other reader. Net -187 LoC.

Example.

before: rollout worker --prompt(16K ids)--> router --prompt--> gen1
        rollout worker <--Completion------- router <--Completion-- gen1
after:  rollout worker --reserve("step=3/group=0/sample=0/turn=0", "s0")--> router  (gen1.load += 1)
        rollout worker <-- gen1.rank0 handle ------------------------------ router
        rollout worker --prompt / <--Completion--> gen1
        rollout worker --release(request_id)--> router  (gen1.load -= 1, also on error)

Must fix

  1. torchtitan/rl/routing/inter_generator.py:144 -- rename release (felipemello1), for example to release_reservation, and rename IntraGeneratorRouter.release to match.
  2. torchtitan/rl/routing/inter_generator.py:140 -- add the TODO felipemello1 asked for: load is one unit per call, and it ignores request size and the KV that sessions hold between turns.
  3. torchtitan/rl/routing/inter_generator.py:142 -- add the 1-2 line comment felipemello1 asked for on returning the handle vs. an index.
Details

felipemello1's controller.py:603 question ("if return await generator.generate.call_one is called, nothing calls release"). This one is mistaken. A finally block runs when the try body returns, raises, or is cancelled. So release is awaited after every generate.call_one returns, before generate hands the completion back. The new test_generate_fn_forwards_the_session_and_releases_on_failure covers the raise path. The real gaps are a cancelled caller that releases early and a dead caller that never releases, and the TODO at controller.py:588 already records both.

Ordering checks.

  • Both release paths are ordered correctly. release is awaited inside generate, and the rollouter calls release_session only after the session's last generate returns. So a session's load is always released before its pin is dropped.
  • A repin while a call is in flight still decrements the right generator, because _reservations maps each request to the handle it reserved.
  • The request_id uniqueness assert is not a new risk. IntraGeneratorRouter.reserve already asserts the same thing on the generator side.

hot_swap=False. A call reserved just before a drain can now reach the generator after the drain starts, and then it waits for the load. As the description says, this costs latency only. Pinned-but-draining sessions still stay on their generator, as before.

Not verified: the GPU smoke-test numbers in the description, and that Monarch actor-mesh handles returned from the router endpoint stay cheap to use from rollout-worker processes at larger scale.

A maintainer still needs to review.

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

thanks, one comment

…nerates

InterGeneratorRouter.generate proxied every generate call: the prompt and the
completion were unpickled and repickled in the singleton router process and
crossed the network twice, although routing only needs the request id and the
routing session. Pickling plus unpickling a 16K-token prompt alone takes
~320 us of router CPU, before the completion's token ids and logprobs.

The router now only routes, mirroring IntraGeneratorRouter's reserve/release:
reserve(request_id, routing_session_id) picks a generator (same strategy and
draining rules as before), adds one unit of load to it, and returns its rank-0
handle. The controller's GenerateFn sends the generate call to that handle and
then awaits release(request_id), so load still counts in-flight generate calls.

Trade-offs:
- A turn now makes two small router round trips (reserve, release; ~0.4-0.6 ms
  each on one host) around the direct generate call, instead of routing the
  payload through the router. The returned handle is ~2.8 KB and takes ~46 us
  to pickle on the router. (Measured with Monarch 0.6.0 CPU actors on one host.)
- release is awaited rather than broadcast, because Monarch's broadcast drops
  endpoint errors.
- The router no longer sends both the generate call and load_model_state_dict to
  a generator, so they are no longer ordered: with hot_swap=False, a call
  reserved just before a load can reach the generator after the drain starts and
  wait for the load. Latency only.

RoutingContext.estimated_cost loses its only writer (the proxy always passed 1)
and its only reader, and is removed. Two sticky-session tests now set
repin_load_ratio=None: with default repinning they passed even with eviction or
session release broken.
… load-unit and handle trade-offs

- Rename `release` to `release_reservation` on `InterGeneratorRouter` and its
  Monarch actor, so it isn't confused with `release_session` and
  `release_groups`, which free KV on a generator.
- TODO where `reserve` adds a load unit: one unit per call ignores request
  size, KV held between turns and generated tokens.
- Comment on returning the generator handle rather than an index.
The rollout worker no longer waits a router round trip after each generate
call. A release that raises now fails the router actor (a supervision
error) instead of being returned to the caller; for `@concurrent_endpoint`
this needs meta-pytorch/monarch#5283.
@pzhan9
pzhan9 force-pushed the pzhang/look_aside_router branch from ca15f66 to 49b5321 Compare November 12, 2026 22:55
@pzhan9
pzhan9 merged commit febafbd into pytorch:main Nov 13, 2026
@pzhan9
pzhan9 deleted the pzhang/look_aside_router branch November 13, 2026 03:52
ZhitongGuo added a commit to ZhitongGuo/torchtitan that referenced this pull request Nov 25, 2026
Reserve prompt tokens + max_tokens per call instead of one unit, and keep a session's last estimate on its generator between turns, so routing sees the KV that idle sessions hold. Follow-up to the TODO in pytorch#5990; part of pytorch#3755.
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